void Formula_Zorgtoeslag_2019_Rekenvoorbeeld1() { VariableCollection variables = context.Variables; // stap 1 variables["standaardpremie"] = 1609; variables["drempelinkomen"] = 20941; variables["toetsingsinkomen_aanvrager"] = 19000; variables["toetsingsinkomen_partner"] = 0; // stap 2 IGenericExpression <Double> eDynamic0 = context.CompileGeneric <Double>("toetsingsinkomen_aanvrager + toetsingsinkomen_partner"); variables["toetsingsinkomen"] = eDynamic0.Evaluate(); // stap 3 // Let op!Leidt het tweede deel van de formule tot een negatief bedrag? Reken dan met € 0. // using c# math expression min(n,0) IGenericExpression <Double> eDynamic = context.CompileGeneric <Double>("min(percentage(2.005) * drempelinkomen + max(percentage(13.520) * (toetsingsinkomen - drempelinkomen),0), 1189)"); variables["normpremie"] = eDynamic.Evaluate(); // stap 4 IGenericExpression <Double> eDynamic2 = context.CompileGeneric <Double>("standaardpremie - normpremie"); variables["zorgtoeslagjaar"] = eDynamic2.Evaluate(); IGenericExpression <Double> eDynamic3 = context.CompileGeneric <Double>("round(zorgtoeslagjaar/12,2)"); variables["zorgtoeslagmaand"] = eDynamic3.Evaluate(); Assert.True((double)variables["zorgtoeslagmaand"] == 99.09); IGenericExpression <Double> eDynamic4 = context.CompileGeneric <Double>("round(zorgtoeslagmaand,0)"); variables["zorgtoeslagmaandafgerond"] = eDynamic4.Evaluate(); Assert.True((double)variables["zorgtoeslagmaandafgerond"] == 99); }
static void Main(string[] args) { //Sample Scenario 1 ExpressionContext context = new ExpressionContext(); context.ParserOptions.DecimalSeparator = '.'; context.ParserOptions.FunctionArgumentSeparator = ','; VariableCollection variables = context.Variables; variables.Add("a", 1); variables.Add("b", 1); IGenericExpression <bool> e = context.CompileGeneric <bool>("a=1 AND b=0"); bool result = e.Evaluate(); //Sample Scenario 2 ExpressionContext context2 = new ExpressionContext(); VariableCollection variables2 = context2.Variables; variables2.Add("a", 100); variables2.Add("b", 1); variables2.Add("c", 24); IGenericExpression <bool> ge = context2.CompileGeneric <bool>("(a = 100 OR b > 0) AND c <> 2"); bool result2 = ge.Evaluate(); IGenericExpression <decimal> ge1 = context2.CompileGeneric <decimal>("1/2"); decimal result3 = ge1.Evaluate(); System.Console.ReadKey(); }
public void Formula_Simple_Calculations() { // Define the context of our expression ExpressionContext context = new ExpressionContext(); // Allow the expression to use all static public methods of System.Math context.Imports.AddType(typeof(Math)); context.Variables.ResolveVariableType += Formula_Simple_Calculation_Variables_ResolveVariableType; // this will visit Variables_ResolveVariableType context.Variables.ResolveVariableValue += Formula_Simple_Calculation_Variables_ResolveVariableValue; IGenericExpression <Double> eDynamic = context.CompileGeneric <Double>("sqrt(a) + b"); // This will visit Variables_ResolveVariableValue var result = eDynamic.Evaluate(); Assert.True(result == 9.64575131106459); IGenericExpression <Double> eDynamic1 = context.CompileGeneric <Double>("a + b"); var result1 = eDynamic1.Evaluate(); Assert.True(result1 == 14); IGenericExpression <bool> eDynamic2 = context.CompileGeneric <bool>("a + 1 > b"); var result2 = eDynamic2.Evaluate(); Assert.True(result2); IGenericExpression <bool> eDynamic3 = context.CompileGeneric <bool>("a > b"); var result3 = eDynamic3.Evaluate(); Assert.False(result3); }
public T Execute(Context c) { m_scriptContext.ExecutionContext = c; if (m_compiledExpression == null || m_scriptContext.HaveVariableTypesChanged(m_compiledExpression.Info.GetReferencedVariables(), m_types)) { // Lazy compilation since when the game is loaded, we don't know what types of // variables we have. try { m_compiledExpression = m_scriptContext.ExpressionContext.CompileGeneric <T>(m_expression); m_scriptContext.PopulateVariableTypesCache(m_compiledExpression.Info.GetReferencedVariables(), m_types); } catch (Exception ex) { throw new Exception(string.Format("Error compiling expression '{0}': {1}", Utility.ConvertFleeFormatToVariables(m_expression), ex.Message), ex); } } try { return(m_compiledExpression.Evaluate()); } catch (Exception ex) { throw new Exception(string.Format("Error evaluating expression '{0}': {1}", Utility.ConvertFleeFormatToVariables(m_expression), ex.Message), ex); } }
public static bool ValidadeEquation(string text) { if (!text.Any()) { return(true); } //alterei para text.any() também ExpressionContext context = new ExpressionContext(); VariableCollection variables = context.Variables; foreach (IInvariant invariant in InvariantNum.List()) { if (text.Contains(invariant.getCode() + "_G")) { context.Variables[invariant.getCode() + "_G"] = invariant.Calculate(new Graph(new int[0, 0])); } if (text.Contains(invariant.getCode() + "_lG")) { context.Variables[invariant.getCode() + "_lG"] = invariant.Calculate(new Graph(new int[0, 0])); } if (text.Contains(invariant.getCode() + "_cG")) { context.Variables[invariant.getCode() + "_cG"] = invariant.Calculate(new Graph(new int[0, 0])); } } IGenericExpression <bool> e = context.CompileGeneric <bool>(text); return(e.Evaluate()); }
public static bool EvaluateText(string text, Graph g) { if (!text.Any()) { return(true); } //Alterei de text.count() == 0 para text.any() ExpressionContext context = new ExpressionContext(); VariableCollection variables = context.Variables; foreach (IInvariant invariant in InvariantNum.List()) { if (text.Contains(invariant.getCode() + "_G")) { context.Variables[invariant.getCode() + "_G"] = invariant.Calculate(g); } if (text.Contains(invariant.getCode() + "_lG")) { context.Variables[invariant.getCode() + "_lG"] = invariant.Calculate(Operation.Line(g)); } if (text.Contains(invariant.getCode() + "_cG")) { context.Variables[invariant.getCode() + "_cG"] = invariant.Calculate(Operation.Complement(g)); } } IGenericExpression <bool> e = context.CompileGeneric <bool>(text); return(e.Evaluate()); //throw new ExpressionCompileException(); }
public static double Calculate1DIntegral(IGenericExpression <double> function, Register register, int gp, double[][] pi) { //Jacobian calculation var detJ = Shape.Jacobian(pi); double I = 0; for (int i = 0; i < gp; i++) { double sumx = 0; for (int k = 0; k < pi.Length; k++) { sumx += Shape.Ni(gaussValues1D[gp].gi[i], 1.1, k + 1, pi.Length) * pi[k][0]; } register.x = sumx; var f = function.Evaluate(); //intgreation I += f * detJ * gaussValues1D[gp].wi[i]; } return(I); }
private bool EvaluateExpression(string expression, ExpressionContext context) { IGenericExpression <bool> eGeneric = context.CompileGeneric <bool>(expression); var result = eGeneric.Evaluate(); return(result); }
public static (string expression, bool isValid) IsValid(this string json, string condition) { JObject obj; try { obj = JObject.Parse(json); } catch (Exception error) { Console.WriteLine("========================= Json With Error ========================="); Console.WriteLine(json); Console.WriteLine("========================= Json With Error ========================="); return(error.Message, false); } var expression = ReplaceParameters(obj, condition); ExpressionContext context = new ExpressionContext(); IGenericExpression <bool> e = context.CompileGeneric <bool>(expression); return(expression, e.Evaluate()); }
internal void UpdateVars <T>(IGenericExpression <T> exp) { foreach (var item in Variables) { exp.Context.Variables[item.Key] = item.Value; } }
public static double Calculate2DIntegral_Quadrilateral(IGenericExpression <double> function, Register register, int gp, double[][] pi) { //Jacobian calculation var detJ = Shape.Jacobian(pi); double I = 0; for (int i = 0; i < gp; i++) { for (int j = 0; j < gp; j++) { double sumx = 0, sumy = 0; for (int k = 0; k < pi.Length; k++) { sumx += Shape.Ni(gauss2DQuadValues[gp].gi[i], gauss2DQuadValues[gp].gi[j], k + 1, pi.Length) * pi[k][0]; sumy += Shape.Ni(gauss2DQuadValues[gp].gi[i], gauss2DQuadValues[gp].gi[j], k + 1, pi.Length) * pi[k][1]; } register.x = sumx; register.y = sumy; //evaluate function with new coordiantes var f = function.Evaluate(); //intgreation I += f * detJ * gauss2DQuadValues[gp].wi[i] * gauss2DQuadValues[gp].wi[j]; } } return(I); }
//INtegration of 3/4/8 point area private void Integrate2D_Click(object sender, EventArgs e) { int m = 3; if (comboBox3.SelectedIndex == 1) { m = 4; } if (comboBox3.SelectedIndex == 2) { m = 8; } double [][] pi = new double[m][]; for (int i = 0; i < m; i++) { pi[i] = new double[2]; } if (!ValidateAreaPoints(pi)) { return; } try { var funstr = textBox4.Text; function = context.CompileGeneric <double>(funstr); } catch (Exception ex) { MessageBox.Show("Error in fun definition. ERROR: " + ex.Message); label5.Text = "I=n/a"; return; } int gp = 0; if (int.TryParse(cmbGPoints.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out gp) != true) { MessageBox.Show("Invalid number of Gaussian points!"); label11.Text = ""; return; } double retVal = 0; if (comboBox3.SelectedIndex == 0) { retVal = GaussIntegrator.Calculate2DIntegral_Triangle(function, register, gp, pi); } else { retVal = GaussIntegrator.Calculate2DIntegral_Quadrilateral(function, register, gp, pi); } label11.Text = string.Format("I={0:0.0000000000}", retVal); }
static void Main(string[] args) { //Sample Scenario 1 ExpressionContext context = new ExpressionContext(); VariableCollection variables = context.Variables; variables.Add("a", 1); variables.Add("b", 1); IGenericExpression <bool> e = context.CompileGeneric <bool>("a=1 AND b=0"); bool result = e.Evaluate(); //Sample Scenario 2 ExpressionContext context2 = new ExpressionContext(); VariableCollection variables2 = context2.Variables; variables2.Add("a", 100); variables2.Add("b", 1); variables2.Add("c", 24); IGenericExpression <bool> ge = context2.CompileGeneric <bool>("(a = 100 OR b > 0) AND c <> 2"); bool result2 = ge.Evaluate(); System.Console.ReadKey(); }
//************************************************************************* //* Private * //************************************************************************* //************************************************************************* //* Protected * //************************************************************************* //************************************************************************* //* Public * //************************************************************************* //*-----------------------------------------------------------------------* //* GetCollection * //*-----------------------------------------------------------------------* /// <summary> /// Return the first collection matching the specified expression. /// </summary> /// <param name="expression"> /// Basic expression to parse. Any attribute names are square bracketed. /// For example, to find a collection where the datatype attribute value /// is equal to 'object', use [datatype] = object /// </param> /// <returns> /// Reference to the first matching collection, if found. Otherwise, null. /// </returns> public AttributeCollection GetCollection(string expression) { string content = ""; ExpressionContext context = null; IGenericExpression <bool> evaluator = null; string expressionText = ""; StringCollection fieldNames = new StringCollection(); string keyword = ""; MatchCollection matches = null; //double nValue = 0d; AttributeCollection result = null; VariableCollection variables = null; if (expression?.Length > 0) { expressionText = expression; context = new ExpressionContext(); variables = context.Variables; matches = Regex.Matches(expression, ResourceMain.AttributeKeywordPattern); foreach (Match match in matches) { keyword = Tools.GetValue(match, "keyword"); content = Tools.GetValue(match, "content"); if (content.Length > 0) { // This value is either a field name or a match value. if (keyword.Length > 0) { // Field name found. fieldNames.AddUnique(content); expressionText = expressionText.Replace(keyword, "F" + content); variables.Add("F" + content, content); } else { // Normal value. variables.Add(content, content); } } } foreach (AttributeCollection collection in this) { // Prepare the local variables. foreach (string field in fieldNames) { variables["F" + field] = collection.GetValue(field); } evaluator = context.CompileGeneric <bool>(expressionText); if (evaluator.Evaluate()) { result = collection; break; } } } return(result); }
public void AcceptChildren(IGenericExpressionVisitor visitor) { IGenericExpression expression = Expressions.FirstOrDefault(current => current != null); if (expression != null) { expression.AcceptChildren(visitor); } }
/// <summary> /// Perform integration /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Integrate1D_Click(object sender, EventArgs e) { double a = 0, b = 0; int n = 2; if (double.TryParse(textBox1.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out a) != true) { MessageBox.Show("First point \"a\" of interval is invalid!"); label5.Text = ""; return; } if (double.TryParse(textBox2.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out b) != true) { MessageBox.Show("Second point \"b\" of interval is invalid!"); label5.Text = ""; return; } if (int.TryParse(comboBox4.Text, NumberStyles.None, CultureInfo.InvariantCulture, out n) != true) { MessageBox.Show("Number of points is invalid!"); label5.Text = ""; return; } if (n > 64) { MessageBox.Show("Number of points must be less than 65!"); label5.Text = ""; return; } try { var funstr = textFunction.Text; function = context.CompileGeneric <double>(funstr); } catch (Exception ex) { MessageBox.Show("Error in fun definition. ERROR: " + ex.Message); label5.Text = "I=n/a"; return; } double[][] pi = new double[2][]; pi[0] = new double[2]; pi[1] = new double[2]; pi[0][0] = a; pi[1][0] = b; //perform integration double retVal = GaussIntegrator.Calculate1DIntegral(function, register, n, pi); label5.Text = string.Format("I={0:0.0000000000}", retVal); }
public void getObject() { SqlConnection conn = konn.GetConn(); conn.Open(); string roboIp; SqlCommand cmd = new SqlCommand("SELECT rumus3 from tbl_perumusan where id_kategoripupuk=9", conn); // queryStr = "SELECT nama_pupuk from tbl_perumusan where id_kategoripupuk=9"; // cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn); var queryResult = cmd.ExecuteScalar();//Return an object so first check for null if (queryResult != null) { // If we have result, then convert it from object to string. roboIp = Convert.ToString(queryResult); //txtOutput.Text = roboIp.ToString(); } else { // Else make id = "" so you can later check it. roboIp = ""; //txtOutput.Text = "GAGAL"; //txtOutput.Text = roboIp.Text; } //testtin Flee ExpressionContext context = new ExpressionContext(); // Allow the expression to use all static public methods of System.Math context.Imports.AddType(typeof(Math)); // Define an int variable context.Variables["a"] = 100; // Create a dynamic expression that evaluates to an Object IDynamicExpression eDynamic = context.CompileDynamic("sqrt(a) + pi"); // Create a generic expression that evaluates to a double context.Variables["a"] = 100; context.Variables["b"] = 300; context.Variables["c"] = 320; IGenericExpression <double> eGeneric = context.CompileGeneric <double>(roboIp); // Evaluate the expressions double result = (double)eDynamic.Evaluate(); result = eGeneric.Evaluate(); // Update the value of our variable // Evaluate again to get the updated result result = eGeneric.Evaluate(); double hasilakhir = (double)result + 5; txtOutput.Text = hasilakhir.ToString(); }
public ResponseEvaluator(string expression) { _context.Imports.AddType(typeof(Math)); foreach (var letter in _letters) { _context.Variables[letter] = default(double); } _expression = _context.CompileGeneric <double>(expression.ToUpper()); }
public bool IsValid(JObject obj) { var expression = this.ReplaceParameters(obj, this.Condition); ExpressionContext context = new ExpressionContext(); IGenericExpression <bool> e = context.CompileGeneric <bool>(expression); bool conditionFailed = e.Evaluate(); return(conditionFailed == false); }
public Condition(string expression) { const string variablesPattern = "{[^}]*}"; //{Field} const string inStatementPattern = @"(\w+)(\s+)(IN)(\s+)\([^\(\)]*\)"; //Field IN (value1, value2) expression = ParseVariables(expression, variablesPattern); expression = ParseINStatement(expression, inStatementPattern); // Replace "Field IN (value1, value2)" -> Field = value1 OR Field = value2 this.expression = expression.Replace("!=", "<>"); genericExpression = context.CompileGeneric <bool>(this.expression); }
public static (string expression, bool isValid) IsValid(this string json, string condition) { JObject obj = JObject.Parse(json); var expression = ReplaceParameters(obj, condition); ExpressionContext context = new ExpressionContext(); IGenericExpression <bool> e = context.CompileGeneric <bool>(expression); return(expression, e.Evaluate()); }
public Condition(string expression) { const string variablesPattern = "{[^}]*}"; //{Field} const string inStatementPattern = @"(\w+)(\s+)(IN)(\s+)\([^\(\)]*\)"; //Field IN (value1, value2) expression = ParseVariables(expression, variablesPattern); expression = ParseINStatement(expression, inStatementPattern); // Replace "Field IN (value1, value2)" -> Field = value1 OR Field = value2 this.expression = expression.Replace("!=", "<>"); genericExpression = context.CompileGeneric<bool>(this.expression); }
public override void Compile(bool recursive = false) { base.Compile(recursive); //var context = CreateContext(Renderer); //_resolver = new FeatureVariableResolver(OutputFeatureType); //_resolver.BindContext(context); _startMeasureEvaluator = CompileDoubleExpression(LinearCalibration.StartMeasureField, _linearCalibration.StartMeasure, ref _startMeasure); _endMeasureEvaluator = CompileDoubleExpression(LinearCalibration.EndMeasureField, _linearCalibration.EndMeasure, ref _endMeasure); _compiled = true; }
public override void Compile(bool recursive = false) { //Debug.Assert(InputFeatureType != null); if (_text.LabelBox != null) { var renderer = _text.LabelBox.Renderer as IFeatureRenderer; if (renderer != null) { renderer.InputFeatureType = InputFeatureType; if (recursive) renderer.Compile(true); } } var context = Renderer.Context; //var colorContext = context; //var contentAlignmentContext = context; //_resolver = new FeatureVariableResolver(InputFeatureType); //_resolver.BindContext(context); //_resolver.BindContext(colorContext); //_resolver.BindContext(contentAlignmentContext); var oldFeatureType = Renderer.FeatureVarResolver.FeatureType; Renderer.FeatureVarResolver.FeatureType = InputFeatureType; try { _contentEvaluator = CompileExpression(context, TextStyle.ContentField, _text.Content, ref _content); _angleEvaluator = CompileDoubleExpression(context, TextStyle.AngleField, _text.Angle, ref _angle); _sizeEvaluator = CompileDoubleExpression(context, TextStyle.SizeField, _text.Size, ref _size); _alignEvaluator = CompileEnumExpression(context, TextStyle.AlignmentField, _text.Alignment, ref _alignment); _fontEvaluator = CompileExpression<string>(context, TextStyle.FontField, _text.Font); _colorEvaluator = CompileColorExpression(context, TextStyle.ColorField, _text.Color, ref _color); _scaleXEvaluator = CompileDoubleExpression(context, TextStyle.ScaleXField, _text.ScaleX, ref _scaleX); _scaleYvaluator = CompileDoubleExpression(context, TextStyle.ScaleYField, _text.ScaleY, ref _scaleY); _opacityEvaluator = CompileFloatExpression(context, TextStyle.OpacityField, _text.Opacity, ref _opacity); _overlapableEvaluator = CompileBoolExpression(context, TextStyle.OverlapableField, _text.Overlappable, ref _overlapable); _allowOverlapEvaluator = CompileBoolExpression(context, TextStyle.AllowOverlapField, _text.AllowOverlap, ref _allowOverlap); } finally { Renderer.FeatureVarResolver.FeatureType = oldFeatureType; } //_labelBoxRenderer = _text.LabelBox != null && _text.LabelBox.Renderer != null && !string.IsNullOrWhiteSpace(_text.Content) // ? _text.LabelBox.Renderer as IFeatureRenderer // : null; _labelBoxRenderer = _text.LabelBox != null ? new ContainerNodeRenderer(Renderer, _text.LabelBox, this) : null; _compiled = true; }
public static double Calculate2DIntegral_Triangle(IGenericExpression <double> function, Register register, int gp, double[][] pi) { //Jacobian calculation var detJ = Shape.Jacobian(pi); detJ /= 2.0; double I = 0; int k = 0; if (gp > 3) { register.x = (pi[0][0] - pi[2][0]) * gauss2DTriangleValues[gp].gi[k] + (pi[1][0] - pi[2][0]) * gauss2DTriangleValues[gp].gi[k] + pi[2][0]; register.y = (pi[0][1] - pi[2][1]) * gauss2DTriangleValues[gp].gi[k] + (pi[1][1] - pi[2][1]) * gauss2DTriangleValues[gp].gi[k] + pi[2][1]; var f = function.Evaluate(); //intgreation I += detJ * f * gauss2DTriangleValues[gp].wi[k]; k++; } int i = k; for (; i < gp; i++) { int j = i + 1; if (i == 2 && gp == 3) { j = k; } else if (i == 3 && (gp == 7 || gp == 4)) { j = 1; } else if (i == 6 && gp == 7) { j = 4; } register.x = (pi[0][0] - pi[2][0]) * gauss2DTriangleValues[gp].gi[i] + (pi[1][0] - pi[2][0]) * gauss2DTriangleValues[gp].gi[j] + pi[2][0]; register.y = (pi[0][1] - pi[2][1]) * gauss2DTriangleValues[gp].gi[i] + (pi[1][1] - pi[2][1]) * gauss2DTriangleValues[gp].gi[j] + pi[2][1]; var f = function.Evaluate(); //intgreation I += detJ * f * gauss2DTriangleValues[gp].wi[i]; } return(I); }
// нажатие кнопки табуляции private void TabButton_Click(object sender, RoutedEventArgs e) { int selectedId = Convert.ToInt32(IdList.SelectedItem); try { searchList.Clear(); MySqlConnection conn = new MySqlConnection(connStr); MySqlCommand command = new MySqlCommand(); string commandString = "SELECT * FROM functions WHERE id = '" + selectedId + "';"; command.CommandText = commandString; command.Connection = conn; MySqlDataReader reader; command.Connection.Open(); reader = command.ExecuteReader(); int counter = 0; while (reader.Read()) { searchList.Add(new Formula((int)reader[0], (string)reader[1], (double)reader[2], (double)reader[3], (double)reader[4], (double)reader[5])); counter++; } reader.Close(); selectList.Items.Clear(); selectList.Items.Add(searchList[0].Function + " [" + searchList[0].A + " ; " + searchList[0].B + "] dx = " + searchList[0].Dx); ExpressionContext context = new ExpressionContext(); context.Imports.AddType(typeof(Math)); context.Variables["c"] = Convert.ToDouble(searchList[0].C); context.Variables["x"] = Convert.ToDouble(searchList[0].A); IGenericExpression <double> eGeneric = context.CompileGeneric <double>(searchList[0].Function); for (double i = Convert.ToDouble(searchList[0].A); i < Convert.ToDouble(searchList[0].B) + Convert.ToDouble(searchList[0].Dx); i = i + Convert.ToDouble(searchList[0].Dx)) { context.Variables["x"] = i; double result = eGeneric.Evaluate(); selectList.Items.Add(" x = " + i + " ; y = " + result); } this.outButton.IsEnabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message + char.ConvertFromUtf32(13) + char.ConvertFromUtf32(13) + "Немає звязку з базою " + " Помилка пошуку", "Помилка", MessageBoxButton.OK, MessageBoxImage.Error); } }
protected bool EvaluateCondition(ExpressionContext context, string condition) { try { condition = condition.TrimStart("${".ToCharArray()); condition = condition.TrimEnd('}'); IGenericExpression <bool> e = context.CompileGeneric <bool>(condition); return(e.Evaluate()); } catch (System.Exception) { return(false); } }
public override void Compile(bool recursive = false) { _outputFeatureType = WrapFeatureType(_pointExtractor, InputFeatureType); base.Compile(_outputFeatureType, recursive); //var context = CreateContext(); //_featureVarResolver = new FeatureVariableResolver(OutputFeatureType); //_featureVarResolver.BindContext(context); _startEvaluator = CompileDoubleExpression(PointExtractor.StartField, _pointExtractor.Start, ref _start, false); _endEvaluator = CompileDoubleExpression(PointExtractor.EndField, _pointExtractor.End, ref _end, false); _incEvaluator = CompileDoubleExpression(PointExtractor.IncField, _pointExtractor.Increment, ref _increment, false); _offsetEvaluator = CompileDoubleExpression(PointExtractor.OffsetField, _pointExtractor.Offset, ref _offset); _compiled = true; }
// валидатор математических выражений private bool Validate(string func, double c) { try { ExpressionContext context = new ExpressionContext(); context.Imports.AddType(typeof(Math)); context.Variables["c"] = c; context.Variables["x"] = 1;//test value IGenericExpression <double> eGeneric = context.CompileGeneric <double>(func); double result = eGeneric.Evaluate(); return(true); }catch (Exception ex) { return(false); } }
public void T() { ExpressionContext context2 = new ExpressionContext(); IGenericExpression <decimal> ge1 = context2.CompileGeneric <decimal>("1/2"); decimal result3 = ge1.Evaluate(); ExpressionContext context = new ExpressionContext(); context.ParserOptions.DecimalSeparator = '.'; context.ParserOptions.FunctionArgumentSeparator = ','; context.Options.ParseCulture = CultureInfo.InvariantCulture; var e1 = context.CompileGeneric <bool>("#01/01/2011# < #02/02/2011#"); var result = e1.Evaluate(); Assert.AreEqual(true, result); }
public Func <float, float> getFunctionFromString(string formula) { ExpressionContext context = new ExpressionContext(); context.Imports.AddType(typeof(Math)); context.Variables.Add("x", (double)0); IGenericExpression <double> eGeneric = context.CompileGeneric <double>(formula); Func <float, float> result = (float x) => { context.Variables["x"] = (double)x; return((float)(eGeneric.Evaluate())); }; return(result); }
void Formula_Can_Discover_Parameters() { var localContext = new ExpressionContext(); var variables = new System.Collections.Generic.Dictionary <string, Type>(); localContext.Variables.ResolveVariableType += (object sender, ResolveVariableTypeEventArgs e) => { variables.Add(e.VariableName, typeof(double)); e.VariableType = typeof(double); }; IGenericExpression <object> eDynamic = localContext.CompileGeneric <object>("a + b"); Assert.True(variables.Count == 2); Assert.True(variables.ContainsKey("a")); Assert.True(variables.ContainsKey("b")); }
/// <summary> /// /// </summary> /// <returns></returns> public bool CheckFormula() { // TODO: refactor this. try { compileExpression(); } catch (ExpressionCompileException) { // Expression would not compile, so scoring formula is not valid. // Ensure no unwanted side-effects from compilation. compiledExpression = null; return false; } return true; }
public void FormulaCanReolsveBooleanEquation() { VariableCollection variables = context.Variables; variables["a"] = true; variables["b"] = false; variables["c"] = true; IGenericExpression <bool> eDynamic = context.CompileGeneric <bool>("a AND b AND c"); var result = eDynamic.Evaluate(); Assert.False(result); eDynamic = context.CompileGeneric <bool>("a AND c"); result = eDynamic.Evaluate(); Assert.True(result); eDynamic = context.CompileGeneric <bool>("a AND NOT b"); result = eDynamic.Evaluate(); Assert.True(result); }
public MoveData(string[] args, Dictionary <string, object> variables, string line) : base(variables, line, args) { ExpressionContext expression = FleeHelper.GetExpression(variables); string exceptionMessage = ""; if (args.Length > 2) { throw new ParsingException("Extra agruments supplied, maximum of 2 allowed for this function.", line); } try { exceptionMessage = "Invalid expression for X coordinate!"; x = expression.CompileGeneric <double>(args[0]); exceptionMessage = "Invalid expression for Y coordinate!"; y = expression.CompileGeneric <double>(args[1]); } catch (Exception e) { throw new ParsingException(exceptionMessage, line, e); } }
public override void Compile(bool recursive = false) { //Debug.Assert(InputFeatureType != null); //var context = CreateContext(Renderer); //var colorContext = CreateColorContext(); //_resolver = new FeatureVariableResolver(InputFeatureType); //_resolver.BindContext(context); //_resolver.BindContext(colorContext); var context = Renderer.Context; var colorContext = context; _colorEvaluator = CompileColorExpression(colorContext, SolidFill.ColorPropertyName, _fill.Color, ref _color); _opacityEvaluator = CompileFloatExpression(context, SolidFill.OpacityPropertyName, _fill.Opacity, ref _opacity); _compiled = true; }
public override void Compile(bool recursive = false) { base.Compile(recursive); _bgColorEvaluator = CompileColorExpression(Renderer.Context, Window.BgColorField, _window.BackgroundColor, ref _bgColor, true); _centerXEvaluator = CompileDoubleExpression(Renderer.Context, Window.CenterXField, _window.CenterX, ref _centerX); _centerYEvaluator = CompileDoubleExpression(Renderer.Context, Window.CenterYField, _window.CenterY, ref _centerY); _zoomEvaluator = CompileDoubleExpression(Renderer.Context, Window.ZoomField, _window.Zoom, ref _zoom); _angleEvaluator = CompileDoubleExpression(Renderer.Context, Window.AngleField, _window.Angle, ref _angle); _compiled = true; }
public int validate(string _assestName) { logger.Debug("Validating expression for asset: {0}, expression text: {1}", _assestName, _text); //add items to expression foreach (expressionvar _var in variable) { //if variable validated and initialized with valid OPCItem try { if (_var.validate(_assestName) == 0) { //set expression variable's value to the item's OPCItem value if (_var.OPCItem.type.ToString() == "Boolean") { context.Variables.Add(_var.name, false); } else if (_var.OPCItem.type.ToString() == "Long") { context.Variables.Add(_var.name, 0); } else if (_var.OPCItem.type.ToString() == "String") { context.Variables.Add(_var.name, ""); } } else { logger.Error("Expression variable {0} in expression \" {1} \" failed to validate", _var.name , _text); configOK = false; enabled = false; return -1; } } catch (Exception e) { e.Data["VAR"] = _var.name; IDCService.exceptionLogger(e); configOK = false; enabled = false; return -1; } } //compile expression try { //if valid compile, then no exception will be thrown e = context.CompileGeneric<bool>(_text.ToString()); logger.Debug("Expression \" " + _text.ToString() + " \" successfully validated"); } catch (ExpressionCompileException ex) { if (ex.Reason == CompileExceptionReason.SyntaxError) { logger.Error("Expression \" " + _text.ToString() + " \" could not be compiled"); configOK = false; enabled = false; return -1; } else { logger.Error("Expression complilation threw exception message: " + ex.Message); configOK = false; enabled = false; return -1; } } return 0; }
private void compileExpression() { ExpressionContext context = new ExpressionContext(); // Allows use of all public static Math functions: //context.Imports.AddType(typeof(Math)); // Load values into Flee context. foreach (KeyValuePair<string, long> pair in formulaIDToIntegerValue) { context.Variables[pair.Key] = pair.Value; } foreach (KeyValuePair<string, double> pair in formulaIDToFloatingPointValue) { context.Variables[pair.Key] = pair.Value; } compiledExpression = context.CompileGeneric<double>(cleanFormula(ScoringFormula)); }
public ExpressionChartItem(string expression, int? period) { try { this.OriginalExpressionString = expression; string text = expression; foreach (string current in from x in Game.State.Securities.Keys orderby x.Length descending select x) { text = new Regex("\\[" + current + "\\]", RegexOptions.IgnoreCase).Replace(text, " 1 "); } foreach (string current2 in from x in Game.State.Securities.Keys orderby x.Length descending select x) { text = new Regex("\\b" + current2 + "\\b", RegexOptions.IgnoreCase).Replace(text, " 1 "); } new ExpressionContext().CompileGeneric<double>(text).Evaluate(); } catch { throw new System.Exception("You have entered an invalid charting ticker or expression.\n\nTickers should be input with [Brackets] around them and are not case sensitive. Expressions can contain plus(+), minus(-), multiply(*), divide(/), exponents (^), and/or values.\n\nFor example, a spread can be shown as [CL-Jan]-[CL-Dec], and a conversion spread could be shown as [CL-Spot]-8*[NG-Spot]."); } foreach (string current3 in from x in Game.State.Securities.Keys orderby x.Length descending select x) { expression = new Regex("\\[" + current3 + "\\]", RegexOptions.IgnoreCase).Replace(expression, " " + this.TickerToVariable(current3) + " "); } foreach (string current4 in from x in Game.State.Securities.Keys orderby x.Length descending select x) { expression = new Regex("\\b" + current4 + "\\b", RegexOptions.IgnoreCase).Replace(expression, " " + this.TickerToVariable(current4) + " "); } this.ExpressionString = expression; if (period.HasValue) { this.StartPeriod = (this.StopPeriod = period.Value); } foreach (string current5 in Game.State.Securities.Keys) { if (new Regex("\\b" + this.TickerToVariable(current5) + "\\b").IsMatch(expression)) { this.Securities.Add(current5); this.StartPeriod = System.Math.Max(this.StartPeriod, Game.State.Securities[current5].HistoryChart.StartPeriod); this.StopPeriod = System.Math.Min(this.StopPeriod, Game.State.Securities[current5].HistoryChart.StopPeriod); this.InitialTicks = System.Math.Min(this.InitialTicks, Game.State.Securities[current5].HistoryChart.InitialTicks); this.ExpressionContext.Variables.DefineVariable(this.TickerToVariable(current5), typeof(double)); this.QuotedDecimals = System.Math.Min(Game.State.Securities[current5].Parameters.QuotedDecimals, this.QuotedDecimals); if (this.TicksPerPeriod != Game.State.Securities[current5].HistoryChart.TicksPerPeriod) { throw new System.Exception("Mismatch in TicksPerPeriod."); } } } this.InitialTicks = (this.Securities.Any((string x) => Game.State.Securities[x].HistoryChart.StartPeriod != this.StartPeriod) ? 0 : this.InitialTicks); if (this.Securities.Count == 0) { throw new System.Exception("No valid securities."); } if (this.StartPeriod > this.StopPeriod) { throw new System.Exception("No overlapping periods."); } this.Expression = this.ExpressionContext.CompileGeneric<double>(expression); if (this.Securities.Count == 1) { this.VolumeChart = Game.State.Securities[this.Securities[0]].VolumeChart; } foreach (string current6 in this.Securities) { this.ChartData.Add(current6, new System.Collections.Generic.List<SecurityChartPoint>(Game.State.Securities[current6].HistoryChart.GetData(this.InitialTicks, this.StartPeriod, this.StopPeriod))); } this.TicksAvailable = this.ChartData.Values.Min((System.Collections.Generic.List<SecurityChartPoint> x) => x.Count); this.TotalTicks = this.InitialTicks + (this.StopPeriod - this.StartPeriod + 1) * this.TicksPerPeriod; this.ExpressionYData = new double[4][]; for (int i = 0; i < 4; i++) { this.ExpressionYData[i] = new double[this.TotalTicks]; } for (int j = 0; j < this.TicksAvailable; j++) { try { foreach (string current7 in this.Securities) { this.ExpressionContext.Variables[this.TickerToVariable(current7)] = System.Convert.ToDouble(this.ChartData[current7][j].High); } this.ExpressionYData[0][j] = this.Expression.Evaluate(); foreach (string current8 in this.Securities) { this.ExpressionContext.Variables[this.TickerToVariable(current8)] = System.Convert.ToDouble(this.ChartData[current8][j].Low); } this.ExpressionYData[1][j] = this.Expression.Evaluate(); foreach (string current9 in this.Securities) { this.ExpressionContext.Variables[this.TickerToVariable(current9)] = System.Convert.ToDouble(this.ChartData[current9][j].Open); } this.ExpressionYData[2][j] = this.Expression.Evaluate(); foreach (string current10 in this.Securities) { this.ExpressionContext.Variables[this.TickerToVariable(current10)] = System.Convert.ToDouble(this.ChartData[current10][j].Close); } this.ExpressionYData[3][j] = this.Expression.Evaluate(); } catch { } } this.ExpressionXData = new int[this.TotalTicks]; for (int k = 0; k < this.ExpressionXData.Length; k++) { this.ExpressionXData[k] = k - this.InitialTicks + 1 + (this.StartPeriod - 1) * this.TicksPerPeriod; } foreach (string current11 in this.Securities) { string t = current11; Action<int[], SecurityChartPoint[]> value = delegate(int[] gameticks, SecurityChartPoint[] points) { this.ChartUpdated(t, gameticks, points); }; Game.State.Securities[current11].HistoryChart.ChartUpdated += value; this.ChartUpdateHandlers.Add(current11, value); if (this.VolumeChart != null) { this.VolumeUpdateHandler = new Action<int[], SecurityVolumeChartPoint[]>(this.VolumeUpdated); this.VolumeChart.ChartUpdated += this.VolumeUpdateHandler; } } }
public override void Compile(bool recursive = false) { //Debug.Assert(InputFeatureType != null); //var context = CreateContext(Renderer); //var colorContext = CreateColorContext(); //var contentAlignmentContext = CreateContentAlignmentContext(); //_resolver = new FeatureVariableResolver(InputFeatureType); //_resolver.BindContext(context); //_resolver.BindContext(colorContext); //_resolver.BindContext(contentAlignmentContext); var context = Renderer.Context; //var colorContext = context; var contentAlignmentContext = context; _angleEvaluator = CompileDoubleExpression(context, Marker.AnglePropertyName, _marker.Angle, ref _angle); _scaleXEvaluator = CompileDoubleExpression(context, Marker.ScaleXPropertyName, _marker.ScaleX, ref _scaleX); _scaleYEvaluator = CompileDoubleExpression(context, Marker.ScaleYPropertyName, _marker.ScaleY, ref _scaleY); _opacityEvaluator = CompileFloatExpression(context, Marker.OpacityPropertyName, _marker.Opacity, ref _opacity); _overlappableEvaluator = CompileBoolExpression(context, Marker.OverlappablePropertyName, _marker.Overlappable, ref _overlappable); _alignEvaluator = CompileEnumExpression(context, Marker.AlignmentPropertyName, _marker.Alignment, ref _alignment); _allowOverlapEvaluator = CompileBoolExpression(context, Marker.AllowOverlapPropertyName, _marker.AllowOverlap, ref _allowOverlap); _fileEvaluator = CompileExpression<string>(context, Marker.FilePropertyName, _marker.File); _colorEvaluator = CompileColorExpression(context, Marker.FilePropertyName, _marker.Color, ref _color); _compiled = true; }