/// <summary> /// Assert a fact to the FactBase. /// </summary> private static void CoreAssert(string rel, object e1, object e2, object e3, Tvar val) { // Don't assert a fact that's already been asserted if (!HasBeenAsserted(rel, e1, e2, e3)) { // Assert the fact Fact f = new Fact(rel, e1, e2, e3, val); FactBase.Add(f); // TODO: This breaks when the objects are not Things (hence the try-catch) try { // Add Things to the ThingBase AddThing((Thing)e1); AddThing((Thing)e2); AddThing((Thing)e3); // Look for additional inferences that can be drawn, based on assumptions. Assumptions.TriggerInferences(rel, (Thing)e1, (Thing)e2, (Thing)e3, val); } catch { } } }
/// <summary> /// Returns a test result that indicates this specification has failed because different things happened. /// </summary> /// <param name="actual">The actual events</param> /// <returns>A new <see cref="EventCentricTestResult"/>.</returns> public EventCentricTestResult Fail(Fact[] actual) { if (actual == null) throw new ArgumentNullException("actual"); return new EventCentricTestResult(this, TestResultState.Failed, new Optional<Fact[]>(actual), Optional<Exception>.Empty); }
public void Fact() { const int divident = 37; const int divider = 50; var fact = new Fact {Divident = divident, Divider = divider}; Assert.AreEqual(fact.Percent, divident*2); }
/// <summary> /// Defines a set of facts that happened. /// </summary> /// <param name="facts">The facts that occurred.</param> /// <returns>A builder of facts.</returns> /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="facts"/> is <c>null</c>.</exception> public FactsBuilder That(params Fact[] facts) { if (facts == null) throw new ArgumentNullException("facts"); var combinedFacts = new Fact[_facts.Length + facts.Length]; _facts.CopyTo(combinedFacts, 0); facts.CopyTo(combinedFacts, _facts.Length); return new FactsBuilder(combinedFacts); }
TestSpecificationBuilderContext(Fact[] givens, object when, Fact[] thens, Exception throws) { _givens = givens; _when = when; _thens = thens; _throws = throws; }
public bool IsAFact(Fact fact) { if (this.facts.Contains(fact)) return true; NameVerbValueFact namefact = (NameVerbValueFact)fact; return namefact.IsSatisfiedByContext(this.context); }
/// <summary> /// Initializes a new <see cref="EventCentricTestSpecification"/> instance. /// </summary> /// <param name="givens">The specification givens.</param> /// <param name="when">The specification when.</param> /// <param name="thens">The specification thens.</param> public EventCentricTestSpecification(Fact[] givens, object when, Fact[] thens) { if (givens == null) throw new ArgumentNullException("givens"); if (when == null) throw new ArgumentNullException("when"); if (thens == null) throw new ArgumentNullException("thens"); _givens = givens; _when = when; _thens = thens; }
public DelegatingCommand(Action action, Fact canExecute) { this.action = action; this.canExecute = canExecute; var dispatcher = Dispatcher.CurrentDispatcher; if (canExecute != null) { this.canExecute.PropertyChanged += (sender, args) => dispatcher.Invoke(CanExecuteChanged, this, EventArgs.Empty); } }
/// <summary> /// Defines a set of events that happened to a particular aggregate. /// </summary> /// <param name="identifier">The aggregate identifier the events apply to.</param> /// <param name="events">The events that occurred.</param> /// <returns>A builder of facts.</returns> /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="identifier"/> or <paramref name="events"/> is <c>null</c>.</exception> public FactsBuilder That(string identifier, params object[] events) { if (identifier == null) throw new ArgumentNullException("identifier"); if (events == null) throw new ArgumentNullException("events"); if (events.Length == 0) return this; var combinedFacts = new Fact[_facts.Length + events.Length]; _facts.CopyTo(combinedFacts, 0); for (var index = 0; index < events.Length; index++) { combinedFacts[_facts.Length + index] = new Fact(identifier, events[index]); } return new FactsBuilder(combinedFacts); }
public EnableControlCommand(Control control, Fact canExecute) { this.control = control; this.canExecute = canExecute; ctx = AsyncOperationManager.SynchronizationContext; if (canExecute != null) { this.canExecute.PropertyChanged += (sender, args) => ctx.Post(x => control.Enabled = canExecute.Value, null); } }
public void AssertFact(Fact fact) { if (fact is IsFact) { IsFact isfact = (IsFact)fact; this.context.SetValue(isfact.Name, isfact.Value); this.asserted.Enqueue(fact); return; } if (this.facts.Contains(fact)) return; this.facts.Add(fact); this.asserted.Enqueue(fact); }
/// <summary> /// Compares the expected to the actual fact. /// </summary> /// <param name="expected">The expected fact.</param> /// <param name="actual">The actual fact.</param> /// <returns> /// An enumeration of <see cref="FactComparisonDifference">differences</see>, or empty if none found. /// </returns> public IEnumerable<FactComparisonDifference> Compare(Fact expected, Fact actual) { if (string.CompareOrdinal(expected.Identifier, actual.Identifier) != 0) { yield return new FactComparisonDifference( expected, actual, string.Format("Expected.Identifier != Actual.Identifier ({0},{1})", expected.Identifier, actual.Identifier)); } if (!_comparer.Compare(expected.Event, actual.Event)) { foreach (var difference in _comparer.Differences) { yield return new FactComparisonDifference( expected, actual, difference.ToString()); } } }
public void FactService_Add_Calls_Repository_Add_Method_With_The_Same_Fact_Object_It_Recieved() { // Create test data var newFact = new Fact { Date = "Foo", Place = "Bar" }; //Create Mock var mockRepository = new Mock<IRepository<Fact>>(); _mockUnitOfWork.Setup(d => d.GetRepository<Fact>()).Returns(mockRepository.Object); //Arrange _service = new FactService(_mockUnitOfWork.Object); //Act _service.Add(newFact); //Assert mockRepository.Verify(r => r.Add(newFact)); }
public void FactService_Add_Calls_UnitOfWork_Commit_Method() { // Create test data var newFact = new Fact { Date = "Foo", Place = "Bar" }; //Create Mock var mockRepository = new Mock<IRepository<Fact>>(); _mockUnitOfWork.Setup(d => d.GetRepository<Fact>()).Returns(mockRepository.Object); //Arrange _service = new FactService(_mockUnitOfWork.Object); //Act _service.Add(newFact); //Assert _mockUnitOfWork.Verify(db => db.Commit()); }
public void RetractFact(Fact fact) { if (fact is IsFact) { IsFact isfact = (IsFact)fact; object current = this.context.GetValue(isfact.Name); if (current == null || !current.Equals(isfact.Value)) throw new InvalidOperationException(); this.context.SetValue(isfact.Name, null); this.retracted.Enqueue(fact); return; } if (!this.facts.Contains(fact)) throw new InvalidOperationException(); this.facts.Remove(fact); this.retracted.Enqueue(fact); }
public LhsExpressionArguments(IArgumentMap argumentMap, Tuple tuple, Fact fact) { _argumentMap = argumentMap; _tuple = tuple; _fact = fact; }
/// <summary> /// Instantiates a new Fact event definition. /// </summary> /// <remarks> /// DO NOT ASSERT OR RETRACT FACTS WHEN HANDLING THIS EVENT! /// </remarks> /// <param name="fact">The Fact that generated the event.</param> /// <param name="otherFact">The Other Fact that generated the event.</param> public NewFactEventArgs(Fact fact, Fact otherFact) : this(fact, otherFact, null) { }
/// <summary> /// Instantiates a new Fact event definition. /// </summary> /// <remarks> /// DO NOT ASSERT OR RETRACT FACTS WHEN HANDLING THIS EVENT! /// </remarks> /// <param name="fact">The Fact that generated the event.</param> public NewFactEventArgs(Fact fact) : this(fact, null, null) { }
public BuiltInFunctions() { // Text Functions["len"] = new Len(); Functions["lower"] = new Lower(); Functions["upper"] = new Upper(); Functions["left"] = new Left(); Functions["right"] = new Right(); Functions["mid"] = new Mid(); Functions["replace"] = new Replace(); Functions["rept"] = new Rept(); Functions["substitute"] = new Substitute(); Functions["concatenate"] = new Concatenate(); Functions["char"] = new CharFunction(); Functions["exact"] = new Exact(); Functions["find"] = new Find(); Functions["fixed"] = new Fixed(); Functions["proper"] = new Proper(); Functions["search"] = new Search(); Functions["text"] = new Text.Text(); Functions["t"] = new T(); Functions["hyperlink"] = new Hyperlink(); Functions["value"] = new Value(); // Numbers Functions["int"] = new CInt(); // Math Functions["abs"] = new Abs(); Functions["asin"] = new Asin(); Functions["asinh"] = new Asinh(); Functions["cos"] = new Cos(); Functions["cosh"] = new Cosh(); Functions["power"] = new Power(); Functions["sign"] = new Sign(); Functions["sqrt"] = new Sqrt(); Functions["sqrtpi"] = new SqrtPi(); Functions["pi"] = new Pi(); Functions["product"] = new Product(); Functions["ceiling"] = new Ceiling(); Functions["count"] = new Count(); Functions["counta"] = new CountA(); Functions["countblank"] = new CountBlank(); Functions["countif"] = new CountIf(); Functions["countifs"] = new CountIfs(); Functions["fact"] = new Fact(); Functions["floor"] = new Floor(); Functions["sin"] = new Sin(); Functions["sinh"] = new Sinh(); Functions["sum"] = new Sum(); Functions["sumif"] = new SumIf(); Functions["sumifs"] = new SumIfs(); Functions["sumproduct"] = new SumProduct(); Functions["sumsq"] = new Sumsq(); Functions["stdev"] = new Stdev(); Functions["stdevp"] = new StdevP(); Functions["stdev.s"] = new Stdev(); Functions["stdev.p"] = new StdevP(); Functions["subtotal"] = new Subtotal(); Functions["exp"] = new Exp(); Functions["log"] = new Log(); Functions["log10"] = new Log10(); Functions["ln"] = new Ln(); Functions["max"] = new Max(); Functions["maxa"] = new Maxa(); Functions["median"] = new Median(); Functions["min"] = new Min(); Functions["mina"] = new Mina(); Functions["mod"] = new Mod(); Functions["average"] = new Average(); Functions["averagea"] = new AverageA(); Functions["averageif"] = new AverageIf(); Functions["averageifs"] = new AverageIfs(); Functions["round"] = new Round(); Functions["rounddown"] = new Rounddown(); Functions["roundup"] = new Roundup(); Functions["rand"] = new Rand(); Functions["randbetween"] = new RandBetween(); Functions["rank"] = new Rank(); Functions["rank.eq"] = new Rank(); Functions["rank.avg"] = new Rank(true); Functions["quotient"] = new Quotient(); Functions["trunc"] = new Trunc(); Functions["tan"] = new Tan(); Functions["tanh"] = new Tanh(); Functions["atan"] = new Atan(); Functions["atan2"] = new Atan2(); Functions["atanh"] = new Atanh(); Functions["acos"] = new Acos(); Functions["acosh"] = new Acosh(); Functions["var"] = new Var(); Functions["varp"] = new VarP(); Functions["large"] = new Large(); Functions["small"] = new Small(); Functions["degrees"] = new Degrees(); // Information Functions["isblank"] = new IsBlank(); Functions["isnumber"] = new IsNumber(); Functions["istext"] = new IsText(); Functions["isnontext"] = new IsNonText(); Functions["iserror"] = new IsError(); Functions["iserr"] = new IsErr(); Functions["error.type"] = new ErrorType(); Functions["iseven"] = new IsEven(); Functions["isodd"] = new IsOdd(); Functions["islogical"] = new IsLogical(); Functions["isna"] = new IsNa(); Functions["na"] = new Na(); Functions["n"] = new N(); // Logical Functions["if"] = new If(); Functions["iferror"] = new IfError(); Functions["ifna"] = new IfNa(); Functions["not"] = new Not(); Functions["and"] = new And(); Functions["or"] = new Or(); Functions["true"] = new True(); Functions["false"] = new False(); // Reference and lookup Functions["address"] = new Address(); Functions["hlookup"] = new HLookup(); Functions["vlookup"] = new VLookup(); Functions["lookup"] = new Lookup(); Functions["match"] = new Match(); Functions["row"] = new Row() { SkipArgumentEvaluation = true }; Functions["rows"] = new Rows() { SkipArgumentEvaluation = true }; Functions["column"] = new Column() { SkipArgumentEvaluation = true }; Functions["columns"] = new Columns() { SkipArgumentEvaluation = true }; Functions["choose"] = new Choose(); Functions["index"] = new Index(); Functions["indirect"] = new Indirect(); Functions["offset"] = new Offset() { SkipArgumentEvaluation = true }; // Date Functions["DATEDIF"] = new DATEDIF(); Functions["date"] = new Date(); Functions["today"] = new Today(); Functions["now"] = new Now(); Functions["day"] = new Day(); Functions["month"] = new Month(); Functions["year"] = new Year(); Functions["time"] = new Time(); Functions["hour"] = new Hour(); Functions["minute"] = new Minute(); Functions["second"] = new Second(); Functions["weeknum"] = new Weeknum(); Functions["weekday"] = new Weekday(); Functions["days360"] = new Days360(); Functions["yearfrac"] = new Yearfrac(); Functions["edate"] = new Edate(); Functions["eomonth"] = new Eomonth(); Functions["isoweeknum"] = new IsoWeekNum(); Functions["workday"] = new Workday(); Functions["networkdays"] = new Networkdays(); Functions["networkdays.intl"] = new NetworkdaysIntl(); Functions["datevalue"] = new DateValue(); Functions["timevalue"] = new TimeValue(); // Database Functions["dget"] = new Dget(); Functions["dcount"] = new Dcount(); Functions["dcounta"] = new DcountA(); Functions["dmax"] = new Dmax(); Functions["dmin"] = new Dmin(); Functions["dsum"] = new Dsum(); Functions["daverage"] = new Daverage(); Functions["dvar"] = new Dvar(); Functions["dvarp"] = new Dvarp(); //Financial Functions["Pmt"] = new PMT(); Functions["Rate"] = new Rate(); }
public QuestionRule(Fact dependsFact, string setsFactName, string questions, params string[] allowedValues) : base(dependsFact, new Fact(setsFactName, null)) { AllowedValues = allowedValues; Questions = questions; }
/// <summary> /// Creates a new Proposition with name <tt>name</tt>. /// </summary> /// <param name="name">The name of the Proposition.</param> public ForwardProposition(Fact name) { Name = name; Value = false; }
FactsBuilder(Fact[] facts) { _facts = facts; }
private CartesianSentenceFormDomain GetDomain(ISentenceForm form, Fact sentence) { var domainContents = new List<ISet<TermObject>>(); GetDomainInternal(sentence.GetTerms(), _sentencesModel.GetBodyModel(sentence), domainContents); return new CartesianSentenceFormDomain(form, domainContents); }
public Fact(Fact f) { id = f.id; info = f.info; cfactor = f.cfactor; }
private void forChainButton_Click(object sender, EventArgs e) { if (trueFactsLB.Items.Count == 0) { return; } label3.Text = ""; if (procRulesLB.Items.Count > 0) { int cnt = procRulesLB.Items.Count; for (int i = 0; i < cnt; ++i) { procRulesLB.Items.RemoveAt(0); } } if (resFactsLB.Items.Count > 0) { int cnt = resFactsLB.Items.Count; for (int i = 0; i < cnt; ++i) { resFactsLB.Items.RemoveAt(0); } } trueFacts = new List <Fact>(); for (int i = 0; i < trueFactsLB.Items.Count; ++i) { trueFacts.Add((Fact)trueFactsLB.Items[i]); } List <Fact> resFacts; do { resFacts = new List <Fact>(); for (int i = 0; i < rules.Count; ++i) { int matches = 0; double min = Double.MaxValue; for (int j = 0; j < trueFacts.Count; ++j) { // если встречаем в правой части правила один из достоверных фактов if (trueFacts[j].id.Equals(rules[i].right)) { --matches; } else if (rules[i].left.IndexOf(trueFacts[j].id) != -1) { if (trueFacts[j].cfactor < min) { min = trueFacts[j].cfactor; } ++matches; } } if (matches == rules[i].left.Count) { for (int j = 0; j < facts.Count; ++j) { if (facts[j].id == rules[i].right) { Fact f = new Fact((Fact)factsLB.Items[j]); f.cfactor = min * rules[i].cfactor; calcCombinedCF(ref f, ref resFacts); resFacts.Add(f); break; } } procRulesLB.Items.Add(rules[i].ToString()); } } for (int i = 0; i < resFacts.Count; ++i) { Fact f = resFacts[i]; calcCombinedCF(ref f, ref trueFacts); for (int j = 0; j < resFactsLB.Items.Count; ++j) { if (resFacts[i].id == ((Fact)resFactsLB.Items[j]).id) { resFactsLB.Items.RemoveAt(j); } } trueFacts.Add(f); resFactsLB.Items.Add(f); } } while (resFacts.Count > 0); }
public List<Fact> GetFacts(string sqlcode, List<Dimension> selectedDimensions) { DataTable FactDataTable = new DataTable(); List<Fact> ListOfFacts = new List<Fact>(); try { // Loads a list of all ListOfFacts and then converts it into fact-, case- and event-objects. Open(); MySqlCommand getFactsSQL = new MySqlCommand(sqlcode, Connection); MySqlDataAdapter factAdapter = new MySqlDataAdapter(getFactsSQL); factAdapter.Fill(FactDataTable); string currentFact_id = ""; string currentCase_id = ""; Fact currentFact = null; Case currentCase = null; // iterate over the FactDataTable: object with the same fact_id will be combined into one fact-object. foreach (DataRow row in FactDataTable.Rows) { // if we receive a new fact if (currentFact_id != row["fact_id"].ToString()) { // save the current one if (currentFact != null) ListOfFacts.Add(currentFact); // and create a new one Fact temp_fact = new Fact(row["fact_id"].ToString(), null); currentFact = temp_fact; currentFact_id = row["fact_id"].ToString(); } // now if we receive a new case if (currentCase_id != row["case_id"].ToString()) { // save the current one //if (currentCase != null) // currentFact.addCase(currentCase); // and create a new one currentCase = new Case(row["case_id"].ToString()); currentCase_id = row["case_id"].ToString(); currentFact.addCase(currentCase); } // create an event and add it to the case Event currentEvent = new Event(row["PROC_DESCRIPTION"].ToString()); currentEvent.Information.Add("Event ID", row["event_id"].ToString()); currentEvent.Information.Add("Case ID", row["case_id"].ToString()); currentEvent.Information.Add("Type", row["event"].ToString()); currentEvent.Information.Add("Sequence Number", row["PROC_SEQUENCE_NUM"].ToString()); currentEvent.Information.Add("Timestamp", row["timestamp"].ToString()); currentCase.addEvent(currentEvent); } // since the last case and fact are not saved yet, we need to do this now: TO-DO nochmal anschauen opb das jetzt passt //if (currentCase != null) // currentFact.addCase(currentCase); if (currentFact_id != null) ListOfFacts.Add(currentFact); return ListOfFacts; } finally { Close(); } }
public Task <bool> ProcessFactAsync(Fact fact) { return(Task.Run(() => ProcessFact(fact))); }
public void RaiseLhsExpressionFailed(ISession session, Exception exception, Expression expression, IArgumentMap argumentMap, Tuple tuple, Fact fact, NodeDebugInfo nodeInfo, ref bool isHandled) { var handler = LhsExpressionFailedEvent; if (handler != null) { var arguments = new LhsExpressionArguments(argumentMap, tuple, fact); var @event = new LhsExpressionErrorEventArgs(expression, exception, arguments, tuple, fact, nodeInfo.Rules); handler(session, @event); isHandled |= @event.IsHandled; } _parent?.RaiseLhsExpressionFailed(session, exception, expression, argumentMap, tuple, fact, nodeInfo, ref isHandled); }
public bool hasBuff(Fact fact) { return(buffs.Contains(fact)); }
public void Setup() { this.world = new World(); this.hasfever = new IsFact("HasFever", true); Parser parser = new Parser(new StreamReader("TwoRules.txt")); foreach (var rule in parser.ParseRules()) this.world.AddRule(rule); }
public bool ProcessFact(Fact fact) { return(_factHandlerClient.ProcessFact(fact)); }
public String Post([FromBody] Fact fact) { _context.Facts.Add(fact); _context.SaveChanges(); return("c'est ok"); }
public NameAndArity(Fact sentence) { Name = sentence.RelationName; Arity = sentence.Arity; }
public virtual void Visit(Fact fact) { }
private bool AddSentenceToModel(Fact sentence, IDictionary<TermVariable, TermModel> varsToModelsMap) { var sentenceName = new NameAndArity(sentence); bool changesMade = SentencesModel.CreateIfRequired(sentenceName); return changesMade | TermModel.AddBodyToModel(SentencesModel[sentenceName], sentence.GetTerms(), varsToModelsMap); }
public BuiltInFunctions() { // Text Functions["len"] = new Len(); Functions["lower"] = new Lower(); Functions["upper"] = new Upper(); Functions["left"] = new Left(); Functions["right"] = new Right(); Functions["mid"] = new Mid(); Functions["replace"] = new Replace(); Functions["substitute"] = new Substitute(); Functions["concatenate"] = new Concatenate(); Functions["exact"] = new Exact(); Functions["find"] = new Find(); Functions["proper"] = new Proper(); Functions["text"] = new Text.Text(); Functions["t"] = new T(); // Numbers Functions["int"] = new CInt(); // Math Functions["abs"] = new Abs(); Functions["cos"] = new Cos(); Functions["cosh"] = new Cosh(); Functions["power"] = new Power(); Functions["sign"] = new Sign(); Functions["sqrt"] = new Sqrt(); Functions["sqrtpi"] = new SqrtPi(); Functions["pi"] = new Pi(); Functions["product"] = new Product(); Functions["ceiling"] = new Ceiling(); Functions["count"] = new Count(); Functions["counta"] = new CountA(); Functions["countif"] = new CountIf(); Functions["fact"] = new Fact(); Functions["floor"] = new Floor(); Functions["sin"] = new Sin(); Functions["sinh"] = new Sinh(); Functions["sum"] = new Sum(); Functions["sumif"] = new SumIf(); Functions["sumproduct"] = new SumProduct(); Functions["sumsq"] = new Sumsq(); Functions["stdev"] = new Stdev(); Functions["stdevp"] = new StdevP(); Functions["stdev.s"] = new Stdev(); Functions["stdev.p"] = new StdevP(); Functions["subtotal"] = new Subtotal(); Functions["exp"] = new Exp(); Functions["log"] = new Log(); Functions["log10"] = new Log10(); Functions["ln"] = new Ln(); Functions["max"] = new Max(); Functions["maxa"] = new Maxa(); Functions["min"] = new Min(); Functions["mod"] = new Mod(); Functions["average"] = new Average(); Functions["averagea"] = new AverageA(); Functions["averageif"] = new AverageIf(); Functions["round"] = new Round(); Functions["rounddown"] = new Rounddown(); Functions["roundup"] = new Roundup(); Functions["rand"] = new Rand(); Functions["randbetween"] = new RandBetween(); Functions["quotient"] = new Quotient(); Functions["trunc"] = new Trunc(); Functions["tan"] = new Tan(); Functions["tanh"] = new Tanh(); Functions["atan"] = new Atan(); Functions["atan2"] = new Atan2(); Functions["var"] = new Var(); Functions["varp"] = new VarP(); // Information Functions["isblank"] = new IsBlank(); Functions["isnumber"] = new IsNumber(); Functions["istext"] = new IsText(); Functions["iserror"] = new IsError(); Functions["iserr"] = new IsErr(); Functions["iseven"] = new IsEven(); Functions["isodd"] = new IsOdd(); Functions["islogical"] = new IsLogical(); Functions["isna"] = new IsNa(); Functions["na"] = new Na(); Functions["n"] = new N(); // Logical Functions["if"] = new If(); Functions["not"] = new Not(); Functions["and"] = new And(); Functions["or"] = new Or(); Functions["true"] = new True(); // Reference and lookup Functions["address"] = new Address(); Functions["hlookup"] = new HLookup(); Functions["vlookup"] = new VLookup(); Functions["lookup"] = new Lookup(); Functions["match"] = new Match(); Functions["row"] = new Row(); Functions["rows"] = new Rows() { SkipArgumentEvaluation = true }; Functions["column"] = new Column(); Functions["columns"] = new Columns() { SkipArgumentEvaluation = true }; Functions["choose"] = new Choose(); Functions["index"] = new Index(); Functions["indirect"] = new Indirect(); // Date Functions["date"] = new Date(); Functions["today"] = new Today(); Functions["now"] = new Now(); Functions["day"] = new Day(); Functions["month"] = new Month(); Functions["year"] = new Year(); Functions["time"] = new Time(); Functions["hour"] = new Hour(); Functions["minute"] = new Minute(); Functions["second"] = new Second(); Functions["weeknum"] = new Weeknum(); Functions["weekday"] = new Weekday(); Functions["days360"] = new Days360(); Functions["yearfrac"] = new Yearfrac(); Functions["edate"] = new Edate(); Functions["eomonth"] = new Eomonth(); Functions["isoweeknum"] = new IsoWeekNum(); Functions["workday"] = new Workday(); }
public ObjectFact(types.Object Object = default, Fact Fact = default) { this.Object = Object; this.Fact = Fact; }
public new void removeBuff(Fact buff) { base.removeBuff(buff); this.Owner?.Ensure <UnitPartSizeModifier>()?.Remove(null); }
/// <summary> /// Instantiates a new Fact event definition. /// </summary> /// <remarks> /// DO NOT ASSERT OR RETRACT FACTS WHEN HANDLING THIS EVENT! /// </remarks> /// <param name="fact">The Fact that generated the event.</param> /// <param name="context">The context of the event.</param> public NewFactEventArgs(Fact fact, IEventContext context) : this(fact, null, context) { }
public override void OnFactDeactivate() { this.Owner.RemoveFact(this.m_AppliedFact); this.m_AppliedFact = (Fact)null; }
/// <summary> /// Instantiates a new Fact event definition. /// </summary> /// <remarks> /// DO NOT ASSERT OR RETRACT FACTS WHEN HANDLING THIS EVENT! /// </remarks> /// <param name="fact">The Fact that generated the event.</param> /// <param name="otherFact">The Other Fact that generated the event.</param> /// <param name="context">The context of the event.</param> public NewFactEventArgs(Fact fact, Fact otherFact, IEventContext context) { this.fact = fact; this.otherFact = otherFact; this.context = context; }
//========================================================FORWARD DERIVING======================================================== private void forward_chaining_click(object sender, EventArgs e) { if (true_facts_listbox.Items.Count == 0) { return; } //clear previous info info_label.Text = ""; used_rules_listbox.Items.Clear(); result_facts_listbox.Items.Clear(); True_facts = new List <Fact>(); for (int i = 0; i < true_facts_listbox.Items.Count; i++) { True_facts.Add((Fact)true_facts_listbox.Items[i]); } List <Fact> res_facts; while (true) { res_facts = new List <Fact>(); for (int i = 0; i < Rules.Count; ++i) { int matches = 0; bool flag = true; double min = Double.MaxValue; for (int j = 0; j < True_facts.Count; j++) { //if fact is the right part of the rule if (True_facts[j].id.Equals(Rules[i].right_part)) { flag = false; } else //if left part contains true fact if (Rules[i].left_part.IndexOf(True_facts[j].id) != -1) { if (True_facts[j].cert_factor < min) { min = True_facts[j].cert_factor; } matches++; } } //if the whole right part of the rule found if (matches == Rules[i].left_part.Count && flag) { for (int j = 0; j < Facts.Count; j++) { if (Facts[j].id == Rules[i].right_part) { Fact f = new Fact((Fact)facts_listbox.Items[j]); // info_label.Text = Rules[i].cert_factor.ToString(); f.set_cert_factor(min * Rules[i].cert_factor); double d = 0; //for (int k = 0; k < res_facts.Count; k++) // if (res_facts[k].id == f.id) // { // d = calc_combined_factor(f.cert_factor, res_facts[k].cert_factor); // f.set_cert_factor(d); // //res_facts[k].set_cert_factor(d); // } for (int k = 0; k < True_facts.Count; k++) { if (True_facts[k].id == f.id) { d = calc_combined_factor(f.cert_factor, True_facts[k].cert_factor); f.set_cert_factor(d); True_facts[k].set_cert_factor(d); } } res_facts.Add(f); break; } } used_rules_listbox.Items.Add(Rules[i].ToString()); } } for (int i = 0; i < res_facts.Count; i++) { Fact f = res_facts[i]; double d = 0; for (int k = 0; k < True_facts.Count; k++) { if (True_facts[k].id == f.id) { d = calc_combined_factor(f.cert_factor, True_facts[k].cert_factor); f.set_cert_factor(d); } } for (int j = 0; j < result_facts_listbox.Items.Count; j++) { if (res_facts[i].id == ((Fact)result_facts_listbox.Items[j]).id) { result_facts_listbox.Items.RemoveAt(j); } } result_facts_listbox.Items.Add(f); True_facts.Add(f); } if (res_facts.Count == 0) { return; } } }
public void RaiseLhsExpressionEvaluated(ISession session, Exception exception, Expression expression, IArgumentMap argumentMap, object result, Tuple tuple, Fact fact, NodeDebugInfo nodeInfo) { var handler = LhsExpressionEvaluatedEvent; if (handler != null) { var arguments = new LhsExpressionArguments(argumentMap, tuple, fact); var @event = new LhsExpressionEventArgs(expression, exception, arguments, result, tuple, fact, nodeInfo.Rules); handler(session, @event); } _parent?.RaiseLhsExpressionEvaluated(session, exception, expression, argumentMap, result, tuple, fact, nodeInfo); }
public Fact(Fact f) { id = f.id; data = f.data; cert_factor = f.cert_factor; }
public async Task InsertAndGetByIdAsync() { var db = new Database(this.DbSettings, this.DbTrait, null); //ifdb.CheckTableExists<Article>() await db.DropTableIfExistsAsync <Article>(); await db.CreateTableAsync <Article>(); var repo = db.Repository <Article>(); //var dbset = dbSet.MembersString("Id,Name,Age"); var article1 = new Article() { Id = 1, Name = "Yiy", Description = "Yiy Desc", Age = 20 }; Fact.True(await repo.InsertAsync(article1), "未能插入数据"); var article1_db = await repo.GetByIdAsync(1); Fact.NotNull(article1_db); Fact.Equal(article1_db.Id, 1, "取出的Id不为1"); Fact.Equal(article1_db.Name, article1.Name, "取出的Name与原先不一样"); Fact.Equal(article1_db.Description, article1.Description, "取出的Description与原先不一样"); Fact.True(article1_db.Age.HasValue, "未取出Age"); Fact.Equal(article1_db.Age.Value, article1.Age.Value, "取出的Age与原先不一样"); article1_db = await repo.GetByIdAsync(1, new RepoOptions() { AllowedFields = "Name,Age" }); Fact.NotNull(article1_db); Fact.Equal(article1_db.Id, 1, "取出的Id不为1"); Fact.Equal(article1_db.Name, article1.Name, "取出的Name与原先不一样"); Fact.Null(article1_db.Description, "取出的Description与原先不一样"); Fact.True(article1_db.Age.HasValue, "未取出Age"); Fact.Equal(article1_db.Age.Value, article1.Age.Value, "取出的Age与原先不一样"); //var article2 = new Article() //{ // Id = 2, // Name = "yy", // Description = "yy Desc", // Age = 30 //}; //repo.Insert(article2); //for (var i = 0; i < 7; i++) //{ // article2.Id++; // article2.Name = "xxx" + i.ToString(); // repo.Insert(article2); //} //dbset = dbset.Query(p=>p.Name.StartsWith("xxx")).Page(2,2).Descending(p=>p.Id); //var count = dbset.Count(); //Console.WriteLine("Count:" + count.ToString()); //dbset.Load(); //var len = dbset.Length; //Console.WriteLine("Loaded record{0}",len); }
/// <summary> /// Checks if the FactBase contains a certain Fact. /// </summary> /// <param name="fact">The Fact to check.</param> /// <returns>True if the Fact is already present in the FactBase, otherwise False.</returns> public bool Exists(Fact fact) { return(factList.ContainsKey(fact.GetLongHashCode())); }
/// <summary> /// Updates the fact of the current relationship. /// </summary> /// <param name="fact">The fact to be updated.</param> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns> /// A <see cref="RelationshipState"/> instance containing the REST API response. /// </returns> public RelationshipState UpdateFact(Fact fact, params IStateTransitionOption[] options) { return(UpdateFacts(new Fact[] { fact }, options)); }
internal void track(Fact fact) { Debug.Assert(EvaluationFrame.CurrentRule_ == this); fact.Changed += schedule; _trackedFacts.Add(fact); }
/// <summary> /// Initializes a new instance of the <see cref="FactComparisonDifference"/> class. /// </summary> /// <param name="expected">The expected fact.</param> /// <param name="actual">The actual fact.</param> /// <param name="message">The message describing the difference.</param> public FactComparisonDifference(Fact expected, Fact actual, string message) { _expected = expected; _actual = actual; _message = message; }
internal WorkingMemoryEventArgs(Fact fact) { _fact = fact; }
public ResultRule(Fact dependsFact, string setsFactName, string repair) : base(dependsFact, new Fact(setsFactName, null)) { Repair = repair; }
public ResultPocket(Atom source, Fact fact) { this.source = source; this.fact = fact; }
public FactViewModel(Fact fact) { Date = fact.Date; FactType = fact.FactType.ToString(); Place = fact.Place; }
public SingleFactEnumerator(Fact singleFactResult, IList excludedHashCodes) : base() { this.singleFactResult = singleFactResult; }
private void ProcessRetractedFact(Fact fact) { if (fact is NameVerbValueFact) { this.ProcessRetractedFact((NameVerbValueFact)fact); return; } }
private void ProcessAnd(AtomGroup AG, ArrayList processResult, int parser, ArrayList resultStack) { if (AG.ResolvedMembers[parser] is AtomGroup) { if (((AtomGroup)AG.ResolvedMembers[parser]).Operator == AtomGroup.LogicalOperator.And) { throw new BREException("Nested And unexpectedly found in atom group:" + AG.ResolvedMembers[parser]); } ArrayList subProcessResult = new ArrayList(); ProcessOr((AtomGroup)AG.ResolvedMembers[parser], subProcessResult, resultStack); foreach (ArrayList resultRow in subProcessResult) { foreach (ResultPocket rpRow in resultRow) { if (resultStack.Count == 0) { ArrayList tempResultStack = (ArrayList)resultStack.Clone(); tempResultStack.Add(rpRow); if (parser < (AG.OrderedMembers.Length - 1)) { ProcessAnd(AG, processResult, parser + 1, tempResultStack); } else { processResult.Add(tempResultStack); } } else { // exclude similar results for similar atoms (the engine must produce combinations // of facts in this case) bool ignore = false; foreach (ResultPocket rp in resultStack) { if (rpRow.source.IsIntersecting(rp.source)) { ignore = true; break; } if (!ignore) { ArrayList tempResultStack = (ArrayList)resultStack.Clone(); tempResultStack.Add(rpRow); if (parser < (AG.OrderedMembers.Length - 1)) { ProcessAnd(AG, processResult, parser + 1, tempResultStack); } else { processResult.Add(tempResultStack); } } } } } } } else { // resolve the functions and var parts of the atom // from all the previous facts in the result stack Atom atomToRun = Populate((Atom)AG.ResolvedMembers[parser], resultStack, false); ArrayList excludedHashCodes = new ArrayList(); foreach (ResultPocket rp in resultStack) { if (((Atom)AG.OrderedMembers[parser]).IsIntersecting(rp.source)) { excludedHashCodes.Add(rp.fact.GetLongHashCode()); } } // then get the matching facts IEnumerator results = ProcessAtom(atomToRun, excludedHashCodes); if (results != null) { while (results.MoveNext()) { Fact result = (Fact)results.Current; ArrayList tempResultStack = (ArrayList)resultStack.Clone(); tempResultStack.Add(new ResultPocket((Atom)AG.OrderedMembers[parser], result)); if (parser < (AG.OrderedMembers.Length - 1)) { ProcessAnd(AG, processResult, parser + 1, tempResultStack); } else { processResult.Add(tempResultStack); } } } } }
public Either <Error, Void> AddToken(Biscuit token, Option <PublicKey> root) { if (!token.IsSealed()) { Either <Error, Void> res = token.CheckRootKey(root.Get()); if (res.IsLeft) { return(res.Left); } } if (this.token != null) { return(new FailedLogic(new LogicError.VerifierNotEmpty())); } ulong authority_index = symbols.Get("authority").Get(); ulong ambient_index = symbols.Get("ambient").Get(); foreach (Fact fact in token.Authority.Facts) { if (fact.Predicate.Ids[0].Equals(new ID.Symbol(ambient_index))) { return(new FailedLogic(new LogicError.InvalidAuthorityFact(symbols.PrintFact(fact)))); } Fact converted_fact = FactBuilder.ConvertFrom(fact, token.Symbols).Convert(this.symbols); world.AddFact(converted_fact); } foreach (Rule rule in token.Authority.Rules) { Rule converted_rule = RuleBuilder.ConvertFrom(rule, token.Symbols).Convert(this.symbols); world.AddPrivilegedRule(converted_rule); } List <Check> authority_checks = new List <Check>(); foreach (Check check in token.Authority.Checks) { Datalog.Check converted_check = CheckBuilder.ConvertFrom(check, token.Symbols).Convert(this.symbols); authority_checks.Add(converted_check); } token_checks.Add(authority_checks); for (int i = 0; i < token.Blocks.Count; i++) { Block b = token.Blocks[i]; if (b.Index != i + 1) { return(new InvalidBlockIndex(1 + token.Blocks.Count, token.Blocks[i].Index)); } foreach (Fact fact in b.Facts) { if (fact.Predicate.Ids[0].Equals(new ID.Symbol(authority_index)) || fact.Predicate.Ids[0].Equals(new ID.Symbol(ambient_index))) { return(new FailedLogic(new LogicError.InvalidBlockFact(i, symbols.PrintFact(fact)))); } Fact converted_fact = FactBuilder.ConvertFrom(fact, token.Symbols).Convert(this.symbols); world.AddFact(converted_fact); } foreach (Rule rule in b.Rules) { Rule converted_rule = RuleBuilder.ConvertFrom(rule, token.Symbols).Convert(this.symbols); world.AddRule(converted_rule); } List <Check> block_checks = new List <Check>(); foreach (Check check in b.Checks) { Check converted_check = CheckBuilder.ConvertFrom(check, token.Symbols).Convert(this.symbols); block_checks.Add(converted_check); } token_checks.Add(block_checks); } List <RevocationIdentifier> revocation_ids = token.RevocationIdentifiers; ulong rev = symbols.Get("revocation_id").Get(); for (int i = 0; i < revocation_ids.Count; i++) { byte[] id = revocation_ids[i].Bytes; world.AddFact(new Fact(new Predicate(rev, Arrays.AsList <ID>(new ID.Integer(i), new ID.Bytes(id))))); } return(new Right(null)); }
private void AddFact(object sender, IrcEventArgs e) { var sendto = (string.IsNullOrEmpty(e.Data.Channel)) ? e.Data.Nick : e.Data.Channel; if (e.Data.MessageArray.Length < 3) { BotMethods.SendMessage(SendType.Message, sendto, "Too few arguments for 'add'! Try '!help !+fact'."); return; } if (factoidData.Facts.Where(facts => facts.FactKey == e.Data.MessageArray[1]).SingleOrDefault() == null) { var message = e.Data.Message.Substring(e.Data.MessageArray[0].Length + e.Data.MessageArray[1].Length + 2); var fact = new Fact { FactKey = e.Data.MessageArray[1], FactValue = message }; factoidData.Facts.InsertOnSubmit(fact); factoidData.SubmitChanges(); BotMethods.SendMessage(SendType.Message, sendto, "New Fact '" + fact.FactKey + "' learned. Activate it with !" + fact.FactKey + "."); } else { BotMethods.SendMessage(SendType.Message, sendto, "Sorry, I know that fact already."); } }
public static Atom Populate(Atom targetAtom, ArrayList resultStack, bool evaluateFormulas) { IPredicate[] members = (IPredicate[])targetAtom.Members.Clone(); // populate the variable elements with predicate values coming // from the query part of the implication foreach (ResultPocket rp in resultStack) { if (!(rp.fact is FactBase.NegativeFact)) { Fact.Populate(rp.fact, rp.source, members); } } // if there are formulas in the atom, resolve these expressions, passing // the variable values as arguments if (targetAtom.HasFormula) { if (evaluateFormulas) { // formulas must be evaluated and the results placed in individual predicates IDictionary arguments = new Hashtable(); foreach (ResultPocket rp in resultStack) { if (!(rp.fact is FactBase.NegativeFact)) { for (int i = 0; i < rp.source.Members.Length; i++) { object sourcePredicateKey = null; if (rp.source.Members[i] is Variable) { sourcePredicateKey = rp.source.Members[i].Value; } else if (rp.source.SlotNames[i] != String.Empty) { sourcePredicateKey = rp.source.SlotNames[i]; } if ((sourcePredicateKey != null) && (!arguments.Contains(sourcePredicateKey))) { arguments.Add(sourcePredicateKey, rp.fact.Members[i].Value); } } } } for (int i = 0; i < members.Length; i++) { if (members[i] is Formula) { members[i] = new Individual(((Formula)members[i]).Evaluate(arguments)); } } } else { // formulas must be replaced by variables named after the position of the predicate for (int i = 0; i < members.Length; i++) { if (members[i] is Formula) { members[i] = new Variable(i.ToString()); } } } } // clone the target with new members, because atom is immutable return(targetAtom.CloneWithNewMembers(members)); }
public List<TermModel> GetBodyModel(Fact sentence) { return SentencesModel[new NameAndArity(sentence)]; }