public void TestApply()
        {
            ICell cell1 = container.Resolve <ICell>(new ParameterOverride("rowIndex", 0), new ParameterOverride("colIndex", 1));
            ICell cell2 = container.Resolve <ICell>(new ParameterOverride("rowIndex", 1), new ParameterOverride("colIndex", 1));
            ICell cell3 = container.Resolve <ICell>(new ParameterOverride("rowIndex", 2), new ParameterOverride("colIndex", 1));

            cell1.IsAlive = cell2.IsAlive = cell3.IsAlive = true;
            IGrid <ICell> grid = container.Resolve <IGrid <ICell> >(
                new ParameterOverride("totalRows", 3),
                new ParameterOverride("totalColumns", 3),
                new ParameterOverride("initialActiveCells", new ICell[] { cell1, cell2, cell3 }));

            IRule <IGrid <ICell>, ICell> rule = container.Resolve <IRule <IGrid <ICell>, ICell> >("Live");

            Assert.Throws <ArgumentNullException>(() => rule.Apply(null, cell1));
            Assert.Throws <ArgumentNullException>(() => rule.Apply(grid, null));
            Assert.Throws <InvalidOperationException>(() => rule.Apply(grid, grid[0, 0]));

            ICell result = rule.Apply(grid, grid[0, 1]);

            Assert.AreEqual(result.IsAlive, false);

            result = rule.Apply(grid, grid[1, 1]);
            Assert.AreEqual(result.IsAlive, true);
        }
Esempio n. 2
0
        private IEnumerable <Word> Synthesize(IEnumerable <Word> analyses)
        {
            var validWords = new HashSet <Word>(FreezableEqualityComparer <Word> .Default);

            foreach (Word analysisWord in analyses)
            {
                foreach (Word synthesisWord in LexicalLookup(analysisWord))
                {
                    validWords.UnionWith(_synthesisRule.Apply(synthesisWord).Where(IsWordValid));
                }
            }
            return(validWords);
        }
Esempio n. 3
0
        private IEnumerable <Word> ApplyTemplates(Word input)
        {
            foreach (Word tempOutWord in _templatesRule.Apply(input))
            {
                switch (_stratum.MorphologicalRuleOrder)
                {
                case MorphologicalRuleOrder.Linear:
                    foreach (Word outWord in ApplyMorphologicalRules(tempOutWord))
                    {
                        yield return(outWord);
                    }
                    if (!FreezableEqualityComparer <Word> .Default.Equals(input, tempOutWord))
                    {
                        yield return(tempOutWord);
                    }
                    break;

                case MorphologicalRuleOrder.Unordered:
                    if (!FreezableEqualityComparer <Word> .Default.Equals(input, tempOutWord))
                    {
                        foreach (Word outWord in ApplyMorphologicalRules(tempOutWord))
                        {
                            yield return(outWord);
                        }
                        yield return(tempOutWord);
                    }
                    break;
                }
            }
        }
Esempio n. 4
0
 public void Run(int input)
 {
     for (var i = 1; i <= input; i++)
     {
         _rulesChain.Apply(i);
     }
 }
Esempio n. 5
0
 public void Apply(Config config, TrainCar car, SoundSet soundSet)
 {
     if (Applicable(car))
     {
         rule.Apply(config, car, soundSet);
     }
 }
Esempio n. 6
0
 public static T ApplyRule <T>(this T obj, IRule <T> rule) where T : class
 {
     rule.ClearConditions();
     rule.Initialize(obj);
     if (rule.IsValid())
     {
         rule.Apply(obj);
     }
     return(obj);
 }
Esempio n. 7
0
        public IEnumerable <Word> ParseWord(string word, out object trace)
        {
            // convert the word to its phonetic shape
            Shape shape = _lang.SurfaceStratum.CharacterDefinitionTable.Segment(word);

            var input = new Word(_lang.SurfaceStratum, shape);

            input.Freeze();
            if (_traceManager.IsTracing)
            {
                _traceManager.AnalyzeWord(_lang, input);
            }
            trace = input.CurrentTrace;

            // Unapply rules
            IEnumerable <Word> analyses = _analysisRule.Apply(input);

#if OUTPUT_ANALYSES
            var lines = new List <string>();
            foreach (Word w in analyses)
            {
                string shapeStr = w.ToString();
                string rulesStr = string.Join(", ", w.MorphologicalRules.Select(r => r.Name));
                lines.Add(string.Format("{0} : {1}", shapeStr, rulesStr));
            }

            File.WriteAllLines("analyses.txt", lines.OrderBy(l => l));
#endif

#if SINGLE_THREADED
            IEnumerable <Word> validWords = Synthesize(analyses);
#else
            IEnumerable <Word> validWords = ParallelSynthesize(analyses);
#endif

            var matchList = new List <Word>();
            foreach (Word w in CheckDisjunction(validWords))
            {
                if (_lang.SurfaceStratum.CharacterDefinitionTable.IsMatch(word, w.Shape))
                {
                    if (_traceManager.IsTracing)
                    {
                        _traceManager.Successful(_lang, w);
                    }
                    matchList.Add(w);
                }
                else if (_traceManager.IsTracing)
                {
                    _traceManager.Failed(_lang, w, FailureReason.SurfaceFormMismatch, null, word);
                }
            }
            return(matchList);
        }
Esempio n. 8
0
        public void Apply(int input)
        {
            if (IsRuleMatchingFor(input))
            {
                PerformRuleActionFor(input);
                if (_breakable)
                {
                    return;
                }
            }

            _successor.Apply(input);
        }
Esempio n. 9
0
        public void Apply_Calls_Apply_Of_Rules()
        {
            // Arrange
            m_RuleOne.CanApply(Arg.Any <int>()).Returns(false);
            m_RuleTwo.CanApply(Arg.Any <int>()).Returns(true);
            m_RuleTwo.Apply(Arg.Any <int>()).Returns("Test");

            // Act
            string actual = m_Sut.Apply(1);

            // Assert
            Assert.AreEqual("Test",
                            actual);
        }
Esempio n. 10
0
        public IEnumerable <Word> Apply(Word input)
        {
            if (!_morpher.RuleSelector(_stratum) || input.RootAllomorph.Morpheme.Stratum.Depth > _stratum.Depth)
            {
                return(input.ToEnumerable());
            }

            if (_morpher.TraceManager.IsTracing)
            {
                _morpher.TraceManager.BeginApplyStratum(_stratum, input);
            }

            var output = new HashSet <Word>(FreezableEqualityComparer <Word> .Default);

            foreach (Word mruleOutWord in ApplyMorphologicalRules(input).Concat(ApplyTemplates(input)))
            {
                if (!(mruleOutWord.IsLastAppliedRuleFinal ?? false))
                {
                    if (_morpher.TraceManager.IsTracing)
                    {
                        _morpher.TraceManager.NonFinalTemplateAppliedLast(_stratum, mruleOutWord);
                    }
                }
                else if (mruleOutWord.HasRemainingRulesFromStratum(_stratum))
                {
                    if (_morpher.TraceManager.IsTracing)
                    {
                        _morpher.TraceManager.Failed(_morpher.Language, mruleOutWord, FailureReason.PartialParse, null,
                                                     null);
                    }
                }
                else
                {
                    Word newWord = mruleOutWord.Clone();
                    _prulesRule.Apply(newWord);
                    newWord.IsLastAppliedRuleFinal = null;
                    newWord.Freeze();
                    if (_morpher.TraceManager.IsTracing)
                    {
                        _morpher.TraceManager.EndApplyStratum(_stratum, newWord);
                    }
                    output.Add(newWord);
                }
            }
            if (_morpher.TraceManager.IsTracing && output.Count == 0)
            {
                _morpher.TraceManager.EndApplyStratum(_stratum, input);
            }
            return(output);
        }
        public void WhenApplyIsCalled_WithNoProducts_GenerateShippingSlipIsNeverCalled()
        {
            // GIVEN
            _shippingService.Setup(x => x.GenerateShippingSlip(It.IsAny <Order>())).Verifiable();

            var order = new Order
            {
                CustomerId = 12,
                Id         = 2,
                Total      = 342,
                Items      = new List <Item>()
                {
                    new Item {
                        Id = 5, Name = "test", Type = ItemType.Membership
                    }
                }
            };

            // WHEN
            _productRule.Apply(order);

            // Then
            _shippingService.Verify(x => x.GenerateShippingSlip(It.IsAny <Order>()), Times.Never);
        }
Esempio n. 12
0
        public void WhenApplyIsCalled_WithNoMemberships_ActivateMembershipIsNeverCalled()
        {
            // GIVEN
            _userService.Setup(x => x.ActivateMembership(It.IsAny <int>())).Verifiable();

            var order = new Order
            {
                CustomerId = 12,
                Id         = 2,
                Total      = 342,
                Items      = new List <Item>()
                {
                    new Item {
                        Id = 5, Name = "test", Type = ItemType.Product
                    }
                }
            };

            // WHEN
            _activateMembershipRule.Apply(order);

            // Then
            _userService.Verify(x => x.ActivateMembership(It.IsAny <int>()), Times.Never);
        }
Esempio n. 13
0
        public bool RuleEvaluationReturnsExpectedResultWhen(int numberOfSeats, int seatsTaken, double minTakeOffPercentage)
        {
            var ruleContext = new ScheduledFlightContext()
            {
                Aircraft = AnyAircraft(numberOfSeats),
                ScheduledFlightSummary = new ScheduledFlightSummary()
                {
                    SeatsTaken = seatsTaken
                },
                FlightRoute = AnyFlightRoute(minTakeOffPercentage)
            };

            var result = _rule.Apply(ruleContext);

            return(result.IsSuccess);
        }
Esempio n. 14
0
        public IEnumerable <Word> Apply(Word input)
        {
            if (_morpher.TraceManager.IsTracing)
            {
                _morpher.TraceManager.BeginUnapplyStratum(_stratum, input);
            }

            input         = input.DeepClone();
            input.Stratum = _stratum;

            _prulesRule.Apply(input);
            input.Freeze();

            IEnumerable <Word> mruleOutWords = null;

            switch (_stratum.MorphologicalRuleOrder)
            {
            case MorphologicalRuleOrder.Linear:
                mruleOutWords = ApplyTemplates(input);
                break;

            case MorphologicalRuleOrder.Unordered:
                mruleOutWords = ApplyTemplates(input).Concat(ApplyMorphologicalRules(input));
                break;
            }
            Debug.Assert(mruleOutWords != null);

            var output = new HashSet <Word>(FreezableEqualityComparer <Word> .Default)
            {
                input
            };

            if (_morpher.TraceManager.IsTracing)
            {
                _morpher.TraceManager.EndUnapplyStratum(_stratum, input);
            }
            foreach (Word mruleOutWord in mruleOutWords)
            {
                output.Add(mruleOutWord);
                if (_morpher.TraceManager.IsTracing)
                {
                    _morpher.TraceManager.EndUnapplyStratum(_stratum, mruleOutWord);
                }
            }
            return(output);
        }
        public bool RuleEvaluationReturnsExpectedResultWhen(int numberOfSeats, int airlineEmployeesSeatsTaken, double minTakeOffPercentage)
        {
            var scheduledFlightSummary = new ScheduledFlightSummary();

            scheduledFlightSummary.SalesPerPassengerType[PassengerType.AirlineEmployee] = airlineEmployeesSeatsTaken;

            var ruleContext = new ScheduledFlightContext()
            {
                Aircraft = AnyAircraft(numberOfSeats),
                ScheduledFlightSummary = scheduledFlightSummary,
                FlightRoute            = AnyFlightRoute(minTakeOffPercentage)
            };

            var result = _rule.Apply(ruleContext);

            return(result.IsSuccess);
        }
Esempio n. 16
0
 private IEnumerable <Word> ApplyMorphologicalRules(Word input)
 {
     foreach (Word mruleOutWord in _mrulesRule.Apply(input))
     {
         if (mruleOutWord.IsLastAppliedRuleFinal ?? false)
         {
             yield return(mruleOutWord);
         }
         else
         {
             foreach (Word tempOutWord in ApplyTemplates(mruleOutWord))
             {
                 yield return(tempOutWord);
             }
         }
     }
 }
Esempio n. 17
0
        private IEnumerable <Word> ApplyMorphologicalRules(Word input)
        {
            foreach (Word mruleOutWord in _mrulesRule.Apply(input))
            {
                switch (_stratum.MorphologicalRuleOrder)
                {
                case MorphologicalRuleOrder.Linear:
                    yield return(mruleOutWord);

                    break;

                case MorphologicalRuleOrder.Unordered:
                    foreach (Word tempOutWord in ApplyTemplates(mruleOutWord))
                    {
                        yield return(tempOutWord);
                    }
                    yield return(mruleOutWord);

                    break;
                }
            }
        }
Esempio n. 18
0
 public IEnumerable <TError> Apply() => _condition() ? _rule.Apply() : Enumerable.Empty <TError>();
Esempio n. 19
0
 public void RuleApply(IVRiscuitObjectSet globalTable)
 {
     _rule.Apply(_table, globalTable);
 }
Esempio n. 20
0
        public IEnumerable <Word> ParseWord(string word, out object trace)
        {
            // convert the word to its phonetic shape
            Shape shape = _lang.SurfaceStratum.CharacterDefinitionTable.Segment(word);

            var input = new Word(_lang.SurfaceStratum, shape);

            input.Freeze();
            if (_traceManager.IsTracing)
            {
                _traceManager.AnalyzeWord(_lang, input);
            }
            trace = input.CurrentTrace;

            // Unapply rules
            IEnumerable <Word> analyses = _analysisRule.Apply(input);

#if OUTPUT_ANALYSES
            var lines = new List <string>();
            foreach (Word w in analyses)
            {
                string shapeStr = w.ToString();
                string rulesStr = string.Join(", ", w.MorphologicalRules.Select(r => r.Name));
                lines.Add(string.Format("{0} : {1}", shapeStr, rulesStr));
            }

            File.WriteAllLines("analyses.txt", lines.OrderBy(l => l));
#endif

#if SINGLE_THREADED
            IEnumerable <Word> validWords = Synthesize(analyses);
#else
            IEnumerable <Word> validWords = ParallelSynthesize(analyses);
#endif

            var matchList = new List <Word>();
            foreach (IGrouping <IEnumerable <Allomorph>, Word> group in validWords.GroupBy(validWord => validWord.AllomorphsInMorphOrder, MorphsEqualityComparer))
            {
                // enforce the disjunctive property of allomorphs by ensuring that this word synthesis
                // has the highest order of precedence for its allomorphs
                Word[] words = group.ToArray();
                for (int i = 0; i < words.Length; i++)
                {
                    bool disjunctive = false;
                    for (int j = 0; j < words.Length; j++)
                    {
                        if (i == j)
                        {
                            continue;
                        }

                        // if the two parses differ by one allomorph and that allomorph does not free fluctuate and has a lower precedence, than the parse fails
                        Tuple <Allomorph, Allomorph>[] differentAllomorphs = words[i].AllomorphsInMorphOrder.Zip(words[j].AllomorphsInMorphOrder).Where(t => t.Item1 != t.Item2).ToArray();
                        if (differentAllomorphs.Length == 1 && !differentAllomorphs[0].Item1.FreeFluctuatesWith(differentAllomorphs[0].Item2) &&
                            differentAllomorphs[0].Item1.Index >= differentAllomorphs[0].Item2.Index)
                        {
                            disjunctive = true;
                            if (_traceManager.IsTracing)
                            {
                                _traceManager.ParseFailed(_lang, words[i], FailureReason.DisjunctiveAllomorph, null, words[j]);
                            }
                            break;
                        }
                    }

                    if (!disjunctive)
                    {
                        if (_lang.SurfaceStratum.CharacterDefinitionTable.IsMatch(word, words[i].Shape))
                        {
                            if (_traceManager.IsTracing)
                            {
                                _traceManager.ParseSuccessful(_lang, words[i]);
                            }
                            matchList.Add(words[i]);
                        }
                        else if (_traceManager.IsTracing)
                        {
                            _traceManager.ParseFailed(_lang, words[i], FailureReason.SurfaceFormMismatch, null, word);
                        }
                    }
                }
            }
            return(matchList);
        }
Esempio n. 21
0
 protected virtual IEnumerable <TData> ApplyRule(IRule <TData, TOffset> rule, int index, TData input)
 {
     return(rule.Apply(input));
 }
Esempio n. 22
0
        public IEnumerable <string> GenerateWords(LexEntry rootEntry, IEnumerable <Morpheme> otherMorphemes,
                                                  FeatureStruct realizationalFS, out object trace)
        {
            Stack <Tuple <IMorphologicalRule, RootAllomorph> >[] rulePermutations = PermuteRules(otherMorphemes.ToArray())
                                                                                    .ToArray();

            object rootTrace = _traceManager.IsTracing ? _traceManager.GenerateWords(_lang) : null;

            trace = rootTrace;

            var validWordsStack = new ConcurrentStack <Word>();

            Exception exception = null;

            Parallel.ForEach(rootEntry.Allomorphs.SelectMany(a => rulePermutations,
                                                             (a, p) => new { Allomorph = a, RulePermutation = p }), (synthesisInfo, state) =>
            {
                try
                {
                    var synthesisWord = new Word(synthesisInfo.Allomorph, realizationalFS);
                    foreach (Tuple <IMorphologicalRule, RootAllomorph> rule in synthesisInfo.RulePermutation)
                    {
                        synthesisWord.MorphologicalRuleUnapplied(rule.Item1);
                        if (rule.Item2 != null)
                        {
                            synthesisWord.NonHeadUnapplied(new Word(rule.Item2, new FeatureStruct()));
                        }
                    }

                    synthesisWord.CurrentTrace = rootTrace;

                    if (_traceManager.IsTracing)
                    {
                        _traceManager.SynthesizeWord(_lang, synthesisWord);
                    }

                    synthesisWord.Freeze();

                    Word[] valid = _synthesisRule.Apply(synthesisWord).Where(IsWordValid).ToArray();
                    if (valid.Length > 0)
                    {
                        validWordsStack.PushRange(valid);
                    }
                }
                catch (Exception e)
                {
                    state.Stop();
                    exception = e;
                }
            });

            if (exception != null)
            {
                throw exception;
            }

            var words = new List <string>();

            foreach (Word w in CheckDisjunction(validWordsStack.Distinct(FreezableEqualityComparer <Word> .Default)))
            {
                if (_traceManager.IsTracing)
                {
                    _traceManager.Successful(_lang, w);
                }
                words.Add(w.Shape.ToString(_lang.SurfaceStratum.CharacterDefinitionTable, false));
            }
            return(words);
        }