コード例 #1
0
		/// <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]);
		}
コード例 #2
0
 public AnnounceActionModel(string name, Dictionary<string, Agent> allAgents , Dictionary<string, Agent> audience , Formula announcement)
     : base(name)
 {
     AllAgents = allAgents;
     _audience = audience;
     _announcement = announcement;
 }
コード例 #3
0
		/// <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;
		}
コード例 #4
0
        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));
        }
コード例 #5
0
ファイル: FormulaInliner.cs プロジェクト: cubeme/safety-sharp
		/// <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);
		}
コード例 #6
0
		/// <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);
		}
コード例 #7
0
ファイル: Formulae.cs プロジェクト: JoeOsborn/SRPGCK
 public void AddFormula(Formula f, string name)
 {
     MakeFormulaeIfNecessary();
     runtimeFormulae[name] = f;
     f.name = name;
     if(formulae.Contains(f)) { formulae.Remove(f); }
     formulae.Add(f);
 }
コード例 #8
0
        public static string ToHtmlString(Formula expression)
        {
            if (expression == null)
                return null;

            dynamic d = expression;
            return ToHtmlString(d);
        }
コード例 #9
0
ファイル: FormulaeEditor.cs プロジェクト: JoeOsborn/SRPGCK
 public override void OnEnable()
 {
     useFormulae = false;
     fdb = target as Formulae;
     base.OnEnable();
     name = "Formulae";
     newFormula = Formula.Constant(0);
     newFormula.name = "";
 }
コード例 #10
0
		/// <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();
		}
コード例 #11
0
		/// <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);
		}
コード例 #12
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;
        }
コード例 #13
0
		/// <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);
			};
		}
コード例 #14
0
ファイル: EpisState.cs プロジェクト: ashkanalinejad/KLab
 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;
 }
コード例 #15
0
        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;
        }
コード例 #16
0
		/// <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));
		}
コード例 #17
0
		/// <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);
		}
コード例 #18
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);
        }
コード例 #19
0
		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);
		}
コード例 #20
0
ファイル: Spreadsheet.cs プロジェクト: Balagangadhar/jison
		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;
        }
コード例 #21
0
 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;
 }
コード例 #22
0
ファイル: StateGraph.cs プロジェクト: isse-augsburg/ssharp
		/// <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;
		}
コード例 #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;
			}
		}
コード例 #24
0
ファイル: FormulaeEditor.cs プロジェクト: JoeOsborn/SRPGCK
 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);
     }
 }
コード例 #25
0
        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;
        }
コード例 #26
0
ファイル: FormulaeEditor.cs プロジェクト: JoeOsborn/SRPGCK
    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();
        }
    }
コード例 #27
0
ファイル: Cell.cs プロジェクト: RubenVerborgh/jison
		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;
			}
		}
コード例 #28
0
 public void Construct1()
 {
     Formula f = new Formula("$xaedfe");
 }
コード例 #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);
        }
コード例 #30
0
        public void Evaluate1()
        {
            Formula f = new Formula("2+3");

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

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

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

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

            Assert.AreEqual(f.Evaluate(s => 0), 0, 1e-6);
        }
コード例 #41
0
ファイル: AsyncMessage_VM.cs プロジェクト: RunOnceEx/sbid-ava
 public AsyncMessage_VM()
 {
     Message = new Formula("异步消息");
 }
コード例 #42
0
        public void Evaluate8()
        {
            Formula f = new Formula("20 - 15 / 17");

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

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

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

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

            f.Evaluate(s => { throw new ArgumentException(); });
        }
コード例 #48
0
        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);
        }
コード例 #49
0
 public void Construct6()
 {
     Formula f = new Formula("((x3) + 2");
 }
コード例 #50
0
        public void Evaluate6()
        {
            Formula f = new Formula("25-5");

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