Ejemplo n.º 1
0
    public boolean evaluate(FeatureClassInfo fci, List<Object> row, StringBuffer reasoning) {
      boolean ret = false;
      switch (op) {
        case NONE_CONN:
          break;
        case AND_CONN:
        case and_CONN:
          ret = true;
          for (Expression e : exp) {
            ret = e.evaluate(fci, row, reasoning);
            if (!ret) {
              break;
            }
          }
          break;
        case or_CONN:
        case OR_CONN:
          for (Expression e : exp) {
            ret = e.evaluate(fci, row, reasoning);
            if (ret) {
              break;
            }
          }
          break;
        default:
      }

      if (reasoning != null) {
        reasoning.append("\n-> " + toString() + ": evaluates " + ret);
      }
      return ret;
    }
Ejemplo n.º 2
0
 @Test
 public void falseConstant() throws EvaluationException {
   Expression e = new ConstantExpression(false);
   assertEquals(Boolean.FALSE, e.evaluate(topLevel));
   e = new ConstantExpression(Boolean.FALSE);
   assertEquals(Boolean.FALSE, e.evaluate(topLevel));
 }
Ejemplo n.º 3
0
 @Test
 public void trueConstant() throws EvaluationException {
   Expression e = new ConstantExpression(true);
   assertEquals(Boolean.TRUE, e.evaluate(topLevel));
   e = new ConstantExpression(Boolean.TRUE);
   assertEquals(Boolean.TRUE, e.evaluate(topLevel));
 }
  /**
   * Calculates the <tt>ComparisonOperation</tt>'s logical value based on the certain property
   * values of the given <tt>Feature</tt>. TODO: Improve datatype handling.
   *
   * @param feature that determines the property values
   * @return true, if the <tt>FeatureFilter</tt> evaluates to true, else false
   * @throws FilterEvaluationException if the expressions to be compared are of different types
   */
  public boolean evaluate(Feature feature) throws FilterEvaluationException {

    Object value1 = expr1.evaluate(feature);
    Object value2 = expr2.evaluate(feature);

    // compare Strings
    if (value1 instanceof String && value2 instanceof String) {
      switch (getOperatorId()) {
        case OperationDefines.PROPERTYISEQUALTO:
          {
            if (value1 == null || value2 == null) return false;
            return value1.equals(value2);
          }
        case OperationDefines.PROPERTYISLESSTHAN:
        case OperationDefines.PROPERTYISGREATERTHAN:
        case OperationDefines.PROPERTYISLESSTHANOREQUALTO:
        case OperationDefines.PROPERTYISGREATERTHANOREQUALTO:
          {
            throw new FilterEvaluationException(
                "'" + getOperatorName() + "' can not be applied to " + "String values!");
          }
        default:
          {
            throw new FilterEvaluationException(
                "Unknown comparison operation: '" + getOperatorName() + "'!");
          }
      }
    }
    // compare Doubles
    else if ((value1 instanceof Number) && (value2 instanceof Number)) {

      double d1 = Double.parseDouble(value1.toString());
      double d2 = Double.parseDouble(value2.toString());
      switch (getOperatorId()) {
        case OperationDefines.PROPERTYISEQUALTO:
          return d1 == d2;
        case OperationDefines.PROPERTYISLESSTHAN:
          return d1 < d2;
        case OperationDefines.PROPERTYISGREATERTHAN:
          return d1 > d2;
        case OperationDefines.PROPERTYISLESSTHANOREQUALTO:
          return d1 <= d2;
        case OperationDefines.PROPERTYISGREATERTHANOREQUALTO:
          return d1 >= d2;
        default:
          {
            throw new FilterEvaluationException(
                "Unknown comparison operation: '" + getOperatorName() + "'!");
          }
      }
    } else {
      //            throw new FilterEvaluationException (
      //                "Can not apply operation '" + getOperatorName () + "' to "
      //              + "different datatypes!");
      return false;
    }
  }
Ejemplo n.º 5
0
  protected void initMap(Map<Expression, Expression> source, Map target, FacesContext context) {

    for (Map.Entry<Expression, Expression> entry : source.entrySet()) {
      Expression k = entry.getKey();
      Expression v = entry.getValue();
      //noinspection unchecked
      target.put(
          k.evaluate(context.getELContext()),
          (v != null) ? v.evaluate(context.getELContext()) : null);
    }
  }
Ejemplo n.º 6
0
 public RGBColor evaluate() {
   ArrayList<RGBColor> evaluatedColors = new ArrayList<RGBColor>();
   for (Expression operand : myOperands) {
     evaluatedColors.add(operand.evaluate());
   }
   return ColorCombinations.sum(evaluatedColors);
 }
Ejemplo n.º 7
0
  @Override
  public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) {
    BigDecimal result = null;
    for (int i = 0; i < children.size(); i++) {
      Expression childExpr = children.get(i);
      if (!childExpr.evaluate(tuple, ptr)) {
        return false;
      }
      if (ptr.getLength() == 0) {
        return true;
      }

      PDataType childType = children.get(i).getDataType();
      BigDecimal bd = (BigDecimal) PDataType.DECIMAL.toObject(ptr, childType);

      if (result == null) {
        result = bd;
      } else {
        result = result.divide(bd, PDataType.DEFAULT_MATH_CONTEXT);
      }
    }
    if (maxLength != null && scale != null) {
      result = NumberUtil.setDecimalWidthAndScale(result, maxLength, scale);
    }
    if (result == null) {
      throw new ValueTypeIncompatibleException(PDataType.DECIMAL, maxLength, scale);
    }
    ptr.set(PDataType.DECIMAL.toBytes(result));
    return true;
  }
Ejemplo n.º 8
0
  /** {@inheritDoc} */
  @Override
  public boolean apply(@Nullable T1 t1, @Nullable T2 t2) {
    lazyCompile();

    if (expr != null) {
      JexlContext ctx = new MapContext();

      ctx.set(var1, t1);
      ctx.set(var2, t2);

      for (Map.Entry<String, Object> e : map.entrySet()) {
        ctx.set(e.getKey(), e.getValue());
      }

      try {
        Object obj = expr.evaluate(ctx);

        if (obj instanceof Boolean) {
          return (Boolean) obj;
        }
      } catch (Exception ex) {
        throw F.wrap(ex);
      }
    }

    return false;
  }
 @Override
 public Object doCompileTimeEvaluation() {
   Expression expr = getCompileTimeConstantExpression();
   return expr instanceof INewExpression
       ? getName() // Enum constant field name
       : expr.evaluate();
 }
Ejemplo n.º 10
0
  protected void initList(List<Expression> source, List target, FacesContext context) {

    for (int i = 0, size = source.size(); i < size; i++) {
      Expression value = source.get(i);
      //noinspection unchecked
      target.add((value != null) ? value.evaluate(context.getELContext()) : null);
    }
  }
 public ValidationException[] apply(Message msg) {
   try {
     Object subject = testExpression.evaluate(msg);
     boolean passed = getPredicate().evaluate(subject);
     return passed ? passed() : failedWithValue(subject, testExpression.getLocation(msg));
   } catch (Exception e) {
     return failed(e);
   }
 }
Ejemplo n.º 12
0
 @SuppressWarnings("unchecked")
 public Comparable evaluate(Object[] parameters) {
   for (Expression e : eList) {
     if (!((Boolean) e.evaluate(parameters))) {
       return Boolean.FALSE;
     }
   }
   return Boolean.TRUE;
 }
Ejemplo n.º 13
0
  // Extract all quotes from the quote bundle which cause the given
  // expression to equate to true. If there is no expression (string is null or
  // empty) then extract all the quotes.
  private List extractQuotesUsingRule(String filterExpression, EODQuoteBundle quoteBundle) {

    // If there is no rule, then just return all quotes
    if (filterExpression == null || filterExpression.length() == 0)
      return extractAllQuotes(quoteBundle);

    // First parse the expression
    Expression expression = null;

    try {
      expression = Parser.parse(filterExpressionString);
    } catch (ExpressionException e) {
      // We should have already checked the string for errors before here
      assert false;
    }

    // Add symbols to list when expression proves true
    ArrayList quotes = new ArrayList();
    Iterator iterator = quoteBundle.iterator();
    TradingDate lastDate = quoteBundle.getLastDate();

    try {
      // Traverse all symbols on all dates
      while (iterator.hasNext()) {
        Quote quote = (Quote) iterator.next();
        Symbol symbol = quote.getSymbol();
        TradingDate date = quote.getDate();
        int dateOffset = 0;

        try {
          dateOffset = quoteBundle.dateToOffset(date);
        } catch (WeekendDateException e) {
          assert false;
        }

        if (!singleDate || (lastDate.equals(quote.getDate()))) {
          if (expression.evaluate(new Variables(), quoteBundle, symbol, dateOffset)
              >= Expression.TRUE_LEVEL) quotes.add(quote);
        }
      }

      return quotes;
    } catch (EvaluationException e) {
      // Tell user expression didnt evaluate properly
      JOptionPane.showInternalMessageDialog(
          DesktopManager.getDesktop(),
          e.getReason() + ": " + expression.toString(),
          Locale.getString("ERROR_EVALUATION_EQUATION"),
          JOptionPane.ERROR_MESSAGE);

      // delete erroneous expression
      expression = null;

      // If the expression didn't evaluate then just return all the quotes
      return extractAllQuotes(quoteBundle);
    }
  }
Ejemplo n.º 14
0
 private Boolean evaluateToBoolean(final Expression expr, final ExecutionContext ctx) {
   final Object l = expr.evaluate(ctx);
   if (l == null) return null;
   if (!(l instanceof Boolean)) {
     final Type t = ctx.getType(l);
     throw new EvaluationException("Boolean expected but was " + t.getName(), expr, ctx);
   }
   final Boolean result = (Boolean) l;
   return result;
 }
 private void evaluateAndAssertResult(
     Expression expression, Object expectedResult, String context) {
   context = context == null ? "" : context;
   ImmutableBytesWritable ptr = new ImmutableBytesWritable();
   assertTrue(expression.evaluate(null, ptr));
   PDataType dataType = expression.getDataType();
   SortOrder sortOrder = expression.getSortOrder();
   Object result =
       dataType.toObject(ptr.get(), ptr.getOffset(), ptr.getLength(), dataType, sortOrder);
   assertEquals(context, expectedResult, result);
 }
Ejemplo n.º 16
0
  public Variable execute(
      ArrayList Parameters, ArrayList ParentTable, Linker MyLinker, boolean function, boolean loop)
      throws Exception {
    try {
      MyModel.incrementIterationCounter(getLine());
      if (MyModel.getExceptionRaised() != null) throw (MyModel.getExceptionRaised());

      HashMap MyTable = new HashMap();
      ParentTable.add(MyTable);

      if (!MyModel.getRunAllCode()) {
        if (Statements.size() > 0)
          while (Comparison.evaluate(ParentTable, MyLinker, function, loop).truthValue()) {
            for (int i = 0; i < Statements.size(); i++) {
              Statement TempStatement = (Statement) Statements.get(i);
              TempStatement.execute(Parameters, ParentTable, MyLinker, function, true);
            }
          }
      } else { // We must be attempting to run all code.
        Comparison.evaluate(ParentTable, MyLinker, function, loop);
        for (int i = 0; i < Statements.size(); i++) {
          Statement TempStatement = (Statement) Statements.get(i);
          TempStatement.execute(Parameters, ParentTable, MyLinker, function, loop);
        }
      }

      ParentTable.remove(ParentTable.size() - 1);

    } catch (Exception e) {
      if (e instanceof ModelReturn) // Pop from the stack if we're here.
      ParentTable.remove(ParentTable.size() - 1);

      if (e instanceof ModelBreak) return (null);

      if (!(e instanceof ModelError))
        throw (new ModelError("Runtime error on line " + getLine() + " when running while loop"));
      else throw (e);
    }
    return (null);
  }
Ejemplo n.º 17
0
  @Test
  public void test_infix() throws Exception {
    Expression exp = new InfixExpression("( ( a + b - c ) * d / e ) ^ 1 ^ 2 ^ 3 % 4 ^ 5");
    assertEquals("((a + b - c) * d / e) ^ 1 ^ 2 ^ 3 % 4 ^ 5", exp.toString());

    for (int i = 0; i < n; i++) {
      int a = r.nextInt(), b = r.nextInt(), c = r.nextInt(), d = r.nextInt(), e = r.nextInt();
      fillTable(new char[] {'a', 'b', 'c', 'd', 'e'}, new int[] {a, b, c, d, e});
      exp.setVarTable(varTable);
      int expected = (a + b - c) * d / e % (1 << 10);
      assertEquals(expected, exp.evaluate());
    }
  }
Ejemplo n.º 18
0
 private static boolean testExpression(LiteralExpression literal, double expected)
     throws SQLException {
   List<Expression> expressions = Lists.newArrayList((Expression) literal);
   Expression sqrtFunction = new ExpFunction(expressions);
   ImmutableBytesWritable ptr = new ImmutableBytesWritable();
   boolean ret = sqrtFunction.evaluate(null, ptr);
   if (ret) {
     Double result =
         (Double) sqrtFunction.getDataType().toObject(ptr, sqrtFunction.getSortOrder());
     assertTrue(twoDoubleEquals(result.doubleValue(), expected));
   }
   return ret;
 }
Ejemplo n.º 19
0
  /**
   * Does the feature in row of fci pass the conditions of this expression.
   *
   * @param fci
   * @param row
   * @return true if row contents passes evaluation
   */
  public boolean evaluate(FeatureClassInfo fci, int row) {
    boolean ret = true;
    StringBuffer reasoning = null;
    if (logger.isLoggable(Level.FINE)) {
      reasoning = new StringBuffer();
    }

    if (exp != null) {
      ret = exp.evaluate(fci, row, reasoning);
    }
    if (reasoning != null) {
      reasoning.append("\n--------");
      logger.fine(reasoning.toString());
    }
    return ret;
  }
Ejemplo n.º 20
0
 protected Value[] evaluateChildren(final ProcessingContext context, final int depth) {
   final List<Expression> children = getChildren();
   final Value[] childValues = new Value[children.size()];
   for (int i = 0; i < children.size(); i++) {
     final Expression child = children.get(i);
     Value childValue;
     if (child instanceof AbstractFunctionalExpression) {
       childValue = ((AbstractFunctionalExpression) child).evaluate(context, depth + 1);
     } else {
       /* (This only happens if an extension implements Expression directly) */
       childValue = child.evaluate(context);
     }
     childValues[i] = childValue;
   }
   return childValues;
 }
Ejemplo n.º 21
0
  private static void testExpression(
      LiteralExpression array, LiteralExpression element, PhoenixArray expected)
      throws SQLException {
    List<Expression> expressions = Lists.newArrayList((Expression) element);
    expressions.add(array);

    Expression arrayPrependFunction = new ArrayPrependFunction(expressions);
    ImmutableBytesWritable ptr = new ImmutableBytesWritable();
    arrayPrependFunction.evaluate(null, ptr);
    PhoenixArray result =
        (PhoenixArray)
            arrayPrependFunction
                .getDataType()
                .toObject(
                    ptr, expressions.get(1).getSortOrder(), array.getMaxLength(), array.getScale());
    assertEquals(result, expected);
  }
Ejemplo n.º 22
0
  @Test
  public void test_postfix() throws Exception {
    Expression exp = new PostfixExpression("a b c d e + - * /");
    assertEquals("a b c d e + - * /", exp.toString());

    for (int i = 0; i < n; i++) {
      int a = r.nextInt(), b = r.nextInt(), c = r.nextInt(), d = r.nextInt(), e = r.nextInt();
      // System.out.println("a: "+a);
      // System.out.println("b: "+b);
      // System.out.println("c: "+c);
      // System.out.println("d: "+a);
      // System.out.println("e: "+b);

      fillTable(new char[] {'a', 'b', 'c', 'd', 'e'}, new int[] {a, b, c, d, e});
      exp.setVarTable(varTable);
      int expected = a / (b * (c - (d + e)));
      assertEquals(expected, exp.evaluate());
    }
  }
Ejemplo n.º 23
0
  public String evaluate(String expString) {
    try {
      ArrayList<Token> tokens = _tokenizer.tokenize(expString);

      LinkedList<String> lst = new LinkedList<>();
      tokens
          .stream()
          .forEach(
              (t) -> {
                lst.add((new Pair<>(t.Literal(), t.Token())).toString());
              });

      Expression exp = _parser.parse(tokens);
      ArrayList<Integer> lst2 = exp.evaluate();

      return lst.toString() + "\n" + lst2.toString();
    } catch (Tokenizer.TokenizerException exception) {
      return "String can't be parsed.";
    }
  }
Ejemplo n.º 24
0
 @Test
 public void testEvalConst() throws Exception {
   Expression expression = Expression.of("92");
   int actual = expression.evaluate();
   assertEquals(92, actual);
 }
Ejemplo n.º 25
0
 @Test
 public void testEvaluateInEnvironment() throws Exception {
   Map<String, Integer> environment = Collections.singletonMap("x", 92);
   Expression expression = Expression.of("x");
   assertEquals(92, expression.evaluate(environment));
 }
Ejemplo n.º 26
0
 @Test
 public void testComplicatedExpression() throws Exception {
   Expression expression = Expression.of("((2)+(2 + 2))");
   int actual = expression.evaluate();
   assertEquals(6, actual);
 }
Ejemplo n.º 27
0
 @Test
 public void testSumWithParenthesis() throws Exception {
   Expression expression = Expression.of("2+(2 + 2)");
   int actual = expression.evaluate();
   assertEquals(6, actual);
 }
Ejemplo n.º 28
0
 @Test
 public void testSpacedExpression() throws Exception {
   Expression expression = Expression.of("(2 + 2)");
   int actual = expression.evaluate();
   assertEquals(4, actual);
 }
Ejemplo n.º 29
0
 @Test
 public void testScopeInteger() throws Exception {
   Expression expression = Expression.of("(42)");
   int actual = expression.evaluate();
   assertEquals(42, actual);
 }
Ejemplo n.º 30
0
 @Test
 public void nullConstant() throws EvaluationException {
   Expression e = new ConstantExpression(null);
   assertNull(e.evaluate(topLevel));
 }