コード例 #1
0
 private object CalculateExpression(string s)
 {
     if (string.IsNullOrWhiteSpace(s))
     {
         return(s);
     }
     NCalc.Expression exp = new NCalc.Expression(s);
     exp.EvaluateParameter += Exp_EvaluateParameter;
     PopulateVariables(exp);
     if (exp.HasErrors())
     {
         return(s);
     }
     else
     {
         try
         {
             return(exp.Evaluate());
         }
         catch (Exception ex)
         {
             /*if (_loggedExceptions.Where(x=>x.HResult == ex.HResult && x.Message == ex.Message).Count() == 0)
              * {
              *  _logger.Error(ex, "Calculating expression failde");
              *  _loggedExceptions.Enqueue(ex);
              *  if (_loggedExceptions.Count > 10)
              *      _loggedExceptions.Dequeue();
              * }*/
             return(s);
         }
     }
 }
コード例 #2
0
        /// <summary>
        /// Gets the function result.
        /// </summary>
        /// <returns>The function result.</returns>
        /// <param name="function">The function.</param>
        /// <param name="input">The arguments values and expected results of the function.</param>
        public double GetFunctionResult(string function, InstinctualLearningInput input)
        {
            //var func = Parser<DoubleEvaluator>.Parse(function);

            //var ctx = new VariableContext<DoubleEvaluator>();
            //var vars = "ABCDEFGH";
            //for(int i = 0;i<input.Arguments.Count;i++)
            //{
            //    ctx.AddVariable(vars.Substring(i, 1), input.Arguments[i]);
            //}

            //var result = func.Eval(ctx);
            var expression = new NCalc.Expression(function);

            for (int i = 0; i < m_parameterNames.Length; i++)
            {
                expression.Parameters.Add(m_parameterNames[i], input.Arguments[i]);
            }

            var result = expression.Evaluate();

            return((double)result);

            //return result.Result;
            // return 0.0;
        }
コード例 #3
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            await Task.Yield();

            if (string.IsNullOrWhiteSpace(input))
            {
                return(TypeReaderResult.FromError(CommandError.ParseFailed, "Input is empty."));
            }

            var i = input.Trim().ToUpperInvariant();

            i = i.Replace("K", "000");

            //can't add m because it will conflict with max atm

            if (TryHandlePercentage(services, context, i, out var num))
            {
                return(TypeReaderResult.FromSuccess(new ShmartNumber(num, i)));
            }
            try
            {
                var expr = new NCalc.Expression(i, NCalc.EvaluateOptions.IgnoreCase);
                expr.EvaluateParameter += (str, ev) => EvaluateParam(str, ev, context, services);
                var lon = (long)(decimal.Parse(expr.Evaluate().ToString()));
                return(TypeReaderResult.FromSuccess(new ShmartNumber(lon, input)));
            }
            catch (Exception)
            {
                return(TypeReaderResult.FromError(CommandError.ParseFailed, $"Invalid input: {input}"));
            }
        }
コード例 #4
0
ファイル: vMixControlButton.cs プロジェクト: kirahan/vMixUTC
 private object CalculateExpression(string s)
 {
     if (string.IsNullOrWhiteSpace(s))
     {
         return(s);
     }
     NCalc.Expression exp = new NCalc.Expression(s);
     PopulateVariables(exp);
     if (exp.HasErrors())
     {
         return(s);
     }
     else
     {
         try
         {
             return(exp.Evaluate());
         }
         catch (Exception ex)
         {
             _logger.Error(ex, "Calculating expression failde");
             return(s);
         }
     }
 }
コード例 #5
0
ファイル: ExlInterpreter.cs プロジェクト: jeff1992/NetExcel
        object ExecExpression(string expression, Dictionary <string, object> data)
        {
            Dictionary <string, object> paramenters = new Dictionary <string, object>();
            var key    = 'a';
            var newExp = regParam.Replace(expression, (Match x) =>
            {
                paramenters.Add(key.ToString(), GetValue(x.Value, data));
                return(key++.ToString());
            });
            var e = new NCalc.Expression(newExp);

            e.Parameters = paramenters;
            return(e.Evaluate());

            //			var list = expression.Split('+', '-', '*', '/', '%');
            //			if (list.Length > 1)
            //			{
            //
            //				return null;
            //			}
            //			else
            //			{

            return(GetValue(expression, data));
            //			}
        }
コード例 #6
0
        public void Evaluate(string expression)
        {
            if (expression != null && expression.Length >= 0)
            {
                NCalc.Expression exp  = new NCalc.Expression(expression);
                object           eval = null;
                try
                {
                    eval = exp.Evaluate();
                }
                catch (ArgumentException)
                {
                    this.AddList("Error in the expression.");
                    return;
                }
                catch (EvaluateException e)
                {
                    this.AddList("Error while evaluating expression, Error Message" + e.Message);
                    return;
                }

                if (exp.HasErrors())
                {
                    this.AddList("Error while evaluating expression, Error Message" + exp.Error);
                }
                else
                {
                    this.AddList(expression, eval);
                }
            }
        }
コード例 #7
0
        private void Calculation(string fullFormula)
        {
            NCalc.Expression e = new NCalc.Expression(fullFormula);
            var x = e.Evaluate();

            OutputWindow.Text = x.ToString();
        }
コード例 #8
0
ファイル: MainWindow.xaml.cs プロジェクト: galbarm/MilulaCalc
        private void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            RemoveRedundantChars();

            try
            {
                var expression = new Expression(_ExpressionBox.Text);
                object resultObj = expression.Evaluate();
                double result = Convert.ToDouble(resultObj);

                String str;

                if (result > 0 & result < 1)
                {
                    str = result.ToString();
                    str += " (" + ((decimal)result).ToString("P") + ")";
                }
                else
                {
                    result = Math.Round(result, 2, MidpointRounding.AwayFromZero);
                    str = result.ToString();
                }

                _ResultBox.Text = str;
            }
            catch (Exception)
            {
            }
        }
コード例 #9
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            await Task.Yield();

            if (string.IsNullOrWhiteSpace(input))
            {
                return(TypeReaderResult.FromError(CommandError.ParseFailed, "Input is empty."));
            }

            var i = input.Trim().ToLowerInvariant();

            if (TryHandlePercentage(services, context, context.User.Id, i, out var num))
            {
                return(TypeReaderResult.FromSuccess(new ShmartNumber(num, i)));
            }
            try
            {
                var expr = new NCalc.Expression(i, NCalc.EvaluateOptions.IgnoreCase);
                expr.EvaluateParameter += (str, ev) => EvaluateParam(str, ev, context, services);
                var lon = (long)(decimal.Parse(expr.Evaluate().ToString()));
                return(TypeReaderResult.FromSuccess(new ShmartNumber(lon, input)));
            }
            catch (Exception ex)
            {
                _log.Info(ex);
                return(TypeReaderResult.FromError(CommandError.ParseFailed, "Invalid input"));
            }
        }
コード例 #10
0
        private bool EvaluateExpression(String expression, out decimal result)
        {
            if (expression.Length <= 0)
            {
                result = 0;
                return(false);
            }
            bool success = true;

            NCalc.Expression.CacheEnabled = false;
            NCalc.Expression ex = new NCalc.Expression(expression);
            if (ex.HasErrors())
            {
                success = false;
                result  = 0;
                return(success);
            }
            try
            {
                result = Decimal.Parse(ex.Evaluate().ToString());
                //result = Decimal.Parse(ex.Evaluate());
            }
            catch (Exception e)
            {
                result  = 0;
                success = false;
            }
            return(success);
        }
コード例 #11
0
        protected object EvaluateExpression(IColumnExpression expression, DataRow row)
        {
            if (expression.Language == LanguageType.NCalc)
            {
                var exp     = new NCalc.Expression(expression.Value);
                var factory = new ColumnIdentifierFactory();

                exp.EvaluateParameter += delegate(string name, NCalc.ParameterArgs args)
                {
                    args.Result = GetValueFromRow(row, factory.Instantiate(name));
                };

                return(exp.Evaluate());
            }
            else if (expression.Language == LanguageType.Native)
            {
                var parse    = expression.Value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                var variable = new ColumnIdentifierFactory().Instantiate(parse.ElementAt(0));
                var value    = GetValueFromRow(row, variable);

                foreach (var nativeFunction in parse.Skip(1))
                {
                    var factory     = new NativeTransformationFactory();
                    var transformer = factory.Instantiate(nativeFunction);
                    value = transformer.Evaluate(value);
                }

                return(value);
            }
            else
            {
                throw new ArgumentOutOfRangeException($"The language {expression.Language} is not supported during the evaluation of an expression.");
            }
        }
コード例 #12
0
ファイル: Form1.cs プロジェクト: shady2k/genetic-programming
        private void drawSolutionFunctionChart(Chart chart, Population population)
        {
            try
            {
                chart.Series.Clear();

                Series mySeriesOfPoint = new Series("Series1");
                mySeriesOfPoint.BorderWidth = 2;
                mySeriesOfPoint.ChartType   = SeriesChartType.Line;
                mySeriesOfPoint.ChartArea   = "ChartArea1";
                for (double x = population.minValue; x <= population.maxValue; x += 0.01)
                {
                    NExpression solutionFunction = population.solutionFunction;
                    solutionFunction.Parameters["x"] = x;
                    double sfr = Convert.ToDouble(solutionFunction.Evaluate());
                    mySeriesOfPoint.Points.AddXY(x, sfr);
                }
                //Добавляем созданный набор точек в Chart
                chart.Series.Add(mySeriesOfPoint);
                chart.ChartAreas[0].RecalculateAxesScale();
            }
            catch
            {
                chart.Series.Clear();
                return;
            }
        }
コード例 #13
0
        public void DictionaryApproach(Dictionary <string, object> dict, string formula)
        {
            var expression = new NCalc.Expression(formula);

            expression.Parameters = dict;
            expression.Evaluate();
        }
コード例 #14
0
        public string Compute(SessionVariables variables, LogLine logLine)
        {
            if (_exp == null)
            {
                _exp = new NCalc.Expression(this.Expression);
                _exp.EvaluateParameter += delegate(string name, NCalc.ParameterArgs args)
                {
                    Variable var = curLL.GetVariableByName(name);
                    if (var != null)
                    {
                        args.Result = var.Value;
                    }
                    else
                    {
                        args.HasResult = false;
                    }
                };
            }
            object obj = "ERR";

            if (!Error)
            {
                curLL = logLine;
                _exp.Parameters.Clear();
                try
                {
                    obj = _exp.Evaluate().ToString();
                }
                catch
                {
                    Error = true;
                }
            }
            return(obj.ToString());
        }
コード例 #15
0
        private void DecodeRuleDetails(CustomList <SalaryRule> ruleDetails)
        {
            try
            {
                foreach (SalaryRule item in ruleDetails)
                {
                    var pattern = new Regex(@"(\@.*?\@)", RegexOptions.IgnorePatternWhitespace);

                    foreach (Match m in pattern.Matches(item.Formula2.ToUpper()))
                    {
                        string[]   parts = m.Groups[1].Value.Split('@');
                        SalaryRule obj   = ruleDetails.Find(f => f.HeadName.ToUpper().Trim() == parts[1].ToUpper().Trim());
                        item.Formula2 = item.Formula2.ToUpper().Replace(m.Groups[1].Value, obj.Formula2);
                    }
                    NCalc.Expression exp = new NCalc.Expression(item.Formula2);
                    object           ret = exp.Evaluate();
                    item.Formula2 = ret.ToString();

                    decimal            val = 0M;
                    EmployeeSalaryTemp eST = new EmployeeSalaryTemp();
                    eST.SalaryRuleCode = item.SalaryRuleCode;
                    eST.SalaryHeadKey  = item.SalaryHeadKey;
                    eST.IsFixed        = item.IsFixed;
                    if (decimal.TryParse(item.Formula2, out val))
                    {
                        eST.Amount = Math.Round(val, 2);
                    }
                    _EmpSalaryTempList.Add(eST);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #16
0
        //-----------------------------------------------------------------------
        public static float Evaluate(this string expression)
        {
            var exp = new NCalc.Expression(expression);
            var obj = exp.Evaluate();

            float value;

            if (obj is double)
            {
                value = (float)(double)obj;
            }
            else if (obj is int)
            {
                value = (float)(int)obj;
            }
            else if (obj is bool)
            {
                value = (bool)obj ? 1 : 0;
            }
            else
            {
                value = (float)obj;
            }

            return(value);
        }
コード例 #17
0
ファイル: LogicalExpression.cs プロジェクト: jawn/WaterLogged
        /// <inheritdoc />
        public string Eval(Evaluator evaluator)
        {
            var expression = new NCalc.Expression(NestedExpression.Eval(evaluator));

            if (expression.HasErrors())
            {
                return("[ERROR]");
            }
            expression.EvaluateParameter += (name, args) =>
            {
                Delegate func = null;
                try
                {
                    func = evaluator.Context.GetDelegate(name);
                }
                catch
                {
                    throw new InvalidOperationException("Invalid logical operation.");
                }

                if (func.GetMethodInfo().GetParameters().Length == 0)
                {
                    args.HasResult = true;
                    args.Result    = func.DynamicInvoke();
                }
                else
                {
                    throw new InvalidOperationException("Invalid logical operation.");
                }
            };
            return(expression.Evaluate().ToString());
        }
コード例 #18
0
 public static IEnumerable <object> Project(ValueDescriptor descriptor, CultureInfo culture, IEnumerable <object> values, NCalc.Expression expression)
 {
     return(values.Select(x =>
     {
         expression.Parameters[ExpressionEvaluator.IdentifierValue] = x;
         return expression.Evaluate();
     }));
 }
コード例 #19
0
 private void ResultBtn_Click(object sender, RoutedEventArgs e)
 {
     if (nonOperation && !string.IsNullOrEmpty(ResultTb.Text))
     {
         NCalc.Expression exp = new NCalc.Expression(ResultTb.Text);
         ResultTb.Text = exp.Evaluate().ToString();
     }
 }
コード例 #20
0
 private void ResultBtn_Click(object sender, RoutedEventArgs e)
 {
     if (nonOperation && !string.IsNullOrEmpty(ResultTb.Text))
     {
         NCalc.Expression exp = new NCalc.Expression(ResultTb.Text);
         ResultTb.Text = exp.Evaluate().ToString();
     }
 }
コード例 #21
0
        public int NCalcMethod(Dictionary <string, object> input, string inputString)
        {
            var e = new NCalc.Expression(inputString);

            e.Parameters = input;
            var result2 = e.Evaluate();

            return(Convert.ToInt16(result2));
        }
コード例 #22
0
 public void ReplaceApproachNoLambda(Dictionary <string, object> dict, string formula)
 {
     foreach (var item in dict)
     {
         formula = formula.Replace("[" + item.Key + "]", item.Value.ToString());
     }
     var expression = new NCalc.Expression(formula);
     var output     = expression.Evaluate();
 }
コード例 #23
0
ファイル: Program.cs プロジェクト: philhutch/NCalcDemo
        static void Main(string[] args)
        {
            int m = 1000000;  // <------------ Number of calculations done. Change for different results

            Stopwatch stopWatch = new Stopwatch();
            var ran = new Random();
            string se = "if(A>=17 && A<= 360, Pow(10,(1.016 * Log10( A ) - 1.71)), if(A<=17, 0.11, 7.7))";
            //se = "if(A>=17, Min(Pow(10,(1.016 * Log10( A ) - 1.71)), 7.7), 0.11)"; // Alternate arrangement
            NCalc.Expression e = new NCalc.Expression(se);
            Console.WriteLine("Using equation for Cadmium (accute): " + se);
            Console.WriteLine("# of loops: " + m);
            if (e.HasErrors())
            {
                Console.WriteLine("Errors detected!");
                Console.ReadLine();
                return;
            }
            double total = 0;

            stopWatch.Start();
            for (int i = 0; i < m; i++)
            {

                e.Parameters["A"] = ran.Next(500);
                var x = e.Evaluate();
                total += (double)x;
                //Console.WriteLine("A="+ e.Parameters["A"] + "; E = " + x);     // Uncomment to see results from equation NOTE: lower the number of loops
            }
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            Console.WriteLine("DONE!");
            Console.WriteLine("Average output: " + total / m);
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
            Console.WriteLine("RunTime " + elapsedTime);
            Console.WriteLine("Now executing same equation, iterating parameters inline...");

            int[] r = new int[m];
            for (int i = 0; i < m; i++)
            {
                r[i] = ran.Next(500);
            }
            stopWatch.Restart();
            e = new NCalc.Expression(se, NCalc.EvaluateOptions.IterateParameters);
            e.Parameters["A"] = r;
            var y = (IList)e.Evaluate();
            stopWatch.Stop();
            total = 0;
            foreach (double i in y) { total += i; }
            ts = stopWatch.Elapsed;
            Console.WriteLine("DONE!");
            Console.WriteLine("Average output: " + total / m);
            elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
            Console.WriteLine("RunTime " + elapsedTime);

            Console.ReadLine();
        }
コード例 #24
0
        public int ParameterAccess1(string formula)
        {
            var expression = new NCalc.Expression(formula);

            expression.Parameters["Variable1"] = 4;
            expression.Parameters["Variable2"] = 9;
            var output = expression.Evaluate();

            return(Convert.ToInt16(output));
        }
コード例 #25
0
 public async Task Calculate([Remainder] string expression)
 {
     var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase);
     expr.EvaluateParameter += Expr_EvaluateParameter;
     var result = expr.Evaluate();
     if (expr.Error == null)
         await Context.Channel.SendConfirmAsync("⚙ " + GetText("result"), result.ToString());
     else
         await Context.Channel.SendErrorAsync("⚙ " + GetText("error"), expr.Error);
 }
コード例 #26
0
 public override HandlerItem[] GetResultsFor(string search)
 {
     List<HandlerItem> ret = new List<HandlerItem>();
     try
     {
         NCalc.Expression exp = new NCalc.Expression(search);
         ret.Add(new HandlerItem(exp.Evaluate() + " = " + exp.ParsedExpression.ToString(),this));
     }
     catch { }
     return ret.ToArray();
 }
コード例 #27
0
ファイル: PredicateFilter.cs プロジェクト: 0guptaShruti0/NBi
        private object EvaluateExpression(IColumnExpression expression, DataRow row)
        {
            var exp = new NCalc.Expression(expression.Value);

            exp.EvaluateParameter += delegate(string name, NCalc.ParameterArgs args)
            {
                args.Result = GetValueFromRow(row, name);
            };

            return(exp.Evaluate());
        }
コード例 #28
0
        public override HandlerItem[] GetResultsFor(string search)
        {
            List <HandlerItem> ret = new List <HandlerItem>();

            try
            {
                NCalc.Expression exp = new NCalc.Expression(search);
                ret.Add(new HandlerItem(exp.Evaluate() + " = " + exp.ParsedExpression.ToString(), this));
            }
            catch { }
            return(ret.ToArray());
        }
コード例 #29
0
ファイル: DataRowScorer.cs プロジェクト: ywscr/NBi
        protected object EvaluateExpression(IColumnExpression expression, DataRow row)
        {
            var exp     = new NCalc.Expression(expression.Value);
            var factory = new ColumnIdentifierFactory();

            exp.EvaluateParameter += delegate(string name, NCalc.ParameterArgs args)
            {
                args.Result = GetValueFromRow(row, factory.Instantiate(name));
            };

            return(exp.Evaluate());
        }
コード例 #30
0
        public Object Evaluate(Dictionary <string, Object> variables)
        {
            if (!isParsed)
            {
                throw new InvalidOperationException("Before calling the Evaluate function, you must call the Parse function.");
            }

            var exp = new NCalc.Expression(Expression);

            exp.Parameters = variables;
            return(exp.Evaluate());
        }
コード例 #31
0
        public double getValue(string func, double x)
        {
            string funcCopy = func;
            string result;

            funcCopy = funcCopy.Replace("x", x.ToString());
            funcCopy = funcCopy.Replace("X", x.ToString());
            NCalc.Expression e = new NCalc.Expression(funcCopy);
            result = e.Evaluate().ToString();
            return(Double.Parse(result));
            //return 20.0;
        }
コード例 #32
0
        /// <summary>
        /// Gets the function result.
        /// </summary>
        /// <returns>The function result.</returns>
        /// <param name="function">The function.</param>
        /// <param name="input">The arguments values and expected results of the function.</param>
        public double GetFunctionResult(string function, FunctionBuilderInput input)
        {
            var expression = new NCalc.Expression(function);

            for (int i = 0; i < m_parameterNames.Length; i++)
            {
                expression.Parameters.Add(m_parameterNames[i], input.Arguments[i]);
            }

            var result = expression.Evaluate();

            return((double)result);
        }
コード例 #33
0
 private static string ProcessStandardCalCommand(string message)
 {
     try
     {
         var expression = new NCalc.Expression(message, NCalc.EvaluateOptions.IgnoreCase);
         if (!expression.HasErrors())
         {
             return(Convert.ToString(expression.Evaluate()));
         }
     }
     catch (Exception) { }
     return(null);
 }
コード例 #34
0
        private double mu(double t)
        {
            exprMU = new NCalc.Expression(muText.Text);
            exprMU.Parameters["pi"] = Math.PI;
            exprMU.Parameters["e"]  = Math.E;
            exprMU.Parameters["a"]  = Convert.ToDouble(aText.Text);
            exprMU.Parameters["b"]  = Convert.ToDouble(bText.Text);
            exprMU.Parameters["t"]  = t;

            double r = Convert.ToDouble(exprMU.Evaluate());

            return(r);
        }
コード例 #35
0
ファイル: CalcCommand.cs プロジェクト: Chewsterchew/NadekoBot
 public static async Task Calculate(IUserMessage msg, [Remainder] string expression)
 {
     try
     {
         var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase);
         expr.EvaluateParameter += Expr_EvaluateParameter;
         var result = expr.Evaluate();
         await msg.Reply(string.Format("⚙ `{0}`", expr.Error ?? result));
     }
     catch (Exception e)
     {
         await msg.Reply($"Failed to evaluate: {e.Message} ");
     }
 }
コード例 #36
0
ファイル: MainWindow.xaml.cs プロジェクト: PabloSzPz/sGA
        private void Evaluate_Function_Button_Click(object sender, RoutedEventArgs e)
        {
            try {
                LogTextBox.Document.Blocks.Clear();
                NCalc.Expression exp = new NCalc.Expression(FormulaTextBox.Text);
                if(!string.IsNullOrWhiteSpace(XValueTextBox.Text)) {
                    Double xValue = 1.0;
                    Double.TryParse(XValueTextBox.Text, out xValue);
                    exp.Parameters["x"] = xValue;
                }

                String result = exp.Evaluate().ToString();
                LogTextBox.AppendText(result);
            } catch(Exception ex) {
                System.Windows.MessageBox.Show(ex.ToString());
            }

            scrollEl.ScrollToBottom();
        }
コード例 #37
0
ファイル: Calc.cs プロジェクト: jstadnicki/NML
        public ISearchResult Search(string phrase)
        {
            phrase = Utils.PhraseWithoutPrefix(phrase, Prefix);

            var result = new TextSearchResult("Calculator");

            if (!string.IsNullOrWhiteSpace(phrase))
            {
                var ex = new NCalc.Expression(phrase);
                try
                {
                    // TODO: allow sin, now only Sin works
                    result.Text = string.Format("{0} = {1}", phrase, ex.Evaluate());
                }
                catch
                {
                    result.Text = null;
                }
            }

            result.SearchIcon = SearchIcon;// GetSearchIcon();
            return result;
        }
コード例 #38
0
ファイル: Combat.cs プロジェクト: jandar78/Novus
 private static double GetAndEvaluateExpression(string calculationName, IActor player) {
     var col = MongoUtils.MongoData.GetCollection<BsonDocument>("Calculations", "Combat");
     var doc = MongoUtils.MongoData.RetrieveObjectAsync<BsonDocument>(col, c => c["_id"] == calculationName).Result;
     NCalc.Expression expression = new NCalc.Expression(ReplaceStringWithNumber(player, doc["Expression"].AsString));
     double expressionResult = (double)expression.Evaluate();
     //let's take into consideration some other factors.  Visibility, stance, etc.
     //TODO: add that here.  They only take away from chance to hit. But some of them can be negated.
     //if it's dark but player can see in the dark for example.
     return expressionResult;
 }
コード例 #39
0
        private void RunRules(String controlId, ControlCatalog catalog, IEnumerable<ControlRule> rules, DateTime now, Object[] answers)
        {
            var results = new List<RuleEvaluated>();
            var validRules = rules.Where(r => r.ControlId == controlId);
            var parameters = ControlAnswers.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Values.First());
            foreach (var rule in validRules)
            {
                var calc = new NCalc.Expression(rule.Rule.If);
                
                foreach (var answer in answers)
                {
                    calc.Parameters.Clear();
                    calc.Parameters = parameters;
                    calc.Parameters[controlId] = answer;

                    try
                    {
                        var result = (Boolean)calc.Evaluate();
                        String message = null;
                        if (result)
                        {
                            switch (rule.Rule.Then.GetType().Name)
                            {
                                case "NoActionOutcome":
                                    message = rule.Rule.Then.Message;
                                    break;
                                case "FailedValidationOutcome":
                                    var outcome = (FailedValidationOutcome)rule.Rule.Then;

                                    message = $"{outcome.ValidatorName} failed for {outcome.ControlId} with message {outcome.Message}";
                                    break;
                                default:
                                    message = rule.Rule.Then.Message;
                                    break;
                            }
                        }
                        else
                        {
                            switch (rule.Rule.Else.GetType().Name)
                            {
                                case "NoActionOutcome":
                                    message = rule.Rule.Else.Message;
                                    break;
                                case "FailedValidationOutcome":
                                    var outcome = (FailedValidationOutcome)rule.Rule.Else;

                                    message = $"{outcome.ValidatorName} failed for {outcome.ControlId} with message {outcome.Message}";
                                    break;
                                default:
                                    message = rule.Rule.Else.Message;
                                    break;
                            }
                        }

                        ApplyChange(new RuleEvaluated
                        {
                            ControlId = controlId,
                            Date = now,
                            FormId = rule.FormId,
                            Id = Guid.NewGuid(),
                            ReportingEntityInstanceId = ReportingEntityId,
                            Result = message,
                            RuleName = rule.Rule.Name,
                            Values = answers,
                            Version = Version
                        });
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Error in expression: {e.Message}");
                    }
                }
            }
        }
コード例 #40
0
ファイル: Combat.cs プロジェクト: vadian/Novus
 private static double GetAndEvaluateExpression(string calculationName, Character.Iactor player)
 {
     MongoCollection col = MongoUtils.MongoData.GetCollection("Calculations", "Combat");
     IMongoQuery query = Query.EQ("_id", calculationName);
     BsonDocument doc = col.FindOneAs<BsonDocument>(query).AsBsonDocument;
     NCalc.Expression expression = new NCalc.Expression(ReplaceStringWithNumber(player, doc["Expression"].AsString));
     double expressionResult = (double)expression.Evaluate();
     //let's take into consideration some other factors.  Visibility, stance, etc.
     //TODO: add that here.  They only take away from chance to hit. But some of them can be negated.
     //if it's dark but player can see in the dark for example.
     return expressionResult;
 }
コード例 #41
0
ファイル: FitnessCalc.cs プロジェクト: PabloSzPz/sGA
        //Set the function to maximize/minimize
        public static bool setFunctionToOperate(string functionAsText)
        {
            bool canEvaluate = false;
            _exp = new NCalc.Expression(functionAsText);
            NCalc.Expression _expTest = new NCalc.Expression(functionAsText);
            _expTest.Parameters["x"] = 1;
            try {
                _expTest.Evaluate();
                canEvaluate = true;
            } catch {
                canEvaluate = false;
            }

            return !_exp.HasErrors() && !_expTest.HasErrors() && canEvaluate;
        }
コード例 #42
0
        private int GetArraySize(string sFieldName)
        {
            int iLength = 1;
            int iStart = 0;
            if (sFieldName.Contains('['))
            {
                while (sFieldName.IndexOf('[', iStart) > 0)
                {
                    string sDimension;
                    int iAStart = sFieldName.IndexOf('[', iStart);
                    int iAEnd = sFieldName.IndexOf(']', iStart + 1);
                    sDimension = sFieldName.Substring(iAStart + 1, iAEnd - iAStart - 1);

                    sDimension=ReplaceDefines(sDimension);

                    NCalc.Expression a = new NCalc.Expression(sDimension.Replace("eHashNumber", "32"));// TODO: make better
                    int t = Convert.ToInt32(a.Evaluate());

                    iLength = iLength * t;
                    iStart = iAEnd;
                }

                return iLength;
            }
            else
            {
                return 1;
            }
        }
コード例 #43
0
ファイル: UnitTest1.cs プロジェクト: ertanyavuz/GGyor
        //[TestMethod]
        public void TestMethod1()
        {
            var str = "(x*2)+5";

            var list = new Dictionary<int, int>();

            var sw = new Stopwatch();

            sw.Start();
            for (int i = 0; i < 2000; i++ )
            {
                var exp = new NCalc.Expression(str);
                exp.Parameters["x"] = i;
                var result =  exp.Evaluate();

                list.Add(i, (int)result);
                break;
            }
            sw.Stop();
            System.Diagnostics.Debug.WriteLine(sw.Elapsed.ToString());

            sw.Reset();
            list.Clear();
            sw.Start();
            for (int i = 0; i < 2000; i++)
            {
                var exp = new NCalc.Expression(str, NCalc.EvaluateOptions.NoCache);
                exp.Parameters["x"] = i;
                var result = exp.Evaluate();

                list.Add(i, (int)result);
            }
            sw.Stop();
            System.Diagnostics.Debug.WriteLine(sw.Elapsed.ToString());

            sw.Reset();
            list.Clear();
            sw.Start();
            var exp2 = new NCalc.Expression(str);
            for (int i = 0; i < 2000; i++)
            {

                exp2.Parameters["x"] = i;
                var result = exp2.Evaluate();

                list.Add(i, (int)result);
            }
            sw.Stop();
            System.Diagnostics.Debug.WriteLine(sw.Elapsed.ToString());

            sw.Reset();
            list.Clear();
            sw.Start();
            var exp1 = new NCalc.Expression(str, NCalc.EvaluateOptions.NoCache);
            for (int i = 0; i < 2000; i++)
            {

                exp1.Parameters["x"] = i;
                var result = exp1.Evaluate();

                list.Add(i, (int)result);
            }
            sw.Stop();
            System.Diagnostics.Debug.WriteLine(sw.Elapsed.ToString());

            //System.Diagnostics.Debug.WriteLine(exp.Evaluate().ToString());

            Assert.IsTrue(true);
        }
コード例 #44
0
        private void ReadStructures(string[] sFile)
        {
            bool bStartFound = false;
            bool bInHashIf = false;
            bool bInComment = false;
            bool bSkipUnionExtraLines = false;
            bool bFirstLineOfUnion = false;
            int iUnionRef = 0;
            int iOpenStructureCount = 0;
            stTableStructure stCurrentTable = new stTableStructure();
            string sTestBuffer = "";

            bStartFound = false;

            for (int i = 0; i < sFile.Count(); i++)
            {
                string sLine = sFile[i].Replace('\t', ' ');

                string sStructureName;
                if (sLine.Contains("/*"))
                {
                    bInComment = true;
                }
                sTestBuffer += sLine + "\r\n";

                if (bInComment == false)
                {
                    if (sLine.Trim().ToUpper().StartsWith("union".ToUpper()))
                    {
                        // oh no
                        bSkipUnionExtraLines = true;
                        iUnionRef = iOpenStructureCount;
                        bFirstLineOfUnion = true;
                    }

                    if (sLine.ToUpper().Contains("typedef struct".ToUpper()) || sLine.StartsWith ("struct")==true )
                    {
                        bStartFound = true;
                        bInHashIf = false;
                        stCurrentTable = new stTableStructure();
                        stCurrentTable.sFields = new List<string>();
                        stCurrentTable.sFieldsType = new List<string>();
                        stCurrentTable.sDescription = new List<string>();
                        stCurrentTable.bBitField = false;

                        if (sLine.Trim().EndsWith("{"))
                        {
                            iOpenStructureCount++;
                        }
                        if (sLine.StartsWith("struct") == true)
                        {
                            stCurrentTable.sStructureName = sLine.Replace("{", "").Trim();
                        }

                    }

                    if (bStartFound)
                    {
                        int iStartPos = sLine.IndexOf("sizeof(");
                        int iEndPos = 0;

                        if (sLine.Trim().StartsWith("{"))
                        {
                            iOpenStructureCount++;
                        }

                        if (sLine.Trim().StartsWith("}"))
                        {
                            iOpenStructureCount--;
                            if (iOpenStructureCount == iUnionRef)
                            {
                                bSkipUnionExtraLines = false;
                            }
                            else
                            {
                                bFirstLineOfUnion = false;
                            }

                            if (iOpenStructureCount == 0)
                            {

                                iEndPos = sLine.Trim().IndexOf(";");
                                sStructureName = sLine.Trim().Substring(1, iEndPos - 1).Trim();
                                if (sStructureName.Length > 0)
                                {
                                    stCurrentTable.sStructureName = sStructureName;
                                }
                                m_TableStructures.Add(stCurrentTable);

                                bStartFound = false;
                                sTestBuffer = "";
                            }
                        }
                        else
                        {
                            if (sLine.ToUpper().Contains("#if".ToUpper()))
                            {
                                string[] sTokens = sLine.Replace("\r", "").Split(' ');
                                sTokens[1] = ReplaceDefines(sTokens[1]);
                                sTokens[1] = ReplaceDefines(sTokens[1]);
                                NCalc.Expression a = new NCalc.Expression(sTokens[1]);// TODO: make better
                                int t;
                                try
                                {
                                    t = Convert.ToInt32(a.Evaluate());
                                }
                                catch (Exception ex)
                                {
                                    t = 1;
                                }
                                if (t == 0)
                                {

                                    bInHashIf = true;
                                }
                            }

                            // just ignore #else variable for now
                            if (sLine.ToUpper().Contains("#else".ToUpper()) || sLine.ToUpper().Contains("#elif".ToUpper())) //#elif
                            {
                                bInHashIf = true;
                            }

                            if (sLine.ToUpper().Contains("#endif".ToUpper()))
                            {
                                bInHashIf = false;
                            }

                            if (sLine.Contains(";") && bInHashIf == false && sLine.Trim().Contains(" ") && sLine.Trim().StartsWith("//") == false && (bSkipUnionExtraLines == false
                            || (bSkipUnionExtraLines == true && bFirstLineOfUnion == true)))
                            {
                                if (iOpenStructureCount == iUnionRef+1)
                                {
                                    bFirstLineOfUnion = false;
                                }

                                //   unsigned char  hour;
                                int iSemiColonPos = sLine.IndexOf(';');
                                int iSpacePos = sLine.LastIndexOf(' ', iSemiColonPos);
                                int iCommandPos = sLine.LastIndexOf("//");
                                if (iCommandPos > 0)
                                {
                                    stCurrentTable.sDescription.Add(sLine.Substring(iCommandPos + 2).Replace("\r", ""));
                                }
                                else
                                {
                                    stCurrentTable.sDescription.Add("");
                                }

                                string sFieldType = GetVaribleType(sLine);
                                if (sLine.Substring(iSpacePos - 1, iSemiColonPos - iSpacePos).Trim().Contains(":"))
                                {
                                    // contains bit field :(
                                    stCurrentTable.bBitField = true;
                                    stCurrentTable.sFields.Add(sLine);
                                    stCurrentTable.sFieldsType.Add(sLine);
                                }
                                else
                                {
                                    stCurrentTable.sFields.Add(sLine.Substring(iSpacePos, iSemiColonPos - iSpacePos).Trim());
                                    stCurrentTable.sFieldsType.Add(sLine.Substring(0, iSpacePos).Trim());
                                }
                            }
                        }
                    }
                }

                if (sLine.Contains("*/"))
                {
                    bInComment = false;
                }

            }
        }
        private bool? evaluateExpressionString()
        {
            string newExpressionString = VariableEngine.substituteVariablesInString(_expressionString);
            NCalc.Expression ex = new NCalc.Expression(newExpressionString);
            _latestExpressionSubstitutionString = newExpressionString;
            Debug.Log(newExpressionString);
            bool result = false;
            try
            {
                result = (bool)ex.Evaluate();
            }
            catch (Exception) { return null; }

            return result;
        }
コード例 #46
0
        /// <summary>
        /// Gets the function result.
        /// </summary>
        /// <returns>The function result.</returns>
        /// <param name="function">The function.</param>
        /// <param name="input">The arguments values and expected results of the function.</param>
        public double GetFunctionResult(string function, FunctionBuilderInput input)
        {
            var expression = new NCalc.Expression(function);

            for (int i = 0; i < m_parameterNames.Length; i++)
            {
                expression.Parameters.Add(m_parameterNames[i], input.Arguments[i]);
            }

            var result = expression.Evaluate();

            return (double)result;
        }
コード例 #47
0
        public override bool Play(MappedItem control, Log log)
        {
            AppProcess process = AppManager.GetProcess(control);
            MappedItem window = AppManager.GetWindow(control);

            IUIItem uiItem = AppPlaybackService.GetControl(process, window, control, AppManager);
            Point clickPoint = new Point(X,Y);
            Point globalPoint = new Point((int)uiItem.Bounds.X + clickPoint.X, (int)uiItem.Bounds.Y + clickPoint.Y);

            Screenshot screenshot = CreateScreenshot(log);

            Cursor.LeftClick(globalPoint);
            string actualText = CopyText();
            string expectedText = textParam.GetValue();

            if (actualText == null)
                actualText = "";

            if (expectedText == null)
                expectedText = "";

            string originalExpectedText = expectedText;

            foreach (Variable v in this.TestItem.Test.Variables.OrderBy(v => v.Name.Length))
            {
                expectedText = expectedText.Replace(v.Name, v.Value.ToString());
            }

            Expression e = new Expression(expectedText);

            try
            {
                expectedText = e.Evaluate().ToString();
            }
            catch (Exception ex)
            {
                //e.Evaluate() errored out.  Probably not an expression

                expectedText = originalExpectedText;
            }

            if(!Equals(actualText, expectedText))
            {
                string error = "Expected \"{0}\" but value was \"{1}\"";
                error = string.Format(error, expectedText, actualText);

                log.CreateLogItem(LogItemCategory.Error, error, screenshot);
                return false;
            }

            string description = "Validated that the text at ({0},{1}) on {2} is equal to \"{3}\"";
            description = string.Format(description, X, Y, control.Name, Text);

            log.CreateLogItem(LogItemCategory.Validation, description, screenshot);

            return true;
        }
コード例 #48
-1
        public Object Evaluate(Dictionary<string, Object> variables)
        {
            if (!isParsed)
                throw new InvalidOperationException("Before calling the Evaluate function, you must call the Parse function.");

            var exp = new NCalc.Expression(Expression);
            exp.Parameters = variables;
            return exp.Evaluate();
        }