Exemple #1
0
        private Node getNodeToPlay(BasicChessboard chessboard, int totalPlayedTimes)
        {
            Node nodeToPlay = null;

            if (PositionsAvailable.Count > 0)
            {
                nextNodeLock.EnterWriteLock();
                if (PositionsAvailable.Count > 0)
                {
                    nodeToPlay = new Node(PositionsAvailable.Dequeue(), chessboard.NextMoveKind);
                    NextNodes.Add(nodeToPlay);
                }
                nextNodeLock.ExitWriteLock();
            }
            if (nodeToPlay == null)
            {
                nextNodeLock.EnterReadLock();
                nodeToPlay = NextNodes.Aggregate((n1, n2) =>
                {
                    return(n1.GetUCB(totalPlayedTimes) > n2.GetUCB(totalPlayedTimes) ? n1 : n2);
                });
                nextNodeLock.ExitReadLock();
            }

            return(nodeToPlay);
        }
        public virtual IDev2Activity Execute(IDSFDataObject data, int update)
        {
            try
            {
                var className = GetType().Name;
                Tracker.TrackEvent(TrackerEventGroup.ActivityExecution, className);
                _debugInputs  = new List <DebugItem>();
                _debugOutputs = new List <DebugItem>();
                ExecuteTool(data, update);
            }
            catch (Exception ex)
            {
                data.Environment.AddError(ex.Message);
                Dev2Logger.Log.Error("OnExecute", ex);
            }
            finally
            {
                if (!_isExecuteAsync || _isOnDemandSimulation)
                {
                    DoErrorHandling(data, update);
                }
            }


            if (NextNodes != null && NextNodes.Any())
            {
                return(NextNodes.First());
            }
            return(null);
        }
 public void Add(IWorkflowNode node)
 {
     if (node != null)
     {
         NextNodes.Add(node);
     }
 }
        public virtual IDev2Activity Execute(IDSFDataObject data)
        {
            try
            {
                var className = GetType().Name;
                Tracker.TrackEvent(TrackerEventGroup.ActivityExecution, className);

                ExecuteTool(data);
            }
            catch (Exception ex)
            {
                Dev2Logger.Log.Error("OnExecute", ex);
                var errorString   = ex.Message;
                var errorResultTO = new ErrorResultTO();
                errorResultTO.AddError(errorString);
            }
            finally
            {
                if (!_isExecuteAsync || _isOnDemandSimulation)
                {
                    DoErrorHandling(data);
                }
            }


            if (NextNodes != null && NextNodes.Count() > 0)
            {
                NextNodes.First().Execute(data);
                return(NextNodes.First());
            }
            return(null);
        }
 public void AddNextNode(VariableReferenceNode node)
 {
     if (node == null)
     {
         return;
     }
     NextNodes.Add(node);
     node.PreviousNodes.Add(this);
 }
 public override IDev2Activity Execute(IDSFDataObject data)
 {
     ExecuteTool(data);
     if (NextNodes != null && NextNodes.Count() > 0)
     {
         NextNodes.First().Execute(data);
         return(NextNodes.First());
     }
     return(null);
 }
Exemple #7
0
 public void Add(Node node)
 {
     lock (NextNodes)
     {
         if (!VistedNodes.Contains(node) && NextNodes.Count < MaxWaitCount)
         {
             NextNodes.Enqueue(node);
             lock (VistedNodes)
             {
                 VistedNodes.Add(node);
             }
         }
     }
 }
Exemple #8
0
        public void SendFindNodes()
        {
            var waitsend = MessageLoop.GetWaitSendCount();

            lock (NextNodes)
            {
                for (int i = 0; i < NextNodes.Count && waitsend < MaxFindSendPer; i++)
                {
                    var next = NextNodes.Dequeue();
                    SendFindNode(next);
                    waitsend++;
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// 次の指し手ノードを追加します。
        /// </summary>
        public void AddNext(MoveNode node)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            if (node.ParentNode != null)
            {
                throw new InvalidOperationException(
                          "すでに親ノードが登録されています。");
            }

            NextNodes.Add(node);
            node.ParentNode = this;
        }
        /// <summary>
        /// The decision node first delegates decision by calling its decision module to select nodes that are going to be run, from among all candidates nodes.
        /// Based on the decision the graph is being slightly modified. The nodes, which are going to be executed as a result of this decision, are discovered
        /// and their execution status is set to NOTACTIVE.
        /// Their Previous nodes (predecesoor nodes) are modified by removing nodes coming from paths that are not taken as a result of this decision.
        /// This successor nodes are being cleared, and only selected nodes are being added to the collection of the Next Nodes.
        /// Thanks to this solution dispatcher doesn't need to know anything about underlying graph.
        /// </summary>
        public override void RunInternal()
        {
            RunnableNodeCollection selectedNodes = m_decisionModule.Decide(m_candidateNodes);

            if (selectedNodes == null || selectedNodes.Count == 0)
            {
                HasError     = true;
                ErrorMessage = "A decision node must make a decision.";
            }
            else
            {
                // send signal only to selected nodes...
                NextNodes.Clear();
                NextNodes.AddRange(selectedNodes);
            }
        }
Exemple #11
0
        /// <summary>
        /// ノード全体を正規化し、変化の重複などをなくします。
        /// </summary>
        public void Regulalize(int moveCount = 0)
        {
            // 変化の重複を削除します。
            for (var i = 0; i < NextNodes.Count(); ++i)
            {
                for (var j = i + 1; j < NextNodes.Count();)
                {
                    var baseNode = NextNodes[i];
                    var compNode = NextNodes[j];

                    if (baseNode.Move == compNode.Move)
                    {
                        // もし同じ指し手の変化があれば、子の指し手をマージします。
                        // 子の重複チェックはこの後行うので、
                        // ここで重複があっても構いません。
                        compNode.NextNodes.ForEach(_ => _.ParentNode = null);
                        compNode.NextNodes.ForEach(_ => baseNode.AddNext(_));

                        NextNodes.RemoveAt(j);
                    }
                    else
                    {
                        ++j;
                    }
                }
            }

            // 手数の再設定
            MoveCount = moveCount;

            // 子ノードに関してもチェックを行います。
            foreach (var node in NextNodes)
            {
                node.Regulalize(moveCount + 1);
            }
        }
Exemple #12
0
        /// <summary>
        /// ノード全体を文字列化します。
        /// </summary>
        private void MakeString(StringBuilder sb, int nmoves)
        {
            if (Move != null)
            {
                var str    = Move.ToString();
                var hanlen = str.HankakuLength();

                sb.AppendFormat(" - {0}{1}",
                                str, new string(' ', Math.Max(0, 14 - hanlen)));
            }

            if (NextNode != null)
            {
                NextNode.MakeString(sb, nmoves + 1);
            }

            for (var i = 1; i < NextNodes.Count(); ++i)
            {
                sb.AppendLine();
                sb.Append(new string(' ', 17 * nmoves));

                NextNodes[i].MakeString(sb, nmoves);
            }
        }
        public override IDev2Activity Execute(IDSFDataObject data, int update)
        {
            _previousParentId = data.ParentInstanceID;
            _debugInputs?.Clear();
            _debugOutputs?.Clear();
            _dataObject = data;
            _update     = update;
            _originalExecutionEnvironment = data.Environment.Snapshot();

            _suspensionId = "";
            var allErrors = new ErrorResultTO();

            try
            {
                _dataObject.ForEachNestingLevel++;
                if (!_persistenceEnabled)
                {
                    throw new Exception(ErrorResource.PersistenceSettingsNoConfigured);
                }

                if (NextNodes is null)
                {
                    throw new Exception(ErrorResource.NextNodeRequiredForSuspendExecution);
                }

                var persistScheduleValue = PersistSchedulePersistValue();

                if (string.IsNullOrEmpty(persistScheduleValue))
                {
                    throw new Exception(string.Format(ErrorResource.SuspendOptionValueNotSet, GetSuspendValidationMessageType(SuspendOption)));
                }

                var currentEnvironment   = _originalExecutionEnvironment.ToJson();
                var currentuserprincipal = _dataObject.ExecutingUser.Identity.Name;
                var versionNumber        = _dataObject.VersionNumber.ToString();
                var resourceId           = _dataObject.ResourceID;
                if (EncryptData)
                {
                    currentEnvironment   = DpapiWrapper.Encrypt(currentEnvironment);
                    currentuserprincipal = DpapiWrapper.Encrypt(currentuserprincipal);
                }

                var firstActivity = NextNodes.First();
                var activityId    = Guid.Parse(firstActivity?.UniqueID ??
                                               throw new Exception(GlobalConstants.NextNodeIDNotFound));
                var values = new Dictionary <string, StringBuilder>
                {
                    { "resourceID", new StringBuilder(resourceId.ToString()) },
                    { "environment", new StringBuilder(currentEnvironment) },
                    { "startActivityId", new StringBuilder(activityId.ToString()) },
                    { nameof(versionNumber), new StringBuilder(versionNumber) },
                    { nameof(currentuserprincipal), new StringBuilder(currentuserprincipal) }
                };

                if (_dataObject.IsDebugMode())
                {
                    var debugItemStaticDataParams = new DebugItemStaticDataParams("Allow Manual Resumption: " + AllowManualResumption, "", true);
                    AddDebugInputItem(debugItemStaticDataParams);
                }

                DispatchDebug(_dataObject, StateType.Before, _update);
                _suspensionId = _scheduler.CreateAndScheduleJob(SuspendOption, persistScheduleValue, values);

                _dataObject.ParentInstanceID = UniqueID;
                _dataObject.IsDebugNested    = true;
                DispatchDebug(_dataObject, StateType.After, _update);

                Response = _suspensionId;
                _dataObject.Environment.Assign(Result, Response, 0);
                _dataObject.Environment.CommitAssign();
                _stateNotifier?.LogActivityExecuteState(this);
                Dev2Logger.Debug($"{_dataObject.ServiceName} execution suspended: SuspensionId {_suspensionId} scheduled", GlobalConstants.WarewolfDebug);
                if (AllowManualResumption)
                {
                    ExecuteSaveDataFunc();
                }

                if (_dataObject.IsServiceTestExecution && _originalUniqueID == Guid.Empty)
                {
                    _originalUniqueID = Guid.Parse(UniqueID);
                }
            }
            catch (Hangfire.BackgroundJobClientException)
            {
                LogException(new Exception(ErrorResource.BackgroundJobClientCreateFailed), allErrors);
            }
            catch (Exception ex)
            {
                _stateNotifier?.LogExecuteException(ex, this);
                LogException(ex, allErrors);
            }
            finally
            {
                var serviceTestStep = HandleServiceTestExecution(_dataObject);
                _dataObject.ParentInstanceID = _previousParentId;
                _dataObject.ForEachNestingLevel--;
                _dataObject.IsDebugNested = false;
                HandleDebug(_dataObject, serviceTestStep);
                HandleErrors(_dataObject, allErrors);
            }
            return(null); //fire once the rest should be done on resumption service
        }
Exemple #14
0
 public void AddNextNode(VariableReferenceNode node)
 {
     NextNodes.Add(node);
     node.PreviousNodes.Add(this);
 }
        protected override List <string> PerformExecution(Dictionary <string, string> evaluatedValues)
        {
            _errorsTo     = new ErrorResultTO();
            _suspensionId = "";
            var allErrors  = new ErrorResultTO();
            var dataObject = _dataObject;

            try
            {
                dataObject.ForEachNestingLevel++;
                if (!_persistenceEnabled)
                {
                    throw new Exception(ErrorResource.PersistenceSettingsNoConfigured);
                }

                if (NextNodes is null)
                {
                    throw new Exception(ErrorResource.NextNodeRequiredForSuspendExecution);
                }

                var activityId = Guid.Parse(NextNodes.First()?.UniqueID ??
                                            throw new Exception(GlobalConstants.NextNodeIDNotFound));
                var currentEnvironment   = _dataObject.Environment.ToJson();
                var currentuserprincipal = _dataObject.ExecutingUser.Identity.Name;
                var versionNumber        = _dataObject.VersionNumber.ToString();
                if (EncryptData)
                {
                    currentEnvironment   = DpapiWrapper.Encrypt(currentEnvironment);
                    currentuserprincipal = DpapiWrapper.Encrypt(currentuserprincipal);
                }

                var values = new Dictionary <string, StringBuilder>
                {
                    { "resourceID", new StringBuilder(_dataObject.ResourceID.ToString()) },
                    { "environment", new StringBuilder(currentEnvironment) },
                    { "startActivityId", new StringBuilder(activityId.ToString()) },
                    { nameof(versionNumber), new StringBuilder(_dataObject.VersionNumber.ToString()) },
                    { nameof(currentuserprincipal), new StringBuilder(currentuserprincipal) }
                };
                var persistScheduleValue = PersistSchedulePersistValue();
                if (_dataObject.IsDebugMode())
                {
                    var debugItemStaticDataParams = new DebugItemStaticDataParams("Allow Manual Resumption: " + AllowManualResumption, "", true);
                    AddDebugInputItem(debugItemStaticDataParams);
                }

                DispatchDebug(dataObject, StateType.Before, _update);
                _suspensionId = _scheduler.CreateAndScheduleJob(SuspendOption, persistScheduleValue, values);

                dataObject.ParentInstanceID = UniqueID;
                dataObject.IsDebugNested    = true;
                DispatchDebug(dataObject, StateType.After, _update);

                Response = _suspensionId;
                _dataObject.Environment.Assign(Result, _suspensionId, 0);
                _dataObject.Environment.CommitAssign();
                _stateNotifier?.LogActivityExecuteState(this);
                Dev2Logger.Debug($"{_dataObject.ServiceName} execution suspended: SuspensionId {_suspensionId} scheduled", GlobalConstants.WarewolfDebug);
                if (AllowManualResumption)
                {
                    ExecuteSaveDataFunc();
                }

                if (_dataObject.IsServiceTestExecution && _originalUniqueID == Guid.Empty)
                {
                    _originalUniqueID = Guid.Parse(UniqueID);
                }

                _dataObject.StopExecution = true;
                return(new List <string> {
                    _suspensionId
                });
            }
            catch (Exception ex)
            {
                _stateNotifier?.LogExecuteException(ex, this);
                Dev2Logger.Error(nameof(SuspendExecutionActivity), ex, GlobalConstants.WarewolfError);
                _dataObject.StopExecution = true;
                allErrors.AddError(ex.GetAllMessages());
                throw;
            }
            finally
            {
                var serviceTestStep = HandleServiceTestExecution(dataObject);
                dataObject.ParentInstanceID = _previousParentId;
                dataObject.ForEachNestingLevel--;
                dataObject.IsDebugNested = false;
                HandleDebug(dataObject, serviceTestStep);
                HandleErrors(dataObject, allErrors);
            }
        }
Exemple #16
0
        public TalkNode(string path)
        {
            Log.Debug($"Parsing node {path}", Plugin.Instance.Config.VerboseOutput);
            NodeFile = path;
            try
            {
                var input        = new StringReader(File.ReadAllText(path));
                var deserializer = new DeserializerBuilder()
                                   .WithNamingConvention(CamelCaseNamingConvention.Instance)
                                   // Workaround to remove YamlAttributesTypeInspector
                                   .WithTypeInspector(inner => inner, s => s.InsteadOf <YamlAttributesTypeInspector>())
                                   .WithTypeInspector(
                    inner => new YamlAttributesTypeInspector(inner),
                    s => s.Before <NamingConventionTypeInspector>()
                    )
                                   .Build();

                TalkNodeSerializationInfo raw_node = deserializer.Deserialize <TalkNodeSerializationInfo>(input);

                Desc  = raw_node.Description;
                Reply = raw_node.Reply;

                //Parse conditions
                //Format:
                //------------
                //conditions:
                // - token: SomeToken
                //   args:
                //    some_arg: some_value
                //    some_arg1: some_value1
                foreach (NpcNodeWithArgsSerializationInfo info in raw_node.Conditions)
                {
                    NodeCondition cond = NodeCondition.GetFromToken(info.Token);
                    if (cond != null)
                    {
                        Log.Debug($"Recognized token: {cond.Name}", Plugin.Instance.Config.VerboseOutput);
                        Conditions.Add(cond, info.Args);
                    }
                    else
                    {
                        Log.Error($"Failed to parse condition: {info.Token} (invalid token)");
                    }
                }

                //Parse actions
                //Format:
                //------------
                //actions:
                // - token: SomeToken
                //   args:
                //    some_arg: some_value
                //    some_arg1: some_value1
                foreach (NpcNodeWithArgsSerializationInfo info in raw_node.Actions)
                {
                    NodeAction cond = NodeAction.GetFromToken(info.Token);
                    if (cond != null)
                    {
                        Log.Debug($"Recognized token: {cond.Name}", Plugin.Instance.Config.VerboseOutput);
                        Actions.Add(cond, info.Args);
                    }
                    else
                    {
                        Log.Error($"Failed to parse action: {info.Token} (invalid token)");
                    }
                }

                //Parse next nodes
                //Format:
                //------------
                //next_nodes:
                // - /relative/path/to/node
                Log.Debug("Parsing next nodes...", Plugin.Instance.Config.VerboseOutput);
                foreach (string item in raw_node.NextNodes)
                {
                    NextNodes.Add(TalkNode.FromFile(Path.Combine(Config.NPCs_nodes_path, item)));
                }
            }
            catch (Exception e)
            {
                Log.Error($"Failed to parse node {path}! {e}");
                this.Desc  = "<ERROR>";
                this.Reply = "<ERROR>";
            }
        }
Exemple #17
0
 /// <summary>
 /// Adds the node to the collection of successor nodes.
 /// </summary>
 /// <param name="nextNode">The next node.</param>
 public virtual void AddNextNode(IRunnableNode nextNode)
 {
     NextNodes.Add(nextNode);
 }
Exemple #18
0
        /// <summary>
        /// creates the next nodes in the tree
        /// </summary>
        private void SetNextNodesNew()
        {
            //get all outgoing messages
            var outgoing  = this.Current.Connections.Where(t => (t is Message || t is LostMessage) && t.FromObject != null && t.FromObject == this.Current).Where(t => t.Locationy <= IncomingHeight);
            var coregions = this.Current.ParentModel.ObjectList.Where(t => t is CoregionBox && Math.Abs((t as CoregionBox).Locationx - this.Current.Locationx) < 1);
            var messages  = new HashSet <Connection>();

            //check if next messages (or coregions) exist, return if not
            if (outgoing.Any() || coregions.Any())
            {
                //get next outgoing connection
                List <Connection> nextmessagesList = new List <Connection>();
                if (outgoing.Any())
                {
                    //order
                    var outgoingordered = outgoing.OrderByDescending(t => t.Locationy).ToList();

                    //handle lost messages as if they were async
                    //add lostmessages to list until normal message found
                    for (int i = 0; i < outgoingordered.Count; i++)
                    {
                        nextmessagesList.Add(outgoingordered[i]);
                        if (!(outgoingordered[i] is LostMessage))
                        {
                            break;
                        }
                    }
                }

                //check if a coregion exists before. if so, use those connections instead
                if (coregions.Any())
                {
                    var fittingCoregions = coregions.Where(t => t.Locationtopleft.Y < this.IncomingHeight);
                    if (nextmessagesList.Any() && fittingCoregions.Any())
                    {
                        fittingCoregions = fittingCoregions.Where(t => t.Locationtopleft.Y > nextmessagesList.First().Locationy).ToList();
                    }

                    if (fittingCoregions.Any())
                    {
                        //coregion found, replace nextmessages with coregion outgoing messages
                        nextmessagesList.Clear();
                        var coregionmax = fittingCoregions.MaxBy(t => t.Locationy) as Item;
                        var coregionOutgoingMessages = coregionmax.Connections.Where(t => t.FromObject == fittingCoregions.MaxBy(r => r.Locationy));
                        nextmessagesList.AddRange(coregionOutgoingMessages);

                        //special case: lost messages between coregion and incoming message
                        var lostmessagesbetweencoregion = outgoing.Where(t => t is LostMessage && t.Locationy < coregionmax.Locationy);
                        if (lostmessagesbetweencoregion.Any())
                        {
                            nextmessagesList.AddRange(lostmessagesbetweencoregion);
                        }
                    }
                }

                //check if a nextmessage still exists
                if (!nextmessagesList.Any())
                {
                    return;
                }

                foreach (var nextmessage in nextmessagesList)
                {
                    //check if nextmessage enters a new container
                    HashSet <BMSCInlineExpressionAltPar> newcontainers = nextmessage.Containers.Where(t => t is BMSCInlineExpressionAltPar && !EnteredContainers.Contains(t))
                                                                         .Cast <BMSCInlineExpressionAltPar>()
                                                                         .ToHashSet <BMSCInlineExpressionAltPar>();
                    if (newcontainers.Any())
                    {
                        //add containers from split message as well
                        var newsplitcontainers = newcontainers.First().ObjectsBelowLine.Where(t => t is Connection)
                                                 .Cast <Connection>().MaxBy(t => t.Locationy).Containers.Cast <BMSCInlineExpressionAltPar>();
                        foreach (BMSCInlineExpressionAltPar nc in newsplitcontainers)
                        {
                            newcontainers.Add(nc);
                        }

                        //iterate through all new containers. pick each top and bottom message and add to list. no duplicates
                        foreach (BMSCInlineExpressionAltPar newcontainer in newcontainers)
                        {
                            //add to known containers
                            EnteredContainers.Add(newcontainer);

                            //get top top message
                            messages.Add(newcontainer.ObjectsAboveLine.Where(t => t is Connection).Cast <Connection>().MaxBy(t => t.Locationy));

                            //get top bottom mesage
                            messages.Add(newcontainer.ObjectsBelowLine.Where(t => t is Connection).Cast <Connection>().MaxBy(t => t.Locationy));
                        }
                    }
                    //nextmessage does not enter a new container
                    else
                    {
                        //check if swaps, meaning next message in lower container and previous in upper
                        var swappingContainers =
                            nextmessage.Containers.Where(
                                t => ((BMSCInlineExpressionAltPar)t).ObjectsAboveLine.Contains(IncomingMessage) &&
                                ((BMSCInlineExpressionAltPar)t).ObjectsBelowLine.Contains(nextmessage));
                        if (swappingContainers.Any())
                        {
                            //if swap, pick next message NOT in the swapping container
                            if (swappingContainers.Count() > 1)
                            {
                                throw new Exception("unexcepted result. more than one swapping container found.");
                            }

                            //check if another outgoing message exists
                            var nextoutgoing = outgoing.Where(t => !swappingContainers.First().ContainingItems.Contains(t));
                            if (nextoutgoing.Any())
                            {
                                messages.Add(nextoutgoing.MaxBy(t => t.Locationy));
                            }
                        }
                        //no swap, pick next message
                        else
                        {
                            messages.Add(nextmessage);
                        }
                    }
                }

                //create new nodes for each message
                foreach (var newmessage in messages)
                {
                    //case: newmessage is LostMessage: find corresponding found message as next node if exists
                    if (newmessage is LostMessage)
                    {
                        //check for foundmessage
                        var foundmessage = (FoundMessage)this.Current.ParentModel.ObjectList.FirstOrDefault(t => t is FoundMessage && t.Locationy < newmessage.Locationy && ((FoundMessage)t).Text == newmessage.Text);
                        if (foundmessage != null)
                        {
                            NextNodes.Add(new BmscNode((Item)foundmessage.ToObject, (Message)foundmessage, this.CurrentDepth + 1, foundmessage.Locationy, EnteredContainers));
                            NextMessages.Add((Message)newmessage);
                        }
                    }
                    else
                    {
                        NextNodes.Add(new BmscNode((Item)newmessage.ToObject, (Message)newmessage, this.CurrentDepth + 1, newmessage.Locationy, EnteredContainers));
                        NextMessages.Add((Message)newmessage);
                    }
                }
            }
        }