示例#1
0
 /**
  * Retrieves a single value from a variety of different argument types according to standard
  * Excel rules.  Does not perform any type conversion.
  * @param arg the Evaluated argument as passed to the function or operator.
  * @param srcCellRow used when arg Is a single column AreaRef
  * @param srcCellCol used when arg Is a single row AreaRef
  * @return a <tt>NumberEval</tt>, <tt>StringEval</tt>, <tt>BoolEval</tt> or <tt>BlankEval</tt>.
  * Never <c>null</c> or <tt>ErrorEval</tt>.
  * @throws EvaluationException(#VALUE!) if srcCellRow or srcCellCol do not properly index into
  *  an AreaEval.  If the actual value retrieved Is an ErrorEval, a corresponding 
  *  EvaluationException Is thrown.
  */
 public static ValueEval GetSingleValue(Eval arg, int srcCellRow, short srcCellCol)
 {
     Eval result;
     if (arg is RefEval)
     {
         result = ((RefEval)arg).InnerValueEval;
     }
     else if (arg is AreaEval)
     {
         result = ChooseSingleElementFromArea((AreaEval)arg, srcCellRow, srcCellCol);
     }
     else
     {
         result = arg;
     }
     if (result is ErrorEval)
     {
         throw new EvaluationException((ErrorEval)result);
     }
     if (result is ValueEval)
     {
         return (ValueEval)result;
     }
     throw new Exception("Unexpected eval type (" + result.GetType().Name + ")");
 }
示例#2
0
        public ValueEval Evaluate(Eval[] args, EvaluationWorkbook workbook, int srcCellSheet, int srcCellRow,
                int srcCellCol)
        {

            double result;
            try
            {
                int basis = 0; // default
                switch (args.Length)
                {
                    case 3:
                        basis = EvaluateIntArg(args[2], srcCellRow, srcCellCol);
                        break;
                    case 2:
                        basis = EvaluateIntArg(args[2], srcCellRow, srcCellCol);
                        break;
                    default:
                        return ErrorEval.VALUE_INVALID;
                }
                double startDateVal = EvaluateDateArg(args[0], srcCellRow, srcCellCol);
                double endDateVal = EvaluateDateArg(args[1], srcCellRow, srcCellCol);
                result = YearFracCalculator.Calculate(startDateVal, endDateVal, basis);
            }
            catch (EvaluationException e)
            {
                return e.GetErrorEval();
            }

            return new NumberEval(result);
        }
示例#3
0
        public Eval Evaluate(Eval[] args, int srcCellRow, short srcCellCol)
        {
            switch (args.Length)
            {
                default:
                    return ErrorEval.VALUE_INVALID;
                case 1:
                    break;
            }
            Eval arg = args[0];
            if (arg is RefEval)
            {
                RefEval re = (RefEval)arg;
                arg = re.InnerValueEval;
            }

            if (arg is StringEval)
            {
                // Text values are returned Unmodified
                return arg;
            }

            if (arg is ErrorEval)
            {
                // Error values also returned Unmodified
                return arg;
            }
            // for all other argument types the result Is empty string
            return StringEval.EMPTY_INSTANCE;
        }
示例#4
0
 public Eval Evaluate(Eval[] args, int srcCellRow, short srcCellCol)
 {
     if (args.Length != 1)
     {
         return ErrorEval.VALUE_INVALID;
     }
     double d;
     try
     {
         ValueEval ve = OperandResolver.GetSingleValue(args[0], srcCellRow, srcCellCol);
         if (ve is BlankEval)
         {
             return NumberEval.ZERO;
         }
         if (ve is StringEval)
         {
             // Note - asymmetric with UnaryMinus
             // -"hello" Evaluates to #VALUE!
             // but +"hello" Evaluates to "hello"
             return ve;
         }
         d = OperandResolver.CoerceValueToDouble(ve);
     }
     catch (EvaluationException e)
     {
         return e.GetErrorEval();
     }
     return new NumberEval(+d);
 }
示例#5
0
        /**
         * Replaces part of a text string based on the number of Chars 
         * you specify, with another text string.
         * 
         * @see org.apache.poi.hssf.record.formula.eval.Eval
         */
        public override ValueEval EvaluateFunc(Eval[] args, int srcCellRow, short srcCellCol)
        {
            if (args.Length != 4)
            {
                return ErrorEval.VALUE_INVALID;
            }

            String oldStr = EvaluateStringArg(args[0], srcCellRow, srcCellCol);
            int startNum = EvaluateIntArg(args[1], srcCellRow, srcCellCol);
            int numChars = EvaluateIntArg(args[2], srcCellRow, srcCellCol);
            String newStr = EvaluateStringArg(args[3], srcCellRow, srcCellCol);

            if (startNum < 1 || numChars < 0)
            {
                return ErrorEval.VALUE_INVALID;
            }
            StringBuilder strBuff = new StringBuilder(oldStr);
            // remove any characters that should be replaced
            if (startNum <= oldStr.Length && numChars != 0)
            {
                strBuff.Remove(startNum - 1, startNum - 1 + numChars);
            }
            // now insert (or append) newStr
            if (startNum > strBuff.Length)
            {
                strBuff.Append(newStr);
            }
            else
            {
                strBuff.Insert(startNum - 1, newStr);
            }
            return new StringEval(strBuff.ToString());
        }
示例#6
0
        public override Eval Evaluate(Eval[] args, int srcRow, short srcCol)
        {
            if (args.Length != 2)
            {
                return ErrorEval.VALUE_INVALID;
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 2; i++)
            {

                ValueEval ve = SingleOperandEvaluate(args[i], srcRow, srcCol);
                if (ve is StringValueEval)
                {
                    StringValueEval sve = (StringValueEval)ve;
                    sb.Append(sve.StringValue);
                }
                else if (ve is BlankEval)
                {
                    // do nothing
                }
                else
                { // must be an error eval
                    return ve;
                }
            }

            return new StringEval(sb.ToString());
        }
示例#7
0
 public Eval Evaluate(Eval[] args, int srcCellRow, short srcCellCol)
 {
     Eval arg3 = null;
     switch (args.Length)
     {
         case 4:
             arg3 = args[3]; // important: assumed array element Is never null
             break;
         case 3:
             break;
         default:
             // wrong number of arguments
             return ErrorEval.VALUE_INVALID;
     }
     try
     {
         // Evaluation order:
         // arg0 lookup_value, arg1 table_array, arg3 range_lookup, Find lookup value, arg2 row_index, fetch result
         ValueEval lookupValue = OperandResolver.GetSingleValue(args[0], srcCellRow, srcCellCol);
         AreaEval tableArray = LookupUtils.ResolveTableArrayArg(args[1]);
         bool IsRangeLookup = LookupUtils.ResolveRangeLookupArg(arg3, srcCellRow, srcCellCol);
         int colIndex = LookupUtils.LookupIndexOfValue(lookupValue, LookupUtils.CreateRowVector(tableArray, 0), IsRangeLookup);
         int rowIndex = LookupUtils.ResolveRowOrColIndexArg(args[2], srcCellRow, srcCellCol);
         ValueVector resultCol = CreateResultColumnVector(tableArray, rowIndex);
         return resultCol.GetItem(colIndex);
     }
     catch (EvaluationException e)
     {
         return e.GetErrorEval();
     }
 }
示例#8
0
        public Eval Evaluate(Eval[] args, int srcCellRow, short srcCellCol)
        {
            switch (args.Length)
            {
                case 1:
                    // expected
                    break;
                case 0:
                    // too few arguments
                    return ErrorEval.VALUE_INVALID;
                default:
                    // too many arguments
                    return ErrorEval.VALUE_INVALID;
            }
            Eval firstArg = args[0];

            int result;
            if (firstArg is AreaEval)
            {
                AreaEval ae = (AreaEval)firstArg;
                result = ae.LastRow - ae.FirstRow + 1;
            }
            else if (firstArg is RefEval)
            {
                result = 1;
            }
            else
            { // anything else Is not valid argument
                return ErrorEval.VALUE_INVALID;
            }
            return new NumberEval(result);
        }
示例#9
0
        public Eval Evaluate(Eval[] args, int srcCellRow, short srcCellCol)
        {
            int nArgs = args.Length;
            if (nArgs < 1)
            {
                // too few arguments
                return ErrorEval.VALUE_INVALID;
            }

            if (nArgs > 30)
            {
                // too many arguments
                return ErrorEval.VALUE_INVALID;
            }

            int temp = 0;
            // Note - observed behavior of Excel:
            // Error values like #VALUE!, #REF!, #DIV/0!, #NAME? etc don't cause this COUNTA to return an error
            // in fact, they seem to Get Counted

            for (int i = 0; i < nArgs; i++)
            {
                temp += CountUtils.CountArg(args[i], predicate);

            }
            return new NumberEval(temp);
        }
示例#10
0
 protected int EvaluateAsInteger(Eval eval)
 {
     int numval = -1;
     if (eval is NumberEval)
     {
         NumberEval neval = (NumberEval)eval;
         double d = neval.NumberValue;
         numval = (int)d;
     }
     else if (eval is StringEval)
     {
         StringEval seval = (StringEval)eval;
         String s = seval.StringValue;
         try
         {
             double d = double.Parse(s);
             numval = (int)d;
         }
         catch (Exception)
         {
         }
     }
     else if (eval is BoolEval)
     {
         BoolEval beval = (BoolEval)eval;
         numval = beval.BooleanValue ? 1 : 0;
     }
     else if (eval is RefEval)
     {
         numval = EvaluateAsInteger(XlateRefEval((RefEval)eval));
     }
     return numval;
 }
示例#11
0
 public Eval Evaluate(Eval[] args, int srcCellRow, short srcCellCol)
 {
     BoolEval beval;
     Eval evalWhenFalse = BoolEval.FALSE;
     switch (args.Length)
     {
         case 3:
             evalWhenFalse = args[2];
             beval = (BoolEval)args[0]; // TODO - class cast exception
             if (beval.BooleanValue)
             {
                 return args[1];
             }
             return evalWhenFalse;
         case 2:
             beval = (BoolEval)args[0]; // TODO - class cast exception
             if (beval.BooleanValue)
             {
                 return args[1];
             }
             return evalWhenFalse;
         default:
             return ErrorEval.VALUE_INVALID;
     }
 }
示例#12
0
        /**
         *Substitutes text in a text string with new text, some number of times.
         * 
         * @see org.apache.poi.hssf.record.formula.eval.Eval
         */
        public override ValueEval EvaluateFunc(Eval[] args, int srcCellRow, short srcCellCol)
        {
            if (args.Length < 3 || args.Length > 4)
            {
                return ErrorEval.VALUE_INVALID;
            }

            String oldStr = EvaluateStringArg(args[0], srcCellRow, srcCellCol);
            String searchStr = EvaluateStringArg(args[1], srcCellRow, srcCellCol);
            String newStr = EvaluateStringArg(args[2], srcCellRow, srcCellCol);
            

            String result;

            switch (args.Length)
            {
                case 4:
                    int instanceNumber = EvaluateIntArg(args[3], srcCellRow, srcCellCol);
                    if (instanceNumber < 1)
                    {
                        return ErrorEval.VALUE_INVALID;
                    }
                    result = ReplaceOneOccurrence(oldStr, searchStr, newStr, instanceNumber);
                    break;
                case 3:
                    result = ReplaceAllOccurrences(oldStr, searchStr, newStr);
                    break;
                default:
                    throw new InvalidOperationException("Cannot happen");

            }

            return new StringEval(result);
        }
示例#13
0
        public override ValueEval EvaluateFunc(Eval[] args, int srcCellRow, short srcCellCol)
        {
            if (args.Length != 3)
            {
                return ErrorEval.VALUE_INVALID;
            }

            String text = EvaluateStringArg(args[0], srcCellRow, srcCellCol);
            int startCharNum = EvaluateIntArg(args[1], srcCellRow, srcCellCol);
            int numChars = EvaluateIntArg(args[2], srcCellRow, srcCellCol);
            int startIx = startCharNum - 1; // convert to zero-based

            // Note - for start_num arg, blank/zero causes error(#VALUE!),
            // but for num_chars causes empty string to be returned.
            if (startIx < 0)
            {
                return ErrorEval.VALUE_INVALID;
            }
            if (numChars < 0)
            {
                return ErrorEval.VALUE_INVALID;
            }
            int len = text.Length;
            if (numChars < 0 || startIx > len)
            {
                return new StringEval("");
            }
            int endIx = Math.Min(startIx + numChars, len);
            String result = text.Substring(startIx, endIx-startIx);
            return new StringEval(result);
        }
示例#14
0
        public override Eval Evaluate(Eval[] operands, int srcCellRow, short srcCellCol)
        {
            Eval retval = BoolEval.FALSE;

            switch (operands.Length)
            {
                case 1:
                    Eval eval = operands[0];
                    if (eval is BoolEval)
                    {
                        retval = BoolEval.TRUE;
                    }
                    else if (eval is RefEval)
                    {
                        Eval xlatedEval = XlateRefEval((RefEval)eval);
                        if (xlatedEval is BoolEval)
                        {
                            retval = BoolEval.TRUE;
                        }
                    }
                    break;
                default:
                    retval = ErrorEval.VALUE_INVALID;
                    break;

            }

            return retval;
        }
示例#15
0
        public Eval Evaluate(Eval[] evals, int srcCellRow, short srcCellCol)
        {
            if (evals.Length > 0)
            {
                return ErrorEval.VALUE_INVALID;
            }

            return new NumberEval(HSSFDateUtil.GetExcelDate(DateTime.Today));
        }
示例#16
0
 public override ValueEval EvaluateFunc(Eval[] args, int srcCellRow, short srcCellCol)
 {
     if (args.Length != 1)
     {
         return ErrorEval.VALUE_INVALID;
     }
     String arg = EvaluateStringArg(args[0], srcCellRow, srcCellCol);
     return Evaluate(arg);
 }
示例#17
0
 protected override double Eval(Eval[] args, int srcCellRow, short srcCellCol)
 {
     if (args.Length != 1)
     {
         throw new EvaluationException(ErrorEval.VALUE_INVALID);
     }
     double d = SingleOperandEvaluate(args[0], srcCellRow, srcCellCol);
     return Evaluate(d);
 }
示例#18
0
 public override Eval Evaluate(Eval[] operands, int srcRow, short srcCol)
 {
     Eval retval = null;
     Function f = GetFunction();
     if (f != null)
         retval = f.Evaluate(operands, srcRow, srcCol);
     else
         retval = ErrorEval.FUNCTION_NOT_IMPLEMENTED;
     return retval;
 }
示例#19
0
        public override ValueEval EvaluateFunc(Eval[] args, int srcCellRow, short srcCellCol)
        {

            StringBuilder sb = new StringBuilder();
			for (int i=0, iSize=args.Length; i<iSize; i++) {
				sb.Append(EvaluateStringArg(args[i], srcCellRow, srcCellCol));
			}
			return new StringEval(sb.ToString());

        }
示例#20
0
        public override ValueEval EvaluateFunc(Eval[] args, int srcCellRow, short srcCellCol)
        {
            if (args.Length != 2)
            {
                return ErrorEval.VALUE_INVALID;
            }

            String s0 = EvaluateStringArg(args[0], srcCellRow, srcCellCol);
            String s1 = EvaluateStringArg(args[1], srcCellRow, srcCellCol);
            return BoolEval.ValueOf(s0.Equals(s1));
        }
示例#21
0
 public Eval Evaluate(Eval[] args, int srcCellRow, short srcCellCol)
 {
     try
     {
         return EvaluateFunc(args, srcCellRow, srcCellCol);
     }
     catch (EvaluationException e)
     {
         return e.GetErrorEval();
     }
 }
示例#22
0
        private static int EvaluateArgParity(Eval arg, int srcCellRow, int srcCellCol)
        {
            ValueEval ve = OperandResolver.GetSingleValue(arg, srcCellRow, (short)srcCellCol);

            double d = OperandResolver.CoerceValueToDouble(ve);
            if (d < 0)
            {
                d = -d;
            }
            long v = (long)Math.Floor(d);
            return (int)(v & 0x0001);
        }
示例#23
0
 private static RefEval EvaluateRef(Eval arg)
 {
     if (arg is RefEval)
     {
         return (RefEval)arg;
     }
     if (arg is ErrorEval)
     {
         throw new EvaluationException((ErrorEval)arg);
     }
     throw new ArgumentException("Unexpected ref arg class (" + arg.GetType().Name + ")");
 }
示例#24
0
        private void AppendArgument(StreamWriter Output, int Indentation, string Name, string Value, bool Quotes, char QuoteChar)
        {
            this.AppendArgument(Output, Indentation, Name);

            if (Quotes)
            {
                Eval.ExportPlantUml("\"" + Value.Replace("\"", "\\\"") + "\"", Output, Indentation, QuoteChar, false);
            }
            else
            {
                Eval.ExportPlantUml(Value, Output, Indentation, QuoteChar, false);
            }
        }
示例#25
0
        public void Equation()
        {
            var eval          = new Eval();
            var ev            = @"a =	-1.90348642570E-002
              b =	2.59124284126E+003
              c =	1.74712818469E+000
              d =	2.19476267227E+000
              x =  10
              =(a*b+c*x^d)/(b+x^d)";
            var expectedValue = 0.0816126249369512;

            Assert.AreEqual(Math.Round(expectedValue, 3), Math.Round(eval.ProcessEquation(ev), 3));
        }
 private bool IsValidAssignment(string name, Location loc)
 {
     if (Eval.GetInScope(name) is ILocatedMember m)
     {
         // Class and function definition are processed first, so only override
         // if assignment happens after declaration
         if (loc.IndexSpan.Start < m.Location.IndexSpan.Start)
         {
             return(false);
         }
     }
     return(true);
 }
示例#27
0
        public void Aggregate()
        {
            var P = RelNode.Import(SourceKind.Csv, Testdata, "P", "PNo:text,PName:text,Color:text,Weight:number,City:text");

            var pagg = P
                       .Project("Color,Weight")
                       .Aggregate("Weight,TotWeight", Eval.Number((v, a) => v + a));

            Assert.AreEqual(2, pagg.Degree);
            Assert.AreEqual("Color,TotWeight", pagg.Heading.ToNames().Join(","));
            Assert.AreEqual(3, pagg.Cardinality);
            Assert.AreEqual("Red,45.0;Green,17.0;Blue,29.0", pagg.Join(";"));
        }
示例#28
0
        public override async Task <bool> WalkAsync(ReturnStatement node, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var value = await Eval.GetValueFromExpressionAsync(node.Expression, cancellationToken);

            if (!value.IsUnknown())
            {
                _result = value;
                return(false);
            }
            return(true);
        }
示例#29
0
    public Eval Evaluate(Eval[] operands, int srcRow, short srcCol) {
        ValueEval retval;
        switch (operands.Length) {
            case 0:
                retval = new NumberEval(new Random().NextDouble());
                break;
            default:
                retval = ErrorEval.VALUE_INVALID;
                break;

        }
        return retval;
    }
示例#30
0
        public void testReplaceAndEvaluate()
        {
            string testExpression = "@+3/20";
            string testRegex      = "@";
            double testValue      = 30d;
            double expectedResult = 30.15d;

            Assert.AreEqual(
                expectedResult,
                Eval.ReplaceNEvaluate(
                    testExpression, testRegex, testValue)
                );
        }
示例#31
0
            public bool Matches(Eval valueEval)
            {
                // Note - observed behavior of Excel:
                // Error values like #VALUE!, #REF!, #DIV/0!, #NAME? etc don't cause this COUNTA to return an error
                // in fact, they seem to get counted

                if (valueEval == BlankEval.INSTANCE)
                {
                    return false;
                }
                // Note - everything but BlankEval counts
                return true;
            }
示例#32
0
 public Value Convert(ResolveResult result)
 {
     if (result.IsCompileTimeConstant && !result.IsError)
     {
         var type = Import(result.Type);
         if (type == null)
         {
             throw new GetValueException("Error: cannot find '{0}'.", result.Type.FullName);
         }
         return(Eval.CreateValue(evalThread, result.ConstantValue, type));
     }
     return(Visit((dynamic)result));
 }
示例#33
0
        static void Main(string[] args)
        {
            var eval = new Eval();
            var res  = "";

            // Test Case
            if ((res = eval.eval(new[] { "1 0 0", "", "", "", }, 0)) != "1")
            {
                throw new Exception(res);
            }
            if ((res = eval.eval(new[] { "1 0 2", "", "", "", }, 0)) != "0")
            {
                throw new Exception(res);
            }
            if ((res = eval.eval(new[] { "3 0 0", "", "", "", }, 0)) != "1")
            {
                throw new Exception(res);
            }
            if ((res = eval.eval(new[] { "4 0 2", "", "", "", }, 0)) != "0")
            {
                throw new Exception(res);
            }
            if ((res = eval.eval(new[] { "3 2 0", "", "", "", }, 0)) != "0.75")
            {
                throw new Exception(res);
            }
            if ((res = eval.eval(new[] { "3 1 1", "", "", "", }, 0)) != "0.25")
            {
                throw new Exception(res);
            }
            if ((res = eval.eval(new[] { "4 1 1", "", "", "", }, 0)) != "0.5")
            {
                throw new Exception(res);
            }
            //if ((res = eval.eval(new[] { "", "", "", "", }, 0)) != "") throw new Exception(res);
            //return;

            File.Delete(OUTPUT);
            var lines = File.ReadAllLines(FILE_NAME);
            var T     = int.Parse(lines[0]);
            var l     = 1; //行数

            for (int t = 0; t < T; t++)
            {
                res = eval.eval(lines, l);
                l  += 1;

                File.AppendAllText(OUTPUT, string.Format("Case #{0}: {1}\n", t + 1, res));
                Console.Write(DateTime.Now.ToShortTimeString() + "." + DateTime.Now.Second + string.Format(" Case #{0}: {1}\n", t + 1, res));
            }
        }
示例#34
0
        public static string GetAns(string statement)
        {
            var complex = false;

            foreach (var symbol in statement)
            {
                if (symbol == 'i')
                {
                    complex = true;
                }
            }

            return(!complex?Eval.Execute <long>(statement).ToString() : MathSolver.GetAnswer(statement));
        }
示例#35
0
        public override void Evaluate()
        {
            var stub = SymbolTable.ReplacedByStubs.Contains(Target) ||
                       _function.DeclaringModule.ModuleType == ModuleType.Stub ||
                       Module.ModuleType == ModuleType.Specialized;

            using (Eval.OpenScope(_function.DeclaringModule, FunctionDefinition, out _)) {
                // Process annotations.
                var annotationType = Eval.GetTypeFromAnnotation(FunctionDefinition.ReturnAnnotation);
                if (!annotationType.IsUnknown())
                {
                    // Annotations are typically types while actually functions return
                    // instances unless specifically annotated to a type such as Type[T].
                    var instance = annotationType.CreateInstance(annotationType.Name, ArgumentSet.Empty);
                    _overload.SetReturnValue(instance, true);
                }
                else
                {
                    // Check if function is a generator
                    var suite     = FunctionDefinition.Body as SuiteStatement;
                    var yieldExpr = suite?.Statements.OfType <ExpressionStatement>().Select(s => s.Expression as YieldExpression).ExcludeDefault().FirstOrDefault();
                    if (yieldExpr != null)
                    {
                        // Function return is an iterator
                        var yieldValue  = Eval.GetValueFromExpression(yieldExpr.Expression) ?? Eval.UnknownType;
                        var returnValue = new PythonGenerator(Eval.Interpreter, yieldValue);
                        _overload.SetReturnValue(returnValue, true);
                    }
                }

                DeclareParameters(!stub);

                // Do process body of constructors since they may be declaring
                // variables that are later used to determine return type of other
                // methods and properties.
                var ctor = _function.Name.EqualsOrdinal("__init__") || _function.Name.EqualsOrdinal("__new__");
                if (ctor || annotationType.IsUnknown() || Module.ModuleType == ModuleType.User)
                {
                    // Return type from the annotation is sufficient for libraries and stubs, no need to walk the body.
                    FunctionDefinition.Body?.Walk(this);
                    // For libraries remove declared local function variables to free up some memory.
                    var optionsProvider = Eval.Services.GetService <IAnalysisOptionsProvider>();
                    if (Module.ModuleType != ModuleType.User && optionsProvider?.Options.KeepLibraryLocalVariables != true)
                    {
                        ((VariableCollection)Eval.CurrentScope.Variables).Clear();
                    }
                }
            }
            Result = _function;
        }
示例#36
0
        // GET: Evals/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Eval eval = db.Evals.Find(id);

            if (eval == null)
            {
                return(HttpNotFound());
            }
            return(View(eval));
        }
示例#37
0
        private object EvalJScript(string src)
        {
            var engine = Engine;

            try
            {
                With.JScriptWith(this, Engine);
                return(Eval.JScriptEvaluate(src, "unsafe", engine));
            }
            finally
            {
                engine.PopScriptObject(/* with */);
            }
        }
        private bool EvaluateScreenAndConditions(Screen screen, ConditionsConfiguration condition)
        {
            if (condition.Primary.HasValue && condition.Primary.Value != screen.Primary)
            {
                return(false);
            }

            if (condition.Expression != null && !Eval.Execute <bool>(condition.Expression, screen.Bounds))
            {
                return(false);
            }

            return(true);
        }
示例#39
0
        private void HandleAllAppendExtend(CallExpression node)
        {
            if (!(node.Target is MemberExpression me))
            {
                return;
            }

            if (!IsHandleableAll(me.Target))
            {
                return;
            }

            if (node.Args.Count == 0)
            {
                return;
            }

            var arg = node.Args[0].Expression;
            var v   = Eval.GetValueFromExpression(arg);

            if (v == null)
            {
                _allIsUsable = false;
                return;
            }

            IPythonCollection values = null;

            switch (me.Name)
            {
            case "append":
                values = PythonCollectionType.CreateList(Module.Interpreter, Eval.GetLoc(arg), new List <IMember>()
                {
                    v
                }, exact: true);
                break;

            case "extend":
                values = v as IPythonCollection;
                break;
            }

            if (values == null)
            {
                _allIsUsable = false;
                return;
            }

            ExtendAll(node, values);
        }
示例#40
0
        public static Parse Any(params Union <Parse, Func <Parse> >[] parsers)
        {
            return((data, charsHandledSoFar, acc, errors) => {
                var result = parsers.Select(
                    x => {
                    var newErrors = new List <Error>();
                    var newAcc = new Result();
                    return new { result = Eval(x)(data, charsHandledSoFar, newAcc, newErrors), acc = newAcc, errors = newErrors };
                }
                    ).ToArray();

                if (result.All(x => x.result.Item1 == State.Failure))
                {
                    errors.Add(new Error("All of the following possibilities failed", result.SelectMany(x => x.errors).ToList(), charsHandledSoFar));
                    return Tuple.Create(State.Failure, data, charsHandledSoFar);
                }

                var longestMatch = result.Where(x => x.result.Item1 == State.Success).MaxBy(x => x.result.Item3);
                acc.AddRange(longestMatch.acc);
                errors.AddRange(longestMatch.errors);
                return longestMatch.result;
            });
        }
 public bool HandleGlobal(GlobalStatement node)
 {
     foreach (var nex in node.Names)
     {
         var m = Eval.LookupNameInScopes(nex.Name, out _, out var v, LookupOptions.Global);
         if (m != null)
         {
             var location = Eval.GetLocationOfName(nex);
             Eval.CurrentScope.DeclareGlobal(nex.Name, location);
             v?.AddReference(location);
         }
     }
     return(false);
 }
        public async Task HandleAnnotatedExpressionAsync(ExpressionWithAnnotation expr, IMember value, CancellationToken cancellationToken = default)
        {
            if (expr?.Annotation == null)
            {
                return;
            }

            var variableType = await Eval.GetTypeFromAnnotationAsync(expr.Annotation, cancellationToken);

            // If value is null, then this is a pure declaration like
            //   x: List[str]
            // without a value. If value is provided, then this is
            //   x: List[str] = [...]

            // Check value type for compatibility
            IMember instance = null;

            if (value != null)
            {
                var valueType = value.GetPythonType();
                if (!variableType.IsUnknown() && !valueType.Equals(variableType))
                {
                    // TODO: warn incompatible value type.
                    // TODO: verify values. Value may be list() while variable type is List[str].
                    // Leave it as variable type.
                }
                else
                {
                    instance = value;
                }
            }
            instance = instance ?? variableType?.CreateInstance(variableType.Name, Eval.GetLoc(expr.Expression), ArgumentSet.Empty) ?? Eval.UnknownType;

            if (expr.Expression is NameExpression ne)
            {
                Eval.DeclareVariable(ne.Name, instance, expr.Expression);
                return;
            }

            if (expr.Expression is MemberExpression m)
            {
                // self.x : int = 42
                var self    = Eval.LookupNameInScopes("self", out var scope);
                var argType = self?.GetPythonType();
                if (argType is PythonClassType cls && scope != null)
                {
                    cls.AddMember(m.Name, instance, true);
                }
            }
        }
示例#43
0
 protected override double Eval(Eval[] args, int srcCellRow, short srcCellCol)
 {
     int nArgs = args.Length;
     if (nArgs < _minArgs || nArgs > _maxArgs)
     {
         throw new EvaluationException(ErrorEval.VALUE_INVALID);
     }
     double[] ds = new double[nArgs];
     for (int i = 0; i < nArgs; i++)
     {
         ds[i] = SingleOperandEvaluate(args[i], srcCellRow, srcCellCol);
     }
     return Evaluate(ds);
 }
示例#44
0
        private void ExtendAll(Node location, IPythonCollection values)
        {
            Eval.LookupNameInScopes(AllVariableName, out var scope, LookupOptions.Global);
            if (scope == null)
            {
                return;
            }

            var all    = scope.Variables[AllVariableName]?.Value as IPythonCollection;
            var list   = PythonCollectionType.CreateConcatenatedList(Module.Interpreter, all, values);
            var source = list.IsGeneric() ? VariableSource.Generic : VariableSource.Declaration;

            Eval.DeclareVariable(AllVariableName, list, source, location);
        }
示例#45
0
        public void Equation_SYM()
        {
            var eval          = new Eval();
            var ev            = @"a =	4.42907255764E-002
b =	4.28646004865E-003
c =	6.79041100634E-004
d =	-6.24669695062E-006
                x = iv.alpha
                =a+b*x+c*x^2+d*x^3";
            var expectedValue = 0.149;

            eval.SetSymbol("iv.alpha", 10);
            Assert.AreEqual(Math.Round(expectedValue, 3), Math.Round(eval.ProcessEquation(ev), 3));
        }
示例#46
0
        protected internal override void TraverseProp(Prop prop)
        {
            var ass = prop.Parent as Assign;

            (ass != null && ass.Lhs == prop).AssertFalse();

            var getter = prop.Property.GetGetMethod(true);
            var @this  = prop.Property.IsInstance() ? prop.This.MkArray() : Seq.Empty <Expression>();
            var args   = prop.InvocationIndexers() ?? Seq.Empty <Expression>();
            var style  = prop.InvokedAsVirtual ? InvocationStyle.Virtual : InvocationStyle.NonVirtual;
            var equiv  = new Eval(new Apply(new Lambda(getter, style), @this.Concat(args)));

            Traverse(equiv);
        }
示例#47
0
 private void TryHandleClassVariable(MemberExpression mex, IMember value)
 {
     if (mex.Target is NameExpression nex && nex.Name == "self")
     {
         var m   = Eval.LookupNameInScopes(nex.Name, out _, LookupOptions.Local);
         var cls = m.GetPythonType <IPythonClassType>();
         if (cls != null)
         {
             using (Eval.OpenScope(Eval.Module, cls.ClassDefinition, out _)) {
                 Eval.DeclareVariable(mex.Name, value, VariableSource.Declaration, Eval.GetLocationOfName(mex));
             }
         }
     }
 }
示例#48
0
        static private AssemblyResults CompileAssembly(String code)
        {
            try
            {
                StreamWriter w = new StreamWriter("C:\\Program Files\\ILNET\\ILNET Server\\Solution\\project.cs");
                w.Write(code);
                w.Close();

                Dictionary <string, string> providerOptions = new Dictionary <string, string>();
                providerOptions.Add("CompilerVersion", "v4.0");
                CodeDomProvider codeProvider = new CSharpCodeProvider(providerOptions);

                ICodeCompiler      icc = codeProvider.CreateCompiler();
                CompilerParameters cp  = new CompilerParameters()
                {
                    GenerateInMemory        = false,
                    IncludeDebugInformation = Debugger.IsAttached,
                    TreatWarningsAsErrors   = false,
                    WarningLevel            = 0,
                    GenerateExecutable      = false,
                    CompilerOptions         = "/optimize+"
                };

                cp.ReferencedAssemblies.Add("System.dll");
                cp.ReferencedAssemblies.Add("System.Core.dll");
                cp.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
                cp.ReferencedAssemblies.Add("System.Data.dll");
                cp.ReferencedAssemblies.Add("System.Drawing.dll");
                cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                cp.ReferencedAssemblies.Add(FullReference("System.Xml.dll"));
                cp.ReferencedAssemblies.Add(FullReference("System.Xml.Linq.dll"));
                //cp.ReferencedAssemblies.Add(FullReference("MySql.Data.dll"));
                cp.ReferencedAssemblies.Add(FullReference("Common.dll"));
                AssemblyResults asm = Eval.CreateAssembly(icc, code, cp, new CSharpLanguage());
                return(asm);
            }
            catch (CompilationException ce)
            {
                foreach (CompilerError error in ce.Errors)
                {
                    if (error.IsWarning)
                    {
                        continue;
                    }
                    throw new Exception(Utils.Extract(code, "fname", code.NthIndexOf("\n", error.Line)).Substring(3), ce);
                }
                throw new Exception("", ce);
            }
        }
示例#49
0
        internal MethodResults CompileConstraints(List <string> constraints, int dims)
        {
            string code = "return ";

            foreach (string eq in constraints)
            {
                code += "(" + FillCode(eq, dims) + ") &&";
            }

            // if no constraints then constraints always met (true)
            if (constraints.Count == 0)
            {
                code += "true";
            }
            else
            {
                code = code.TrimEnd('&', ' ');
            }

            code += ";";

            StringBuilder source = new StringBuilder();

            source.Append("public bool MeetsConstraint(float[] x, float t)");
            source.Append(Environment.NewLine);
            source.Append("{");
            source.Append(Environment.NewLine);
            source.Append(code);
            source.Append(Environment.NewLine);
            source.Append("}");

            try
            {
                return(Eval.CreateVirtualMethod(
                           new CSharpCodeProvider().CreateCompiler(),
                           source.ToString(),
                           "MeetsConstraint",
                           new CSharpLanguage(),
                           false,
                           "System.dll",
                           "System.Drawing.dll"));
            }
            catch (CompilationException ce)
            {
                MessageBox.Show(this, "Compilation Errors: " + Environment.NewLine + ce.ToString());
            }

            return(null);
        }
示例#50
0
文件: wondevWoman.cs 项目: jakkyl/CG
        private static Eval evaluatePush(Action action, Point[] enemyPos)
        {
            var pos = enemyPos[action.id];
            var newEnemyPosition = GetMove(pos, action.moveDirection);

            if (!IsValidLocation(newEnemyPosition))
            {
                return new Eval {
                           blocksEnemy = -1, helpsEnemy = -1, moveHeight = -1, overBuilt = -1, buildHeight = -1
                }
            }
            ;

            //if (action.position.Equals(newEnemyPosition)) return new Eval { blocksEnemy = -1, helpsEnemy = -1, moveHeight = -1, overBuilt = -1, buildHeight = -1 };
            //Console.Error.WriteLine("na: " + action);
            //Console.Error.WriteLine("np: " + newEnemyPosition);
            var build       = GetMove(newEnemyPosition, action.buildDirection);
            var initHeight  = GetHeight(pos);
            var moveHeight  = GetHeight(newEnemyPosition);
            var buildHeight = 0;// GetHeight(build);

            int netHeight = moveHeight - initHeight;
            var myHeight  = GetHeight(action.position);

            int overBuilt   = buildHeight >= 3 ? 1 : 0;
            int helpedEnemy = 0;
            int blocksEnemy = 0;

            for (int i = 0; i < 2; i++)
            {
                int enemyHeight = GetHeight(enemyPos[i]);
                int distance    = build.Distance(enemyPos[i]);
                if (netHeight > 0 /*|| !Neighbors(action.position).Contains(build)*/)
                {
                    helpedEnemy = 1;
                }
                if (netHeight < 0)
                {
                    blocksEnemy = -netHeight;
                }
            }

            var result = new Eval {
                blocksEnemy = blocksEnemy, helpsEnemy = -helpedEnemy, moveHeight = myHeight - netHeight, overBuilt = -overBuilt, buildHeight = buildHeight
            };

            Console.Error.WriteLine("PUSHING: " + result);
            return(result);
        }
        private void CheckValidFunction(IPythonFunctionType function, IReadOnlyList <IParameterInfo> parameters)
        {
            // Don't give diagnostics on functions defined in metaclasses
            if (_self.IsMetaclass())
            {
                return;
            }

            // Static methods don't need any diagnostics
            if (function.IsStatic)
            {
                return;
            }

            // Lambdas never get a self/cls argument.
            if (function.IsLambda())
            {
                return;
            }

            // Error in parameters, don't lint
            if (FunctionDefinition.Body == null)
            {
                return;
            }

            // Otherwise, functions defined in classes must have at least one argument
            if (parameters.IsNullOrEmpty())
            {
                var funcLoc = Eval.GetLocation(FunctionDefinition.NameExpression);
                ReportFunctionParams(Resources.NoMethodArgument, ErrorCodes.NoMethodArgument, funcLoc);
                return;
            }

            var param    = parameters[0].Name;
            var paramLoc = Eval.GetLocation(FunctionDefinition.Parameters[0]);

            // If it is a class method check for cls
            if (function.IsClassMethod && !param.Equals("cls"))
            {
                ReportFunctionParams(Resources.NoClsArgument, ErrorCodes.NoClsArgument, paramLoc);
            }

            // If it is a method check for self
            if (!function.IsClassMethod && !param.Equals("self"))
            {
                ReportFunctionParams(Resources.NoSelfArgument, ErrorCodes.NoSelfArgument, paramLoc);
            }
        }
示例#52
0
        static javascript()
        {
#if USEVSAHOST
            Engine = Evaluator.Evaluator.Engine;
#else
            List <string> assemblies        = new List <string>(DefaultAssemblyReferences);
            Assembly      executingAssembly = Assembly.GetExecutingAssembly();
            foreach (var name in executingAssembly.GetReferencedAssemblies())
            {
                string codeBase = name.CodeBase;
                try
                {
                    Assembly assembly = Assembly.Load(name);

                    if (assembly.GlobalAssemblyCache)
                    {
                        codeBase = Path.GetFileName(assembly.Location);
                    }
                    else
                    {
                        codeBase = assembly.Location;
                    }
                }
                catch (ChatSignal ex)
                {
                    throw;
                }
                catch (Exception)
                {
                }
                if (codeBase == null)
                {
                    codeBase = name.Name + ".dll";
                }
                if (!assemblies.Contains(codeBase))
                {
                    assemblies.Add(codeBase);
                }
            }
            var GS = VsaEngine.CreateEngineAndGetGlobalScope(true, assemblies.ToArray());
            Engine = GS.engine;
#endif
            foreach (string reference in DefaultNamespaceReferences)
            {
                Import.JScriptImport(reference, Engine);
            }
            object o = Eval.JScriptEvaluate("this", Engine);
            writeDebugLine("JSciptThis = " + o);
        }
示例#53
0
        public static Value MakeValue(object obj)
        {
            Value v = null;

            if (!(obj is string))
            {
                v = Eval.CreateValue(WorkbenchServiceFactory.DebuggerManager.DebuggedProcess, obj);
                v.SetPrimitiveValue(obj);
            }
            else
            {
                v = Eval.NewString(WorkbenchServiceFactory.DebuggerManager.DebuggedProcess, obj as string);
            }
            return(v);
        }
        public void HandleAnnotatedExpression(ExpressionWithAnnotation expr, IMember value)
        {
            if (expr?.Annotation == null)
            {
                return;
            }

            var variableType = Eval.GetTypeFromAnnotation(expr.Annotation);

            // If value is null, then this is a pure declaration like
            //   x: List[str]
            // without a value. If value is provided, then this is
            //   x: List[str] = [...]
            HandleTypedVariable(variableType, value, expr.Expression);
        }
示例#55
0
文件: Form1.cs 项目: andgate/Calc
        /* Equality */
        private void eqBtn_Click(object sender, EventArgs e)
        {
            if (output.Text.Trim().Equals(""))
            {
                return;
            }

            string result = Eval.eval(output.Text.Trim());

            //string resultMsg = output.Text + " = " + result;

            history.Add(result);
            resultsBox.Text = string.Join("\n---\n", history);
            output.Clear();
        }
示例#56
0
        // return true if there was eval to setup and it was setup
        internal bool SetupNextEvaluation()
        {
            this.AssertPaused();

            while (pendingEvalsCollection.Count > 0)
            {
                Eval nextEval = pendingEvalsCollection.Dequeue();
                if (nextEval.SetupEvaluation(this.SelectedThread))
                {
                    activeEvals.Add(nextEval);
                    return(true);
                }
            }
            return(false);
        }
示例#57
0
        public Eval Redirect(Eval eval)
        {
            var m = eval.InvokedMethod();
            var a = eval.InvocationArgs().ToReadOnly();

            var redirectors = _redirects.Select(kvp => kvp.Key(m) ? kvp.Value : null).Where(f => f != null);
            var f_mredir = redirectors.AssertSingle().Item1;
            var m_redir = f_mredir(m, a);
            var f_aredir = redirectors.AssertSingle().Item2;
            var a_redir = f_aredir(m, a);

            if (m_redir == null || a_redir == null) return null;
            // todo. this doesn't preserve virtuality of the call!
            return new Eval(new Apply(new Lambda(m_redir), a_redir));
        }
示例#58
0
        public Eval Evaluate(Eval[] operands, int srcRow, short srcCol)
        {
            ValueEval retval;
            switch (operands.Length)
            {
                case 0:
                    retval = PI_EVAL;
                    break;
                default:
                    retval = ErrorEval.VALUE_INVALID;
                    break;

            }
            return retval;
        }
 protected ValueEval SingleOperandEvaluate(Eval eval, int srcRow, short srcCol)
 {
     ValueEval retval;
     if (eval is AreaEval)
     {
         AreaEval ae = (AreaEval)eval;
         if (ae.Contains(srcRow, srcCol))
         { // circular ref!
             retval = ErrorEval.CIRCULAR_REF_ERROR;
         }
         else if (ae.IsRow)
         {
             if (ae.ContainsColumn(srcCol))
             {
                 ValueEval ve = ae.GetValue(ae.FirstRow, srcCol);
                 ve = Xlator.AttemptXlateToNumeric(ve);
                 retval = Xlator.AttemptXlateToNumeric(ve);
             }
             else
             {
                 retval = ErrorEval.VALUE_INVALID;
             }
         }
         else if (ae.IsColumn)
         {
             if (ae.ContainsRow(srcRow))
             {
                 ValueEval ve = ae.GetValue(srcRow, ae.FirstColumn);
                 retval = Xlator.AttemptXlateToNumeric(ve);
             }
             else
             {
                 retval = ErrorEval.VALUE_INVALID;
             }
         }
         else
         {
             retval = ErrorEval.VALUE_INVALID;
         }
     }
     else
     {
         retval = Xlator.AttemptXlateToNumeric((ValueEval)eval);
     }
     return retval;
 }
示例#60
0
            public bool Matches(Eval valueEval)
            {

                if (valueEval is NumberEval)
                {
                    // only numbers are counted
                    return true;
                }
                if (valueEval == MissingArgEval.instance)
                {
                    // oh yeah, and missing arguments
                    return true;
                }

                // error values and string values not counted
                return false;
            }