Exemplo n.º 1
0
        public bool Operations(bool a, bool b, bool c, bool d)
        {
            bool temp = false;

            try
            {
                if (cantVars == 2)
                {
                    temp = Eval.Execute <bool>(op, new { a, b });
                }
                if (cantVars == 3)
                {
                    temp = Eval.Execute <bool>(op, new { a, b, c });
                }
                if (cantVars == 4)
                {
                    temp = Eval.Execute <bool>(op, new { a, b, c, d });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                verif = true;
            }
            return(temp);
        }
Exemplo n.º 2
0
        public void AddTwoNumbers()
        {
            string testAddingNumebrs = "2+3";
            int    result            = Eval.Execute <int>(testAddingNumebrs);

            Assert.IsTrue(result == 5);
        }
Exemplo n.º 3
0
        public double Evaluate(List <double> argumentsValues)
        {
            if (argumentsValues.Count != this.argumentsSymbol.Count)
            {
                throw new Exception();
            }

            Dictionary <string, double> argument_value = new Dictionary <string, double>();

            for (int i = 0; i < this.argumentsSymbol.Count; i++)
            {
                argument_value.Add(this.argumentsSymbol[i], argumentsValues[i]);
            }

            double result = 0;

            try
            {
                result = Eval.Execute <double>(this.FunctionExpression, argument_value);
            }
            catch
            {
                throw new Exception();
            }

            return(result);
        }
Exemplo n.º 4
0
        public void SubTwoNumbers()
        {
            string testSubNumebrs = "2-3";
            int    result         = Eval.Execute <int>(testSubNumebrs);

            Assert.IsTrue(result == -1);
        }
Exemplo n.º 5
0
        public void TestEvalwithEmptyCallObject()
        {
            var code = new StringBuilder();

            code.AppendLine("if (_call.LineOfBusiness.Equals(\"PAU\")) {");
            code.AppendLine("\t\t_call.Claim.ClaimNumber = \"123456789\"; }");
            code.AppendLine("else {");
            code.AppendLine("\t\t_call.Claim.SetValue(\"ERRORSTRING\",\"LOB_CD NOT PAU\"); }");

            var eval = new Eval {
                Expression = code.ToString()
            };
            //eval.Parameter = call.ToXml();

            var results = eval.Execute();

            NUnit.Framework.Assert.IsEmpty(eval.LastError, eval.LastError);
            NUnit.Framework.Assert.IsNotEmpty(results, "Nothing returned!");

            var resultCall = new CallObject();

            resultCall.LoadFromXml(results);
            NUnit.Framework.Assert.IsNotEmpty(resultCall.GetValue("LASTERROR"), "Expected error was not returned!");
            Console.WriteLine(resultCall.GetValue("LASTERROR"));
        }
Exemplo n.º 6
0
        public void MulTwoNumbers()
        {
            string testMulNumebrs = "2*3";
            int    result         = Eval.Execute <int>(testMulNumebrs);

            Assert.IsTrue(result == 6);
        }
Exemplo n.º 7
0
        public ActionResult Index(string biggo, string cal = "0+0")
        {
            ViewBag.result = Eval.Execute <double>(cal);


            return(View());
        }
Exemplo n.º 8
0
        public void SinOfNull()
        {
            string testSinOfNull = "sin(0)";
            double result        = Eval.Execute <double>(testSinOfNull);

            Assert.IsTrue(result == 0);
        }
Exemplo n.º 9
0
        public void DivTwoNumbers()
        {
            string testDivNumebrs = "4/2";
            int    result         = Eval.Execute <int>(testDivNumebrs);

            Assert.IsTrue(result == 2);
        }
Exemplo n.º 10
0
        public void CosOfNull()
        {
            string testCosOfNull = "cos(0)";
            int    result        = Eval.Execute <int>(testCosOfNull);

            Assert.IsTrue(result == 1);
        }
Exemplo n.º 11
0
        public void TanOfNull()
        {
            string testTanOfNull = "tan(0)";
            int    result        = Eval.Execute <int>(testTanOfNull);

            Assert.IsTrue(result == 0);
        }
        public static double Evaluate(String input)
        {
            var E = new Eval();

            return(E.Execute(input));

            //http://stackoverflow.com/questions/333737/evaluating-string-342-yield-int-18?noredirect=1&lq=1  Modified for numbers of more than one character

/*
 *          String expr = "(" + input + ")";
 *          Stack<String> ops = new Stack<String>();
 *          Stack<Double> vals = new Stack<Double>();
 *          int SSLength = 1;
 *
 *
 *          for (int i = 0; i < expr.Length; i=i+0)
 *          {
 *              SSLength = 1;
 *
 *              if (char.IsDigit(expr[i]) || expr[i].Equals('.'))
 *              {
 *                  int j = i+1;
 *                  while (j < expr.Length && (char.IsDigit(expr[j]) || expr[j].Equals('.'))){
 *                      SSLength++;
 *                      j++;
 *                  }
 *
 *              }
 *
 *              String s = expr.Substring(i, SSLength);
 *              i = i + SSLength;
 *
 *              if (s.Equals("(")) { }
 *              else if (s.Equals("+")|| s.Equals("-")|| s.Equals("*")||s.Equals("/"))
 *               ops.Push(s);
 *
 *
 *              else if (s.Equals(")"))
 *              {
 *                  int count = ops.Count;
 *                  while (count > 0)
 *                  {
 *                      String op = ops.Pop();
 *                      double v = vals.Pop();
 *                      if (op.Equals("+")) v = vals.Pop() + v;
 *                      else if (op.Equals("-")) v = vals.Pop() - v;
 *                      else if (op.Equals("*")) v = vals.Pop() * v;
 *                      else if (op.Equals("/")) v = vals.Pop() / v;
 *                      //else if (op.Equals("sqrt")) v = Math.Sqrt(v);
 *                      vals.Push(v);
 *
 *                      count--;
 *                  }
 *              }
 *              else vals.Push(Double.Parse(s));
 *          }
 *          return vals.Pop();
 */
        }
Exemplo n.º 13
0
 private double DoExpression(string str, double x, double y)
 {
     try
     {
         return(Eval.Execute <double>(str, new { x = x, y = y }));
     }
     catch
     {
         return(0);
     }
 }
Exemplo n.º 14
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));
        }
        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);
        }
Exemplo n.º 16
0
        public static double Evaluate(string expression, Dictionary <string, double> symbolsValues)
        {
            double result = 0;

            try
            {
                result = Eval.Execute <double>(expression, symbolsValues);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            return(result);
        }
Exemplo n.º 17
0
        public void CotOfNull()
        {
            bool isExcept = false;

            try
            {
                string testTanOfNull = "tan(0)";
                int    result        = Eval.Execute <int>(testTanOfNull);
                int    inf           = 1 / result;
            } catch (Exception)
            {
                isExcept = true;
            }
            Assert.IsTrue(isExcept);
        }
Exemplo n.º 18
0
        public string Count(string expression)
        {
            string result = "";

            try
            {
                var outcome = Eval.Execute <int>(expression);

                result = outcome.ToString();
            }
            catch
            {
                result = "ERROR";
            }
            return(result);
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            dynamic expando = new ExpandoObject();

            AddProperty(expando, "a", 5);

            int result = Eval.Execute <int>(@"
                var y = a;
                if ( y == 5 ) {
                    y += 5;
                }
                var list = new List<int>() {1, 2, 3, 4, 5};
                var filter = list.Where(x => x < 3);
                return filter.Sum(x => x) + y", expando);

            Console.WriteLine(result);
            Console.ReadLine();
        }
Exemplo n.º 20
0
        public void TestEvalwithCompilationErrors()
        {
            var code = new StringBuilder();

            code.AppendLine("if (_call.LineOfBusiness.Equals(\"PAU\")) {");
            code.AppendLine("\t\t_call1.Claim.ClaimNumber = \"123456789\"; }"); // typo here
            code.AppendLine("else {");
            code.AppendLine("\t\t_call.Claim.SetValue(\"ERRORSTRING\",\"LOB_CD NOT PAU\"); }");

            var eval = new Eval {
                Expression = code.ToString(), Parameter = _call.ToXml()
            };

            var results = eval.Execute();

            NUnit.Framework.Assert.IsNotEmpty(eval.LastError, eval.LastError);
            NUnit.Framework.Assert.IsEmpty(results, "Something returned!");

            Console.WriteLine(eval.LastError);
        }
Exemplo n.º 21
0
        /// <summary>
        /// {table1:[{a:1,b:2},{.}],table2:[]}
        /// </summary>
        /// <param name="data">{table1:[{a:1,b:2},{.}],table2:[]}</param>
        /// <param name="lines">{FromTableName,ToTableName,FromColName,ToColName}</param>
        /// <returns></returns>
        public LogicLayerResponse MultiJoin(Dictionary <string, List <Dictionary <string, object> > > data, JoinLine[] lines)
        {
            var result = new LogicLayerResponse();

            try {
                var currentData = new List <string> ();
                var tmp         = "";
                for (var i = 0; i < lines.Length; i++)
                {
                    var fromTable = lines[i].FromTableName.Replace(" ", "_");
                    var toTable   = lines[i].ToTableName.Replace(" ", "_");
                    var fromCol   = lines[i].FromColName;
                    var toCol     = lines[i].ToColName;
                    if (i == 0)
                    {
                        tmp += $"data[\"{fromTable}\"].Join(data[\"{toTable}\"], {fromTable}=>{fromTable}[\"{fromCol}\"], {toTable}=>{toTable}[\"{toCol}\"], ({fromTable},{toTable})=>new{{{fromTable},{toTable}}})";
                    }
                    else
                    {
                        tmp += $".Join(data[\"{toTable}\"], query=>query.{fromTable}[\"{fromCol}\"], {toTable}=>{toTable}[\"{toCol}\"], (query,{toTable})=>new{{{Query2dTo1d(currentData.ToArray())}{toTable}}})";
                    }
                    if (currentData.FirstOrDefault(x => x == fromTable) == null)
                    {
                        currentData.Add(fromTable);
                    }
                    if (currentData.FirstOrDefault(x => x == toTable) == null)
                    {
                        currentData.Add(toTable);
                    }
                }
                result.Status = 200;
                result.Result = Eval.Execute(tmp, new { data = data });
            } catch (Exception e) {
                result.Status = 400;
                result.Result = e.ToString();
            }
            return(result);
        }
Exemplo n.º 22
0
 private void btnEvaluate_Click(object sender, EventArgs e)
 {
     try
     {
         // Evaluate the current expression
         Eval eval = new Eval();
         eval.ProcessSymbol   += ProcessSymbol;
         eval.ProcessFunction += ProcessFunction;
         txtResult.Text        = eval.Execute(txtExpression.Text).ToString();
     }
     catch (EvalException ex)
     {
         // Report expression error and move caret to error position
         MessageBox.Show(ex.Message);
         txtExpression.Select(ex.Column, 0);
         txtExpression.Select();
     }
     catch (Exception ex)
     {
         // Unknown error
         MessageBox.Show("Unexpected error : " + ex.Message);
     }
 }
Exemplo n.º 23
0
        /// <summary>
        /// Функция
        /// </summary>
        /// <param name="X"> Первый аргумент </param>
        /// <param name="Y"> Второй аргумент </param>
        /// <returns> Результат применения функции к X и Y </returns>
        private int Fun(int X, int Y)
        {
            int answer = Eval.Execute <int>(operation, new { X, Y }) % p;

            return(answer + ((answer < 0) ? p : 0));
        }
        KeyValuePair <string, string> ComprobarTiposParaAsignacion(Variables AAsginar, string sentencia)
        {
            var splited   = sentencia.Split(' ');
            var stack     = new Stack <KeyValuePair <string, string> >();
            var operacion = "";

            for (int i = 0; i < splited.Length; i++)
            {
                if (splited[i] == ";")
                {
                    break;
                }
                else
                {
                    if (splited[i].Contains('▄'))
                    {
                        var cadena = Cadenas[splited[i].Trim()];
                        stack.Push(new KeyValuePair <string, string>("string", cadena)); operacion += $" {cadena}";
                        operacion = operacion.Trim();;
                    }
                    else if (Number.IsMatch(splited[i]))
                    {
                        stack.Push(new KeyValuePair <string, string>("int", splited[i])); operacion += $" {splited[i]}";
                        operacion = operacion.Trim();;
                    }
                    else if (Boolean.IsMatch(splited[i]))
                    {
                        stack.Push(new KeyValuePair <string, string>("boolean", splited[i]));
                        operacion += $" {splited[i]}";
                        operacion  = operacion.Trim();;
                    }
                    else if (Identifier.IsMatch(splited[i]))
                    {
                        var Referencia = BuscarVariables(splited[i]);
                        if (Referencia == null)
                        {
                            Referencia = BuscarEnParametros(splited[i]);
                        }
                        switch (Referencia.tipo)
                        {
                        case "string":
                            stack.Push(new KeyValuePair <string, string>("string", Referencia.val == null ? "\"\"": Referencia.val));
                            break;

                        case "boolean":
                            stack.Push(new KeyValuePair <string, string>("boolean", Referencia.val == null ? "false" : Referencia.val));
                            break;

                        case "int":
                            stack.Push(new KeyValuePair <string, string>("int", Referencia.val == null ? "0" : Referencia.val));

                            break;

                        default:
                            break;
                        }
                        operacion += $" {Referencia.val}";
                        operacion  = operacion.Trim();
                    }
                    else
                    {
                        operacion += $" {splited[i]}";
                        operacion  = operacion.Trim();;
                    }
                }
            }
            var tipoGeneral = stack.Peek().Key;
            var resultado   = new KeyValuePair <string, string>();

            foreach (var item in stack)
            {
                if (item.Key != tipoGeneral)
                {
                    return(new KeyValuePair <string, string>(item.Key, item.Value));
                }
            }
            switch (tipoGeneral)
            {
            case "int":
                DataTable dt     = new DataTable();
                var       limiea = sentencia.Replace(";", "").Trim();
                //int answer = (int)dt.Compute(sentencia.Replace(";","").Replace(" ", "").Trim(), ""); ;
                var sdasd = Eval.Execute <int>(operacion);
                return(new KeyValuePair <string, string>("int", sdasd.ToString()));

                break;

            case "string":


                return(new KeyValuePair <string, string>("string", operacion));

                break;

            case "boolean":
                return(new KeyValuePair <string, string>("boolean", operacion));

                break;

            default:
                break;
            }

            return(resultado);
        }
Exemplo n.º 25
0
 private void calculateResult(object sender, MouseEventArgs e)
 {
     labelResult.Text = Eval.Execute <double>(labelResult.Text).ToString();
 }
Exemplo n.º 26
0
Arquivo: Redis.cs Projeto: vanehu/MM
        /// <summary>
        /// 修改——通过函数式方式修改
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="funStr">函数式</param>
        /// <returns>成功返回true,失败返回false</returns>
        public void SetEval(string key, string funStr)
        {
            var value = Get(key);

            _Redis.Set(key, Eval.Execute(string.Format(funStr, value)));
        }
Exemplo n.º 27
0
        public void LoadTemplate(string fileName)
        {
            Eval eval = new Eval();

            eval.ProcessSymbol   += ProcessSymbol;
            eval.ProcessFunction += ProcessFunction;
            PopulateSysVariables();
            string[] lines = System.IO.File.ReadAllLines(fileName);
            int      secId = 1;

            foreach (string line in lines)
            {
                if (string.IsNullOrWhiteSpace(line) && secId != 3)
                {
                    continue;
                }
                if (line == "Section Vars")
                {
                    secId = 1;
                    continue;
                }
                if (line == "Section Calculations")
                {
                    secId = 2;
                    continue;
                }
                if (line == "Section Template")
                {
                    secId = 3;
                    continue;
                }
                if (secId == 1)
                {
                    var items = line.Split('=');
                    if (ContoVars.ContainsKey(items[0]))
                    {
                        ContoVars[items[0]] = items[1];
                    }
                    else
                    {
                        ContoVars.Add(items[0], items[1]);
                    }
                }
                if (secId == 2)
                {
                    var    items = line.Split('=');
                    string rez   = items[1];
                    rez = ReplaceValues(rez);
                    rez = eval.Execute(rez).ToString();
                    if (ContoVars.ContainsKey(items[0]))
                    {
                        ContoVars[items[0]] = rez;
                    }
                    else
                    {
                        ContoVars.Add(items[0], rez);
                    }
                }
                if (secId == 3)
                {
                    SectionTemplate.AppendLine(ReplaceValues(line));
                }
            }
            ResultTemplate = SectionTemplate.ToString();
        }
Exemplo n.º 28
0
 public static string GetAns(string statement)
 {
     return(Eval.Execute <long>(statement).ToString());
 }