Example #1
0
 /// <summary>
 /// Remove a decision from the list of decisions that the human needs to make. It can always be added later
 /// </summary>
 public void RemoveDecision(Decision decision)
 {
     if (Decisions.RemoveAll(match => match == decision) > 0) // I have to use a predicate because I overrode `Decision.Equals` //TODO: wtf is this kid on about
     {
         RefreshBannedSubjectsList();
     }
 }
Example #2
0
        protected bool isNotSplitted = true;          // Is player hand not splited. We can split the hand only one time.

        public Player(byte dealersFirst, uint money, Decks playingDecks, uint wager = 0)
        {
            Money            = money;
            FirstWager       = wager;
            Money           -= FirstWager;
            PlayersDecisions = new Decisions[21];
            PlayingDecks     = new Decks();
            PlayingDecks     = playingDecks;
            for (int i = 0; i < 21; i++)
            {
                PlayersDecisions[i] = 0;
            }
            dealerCard = dealersFirst;
            FirstHand  = new byte[21];
            for (int i = 2; i < 21; i++)
            {
                FirstHand[i] = 0;
            }
            SecondHand = new byte[21];
            for (int i = 0; i < 21; i++)
            {
                SecondHand[i] = 0;
            }
            FirstHand[0] = PlayingDecks.GetCard();
            FirstHand[1] = PlayingDecks.GetCard();
            FirstSum     = 0;
            SecondSum    = 0;
        }
Example #3
0
 internal void Add(Decision decision)
 {
     if (decision != null)
     {
         Decisions.Add(decision);
     }
 }
        private static ScaleSetVirtualMachineStripped[] GetInstanceIds(IEnumerable <ScaleSetVirtualMachineStripped> vmScaleSetData, int poolId = TestsConstants.TestPoolId, string jsonData = TestsConstants.Json1JobIsRunning)
        {
            var dataRetriever = RetrieveTests.CreateRetriever(jsonData);

            return(Decisions.CollectInstanceIdsToDeallocate(vmScaleSetData.Where(vm => vm.VmInstanceState.Equals(PowerState.Running)),
                                                            dataRetriever.GetRuningJobs(poolId)));
        }
Example #5
0
 private void SaveDecisions()
 {
     foreach (var decision in Decisions.Where(decision => decision.Changed))
     {
         decision.SaveChanges();
     }
 }
Example #6
0
        public void WhenCodeIsDifferent_SeedDifferent_DecisionsDontMatch()
        {
            Random seedGenerator = new Random();

            Random random1;
            Random random2;

            Decisions decisions1 = CreateDecision(seedGenerator.Next(), out random1);
            Decisions decisions2 = CreateDecision(seedGenerator.Next(), out random2);

            bool match = true;

            for (int j = 0; j < 10000; j++)
            {
                int rnd1 = random1.Next();
                int rnd2 = random2.Next();

                Decisions.Outcome outcome1 = decisions1.GetDecision(rnd1);
                Decisions.Outcome outcome2 = decisions2.GetDecision(rnd2);

                match = match & outcome1 == outcome2;
            }

            Assert.IsFalse(match);
        }
Example #7
0
    void ShowHideTasks(bool showAddDetergent, bool showHotColdWash, bool showWashLength, bool showWetClothes, bool showFeedback)
    {
        // Canvas elements don't have a SetActive method, but they have an 'enabled' property

        if (showAddDetergent)
        {
            firstDetergent.GetComponent <MeshRenderer>().material  = badDetergent;
            secondDetergent.GetComponent <MeshRenderer>().material = avgDetergent;
            thirdDetergent.GetComponent <MeshRenderer>().material  = goodDetergent;
        }
        else
        {
            firstDetergent.GetComponent <MeshRenderer>().material  = defaultDetergent;
            secondDetergent.GetComponent <MeshRenderer>().material = defaultDetergent;
            thirdDetergent.GetComponent <MeshRenderer>().material  = defaultDetergent;
        }

        wetClothes.SetActive(showWetClothes);
        hotColdWash.enabled   = showHotColdWash;
        longShortWash.enabled = showWashLength;

        if (showFeedback)
        {
            feedbackText.text = Decisions.GetFeedback();
        }

        feedback.enabled = showFeedback;
    }
Example #8
0
        public void WhenCodeIsSame_SeedSame_DecisionsMatch()
        {
            Random seedGenerator = new Random();

            int seed = seedGenerator.Next();

            Random random1;
            Random random2;

            Decisions decisions1 = CreateDecision(seed, out random1);
            Decisions decisions2 = CreateDecision(seed, out random2);

            Dictionary <Decisions.Outcome, int> outcomeCount = new Dictionary <Decisions.Outcome, int> {
                { Decisions.Outcome.True, 0 },
                { Decisions.Outcome.False, 0 },
                { Decisions.Outcome.Die, 0 }
            };

            for (int j = 0; j < 10000; j++)
            {
                int rnd1 = random1.Next();
                int rnd2 = random2.Next();

                Assert.AreEqual(rnd1, rnd2);

                Decisions.Outcome outcome1 = decisions1.GetDecision(rnd1);
                Decisions.Outcome outcome2 = decisions2.GetDecision(rnd2);

                outcomeCount [outcome1]++;

                Assert.AreEqual(outcome1, outcome2);
            }
        }
Example #9
0
        private static void DeallocateVms(IEnumerable <ScaleSetVirtualMachineStripped> vmInstances, IVirtualMachineScaleSet scaleSet, int agentsCountToDeallocate)
        {
            var virtualMachinesCounter = 0;

            foreach (var vmInstance in vmInstances)
            {
                if (virtualMachinesCounter >= agentsCountToDeallocate)
                {
                    break;
                }
                Console.WriteLine($"Deallocating VM with instance ID {vmInstance}");
                virtualMachinesCounter++;
                if (Properties.IsDryRun)
                {
                    continue;
                }

                if (Decisions.IsVmExecutingJob(vmInstance.VmName))
                {
                    //this VM just got job assigned, so we should not deallocate it
                    continue;
                }

                scaleSet.VirtualMachines.Inner.BeginDeallocateWithHttpMessagesAsync(Properties.VmScaleSetResourceGroupName, Properties.VmScaleSetName,
                                                                                    vmInstance.VmInstanceId);
            }
        }
Example #10
0
        // The relationship between literal and installed map:
        //
        // |----------------------------------------------|
        // |             |   installed   |  un-installed  |
        // |==============================================|
        // |      +      |     keep      |    install     |
        // |----------------------------------------------|
        // |      -      |   uninstall   | don't install  |
        // |----------------------------------------------|

        /// <summary>
        /// Initializes a new instance of the <see cref="Transaction"/> class.
        /// </summary>
        public Transaction(IPolicy policy, Pool pool, IDictionary <int, IPackage> installedMap, Decisions decisions)
        {
            this.policy       = policy;
            this.pool         = pool;
            this.installedMap = installedMap;
            this.decisions    = decisions;
            transaction       = new LinkedList <IOperation>();
        }
Example #11
0
 private void LoadStakeholders()
 {
     Stakeholders.Clear();
     foreach (var stakeholder in Decisions.SelectMany(decision => decision.Stakeholders).Distinct())
     {
         Stakeholders.Add(stakeholder.Stakeholder);
     }
 }
Example #12
0
    void LoadEatDecision(Creature creature)
    {
        Decisions decisions = creature.DecisionsLookup [Creature.DecisionTypes.Eat];

        decisions.ClearTransientValues();
        decisions.LoadTransientValue(new Value(creature.Energy, "Current Energy"));

        _eatDecisionText.Buffer.Text = decisions.GetDecisionProvider(creature.DecisionPredicateIndex_Eat).Describe();
    }
Example #13
0
        public override void Resolve()
        {
            Target.Card().ReturnToHand();

            if (Discard > 0)
            {
                Decisions.EnqueueDiscardCards(Target.Card().Controller, Discard);
            }
        }
        public static void AmountOfAgentsWithBusinessTimesSet(int jobsCount, int agentsCount, int maxAgentsCount, string testDateTime, int expectedAmount)
        {
            TestInitilizers.InitAppSettingsForBusinessTimesTests();
            Clock.TestApi.Now = () => TestInitilizers.ParseDateTimeForTest(testDateTime);
            var amount = Decisions.HowMuchAgents(jobsCount, agentsCount, maxAgentsCount);

            Assert.AreEqual(expectedAmount, amount);
            Clock.TestApi.Reset();
        }
Example #15
0
 public StepDecision(Decision decision, WorkflowState wfState = null)
     : this()
 {
     if (decision != null)
     {
         Decisions.Add(decision);
     }
     WfState = wfState;
 }
Example #16
0
        /// <summary>
        /// Propagates a decision on a literal to all rules watching the literal.
        /// </summary>
        /// <remarks>
        /// If a decision, e.g. +A has been made, then all rules containing -A, e.g.
        /// (-A|+B|+C) now need to satisfy at least one of the other literals, so
        /// that the rule as a whole becomes true, since with +A applied the rule
        /// is now (false|+B|+C) so essentially (+B|+C).
        /// This means that all rules watching the literal -A need to be updated to
        /// watch 2 other literals which can still be satisfied instead. So literals
        /// that conflict with previously made decisions are not an option.
        /// Alternatively it can occur that a unit clause results: e.g. if in the
        /// above example the rule was (-A|+B), then A turning true means that
        /// B must now be decided true as well.
        /// </remarks>
        /// <param name="decidedLiteral">The literal which was decided.</param>
        /// <param name="level">The level at which the decision took place and at which all resulting decisions should be made.</param>
        /// <param name="decisions">Used to check previous decisions and to register decisions resulting from propagation.</param>
        /// <returns>If a conflict is found the conflicting rule is returned.</returns>
        public Rule PropagateLiteral(int decidedLiteral, int level, Decisions decisions)
        {
            // we invert the decided literal here, example:
            // A was decided => (-A|B) now requires B to be true, so we look for
            // rules which are fulfilled by -A, rather than A.
            // This means finding out the conflicts or requires.
            var literal = -decidedLiteral;

            if (!watchChains.TryGetValue(literal, out LinkedList <RuleWatchNode> chain))
            {
                return(null);
            }

            foreach (var node in chain.ToArray())
            {
                var otherWatch = node.GetOtherWatch(literal);
                if (!node.GetRule().Enable || decisions.IsSatisfy(otherWatch))
                {
                    continue;
                }

                var ruleLiterals        = node.GetRule().GetLiterals();
                var alternativeLiterals = Arr.Filter(ruleLiterals, (ruleLiteral) =>
                {
                    // Guaranteed selection decision is not at the same time
                    // as Watch1 and Watch2, guaranteeing no conflict.
                    return(literal != ruleLiteral && otherWatch != ruleLiteral && !decisions.IsConflict(ruleLiteral));
                });

                if (alternativeLiterals.Length > 0)
                {
                    var toLiteral = alternativeLiterals[0];

                    if (!watchChains.TryGetValue(toLiteral, out LinkedList <RuleWatchNode> toChain))
                    {
                        watchChains[toLiteral] = toChain = new LinkedList <RuleWatchNode>();
                    }

                    node.MoveWatch(literal, toLiteral);
                    chain.Remove(node);
                    toChain.AddFirst(node);
                    continue;
                }

                if (decisions.IsConflict(otherWatch))
                {
                    return(node.GetRule());
                }

                decisions.Decide(otherWatch, level, node.GetRule());
            }

            return(null);
        }
Example #17
0
 // Use this for initialization
 void Start()
 {
     InMove          = false;
     InPause         = false;
     decisions       = transform.GetComponent <Decisions>();
     CurrentSel      = Camera.main.GetComponent <selection>();
     CurrentRC       = Camera.main.GetComponent <RoundCounter>();
     playerBList     = new List <Transform>();
     firstPhaseList  = new List <Transform>();
     secondPhaseList = new List <Transform>();
     thirdPhaseList  = new List <Transform>();
 }
Example #18
0
        public void DecisionsRunWithoutException()
        {
            Random seedGenerator = new Random();
            Random random;

            Decisions decisions = CreateDecision(seedGenerator.Next(), out random);

            for (int i = 0; i < 1000; i++)
            {
                decisions.GetDecision(random.Next());
            }
        }
        public DmnDefinitionBuilderEx WithLogicalAndDecision(
            string name,
            Action <LogicalAndDecision> builder,
            out Decision.Ref decisionRef)
        {
            var decision = new LogicalAndDecision(Variables, Decisions, name);

            decisionRef = decision.Reference;
            Decisions.AddDecision(decision);
            builder?.Invoke(decision);
            return(this);
        }
Example #20
0
        public Game()
        {
            AddParameter(new Parameter(ParameterIds.HappinessSensitivity, "Happiness Sensitivity", 0.25, 0, 1));  // How quickly happiness follows Satisfaction, 0: never, 1: immediately

            Date = new Date(2013, 1, 1);

            ProductTypes.Add(new ProductType("Food", 0.5, 1));
            ProductTypes.Add(new ProductType("Clothes", 1, 1));

            Country = new Polity.Country(StartPopulation);

            Event e = new Event("Discovery");

            e.Condition = new ChanceCondition(0.01);
            e.Effect    = new MultipleEffects();
            e.AddEffect(new MessageEffect("New technologies increase productivity!"));
            e.AddEffect(new ChangeParameterEffect(Country, ParameterIds.Productivity, 1, 0.05));

            e             = new Event("MPs Propose to Lower Taxes");
            e.Condition   = new ChanceCondition(0.3);
            e.HappensOnce = true;
            Issues iss = new Issues();

            iss.AddIssue(IssueIds.Populism, 1);
            iss.AddIssue(IssueIds.BigGovernment, -1);
            e.Effect = new SubmitBillEffect(new Bill(iss, new ChangeParameterEffect(Country, ParameterIds.IncomeTaxRate, 1, -0.05)), Country.Parliament);
            Events.Add(e);

            Decision d = new Decision("Celebrate");

            d.DisplayCondition = new HasMoneyCondition(Country.Budget, 5);
            d.Effect           = new MessageEffect("We have lots of money! Hurray!");
            Decisions.Add(d);

            d   = new Decision("Decrease Income Tax");
            iss = new Issues();
            iss.AddIssue(IssueIds.Populism, 0.5);
            iss.AddIssue(IssueIds.BigGovernment, -0.5);
            d.Effect = new SubmitBillEffect(new Bill(iss, new ChangeParameterEffect(Country, ParameterIds.IncomeTaxRate, 1, -0.02)), Country.Parliament);
            Decisions.Add(d);

            d   = new Decision("Increase Income Tax");
            iss = new Issues();
            iss.AddIssue(IssueIds.Populism, -0.5);
            iss.AddIssue(IssueIds.BigGovernment, 0.5);
            d.Effect = new SubmitBillEffect(new Bill(iss, new ChangeParameterEffect(Country, ParameterIds.IncomeTaxRate, 1, 0.02)), Country.Parliament);
            Decisions.Add(d);

            d = new Decision("See Invisible Pink Unicorn");
            d.DisplayCondition = new ConstCondition(false);
            d.Effect           = new MessageEffect("Wow! Here it is: the invisible pink unicorn");
            Decisions.Add(d);
        }
Example #21
0
    void HandleWetClothes()
    {
        string destination = DestinationObject.GetWetClothesDestination();

        if (destination == "Dryer")
        {
            Decisions.AddChoice("Dryer");
        }
        else if (destination == "Clothesline")
        {
            Decisions.AddChoice("Clothesline");
        }
    }
Example #22
0
        private void LoadDecisions()
        {
            Decisions.Clear();
            foreach (var decision in GetDecisionsForTopic())
            {
                Decisions.Add(Decision.Load(decision, false));
            }
            var temp = Utils.SortDecisionsByState(Decisions.ToList());

            Decisions = new BindingList <IDecision>(temp);
            Decisions.RaiseListChangedEvents = true;
            Decisions.ListChanged           += ListMemberChanged;
        }
Example #23
0
        public static Decisions AfficheErreurs(CPileErreur pile)
        {
            CFormErreurValidation form = new CFormErreurValidation();

            form.m_erreurs = pile;
            Decisions decision = Decisions.Corriger;

            if (form.ShowDialog() == DialogResult.OK)
            {
                decision = form.m_decision;
            }
            form.Dispose();
            return(decision);
        }
Example #24
0
        /// <summary>
        /// Resolve the requires of the requested.
        /// </summary>
        /// <param name="request">The request instance.</param>
        /// <param name="ignorePlantform">Whether is ignore plantform check.</param>
        /// <returns>An array of operation.</returns>
        public IOperation[] Solve(Request request, bool ignorePlantform = false)
        {
            jobs = request.GetJobs();

            SetupInstalledMap();
            rules = ruleSetGenerator.GetRulesFor(jobs, installedMap, ignorePlantform);
            CheckForRootRequiresProblems(ignorePlantform);

            decisions  = new Decisions(pool);
            watchGraph = new RuleWatchGraph();
            learnedWhy.Clear();
            learnedPool.Clear();
            branches.Clear();

            foreach (var rule in rules)
            {
                watchGraph.Add(rule);
            }

            SetupAssertionRuleDecisions();

            io.WriteError("Resolving requires through SAT", true, Verbosities.Debug);
            stopwatch.Restart();
            stopwatch.Start();

            RunSAT();

            io.WriteError(string.Empty, true, Verbosities.Debug);
            io.WriteError($"Dependency resolution completed in {stopwatch.Elapsed.TotalSeconds.ToString("0.00")} seconds", true, Verbosities.Debug);

            // If we don't make a decision about the packages we have
            // installed, then we think these packages will be uninstall.
            foreach (var item in installedMap)
            {
                var packageId = item.Key;
                if (decisions.IsUndecided(packageId))
                {
                    decisions.Decide(-packageId, 1, null);
                }
            }

            if (problems.Count > 0)
            {
                throw new SolverProblemsException(problems, installedMap);
            }

            var transaction = new Transaction(policy, pool, installedMap, decisions);

            return(transaction.GetOperations());
        }
Example #25
0
        /// <summary>
        /// Here we will proceed working with VMSS ((de)provision additional agents, keep current agents count)
        /// </summary>
        /// <param name="onlineAgents"></param>
        /// <param name="maxAgentsInPool"></param>
        /// <param name="areWeCheckingToStartVmInVmss">Describes, which functions calls out - provisioning or deprovisioning</param>
        public static void WorkWithVmss(int onlineAgents, int maxAgentsInPool, bool areWeCheckingToStartVmInVmss)
        {
            //working with VMSS
            var vmss            = GetVirtualMachinesScaleSet(Properties.VmScaleSetResourceGroupName, Properties.VmScaleSetName);
            var virtualMachines = vmss.VirtualMachines.List()
                                  //there could be failed VMs during provisioning
                                  .Where(vm => !vm.Inner.ProvisioningState.Equals("Failed", StringComparison.OrdinalIgnoreCase))
                                  .Select(vmssVm => new ScaleSetVirtualMachineStripped
            {
                VmInstanceId    = vmssVm.InstanceId,
                VmName          = vmssVm.ComputerName,
                VmInstanceState = vmssVm.PowerState
            }).ToArray();

            //get jobs again to check, if we could deallocate a VM in VMSS
            //(if it is running a job - it is not wise to deallocate it)
            //since getting VMMS is potentially lengthy operation - we could need this)
            var currentJobs    = Checker.DataRetriever.GetRuningJobs(Properties.AgentsPoolId);
            var amountOfAgents = Decisions.HowMuchAgents(currentJobs.Length, onlineAgents, maxAgentsInPool);
            var addMoreAgents  = amountOfAgents > 0;

            if (amountOfAgents == 0)
            {
                //nevertheless - should we (de)provision agents: we are at boundaries
                Console.WriteLine("Should not add/remove more agents...");
                return;
            }

            //further I need to work with positive numbers only
            amountOfAgents = Math.Abs(amountOfAgents);

            if (addMoreAgents != areWeCheckingToStartVmInVmss)
            {
                //target event is not the same as source one
                return;
            }

            //I wish this record to be processed on it's own; it is just tracking
            RecordDataInTable(addMoreAgents, amountOfAgents);

            if (addMoreAgents)
            {
                AllocateVms(virtualMachines, amountOfAgents, vmss);
            }
            else
            {
                DeallocationWorkWithScaleSet(virtualMachines, currentJobs, vmss, amountOfAgents);
            }
        }
Example #26
0
        public Decision AddDecision(SoftwareSystem softwareSystem, string id, DateTime date, string title, DecisionStatus status, Format format, string content)
        {
            CheckIdIsSpecified(id);
            CheckTitleIsSpecified(title);
            CheckContentIsSpecified(content);
            CheckDecisionStatusIsSpecified(status);
            CheckFormatIsSpecified(format);
            CheckDecisionIsUnique(softwareSystem, id);

            Decision decision = new Decision(softwareSystem, id, date, title, status, format, content);

            Decisions.Add(decision);

            return(decision);
        }
Example #27
0
        /// <summary>
        /// Executes (evaluates) decision with given <paramref name="decisionName"/>
        /// </summary>
        /// <param name="decisionName">Name of the decision to execute</param>
        /// <returns>Decision result</returns>
        /// <exception cref="ArgumentException"><paramref name="decisionName"/> is null or empty</exception>
        /// <exception cref="DmnExecutorException">Decision with <paramref name="decisionName"/> not found</exception>
        public DmnDecisionResult ExecuteDecision(string decisionName)
        {
            if (string.IsNullOrWhiteSpace(decisionName))
            {
                throw Logger.Fatal <ArgumentException>($"{nameof(decisionName)} is null or empty");
            }
            if (!Decisions.ContainsKey(decisionName))
            {
                throw Logger.Fatal <DmnExecutorException>($"ExecuteDecision: - decision {decisionName} not found");
            }

            var decision = Decisions[decisionName];

            return(ExecuteDecision(decision));
        }
Example #28
0
        public Plan(Plan other)
        {
            AssignedTimes = new Dictionary <Subject, Time>(other.AssignedTimes);
            Decisions.AddRange(other.Decisions);

            SelectedSubjects = new List <Subject>(other.SelectedSubjects);
            SelectedCourses  = new List <Course>(other.SelectedCourses);
            foreach (var BannedContent in other.BannedContents)
            {
                BannedContents.Add(BannedContent.Key, new List <Content>(BannedContent.Value));
            }
            EarliestCompletionTimes = new Dictionary <Subject, Time>(other.EarliestCompletionTimes);

            SubjectsWithForcedTimes = new HashSet <Subject>(other.SubjectsWithForcedTimes);
            MaxCreditPoints         = new Dictionary <Time, int>(other.MaxCreditPoints);
            ContentRelations        = new HashSet <Edge>(other.ContentRelations);
        }
Example #29
0
        public IDecision MakeDecision()
        {
            IDecision decision = new NoDecision();

            if (LowHealth < Health && HighHealth > Health)
            {
                if (!StatusEffect.Contains(Code.StatusEffect.Dia))
                {
                    if (Decisions.Contains(typeof(RestDecision)))
                    {
                        decision = new RestDecision();
                    }
                }
            }

            return(decision);
        }
Example #30
0
            private void MergeDecisions()
            {
                var allData      = new List <Decisions>();
                var dataInProper = new List <Decisions>();

                for (int i = 0; i < databases.Length; i++)
                {
                    var l = Decisions.Read(this.databases[i]);
                    if (i == 0)
                    {
                        dataInProper = l;
                    }
                    allData.AddRange(l);
                }
                var toWrite = this.SubtractHashSet(new HashSet <Decisions>(allData), new HashSet <Decisions>(dataInProper));

                Decisions.Insert(this.proper, toWrite);
            }
Example #31
0
 // Use this for initialization
 void Start()
 {
     InMove = false;
     InPause = false;
     decisions = transform.GetComponent<Decisions>();
     CurrentSel = Camera.main.GetComponent<selection>();
     CurrentRC = Camera.main.GetComponent<RoundCounter>();
     playerBList = new List<Transform>();
     firstPhaseList = new List<Transform>();
     secondPhaseList = new List<Transform>();
     thirdPhaseList = new List<Transform>();
 }