Beispiel #1
0
        protected override async Task PerformInternal(UserViewModel user, IEnumerable <string> arguments)
        {
            string replacementText = await this.ReplaceStringWithSpecialModifiers(this.SpecialIdentifierReplacement, user, arguments);

            if (this.SpecialIdentifierShouldProcessMath)
            {
                try
                {
                    // Process Math
                    CalculationEngine engine = new CalculationEngine();
                    engine.AddFunction("random", Random);
                    engine.AddFunction("randomrange", RandomRange);

                    double result = engine.Calculate(replacementText);
                    replacementText = result.ToString();
                }
                catch (Exception ex)
                {
                    // Calculation failed, log and set to 0
                    Logger.Log(ex, false, false);
                    replacementText = "0";
                }
            }

            if (this.MakeGloballyUsable)
            {
                SpecialIdentifierStringBuilder.AddCustomSpecialIdentifier(this.SpecialIdentifierName, replacementText);
            }
            else
            {
                this.extraSpecialIdentifiers[this.SpecialIdentifierName] = replacementText;
            }
        }
Beispiel #2
0
        public static double ProcessMathEquation(string equation)
        {
            double result = 0;

            try
            {
                equation = equation.Replace("random(", "customrandom(");

                // Process Math
                CalculationEngine engine = new CalculationEngine(new System.Globalization.CultureInfo("en-US"));
                engine.AddFunction("customrandom", Random);
                engine.AddFunction("randomrange", RandomRange);

                // If they used +1, then trim it off
                equation = equation.TrimStart(' ', '+');

                result = engine.Calculate(equation);
            }
            catch (Exception ex)
            {
                // Calculation failed, log and set to 0
                Logger.Log(ex);
            }
            return(result);
        }
        protected override async Task PerformInternal(UserViewModel user, IEnumerable <string> arguments)
        {
            string replacementText = await this.ReplaceStringWithSpecialModifiers(this.SpecialIdentifierReplacement, user, arguments);

            if (this.SpecialIdentifierShouldProcessMath)
            {
                try
                {
                    replacementText = replacementText.Replace("random(", "customrandom(");

                    // Process Math
                    CalculationEngine engine = new CalculationEngine(new System.Globalization.CultureInfo("en-US"));
                    engine.AddFunction("customrandom", Random);
                    engine.AddFunction("randomrange", RandomRange);

                    double result = engine.Calculate(replacementText);
                    replacementText = result.ToString();
                }
                catch (Exception ex)
                {
                    // Calculation failed, log and set to 0
                    Logger.Log(ex);
                    replacementText = "0";
                }
            }
            else
            {
                replacementText = await this.ProcessStringFunction(replacementText, "removespaces", (text) => { return(Task.FromResult(text.Replace(" ", string.Empty))); });

                replacementText = await this.ProcessStringFunction(replacementText, "removecommas", (text) => { return(Task.FromResult(text.Replace(",", string.Empty))); });

                replacementText = await this.ProcessStringFunction(replacementText, "tolower", (text) => { return(Task.FromResult(text.ToLower())); });

                replacementText = await this.ProcessStringFunction(replacementText, "toupper", (text) => { return(Task.FromResult(text.ToUpper())); });

                replacementText = await this.ProcessStringFunction(replacementText, "urlencode", (text) => { return(Task.FromResult(HttpUtility.UrlEncode(text))); });
            }

            if (this.MakeGloballyUsable)
            {
                SpecialIdentifierStringBuilder.AddCustomSpecialIdentifier(this.SpecialIdentifierName, replacementText);
            }
            else
            {
                this.extraSpecialIdentifiers[this.SpecialIdentifierName] = replacementText;
            }
        }
        public void TestCustomFunctionCompiled()
        {
            CalculationEngine engine = new CalculationEngine(CultureInfo.InvariantCulture, ExecutionMode.Compiled);

            engine.AddFunction("test", (a, b) => a + b);

            double result = engine.Calculate("test(2,3)");

            Assert.AreEqual(5.0, result);
        }
Beispiel #5
0
        public void TestCustomFunctionFunc11Compiled()
        {
            CalculationEngine engine = new CalculationEngine(CultureInfo.InvariantCulture,
                                                             ExecutionMode.Compiled, false, false);

            engine.AddFunction("test", (a, b, c, d, e, f, g, h, i, j, k) => a + b + c + d + e + f + g + h + i + j + k);
            double result   = engine.Calculate("test(1,2,3,4,5,6,7,8,9,10,11)");
            double expected = (11 * (11 + 1)) / 2.0;

            Assert.AreEqual(expected, result);
        }
        public void TestCustomFunctionCompiled()
        {
            CalculationEngine engine = new CalculationEngine();

            engine.AddFunction("test", (a, b) => a + b);

            Func <float> f = engine
                             .Formula("test(2, 3)")
                             .Build();

            float result = f();

            Assert.AreEqual(5.0f, result);
        }
Beispiel #7
0
        public void TestCalculationCompiledExpressionInterpreted()
        {
            CalculationEngine engine = new CalculationEngine(CultureInfo.InvariantCulture, ExecutionMode.Interpreted, true, true, false);

            Expression <Func <double, double, double> > expression = (a, b) => a + b;

            expression.Compile();

            engine.AddFunction("test", expression.Compile());

            double result = engine.Calculate("test(2, 3)");

            Assert.AreEqual(5.0, result);
        }
Beispiel #8
0
        public void TestCustomFunctionInterpreted()
        {
            CalculationEngine engine = new CalculationEngine(CultureInfo.InvariantCulture,
                                                             ExecutionMode.Interpreted, false, false);

            engine.AddFunction("test", (a, b) => a + b);

            double result = engine.Calculate("test(2,3)");

#if !NETCORE
            Assert.AreEqual(5.0, result);
#else
            Assert.Equal(5.0, result);
#endif
        }
        public void TestCustomFunctionFunc11Compiled()
        {
            CalculationEngine engine = new CalculationEngine();

            engine.AddFunction("test", (a, b, c, d, e, f, g, h, i, j, k) => a + b + c + d + e + f + g + h + i + j + k);

            Func <float> func = engine
                                .Formula("test(1,2,3,4,5,6,7,8,9,10,11)")
                                .Build();

            float result   = func();
            float expected = (11 * (11 + 1)) / 2.0f;

            Assert.AreEqual(expected, result);
        }
Beispiel #10
0
        public void TestCustomFunctionDynamicFuncNestedDynamicCompiled()
        {
            CalculationEngine engine = new CalculationEngine(CultureInfo.InvariantCulture,
                                                             ExecutionMode.Compiled, false, false);

            double DoSomething(params double[] a)
            {
                return(a.Sum());
            }

            engine.AddFunction("test", DoSomething);
            double result   = engine.Calculate("test(1,2,3,test(4,5,6)) + test(7,8,9,10,11)");
            double expected = (11 * (11 + 1)) / 2.0;

            Assert.AreEqual(expected, result);
        }
        public void TestCustomFunctionInterpreted()
        {
            CalculationEngine engine = new CalculationEngine(CultureInfo.InvariantCulture,
                ExecutionMode.Interpreted, false, false);
            engine.AddFunction("test", (a, b) => a + b);

            double result = engine.Calculate("test(2,3)");
            Assert.AreEqual(5.0, result);
        }
Beispiel #12
0
        public void Load()
        {
            // TODO Funcs: min, max, clamp, if_zero, if_positive, if_negative, floor, log, sqrt
            CalculationEngine = new CalculationEngine(CultureInfo.InvariantCulture, ExecutionMode.Compiled, true, true, false);
            CalculationEngine.AddFunction("clamp", (a, b, c) => a < b ? b : (a > c ? c : a));
            CalculationEngine.AddFunction("if_negative", (a, b, c) => a < 0 ? b : c);
            CalculationEngine.AddFunction("if_positive", (a, b, c) => a > 0 ? b : c);
            CalculationEngine.AddFunction("if_zero", (a, b, c) => a == 0 ? b : c);

            _unitFormulas = new Dictionary <FormulaOwnerType, Dictionary <UnitFormulaKind, UnitFormula> >();
            foreach (var owner in Enum.GetValues(typeof(FormulaOwnerType)))
            {
                _unitFormulas.Add((FormulaOwnerType)owner, new Dictionary <UnitFormulaKind, UnitFormula>());
            }
            _wearableFormulas = new Dictionary <WearableFormulaType, WearableFormula>();
            _unitVariables    =
                new Dictionary <uint, Dictionary <UnitFormulaVariableType, Dictionary <uint, UnitFormulaVariable> > >();
            _formulas = new Dictionary <uint, Formula>();

            using (var connection = SQLite.CreateConnection())
            {
                _log.Info("Loading formulas...");
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * from unit_formulas";
                    command.Prepare();
                    using (var sqliteReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteReader))
                        {
                            while (reader.Read())
                            {
                                var formula = new UnitFormula
                                {
                                    Id          = reader.GetUInt32("id"),
                                    TextFormula = reader.GetString("formula"),
                                    Kind        = (UnitFormulaKind)reader.GetByte("kind_id"),
                                    Owner       = (FormulaOwnerType)reader.GetByte("owner_type_id")
                                };
                                if (formula.Prepare())
                                {
                                    _unitFormulas[formula.Owner].Add(formula.Kind, formula);
                                }
                            }
                        }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * from unit_formula_variables";
                    command.Prepare();
                    using (var sqliteReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteReader))
                        {
                            while (reader.Read())
                            {
                                var variable = new UnitFormulaVariable
                                {
                                    FormulaId = reader.GetUInt32("unit_formula_id"),
                                    Type      = (UnitFormulaVariableType)reader.GetByte("variable_kind_id"),
                                    Key       = reader.GetUInt32("key"),
                                    Value     = reader.GetFloat("value")
                                };
                                if (!_unitVariables.ContainsKey(variable.FormulaId))
                                {
                                    _unitVariables.Add(variable.FormulaId,
                                                       new Dictionary <UnitFormulaVariableType, Dictionary <uint, UnitFormulaVariable> >());
                                }
                                if (!_unitVariables[variable.FormulaId].ContainsKey(variable.Type))
                                {
                                    _unitVariables[variable.FormulaId].Add(variable.Type,
                                                                           new Dictionary <uint, UnitFormulaVariable>());
                                }
                                _unitVariables[variable.FormulaId][variable.Type].Add(variable.Key, variable);
                            }
                        }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * from wearable_formulas";
                    command.Prepare();
                    using (var sqliteReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteReader))
                        {
                            while (reader.Read())
                            {
                                var formula = new WearableFormula
                                {
                                    Id          = reader.GetUInt32("id"),
                                    Type        = (WearableFormulaType)reader.GetByte("kind_id"),
                                    TextFormula = reader.GetString("formula")
                                };
                                if (formula.Prepare())
                                {
                                    _wearableFormulas.Add(formula.Type, formula);
                                }
                            }
                        }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * from formulas";
                    command.Prepare();
                    using (var sqliteReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteReader))
                        {
                            while (reader.Read())
                            {
                                var formula = new Formula
                                {
                                    Id          = reader.GetUInt32("id"),
                                    TextFormula = reader.GetString("formula")
                                };
                                if (formula.Prepare())
                                {
                                    _formulas.Add(formula.Id, formula);
                                }
                            }
                        }
                }

                _log.Info("Formulas loaded");
            }
        }
Beispiel #13
0
 private static void AddIIFFunction(CalculationEngine calculator)
 {
     calculator.AddFunction("iif", (a, b, c) => a != 0.0 ? b : c);
 }
Beispiel #14
0
        private static IneqTree BuildIneqTree(string vyraz)
        {
            int      i, pocet_zavorek = 0, pozice_operatoru = -1;
            bool     nasel_se_and = false;
            bool     nasel_se_or  = false;
            bool     nasla_se_ner = false;
            char     z; // zkoumany znak retezce
            IneqTree vysledek = null, node_levy = null, node_pravy = null;

            error = error || (vyraz.Length == 0);

            if (!error)
            {
                i = 0;
                while ((i < vyraz.Length) && (!nasel_se_or))
                {
                    z = vyraz[i];
                    if (z == '(')
                    {
                        pocet_zavorek++;
                    }
                    else if (z == ')')
                    {
                        pocet_zavorek--;
                    }
                    else if (pocet_zavorek == 0)
                    {
                        //budu zkoumat, jestli se nenasel zajimavy logicky operator nebo nerovnost
                        if (z == '|')
                        {
                            // nasel se OR, zapamatuji si kde a cyklus skonci
                            nasel_se_or      = true;
                            pozice_operatoru = i;
                        }
                        else if (!nasel_se_and)   // jestli se uz nejake AND naslo, tak uz me zajima jenom pripadne nasledne OR
                        {
                            if (z == '&')
                            {
                                // nasel se prvni and, zapamatuji si kde a budu hledat dal, jestli tam treba neni or
                                pozice_operatoru = i;
                                nasel_se_and     = true;
                            }
                            else if (!nasla_se_ner) // naslo-li se nejake < nebo >, hledam uz jenom logicke operatory
                            {
                                if ((z == '<') || (z == '>'))
                                {
                                    pozice_operatoru = i;
                                    nasla_se_ner     = true;
                                }
                            } // if (!nasla_se_ner)
                        }     // if (!nasel_se_and)
                    }         // if (pocet_zavorek==0)
                    i++;
                }             // while

                if (pocet_zavorek != 0)  // je to blbe, nesouhlasi pocet zavorek
                {
                    error = true;
                }
                else if (nasel_se_or)
                {
                    // vytvorim uzel a rozdelim retezec a pustim na jeho casti stromovac
                    string levy  = vyraz.Substring(0, pozice_operatoru);
                    string pravy = vyraz.Substring(pozice_operatoru + 1, vyraz.Length - pozice_operatoru - 1);
                    node_levy  = BuildIneqTree(levy);
                    node_pravy = BuildIneqTree(pravy);
                    vysledek   = new IneqTree(IneqTree.NodeType.NodeOr, node_levy, node_pravy);
                }
                else if (nasel_se_and)
                {
                    // dtto
                    string levy  = vyraz.Substring(0, pozice_operatoru);
                    string pravy = vyraz.Substring(pozice_operatoru + 1, vyraz.Length - pozice_operatoru - 1);
                    node_levy = BuildIneqTree(levy); node_pravy = BuildIneqTree(pravy);
                    vysledek  = new IneqTree(IneqTree.NodeType.NodeAnd, node_levy, node_pravy);
                }
                else if (nasla_se_ner)
                {
                    //  upravim nerovnost, ukoncim vetev, ulozim retezec
                    PrepareFormula(ref vyraz, pozice_operatoru);

                    engine.AddFunction("exp", (Func <double, double>)((a) => Math.Exp(a)));

                    Func <double, double, double, double> formula = (Func <double, double, double, double>)engine.Formula(vyraz)
                                                                    .Parameter("x", DataType.FloatingPoint)
                                                                    .Parameter("y", DataType.FloatingPoint)
                                                                    .Parameter("z", DataType.FloatingPoint)
                                                                    .Result(DataType.FloatingPoint)
                                                                    .Build();

                    double testEval = formula(0, 0, 0);

                    vysledek = new IneqTree(formula);
                }
                else // vsechny zavorky jsou zavrene, ale nenasel se operator
                {
                    // mohou nastat dve moznosti: jsou tam zavorky navic nebo je to blbe
                    if ((vyraz[0] == '(') && (vyraz[vyraz.Length - 1] == ')'))
                    {
                        string kratsi = vyraz.Substring(1, vyraz.Length - 2);
                        vysledek = BuildIneqTree(kratsi);
                    }
                    else
                    {
                        error = true;
                    }
                } // nenasel se operator
            }     // if ( !error )

            return(vysledek);
        }  // funkce