/// <summary>
		///   Serializes the <paramref name="model" />.
		/// </summary>
		private unsafe void SerializeModel(BinaryWriter writer, ModelBase model, Formula[] formulas)
		{
			// Collect all objects contained in the model
			var objectTable = CreateObjectTable(model, formulas);

			// Prepare the serialization of the model's initial state
			lock (_syncObject)
			{
				_stateVector = SerializationRegistry.Default.GetStateVectorLayout(model, objectTable, SerializationMode.Full);
				_deserializer = null;
			}

			var stateVectorSize = _stateVector.SizeInBytes;
			var serializer = _stateVector.CreateSerializer(objectTable);

			// Serialize the object table
			SerializeObjectTable(objectTable, writer);

			// Serialize the object identifier of the model itself and the formulas
			writer.Write(objectTable.GetObjectIdentifier(model));
			writer.Write(formulas.Length);
			foreach (var formula in formulas)
				writer.Write(objectTable.GetObjectIdentifier(formula));

			// Serialize the initial state
			var serializedState = stackalloc byte[stateVectorSize];
			serializer(serializedState);

			// Copy the serialized state to the stream
			writer.Write(stateVectorSize);
			for (var i = 0; i < stateVectorSize; ++i)
				writer.Write(serializedState[i]);
		}
 public AnnounceActionModel(string name, Dictionary<string, Agent> allAgents , Dictionary<string, Agent> audience , Formula announcement)
     : base(name)
 {
     AllAgents = allAgents;
     _audience = audience;
     _announcement = announcement;
 }
		/// <param name="model">A copy of the original model the runtime model was generated from.</param>
		/// <param name="buffer">The buffer the model was deserialized from.</param>
		/// <param name="objectTable">The table of objects referenced by the model.</param>
		/// <param name="formulas">The formulas that are checked on the model.</param>
		internal SerializedRuntimeModel(ModelBase model, byte[] buffer, ObjectTable objectTable, Formula[] formulas)
		{
			Model = model;
			Buffer = buffer;
			ObjectTable = objectTable;
			Formulas = formulas;
		}
        public void AtualizarFormula(Formula formula, List<IngredienteFormula> listaIngredientes)
        {
            var listaAtualIngredietes = formulaIngredienteBm.GetByFormula(formula);

            foreach(var item in listaAtualIngredietes)
                formulaIngredienteBm.Delete(item);

            foreach (var itemNovo in listaIngredientes)
            {

                var FormulaIngrediente = new IngredienteFormula()
                {
                    AGosto = itemNovo.AGosto,
                    Formula = formulaBm.GetByID(formula.IdFormula),
                    Ingrediente = ingredienteBm.GetByID(itemNovo.Ingrediente.IdIngrediente),
                    Quantidade = itemNovo.Quantidade
                };

                formulaIngredienteBm.Insert(FormulaIngrediente);

            }

            formula.RendimentoPadrao = listaIngredientes.Sum(x => x.Quantidade);
            formulaBm.Update(formula);

            AtualizarTabelaNutricionalFormula(formulaBm.GetByID(formula.IdFormula));
        }
Beispiel #5
0
		/// <summary>
		///     Recursively inlines all methods invoked within the <paramref name="formula" />.
		/// </summary>
		/// <param name="formula">The formula which should have all invoked methods inlined.</param>
		public static Formula Inline(Formula formula)
		{
			Requires.NotNull(formula, () => formula);

			var inliner = new FormulaInliner();
			return (Formula)inliner.Visit(formula);
		}
		/// <summary>
		///   Initizializes the model that should be analyzed.
		/// </summary>
		/// <param name="configuration">The configuration that should be used for the analyses.</param>
		/// <param name="model">The model that should be analyzed.</param>
		/// <param name="hazard">The hazard that should be analyzed.</param>
		internal void InitializeModel(AnalysisConfiguration configuration, ModelBase model, Formula hazard)
		{
			Model = model;
			ForcedFaults = new FaultSet(Model.Faults.Where(fault => fault.Activation == Activation.Forced));
			SuppressedFaults = new FaultSet(Model.Faults.Where(fault => fault.Activation == Activation.Suppressed));

			InitializeModel(configuration, hazard);
		}
Beispiel #7
0
 public void AddFormula(Formula f, string name)
 {
     MakeFormulaeIfNecessary();
     runtimeFormulae[name] = f;
     f.name = name;
     if(formulae.Contains(f)) { formulae.Remove(f); }
     formulae.Add(f);
 }
        public static string ToHtmlString(Formula expression)
        {
            if (expression == null)
                return null;

            dynamic d = expression;
            return ToHtmlString(d);
        }
Beispiel #9
0
 public override void OnEnable()
 {
     useFormulae = false;
     fdb = target as Formulae;
     base.OnEnable();
     name = "Formulae";
     newFormula = Formula.Constant(0);
     newFormula.name = "";
 }
		/// <summary>
		///   Compiles the <paramref name="formula" />.
		/// </summary>
		/// <param name="formula">The formula that should be compiled.</param>
		public static Func<bool> Compile(Formula formula)
		{
			Requires.NotNull(formula, nameof(formula));

			var visitor = new CompilationVisitor();
			visitor.Visit(formula);

			return Expression.Lambda<Func<bool>>(visitor._expression).Compile();
		}
		/// <summary>
		///   Initizializes the model that should be analyzed.
		/// </summary>
		/// <param name="configuration">The configuration that should be used for the analyses.</param>
		/// <param name="hazard">The hazard that should be analyzed.</param>
		protected override void InitializeModel(AnalysisConfiguration configuration, Formula hazard)
		{
			var serializer = new RuntimeModelSerializer();
			serializer.Serialize(Model, !hazard);

			Func<AnalysisModel> createModel = () =>
				new ActivationMinimalExecutedModel(CreateModel(hazard), configuration.SuccessorCapacity);

			_invariantChecker = new InvariantChecker(createModel, OnOutputWritten, configuration, formulaIndex: 0);
		}
        public ConditionalFormattingRule Convert(IXLConditionalFormat cf, int priority, XLWorkbook.SaveContext context)
        {
            var conditionalFormattingRule = new ConditionalFormattingRule { FormatId = (UInt32)context.DifferentialFormats[cf.Style], Type = cf.ConditionalFormatType.ToOpenXml(), Priority = priority };

            var formula = new Formula { Text = "NOT(ISERROR(" + cf.Range.RangeAddress.FirstAddress.ToStringRelative(false) + "))" };

            conditionalFormattingRule.Append(formula);

            return conditionalFormattingRule;
        }
		/// <summary>
		///   Gets a function that initializes the runtime model.
		/// </summary>
		private Func<RuntimeModel> CreateModel(Formula hazard)
		{
			var serializer = new RuntimeModelSerializer();
			serializer.Serialize(Model, !hazard);

			return () =>
			{
				var serializedData = serializer.LoadSerializedData();
				return new RuntimeModel(serializedData, _stateHeaderBytes);
			};
		}
Beispiel #14
0
 public bool SatisfiesFormula(Formula formula)
 {
     VariableCollection variable = _expressionContext.Variables;
     foreach (var statu in _status)
     {
         variable.Add(statu.Key.ToString() , statu.Value);
     }
     bool eval = _expressionContext.CompileGeneric<bool>(formula.Expression).Evaluate();
     variable.Clear();
     return eval;
 }
        public ConditionalFormattingRule Convert(IXLConditionalFormat cf, int priority, XLWorkbook.SaveContext context)
        {
            String val = cf.Values[1].Value;
            var conditionalFormattingRule = new ConditionalFormattingRule { FormatId = (UInt32)context.DifferentialFormats[cf.Style], Operator = cf.Operator.ToOpenXml(), Text = val, Type = cf.ConditionalFormatType.ToOpenXml(), Priority = priority };

            var formula = new Formula { Text = "RIGHT(" + cf.Range.RangeAddress.FirstAddress.ToStringRelative(false) + "," + val.Length.ToString() + ")=\"" + val + "\"" };

            conditionalFormattingRule.Append(formula);

            return conditionalFormattingRule;
        }
		/// <summary>
		///   Initializes a new instance.
		/// </summary>
		/// <param name="createModel">Creates the model that should be checked.</param>
		/// <param name="stateFormulas">The state formulas that can be evaluated over the generated state graph.</param>
		/// <param name="output">The callback that should be used to output messages.</param>
		/// <param name="configuration">The analysis configuration that should be used.</param>
		internal StateGraphGenerator(Func<AnalysisModel> createModel, Formula[] stateFormulas,
									 Action<string> output, AnalysisConfiguration configuration)
			: base(createModel, output, configuration)
		{
			var analyzedModel = AnalyzedModels.First();

			_stateGraph = new StateGraph(
				Context, stateFormulas, analyzedModel.TransitionSize,
				analyzedModel.RuntimeModel, analyzedModel.RuntimeModelCreator);

			Context.TraversalParameters.BatchedTransitionActions.Add(() => new StateGraphBuilder(_stateGraph));
		}
		/// <summary>
		///   Initizializes the model that should be analyzed.
		/// </summary>
		/// <param name="configuration">The configuration that should be used for the analyses.</param>
		/// <param name="hazard">The hazard that should be analyzed.</param>
		protected override void InitializeModel(AnalysisConfiguration configuration, Formula hazard)
		{
			var checker = new SSharpChecker { Configuration = configuration };
			checker.Configuration.ProgressReportsOnly = false;
			checker.OutputWritten += OnOutputWritten;

			var stateGraph = checker.GenerateStateGraph(Model, !hazard);

			configuration.StateCapacity = Math.Max(1024, (int)(stateGraph.StateCount * 1.5));
			_checker = new InvariantChecker(() => new StateGraphModel(stateGraph, configuration.SuccessorCapacity), OnOutputWritten,
				configuration, formulaIndex: 0);
		}
        public SecretAnnouncement(string name, Dictionary<string, Agent> allAgents, Dictionary<string, Agent> audience, Formula announcement)
            : base(name , allAgents , audience , announcement)
        {
            ActionState trueState = new ActionState("TrueState");
            SecretState = new ActionState("Secret");
            SecretState.Precondition = announcement;
            ActionStates.Add(trueState);
            ActionStates.Add(SecretState);

            Relation = new ActionIndecisionPair(SecretState, trueState);
            Relation.TagedAgents = GetSubtractionOfAgentDics(allAgents, audience);
            TransitionRelation.Add(Relation);
        }
		protected void Check(Formula actual, Formula expected)
		{
			var builder = new StringBuilder();
			builder.AppendLine("Actual:");
			builder.AppendLine(actual.ToString());
			builder.AppendLine();

			builder.AppendLine("Expected:");
			builder.AppendLine(expected.ToString());

			Output.Log("{0}", builder.ToString());

			actual.IsStructurallyEquivalent(expected).ShouldBe(true);
		}
Beispiel #20
0
		public static Expression UpdateCellValue(Cell cell)
        {
            if (cell.HasFormula && cell.State.Count < 1)
            {
                cell.State.Push("Parsing");
				cell.CalcCount++;
				cell.CalcLast = CalcLast;
                var formula = new Formula();
                var value = formula.Parse(cell.Formula);
                cell.State.Pop();
                return value;
            }
            return cell.Exp;
        }
 public static List<Formula> BuildProof(Formula f)
 {
     var variables = f.Variables.ToArray();
     Array.Sort(variables);
     var result = new List<Formula>();
     for (int i = 0; i < 1 << variables.Length; ++i)
     {
         bool[] values = new bool[variables.Length];
         for (int j = variables.Length - 1; j >= 0; --j)
             values[variables.Length - 1 - j] = ((i >> j) & 1) == 1;
         var variablesEvaluation = new Dictionary<PropositionalVariable, bool>();
         for (int j = 0; j < variables.Length; j++)
             variablesEvaluation.Add(variables[j], values[j]);
         var partialProof = WriteProofInPartsEvaluation(f, variablesEvaluation);
         var assumptions =
             variablesEvaluation.Select(x => (x.Value ? x.Key as Formula : new Inversion(x.Key))).ToList();
         result.AddRange(ConvertAssumptions(assumptions, partialProof));
     }
     for (int i = 0; i < variables.Length; ++i)
     {
         result.AddRange(Formula.InlineAll(ProofBuildingResources.TND, new Dictionary<PropositionalVariable, Formula>
         {
             {"A", variables[i]}
         }));
         for (int j = 0; j < 1 << variables.Length - 1 - i; ++j)
         {
             int otherVarsCount = variables.Length - 1 - i;
             Formula fWithOtherVars = f;
             bool[] values = new bool[otherVarsCount];
             for (int k = 0; k<otherVarsCount; ++k)
                 values[k] = ((j >> k) & 1) == 1;
             for (int k = 0; k < otherVarsCount; ++k)
                 fWithOtherVars = new Implication(
                     values[k]?
                         variables[variables.Length-1-k] as Formula:
                         new Inversion(variables[variables.Length-1-k]),
                    fWithOtherVars);
             result.AddRange(Formula.InlineAll(ProofBuildingResources.AEx, new Dictionary<PropositionalVariable, Formula>
             {
                 {"A", fWithOtherVars},
                 {"V", variables[i]}
             }));
         }
     }
     return result;
 }
Beispiel #22
0
		/// <summary>
		///   Initializes a new instance.
		/// </summary>
		/// <param name="context">The context of the traversal process.</param>
		/// <param name="stateFormulas">The state formulas that can be evaluated over the generated state graph.</param>
		/// <param name="transitionSizeInBytes">The size of a transition in bytes.</param>
		/// <param name="model">The runtime model the state graph is generated for.</param>
		/// <param name="createModel">
		///   The factory function that should be used to create instances of the <see cref="RuntimeModel" />
		///   the state graph is generated for.
		/// </param>
		internal StateGraph(TraversalContext context, Formula[] stateFormulas, int transitionSizeInBytes,
							RuntimeModel model, Func<RuntimeModel> createModel)
		{
			Requires.NotNull(context, nameof(context));

			StateFormulas = stateFormulas;
			TransitionSize = transitionSizeInBytes;
			RuntimeModel = model;
			RuntimeModelCreator = createModel;

			_stateStorage = context.States;
			_transitionCapacity = context.Configuration.TransitionCapacity;

			_transitionsBuffer.Resize(TransitionSize * _transitionCapacity, zeroMemory: false);
			_stateMapBuffer.Resize(context.Configuration.StateCapacity * sizeof(TransitionRange), zeroMemory: false);

			_transitions = _transitionsBuffer.Pointer;
			_stateMap = (TransitionRange*)_stateMapBuffer.Pointer;
		}
Beispiel #23
0
		private bool supportAdded, supportRemoved; // Referred cells' support sets up to date

		// Invariant: Every cell within the display area sheet[ulCa, lrCa] is an 
		// ArrayFormula whose CachedArrayFormula instance is this one.

		public CachedArrayFormula(Formula formula,
								  Sheet sheet,
								  int formulaCol,
								  int formulaRow,
								  CellAddr ulCa,
								  CellAddr lrCa) {
			if (formula == null) {
				throw new Exception("CachedArrayFormula arguments");
			}
			else {
				this.formula = formula;
				this._sheet = sheet;
				this.formulaCol = formulaCol;
				this.formulaRow = formulaRow;
				this.ulCa = ulCa;
				this.lrCa = lrCa;
				this.supportAdded = this.supportRemoved = false;
			}
		}
Beispiel #24
0
 public void EditFormulaField(Formula f, int i)
 {
     string name = "formulae.formula."+i;
     bool priorWrap = EditorStyles.textField.wordWrap;
     EditorStyles.textField.wordWrap = true;
     GUI.SetNextControlName(""+fdb.GetInstanceID()+"."+i);
     EditorGUI.BeginChangeCheck();
     f.text = EditorGUILayout.TextArea(f.text, GUILayout.Height(32), GUILayout.Width(Screen.width-24)).RemoveControlCharacters();
     if(EditorGUI.EndChangeCheck() ||
        (GUI.GetNameOfFocusedControl() != name && lastFocusedControl == name)) {
         // Debug.Log("compile "+f.text);
         FormulaCompiler.CompileInPlace(f);
     }
     GUI.SetNextControlName("");
     EditorStyles.textField.wordWrap = priorWrap;
     if(f.compilationError != null && f.compilationError.Length > 0) {
         EditorGUILayout.HelpBox(f.compilationError, MessageType.Error);
     }
 }
        public ConditionalFormattingRule Convert(IXLConditionalFormat cf, int priority, XLWorkbook.SaveContext context)
        {
            String val = GetQuoted(cf.Values[1]);

            var conditionalFormattingRule = new ConditionalFormattingRule { FormatId = (UInt32)context.DifferentialFormats[cf.Style], Operator = cf.Operator.ToOpenXml(), Type = cf.ConditionalFormatType.ToOpenXml(), Priority = priority };

            var formula = new Formula();
            if (cf.Operator == XLCFOperator.Equal || cf.Operator == XLCFOperator.NotEqual)
                formula.Text = val;
            else
                formula.Text = val;
            conditionalFormattingRule.Append(formula);

            if(cf.Operator == XLCFOperator.Between || cf.Operator == XLCFOperator.NotBetween)
            {
                var formula2 = new Formula { Text = GetQuoted(cf.Values[2]) };
                conditionalFormattingRule.Append(formula2);
            }

            return conditionalFormattingRule;
        }
Beispiel #26
0
    public override void OnSRPGCKInspectorGUI()
    {
        int toBeRemoved = -1;
        for(int i = 0; i < fdb.formulae.Count; i++) {
            Formula f = fdb.formulae[i];
            EditorGUILayout.BeginHorizontal();
            GUI.SetNextControlName(fdb.GetInstanceID()+".formulae."+i+".name");
            f.name = EditorGUILayout.TextField(f.name).NormalizeName();
            GUI.SetNextControlName("");
            GUILayout.FlexibleSpace();
            if(GUILayout.Button("Delete")) {
                toBeRemoved = i;
            }
            EditorGUILayout.EndHorizontal();
            EditFormulaField(f, i);
        }
        EditorGUILayout.Space();
        EditorGUILayout.BeginHorizontal();
        if(newFormula.name == null) { newFormula.name = ""; }
        GUI.SetNextControlName(fdb.GetInstanceID()+".formulae.new.name");
        newFormula.name = EditorGUILayout.TextField(newFormula.name).NormalizeName();
        GUI.SetNextControlName("");
        GUI.enabled = newFormula.name.Length > 0;
        if(GUILayout.Button("New Formula")) {
            fdb.AddFormula(newFormula, newFormula.name);
            newFormula = Formula.Constant(0);
            newFormula.name = "";
            um.ForceDirty();
        }
        GUI.enabled = true;
        EditorGUILayout.EndHorizontal();
        EditFormulaField(newFormula, fdb.formulae.Count);

        if(toBeRemoved != -1) {
            fdb.RemoveFormula(toBeRemoved);
            um.ForceDirty();
        }
    }
Beispiel #27
0
		public Expression UpdateValue()
		{
			if (HasFormula && State.Count < 1) {
				State.Push ("Parsing");
				CalcCount++;
				var formula = new Formula ();
				var value = formula.Parse (Formula);
				State.Pop ();
				return value;
			} else {
				var exp = new Expression();
			    double num;
                if (double.TryParse(Value, out num))
                {
                    exp.Set(num);
                }
                else
                {
                    exp.Set(Value);
                }
			    return exp;
			}
		}
Beispiel #28
0
 public void Construct1()
 {
     Formula f = new Formula("$xaedfe");
 }
Beispiel #29
0
        private double CalculateProbabilityToReachStateFormulaInBoundedSteps(Formula psi, int steps)
        {
            // calculate P [true U<=steps psi]


            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var psiEvaluator = MarkovChain.CreateFormulaEvaluator(psi);
            var stateCount   = MarkovChain.States;

            var precalculatedStates = CreateEmptyPrecalculatedStatesArray();

            CalculateSatisfiedStates(precalculatedStates, psiEvaluator);
            //CalculateExcludedStates(precalculatedStates);  // change for \phi Until \psi

            var enumerator = MarkovChain.GetEnumerator();

            var xold  = new double[stateCount];
            var xnew  = CreateDerivedVector(precalculatedStates, PrecalculatedState.Satisfied);
            var loops = 0;

            while (loops < steps)
            {
                // switch xold and xnew
                var xtemp = xold;
                xold = xnew;
                xnew = xtemp;
                loops++;
                for (var i = 0; i < stateCount; i++)
                {
                    if (precalculatedStates[i].HasFlag(PrecalculatedState.Satisfied))
                    {
                        //we could remove this line, because already set by CreateDerivedVector and never changed when we initialize xold with CreateDerivedVector(directlySatisfiedStates)
                        xnew[i] = 1.0;
                    }
                    else if (precalculatedStates[i].HasFlag(PrecalculatedState.Excluded))
                    {
                        //we could remove this line, because already set by CreateDerivedVector and never changed when we initialize xold with CreateDerivedVector(directlySatisfiedStates)
                        xnew[i] = 0.0;
                    }
                    else
                    {
                        enumerator.SelectSourceState(i);
                        var sum = 0.0;
                        while (enumerator.MoveNextTransition())
                        {
                            var entry = enumerator.CurrentTransition;
                            sum += entry.Value * xold[entry.Column];
                        }
                        xnew[i] = sum;
                    }
                }

                if (loops % 10 == 0)
                {
                    stopwatch.Stop();
                    var currentProbability = CalculateFinalProbability(xnew);
                    _output?.WriteLine($"{loops} Bounded Until iterations in {stopwatch.Elapsed}. Current probability={currentProbability.ToString(CultureInfo.InvariantCulture)}");
                    stopwatch.Start();
                }
            }

            var finalProbability = CalculateFinalProbability(xnew);

            stopwatch.Stop();
            return(finalProbability);
        }
Beispiel #30
0
        public void Evaluate1()
        {
            Formula f = new Formula("2+3");

            Assert.AreEqual(f.Evaluate(s => 0), 5.0, 1e-6);
        }
Beispiel #31
0
        public void Evaluate12()
        {
            Formula f = new Formula("6 / 2 + 1");

            Assert.AreEqual(f.Evaluate(s => 0), 4, 1e-6);
        }
Beispiel #32
0
 public void Construct9()
 {
     Formula f = new Formula("(*)");
 }
Beispiel #33
0
 public void Construct10()
 {
     Formula f = new Formula("2.5e9 + x5 / 17*");
 }
Beispiel #34
0
        public void Evaluate13()
        {
            Formula f = new Formula("(5 + X1) / (X1 - 3)");

            Assert.AreEqual(f.Evaluate(s => 1), -3, 1e-6);
        }
Beispiel #35
0
        public void Evaluate11()
        {
            Formula f = new Formula("6 / x");

            Assert.AreEqual(f.Evaluate(s => 0), 0, 1e-6);
        }
Beispiel #36
0
 public void Normalize3()
 {
     Formula f = new Formula("20 - (x3 / 2)", x => x.Insert(0, "$"), x => true);
 }
Beispiel #37
0
 public void Validate1()
 {
     Formula f = new Formula("20 - (x3 / 2)", x => x.Insert(0, "_"), x => x.Length > 10? true : false);
 }
Beispiel #38
0
 internal override bool CalculateBoolean(Formula formulaToCheck)
 {
     throw new NotImplementedException();
 }
Beispiel #39
0
 internal override RewardResult CalculateReward(Formula formulaToCheck)
 {
     throw new NotImplementedException();
 }
Beispiel #40
0
        public void Evaluate9()
        {
            Formula f = new Formula("20 - (40/2)");

            Assert.AreEqual(f.Evaluate(s => 0), 0, 1e-6);
        }
Beispiel #41
0
 public AsyncMessage_VM()
 {
     Message = new Formula("异步消息");
 }
Beispiel #42
0
        public void Evaluate8()
        {
            Formula f = new Formula("20 - 15 / 17");

            Assert.AreEqual(f.Evaluate(s => 0), 19.1176471, 1e-6);
        }
Beispiel #43
0
 public C()
 {
     X = F == 3 || F == 5;
 }
Beispiel #44
0
        public void Evaluate7()
        {
            Formula f = new Formula("2.5e2 + 15 / 17");

            Assert.AreEqual(f.Evaluate(s => 0), 250.882353, 1e-6);
        }
Beispiel #45
0
        public void Evaluate3()
        {
            Formula f = new Formula("x5 + y6");

            f.Evaluate(s => { throw new ArgumentException(); });
        }
Beispiel #46
0
        public void Evaluate10()
        {
            Formula f = new Formula("20 - (x3 / 2)");

            Assert.AreEqual(f.Evaluate(s => 40), 0, 1e-6);
        }
Beispiel #47
0
        public void Evaluate5()
        {
            Formula f = new Formula("20/0");

            f.Evaluate(s => { throw new ArgumentException(); });
        }
        public String Check()
        {
            // Удаляем ненужные пробелы из строки и переводим все в нижний регистр
            Formula = Formula.Replace(" ", "").ToLower();

            // Проверка, пустая ли строка
            if (String.IsNullOrEmpty(Formula))
            {
                return("NullOrEmpty Error!");
            }

            // Проверяем на правильность написания операций
            if (!SyntaxСheck(Formula))
            {
                return("Syntax Error!");
            }

            // Проверка на правильность написания скобок
            if (!BracketCheck(Formula))
            {
                // дальше не идет, выводит что то другое!
                // Вывод текста с ошибкой
                return("Bracket Error!");
            }

            // Делим введенную формулу на элементы массива, используя паттерн арифметический операций
            string[] array = Regex.Split(Formula, pattern);

            // Булевая функция
            // true - если такой символ с формуле допустим
            // false - такого символ не определен
            bool variableArrayCheck;

            for (int i = 0; i < array.Length; i++)
            {
                variableArrayCheck = false;

                foreach (var element in Variables)
                {
                    // Если этот элемент не является названием исходной переменной
                    if (array[i] != element.Key.ToLower())
                    {
                        // Если это целое или десячичное число
                        if (Regex.IsMatch(array[i], @"^\d+([\.]\d+)?$"))
                        {
                            variableArrayCheck = true;
                        }

                        // Если это операционное выражение
                        if (Regex.IsMatch(array[i], pattern))
                        {
                            variableArrayCheck = true;
                        }

                        // Если это выражения квадратного корня, косинус, синус, или пустая строка
                        if (array[i] == "sqrt" || array[i] == "")
                        {
                            variableArrayCheck = true;
                        }
                    }

                    // Если элемент массива является названием исходной переменной, то заменяем название переменной на ее значение
                    if (array[i] == element.Key.ToLower())
                    {
                        array[i]           = element.Value.ToString();
                        variableArrayCheck = true;
                    }

                    // Если значение переменной является десятичным числом с запятой, то меняем запятую на точку, чтобы не возникало ошибок при обработке
                    if (Regex.IsMatch(array[i], @"^\d+([(\.)|(\,)]\d+)?$"))
                    {
                        // Заменяем запятую на точку
                        array[i]           = array[i].Replace(",", ".");
                        variableArrayCheck = true;
                    }
                }

                // Если такой элемент массива недопустим, то выводится ошибка
                if (!variableArrayCheck)
                {
                    return("UnknownData Error!");
                }
            }

            // Соединяем элементы массива обратно в строку
            Formula = string.Join(null, array);

            // Высчитываем готовый ответ с помощью пользвательской библиотеки "mXparser"
            Expression expFormula        = new Expression(Formula);
            string     calculatedFormula = expFormula.calculate().ToString();

            // Выводим ответ
            return(calculatedFormula);
        }
Beispiel #49
0
 public void Construct6()
 {
     Formula f = new Formula("((x3) + 2");
 }
Beispiel #50
0
        public void Evaluate6()
        {
            Formula f = new Formula("25-5");

            Assert.AreEqual(f.Evaluate(s => 0), 20.0, 1e-6);
        }
Beispiel #51
0
 public void Construct7()
 {
     Formula f = new Formula("2e10*");
 }
Beispiel #52
0
 public void Construct8()
 {
     Formula f = new Formula("((x3) + 2)*");
 }
Beispiel #53
0
 public void Construct2()
 {
     Formula f = new Formula("2++3");
 }
Beispiel #54
0
 public AwayFromLayout(Formula formula, ITileLocator tileLocator)
 {
     this.formula     = formula;
     this.tileLocator = tileLocator;
 }
 public void AlterarFormula(Formula formula)
 {
     formulaBm.Update(formula);
 }
Beispiel #56
0
 public void Construct3()
 {
     Formula f = new Formula("2 3");
 }
 public void DesativarFormula(Formula formula)
 {
     formula.EmUso = false;
     formulaBm.Update(formula);
 }
Beispiel #58
0
 public void Construct4()
 {
     Formula f = new Formula("");
 }
 public void CopyFrom(AnnounceActionModel announcementAction)
 {
     Audience = announcementAction.Audience;
     _announcement = announcementAction._announcement;
 }
Beispiel #60
0
 public void Construct5()
 {
     Formula f = new Formula("(x3)) + 2");
 }