Esempio n. 1
0
 public void Initialize(Action action, ActionSelector actionSelector)
 {
     this.actionSelector = actionSelector;
     this.action         = action;
     name = action.name;
     transform.GetChild(0).GetComponent <Text>().text = name;
 }
Esempio n. 2
0
        static void Main()
        {
            ShowProgramHeader();
            bool run = true;

            ActionSelector<string> selector = new ActionSelector<string>(new Type[] { typeof(int), typeof(uint), typeof(ushort), typeof(string) });
            selector.RegisterActionsFromContainer(new MainActionsContainer(_machine, delegate()
            {
                run = false;
            }), true);
            string inputString;

            Console.Write("Loading microprogram.xml..");
            selector.ExecuteCommand("load micro microprogram.xml");
            Console.WriteLine("[done]\n");

            while (run)
            {
                Console.Write(">");
                inputString = Console.ReadLine();
                try
                {
                    Console.WriteLine(selector.ExecuteCommand(inputString));
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }

                Console.WriteLine();
            }
        }
Esempio n. 3
0
        public List <ConfigurationAction> SetConfigurationPrimary(string containerName, string primary)
        {
            List <ConfigurationAction> result = new List <ConfigurationAction>();

            result.Add(ActionSelector.GetMakeSoloPrimaryAction(containerName, primary));
            return(result);
        }
Esempio n. 4
0
        public string HandleRequest(HttpListenerContext ct)
        {
            log.Info("Handle Request");
            string result = "";

            try
            {
                ActionSelector actionselector = new ActionSelector();
                Handlers       messageHandler = new Handlers();
                HandlerData    handlerData    =
                    actionselector.GetHandlerData(ct.Request.HttpMethod + ct.Request.RawUrl);
                string Name = handlerData.handler.Method.Name;
                if (Name.Equals("Authenticate") || Name.Equals("IsAuthenticated") ||
                    Name.Equals("SignOut") || Name.Equals("Touch") ||
                    messageHandler.IsSessionIdOk(ct))
                {
                    result = handlerData.handler(ct, handlerData.actionInfo);
                }
                else
                {
                    throw (new Exception("Not Authenticated."));
                }
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                throw (e);
            }
            return(result ?? "");
        }
Esempio n. 5
0
        /// <summary>Call this method to choose Next action from Action list which is ready CAN OVERRIDE</summary>
        /// <remarks>if action is ready and the distance between player is smaller than the setting distance will add this action to list.Finally choose the action randomly by probability</remarks>
        public virtual void ChooseNextAction( )
        {
            List <Action> ableActions = new List <Action> ( );
            float         distance    = Vector2.Distance(this.tf.position, this.Player.tf.position);
            Action        actResult;

            //先將可以使用的行動收集起來
            foreach (Action act in this.Actions)
            {
                if (act.IsCanUse && act.Distance >= distance)
                {
                    ableActions.Add(act);
                }
            }
            //從中選出行動
            if (ableActions.Count == 0)
            {
                return;
            }
            actResult = ableActions [ActionSelector.SelectWithProbability(ableActions)];
            actResult.ResetCD( );
            //根據行動切換對應的動畫
            if (actResult.Trigger != "")
            {
                this.Animator.SetTrigger(actResult.Trigger);
            }
        }
        public void should_select_action_when_single_action_name_matches()
        {
            var actions       = GetTestActions();
            var commandAction = new ActionSelector().Select("my-action", null, actions);

            Assert.That(commandAction.Name, Is.EqualTo("my-action"));
        }
        public FormRobotControl()
        {
            InitializeComponent();

            // Definition
            globalDataSet   = new GlobalDataSet();
            helperFunctions = new HelperFunctions(globalDataSet);
            dataPackager    = new DataPackager(globalDataSet);
            tcpServer       = new ServerUnit(globalDataSet);

            // Initialize
            sampleStep  = DEFAULT_SAMPLE_TIME_FACTOR;
            aliveBit    = false;
            notExecuted = true;

            // User defines
            globalDataSet.DebugMode           = false;
            globalDataSet.ShowProgramDuration = false;

            // Set event that is fired by datapackager named newPackageEvent with method dataPackageReceived (listener: server)
            // Set event that is fired by server named newServerEvent with method dataPackageServerReceived (listener: dataPackager)
            dataPackager.newPackageEvent += new DataPackager.DataPackagedEventHandler(tcpServer.dataPackageReceived);

            // Start server
            tcpServer.startServer();

            // Start thread to package data (the data were packaged before the client is connected
            dataPackager.startPackaging();

            // Check sensor alive in background
            indicatorLedThread = new Thread(new ThreadStart(indicatorLed));
            indicatorLedThread.Start();

            ActionSelector actionSelector = new ActionSelector(globalDataSet);
        }
Esempio n. 8
0
    //When the character interact with this selectable, check all the actions and see if any should be triggered.
    public void Use(PlayerCharacter character)
    {
        if (enabled)
        {
            ItemSlot islot   = InventoryBar.Get().GetSelectedSlot();
            ItemSlot eslot   = EquipBar.Get().GetSelectedSlot();
            ItemSlot slot    = eslot != null ? eslot : islot;
            MAction  maction = slot != null && slot.GetItem() != null?slot.GetItem().FindMergeAction(this) : null;

            AAction aaction = FindAutoAction();
            if (maction != null && maction.CanDoAction(character, this))
            {
                maction.DoAction(character, slot, this);
                TheUI.Get().CancelSelection();
            }
            else if (aaction != null && aaction.CanDoAction(character, this))
            {
                aaction.DoAction(character, this);
            }
            else if (actions.Length > 0)
            {
                ActionSelector.Get().Show(character, this);
            }

            if (onUse != null)
            {
                onUse.Invoke(character);
            }
        }
    }
Esempio n. 9
0
        private void SetupActionSelector()
        {
            ActionSelector.Add("Authenticate", "POST", "/authentication/rest/authenticate", "", "", messageHandler.Authenticate);
            ActionSelector.Add("Touch", "GET", "/authentication/rest/touch", "", "", messageHandler.Touch);
            ActionSelector.Add("GetCurrentUser", "GET", "/users/rest/currentuser", "", "", messageHandler.GetCurrentUser);
            ActionSelector.Add("GetCurrentCustomer", "GET", "/accounts/rest/currentcustomer", "", "", messageHandler.GetCurrentCustomer);
            ActionSelector.Add("GetAllCustomers", "GET", "/accounts/rest/customers", "", "", messageHandler.GetAllCustomers);
            ActionSelector.Add("GetCurrentUserBuyers", "GET", "/accounts/rest/customers/currentuser/buyers", "", "", messageHandler.GetCurrentUserBuyers);
            ActionSelector.Add("GetBuyerExtractionConfiguration", "GET", "/accounts/rest/customers/buyers", "/services/extraction", "/{buyerId}", messageHandler.GetAccountExtractionConfiguration);
            ActionSelector.Add("UploadImage2", "POST", "/files/rest/image2", "", "", messageHandler.UploadImage2);
            ActionSelector.Add("GetCustomerExtractionConfiguration", "GET", "/accounts/rest/customers", "/services/extraction", "/{customerId}", messageHandler.GetCustomerExtractionConfiguration);
            ActionSelector.Add("GetOutputDocumentsByCurrentCustomer", "GET", "/documents/rest/customers/outputdocumentsbycurrentcustomer", "", "", messageHandler.GetOutputDocumentsByCurrentCustomer);
            ActionSelector.Add("GetDocumentOutputImage", "GET", "/documents/rest/file", "/image", "/{documentId}", messageHandler.GetDocumentOutputImage);
            ActionSelector.Add("GetDocumentOutputData", "POST", "/documents/rest/file", "/data", "/{documentId}", messageHandler.GetDocumentOutputData);
            ActionSelector.Add("DocumentStatus", "PUT", "/documents/rest", "/documentstatus", "/{documentId}", messageHandler.DocumentStatus);
            ActionSelector.Add("IsAuthenticated", "GET", "/authentication/rest/isauthenticated", "", "", messageHandler.IsAuthenticated);
            ActionSelector.Add("SignOut", "POST", "/authentication/rest/signout", "", "", messageHandler.SignOut);
            ActionSelector.Add("ActivateCustomer", "POST", "/accounts/rest/customers", "/activate", "/{customerId}", messageHandler.ActivateCustomer);
            ActionSelector.Add("CreateCustomer", "POST", "/accounts/rest/customers", "", "", messageHandler.CreateCustomer);
            ActionSelector.Add("GetOutputDocuments", "GET", "/documents/rest/customers", "/outputdocuments", "/{customerId}", messageHandler.GetOutputDocuments);
            ActionSelector.Add("GetDocument", "GET", "/documents/rest", "", "/{customerId}", messageHandler.GetDocument);
            ActionSelector.Add("LearnDocument", "POST", "/documents/rest", "/learningdocument", "/{documentId}", messageHandler.LearnDocument);
            ActionSelector.Add("GetUserConfiguration", "GET", "/accounts/rest/customers", "/userconfiguration", "/{organizationId}", messageHandler.GetUserConfiguration);



            //Should always be the last handler.
            ActionSelector.Add("DummyHandler", "", "/", "", "", messageHandler.Dummy);
        }
Esempio n. 10
0
        public CommeilFautAsset()
        {
            m_ea = null;
            m_attributionRules = new HashSet<AttributionRule>();
            m_claimTree = new NameSearchTree<uint>();
            m_conferalActions = new ActionSelector<Conferral>(ValidateConferral);

            m_cachedSI = new NameSearchTree<NameSearchTree<float>>();
        }
Esempio n. 11
0
    void Awake()
    {
        _instance = this;
        animator  = GetComponent <Animator>();
        gameObject.SetActive(false);

        foreach (ActionSelectorButton button in buttons)
        {
            button.onClick += OnClickAction;
        }
    }
Esempio n. 12
0
    protected override void Start()
    {
        base.Start();
        actionselector = GetComponentInParent <ActionSelector>();
        text.text      = "";

        /*if (item.heldItem.stack > 1)
         * {*/
        text.text = item.heldItem.stack.ToString();
        //}
        sprite.sprite = item.heldItem.useItem.icon;
    }
Esempio n. 13
0
 void Start()
 {
     mLastPos         = new Vector3Int(0, 0, 0);
     mTileSelector    = GameObject.Find("TileSelector");
     mMouseLocation   = transform.parent.gameObject.GetComponent <MouseLocation>();
     mDrawnObjects    = new List <GameObject>();
     mMovementStack   = new List <Vector3>();
     mFlowController  = GameObject.Find("FlowController").GetComponent <FlowController>();
     mActionComponent = mActionSelector.GetComponent <ActionSelector>();
     //GameObject.Find("Allies").GetComponentInChildren<CharacterStats>().UI_SetStats();
     mDialogueController = GameObject.Find("DialogueController");
 }
Esempio n. 14
0
    void OnActionClicked(ActionSelector actionOpt)
    {
        this.SelectedAction.GameActionData = actionOpt.GameActionData;
        this.SelectedAction.gameObject.SetActive(true);
        this.Overlay.IsSwallowingClicks = false;
        this.Menu.SetActive(false);

        actionOpt.IsHighlighted = false;

        this.InputManager.SetSelectedAction(actionOpt.GameActionData);

        LevelMng.Instance.Player.IsIntractable = false;
    }
Esempio n. 15
0
    void DisableTooExpensiveActions()
    {
        int stamina = LevelMng.Instance.Player.Stamina;

        foreach (Transform child in this.Menu.transform)
        {
            ActionSelector actionOpt = child.GetComponent <ActionSelector>();
            if (actionOpt != null)
            {
                actionOpt.Disabled = actionOpt.GameActionData.StaminaCost > stamina;
            }
        }
    }
    void SetupMenu()
    {
        ActionSelector newMenu = Instantiate(menuPrefab);

        newMenu.manager = this;
        newMenu.Setup(turnee);
        newMenu.transform.SetParent(mainCanvas.transform);
        newMenu.transform.localScale = new Vector3(1, 1, 1);
        //newMenu.transform.position = Camera.main.WorldToScreenPoint(turnee.transform.position);
        activeMenu = newMenu;

        PSS = PlayerSelectionStage.SelectAction;
    }
 protected override void Start()
 {
     base.Start();
     actionselector = GetComponentInParent <ActionSelector>();
     text.text      = "";
     if (attack.cost > 0)
     {
         text.text = attack.cost + "";
     }
     sprite.sprite = attack.icon;
     if (attack.cost > actionselector.focus.MP)
     {
         sprite.color = Color.grey;
     }
 }
Esempio n. 18
0
 protected virtual bool TryFindActionDescriptor(string actionName, ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, out ActionDescriptor actionDescriptor)
 {
     actionDescriptor = null;
     try
     {
         var actionSelector = new ActionSelector();
         actionDescriptor = actionSelector.FindAction(controllerContext, controllerDescriptor, actionName);
         if (actionDescriptor != null)
         {
             return(true);
         }
     }
     catch
     {
         return(false);
     }
     return(false);
 }
Esempio n. 19
0
        private void EnableActionSelector(Type limb)
        {
            string prefab = "UI/MinionUI/MinionUIActionSelector";

            if (limb == typeof(Feet))
            {
                prefab = "UI/MinionUI/MinionUIActionSelectorFeet";
            }
            else if (limb == typeof(Arms))
            {
                prefab = "UI/MinionUI/MinionUIActionSelectorArms";
            }
            else if (limb == typeof(Brain))
            {
                prefab = "UI/MinionUI/MinionUIActionSelectorBrain";
            }
            else if (limb == typeof(Eyes))
            {
                prefab = "UI/MinionUI/MinionUIActionSelectorEyes";
            }

            this.CloseSelectors();
            GameObject objectUI = Instantiate(
                Resources.Load(prefab),
                this.transform.position,
                Quaternion.identity
                ) as GameObject;

            objectUI.transform.SetParent(GameObject.Find("DifferentialImageHolder").transform);
            objectUI.GetComponent <RectTransform>().anchoredPosition = Vector2.zero;
            objectUI.transform.localScale = new Vector3(0.8f, 1.6f, 1.0f);

            ActionSelector actionSelector = objectUI.GetComponent <ActionSelector>();

            if (actionSelector == null)
            {
                actionSelector = objectUI.AddComponent <ActionSelector>();
            }

            actionSelector.LimbType = limb;
            actionSelector.Minion   = this.minions[this.currentMinionIdx];
        }
 public SyncOrAsyncActionSelector
 (
     IActionDescriptorCollectionProvider
     actionDescriptorCollectionProvider
     , ActionConstraintCache
     actionConstraintCache
     , ILoggerFactory
     loggerFactory
     , IConfiguration
     configuration
 )
 {
     _actionSelector = new ActionSelector
                       (
         actionDescriptorCollectionProvider
         , actionConstraintCache
         , loggerFactory
                       );
     _configuration = configuration;
 }
Esempio n. 21
0
    private ControllerActionDescriptor InvokeActionSelector(RouteContext context)
    {
        var actionDescriptorProvider           = GetActionDescriptorProvider();
        var actionDescriptorCollectionProvider = new DefaultActionDescriptorCollectionProvider(
            new[] { actionDescriptorProvider },
            Enumerable.Empty <IActionDescriptorChangeProvider>());

        var actionConstraintProviders = new[]
        {
            new DefaultActionConstraintProvider(),
        };

        var actionSelector = new ActionSelector(
            actionDescriptorCollectionProvider,
            GetActionConstraintCache(actionConstraintProviders),
            NullLoggerFactory.Instance);

        var candidates = actionSelector.SelectCandidates(context);

        return((ControllerActionDescriptor)actionSelector.SelectBestCandidate(context, candidates));
    }
 //   Use this for initialization
 void Start()
 {
     ActionSelector = mActionSelector.GetComponent <ActionSelector>();
 }
Esempio n. 23
0
        void OnWizardCreate()
        {
            string[] allPrefabs = GetAllPrefabs();
            foreach (string prefab_path in allPrefabs)
            {
                GameObject prefab = (GameObject)AssetDatabase.LoadMainAssetAtPath(prefab_path);
                if (prefab != null)
                {
                    //Add buildable to constructions
                    if (prefab.GetComponent <Construction>() != null && prefab.GetComponent <Buildable>() == null)
                    {
                        prefab.AddComponent <Buildable>();
                        EditorUtility.SetDirty(prefab);
                        Debug.Log("Added Buildable Component to: " + prefab_path);
                    }

                    //Add buildable to plants
                    if (prefab.GetComponent <Plant>() != null && prefab.GetComponent <Buildable>() == null)
                    {
                        prefab.AddComponent <Buildable>();
                        EditorUtility.SetDirty(prefab);
                        Debug.Log("Added Buildable Component to: " + prefab_path);
                    }

                    //Add character to animals
                    if (prefab.GetComponent <AnimalWild>() != null && prefab.GetComponent <Character>() == null)
                    {
                        prefab.AddComponent <Character>();
                        EditorUtility.SetDirty(prefab);
                        Debug.Log("Added Character Component to: " + prefab_path);
                    }

                    //Add character to birds
                    if (prefab.GetComponent <Bird>() != null && prefab.GetComponent <Character>() == null)
                    {
                        prefab.AddComponent <Character>();
                        EditorUtility.SetDirty(prefab);
                        Debug.Log("Added Character Component to: " + prefab_path);
                    }

                    //Add PlayerCharacterCombat
                    if (prefab.GetComponent <PlayerCharacter>() != null && prefab.GetComponent <PlayerCharacterCombat>() == null)
                    {
                        prefab.AddComponent <PlayerCharacterCombat>();
                        EditorUtility.SetDirty(prefab);
                        Debug.Log("Added PlayerCharacterCombat Component to: " + prefab_path);
                    }

                    //Add PlayerCharacterAttribute
                    if (prefab.GetComponent <PlayerCharacter>() != null && prefab.GetComponent <PlayerCharacterAttribute>() == null)
                    {
                        prefab.AddComponent <PlayerCharacterAttribute>();
                        EditorUtility.SetDirty(prefab);
                        Debug.Log("Added PlayerCharacterAttribute Component to: " + prefab_path);
                    }

                    //Add PlayerCharacterAttribute
                    if (prefab.GetComponent <PlayerCharacter>() != null && prefab.GetComponent <PlayerCharacterInventory>() == null)
                    {
                        prefab.AddComponent <PlayerCharacterInventory>();
                        EditorUtility.SetDirty(prefab);
                        Debug.Log("Added PlayerCharacterInventory Component to: " + prefab_path);
                    }

                    //Add PlayerCharacterCraft
                    if (prefab.GetComponent <PlayerCharacter>() != null && prefab.GetComponent <PlayerCharacterCraft>() == null)
                    {
                        prefab.AddComponent <PlayerCharacterCraft>();
                        EditorUtility.SetDirty(prefab);
                        Debug.Log("Added PlayerCharacterCraft Component to: " + prefab_path);
                    }

                    //Fix selectable
                    Selectable selectable = prefab.GetComponent <Selectable>();
                    if (selectable != null)
                    {
                        if (selectable.surface && selectable.type == SelectableType.Interact)
                        {
                            selectable.type = SelectableType.InteractSurface;
                            EditorUtility.SetDirty(prefab);
                            Debug.Log("Changed seletable type to " + selectable.type + " on: " + prefab_path);
                        }
                    }

                    //Remove Anywhere mode in Buildable
                    Buildable buildable = prefab.GetComponent <Buildable>();
                    if (buildable != null)
                    {
                        if ((int)buildable.type == 5)          //Anywhere
                        {
                            buildable.type = (BuildableType)0; //Default
                            EditorUtility.SetDirty(prefab);
                            Debug.Log("Changed buildable type to " + buildable.type + " on: " + prefab_path);
                        }
                        if ((int)buildable.type == 15)          //AnywhereGrid
                        {
                            buildable.type = (BuildableType)10; //Grid
                            EditorUtility.SetDirty(prefab);
                            Debug.Log("Changed buildable type to " + buildable.type + " on: " + prefab_path);
                        }
                    }

                    //Add event trigger in UISlot
                    GameObject     ui_parent    = null;
                    ActionSelector actionselect = prefab.GetComponent <ActionSelector>();
                    TheUI          theui        = prefab.GetComponent <TheUI>();
                    if (actionselect != null)
                    {
                        ui_parent = actionselect.gameObject;
                    }
                    if (theui != null)
                    {
                        ui_parent = theui.gameObject;
                    }
                    if (ui_parent != null)
                    {
                        foreach (UISlot slot in ui_parent.GetComponentsInChildren <UISlot>())
                        {
                            if (slot.GetComponent <UnityEngine.UI.Button>() == null && slot.GetComponent <UnityEngine.EventSystems.EventTrigger>() == null)
                            {
                                slot.gameObject.AddComponent <UnityEngine.EventSystems.EventTrigger>();
                                EditorUtility.SetDirty(prefab);
                                Debug.Log("Added Event Trigger to " + slot.gameObject.name + " on: " + prefab_path);
                            }
                        }
                    }

                    //Add gameplay ui
                    if (theui != null && theui.GetComponentInChildren <PlayerUI>() == null)
                    {
                        for (int i = 0; i < theui.transform.childCount; i++)
                        {
                            Transform child = theui.transform.GetChild(i);
                            if (child.gameObject.name == "Gameplay")
                            {
                                child.gameObject.AddComponent <PlayerUI>();
                                EditorUtility.SetDirty(prefab);
                                Debug.Log("Added PlayerUI on: " + prefab_path);
                            }
                        }
                    }
                }
            }

            AssetDatabase.SaveAssets();
        }
Esempio n. 24
0
        private List <ConfigurationAction> ChooseReconfigActions(Dictionary <string, ClientUsageData> clientData, List <ConfigurationConstraint> constraints, ReplicaConfiguration config)
        {
            Dictionary <string, ConfigurationAction> actions = new Dictionary <string, ConfigurationAction>();

            // build sorted list of all SLAs
            SortedSet <ServiceLevelAgreement> SLAs = new SortedSet <ServiceLevelAgreement>(new ServiceLevelAgreementComparer());

            foreach (ClientUsageData client in clientData.Values)
            {
                SLAs.UnionWith(client.SLAs);
            }

            AppendToLogger("Start Computing Actions");
            foreach (string clientName in clientData.Keys)
            {
                foreach (ServiceLevelAgreement sla in clientData[clientName].SLAs)
                {
                    Dictionary <string, ConfigurationAction> tmp = ActionSelector.ComputeActions(this.containerName, config, sla, clientData[clientName]);
                    foreach (string id in tmp.Keys)
                    {
                        if (!actions.ContainsKey(id))
                        {
                            actions[id] = tmp[id];
                        }
                        else
                        {
                            actions[id].Merge(tmp[id]);
                        }

                        //We keep track of clients. We will use this list in the checking phase (below)
                        actions[id].Clients.Add(clientName);

                        AppendToLogger(tmp[id].ToString());
                    }
                }
            }

            AppendToLogger("Start Checking Actions");
            foreach (string clientName in clientData.Keys)
            {
                foreach (ServiceLevelAgreement sla in clientData[clientName].SLAs)
                {
                    foreach (ConfigurationAction action in actions.Values)
                    {
                        if (!action.OriginatingSLAs.Contains(sla.Id) || !action.Clients.Contains(clientName))
                        {
                            ActionSelector.CheckAction(action, sla, clientData[clientName], config);
                        }
                    }
                }
            }

            foreach (ConfigurationAction action in actions.Values)
            {
                AppendToLogger(action.ToString());
            }

            List <ConfigurationAction> pickedAction  = new List <ConfigurationAction>();
            List <ConfigurationAction> sortedActions = actions.Values.ToList();

            //we do not even consider actions with negative gained utility.
            sortedActions.RemoveAll(e => e.GainedUtility < 0);
            sortedActions.Sort(new ConfigurationActionComparer());

            // we sort constraints based on their priority.
            constraints.Sort(new ConfigurationConstraintComparer());

            bool foundAction = false;

            for (int i = sortedActions.Count - 1; i >= 0; i--)
            {
                pickedAction.Clear();
                pickedAction.Add(sortedActions[i]);

                if (constraints.Count() == 0)
                {
                    foundAction = true;
                    break;
                }

                //Remove actions that are not satisfying constraints.
                foreach (ConfigurationConstraint c in constraints)
                {
                    c.Apply(pickedAction, constraints, SLAs, clientData);
                    if (pickedAction.All(e => e.Source == ConfigurationActionSource.Constraint))
                    {
                        //the action is removed because of conflict with other constraints.
                        foundAction = false;
                        break;
                    }
                    else
                    {
                        foundAction = true;
                    }
                }

                if (foundAction)
                {
                    break;
                }
            }

            if (!foundAction)
            {
                //no action is applicable with all constraints. so, we just try to apply constraints.
                //hence, no non-constraint action will be executed to improve utility.
                pickedAction.Clear();
                foreach (ConfigurationConstraint c in constraints)
                {
                    c.Apply(pickedAction, constraints, SLAs, clientData);
                }
            }

            return(pickedAction);
        }
Esempio n. 25
0
        /// <summary>
        /// Applies the constraint to the given actions.
        /// Note that this function can add several new actions to the list of new actions. Those actions that are added by this constraint set their source field to Constraint.
        /// So, the reconfigurator will notice whether the action is added by the Apply from the constraint or is computed by itself.
        /// </summary>
        /// <param name="newActions"></param>
        /// <param name="constraints"></param>
        /// <param name="SLAs"></param>
        /// <param name="sessionStates"></param>
        internal override void Apply(List <ConfigurationAction> newActions, List <ConfigurationConstraint> constraints, SortedSet <ServiceLevelAgreement> SLAs, Dictionary <string, ClientUsageData> clientData)
        {
            int currentReplicaFactor = Configuration.PrimaryServers.Count + Configuration.SecondaryServers.Count;

            newActions.ForEach(a => currentReplicaFactor += a.NumberOfAddingReplica());

            if (currentReplicaFactor >= MinReplicationFactor && currentReplicaFactor <= MaxReplicationFactor)
            {
                return;
            }

            if (currentReplicaFactor < MinReplicationFactor)
            {
                //We have to add some secondary replica
                //We assume here that configurator does not add any remove replica action because configurator has a tendency of adding replicas
                //Without this assumption, we first need to see if there is such an action, and erase that action from newActions list instead of adding a new replica.

                // Make copy of list of non-replica servers
                List <string> availableServers = new List <string>();
                foreach (string server in Configuration.NonReplicaServers)
                {
                    availableServers.Add(server);
                }

                int mustAdd = MinReplicationFactor - currentReplicaFactor;

                foreach (ConfigurationAction action in newActions)
                {
                    if (action.NumberOfAddingReplica() > 0)
                    {
                        availableServers.Remove(action.ServerName);
                    }
                    else if (action.NumberOfAddingReplica() < 0)
                    {
                        availableServers.Add(action.ServerName);
                    }
                }


                if (availableServers.Count < mustAdd)
                {
                    throw new Exception("There are not enough servers to enforce this constraint.");
                }

                List <ConfigurationAction> toBeAdded = new List <ConfigurationAction>();
                while (mustAdd > 0)
                {
                    //we should add a new replica
                    string serverName          = availableServers.First();
                    ConfigurationAction action = new AddSecondaryServer(Configuration.Name, serverName, 0, null, ConfigurationActionSource.Constraint);
                    bool compatible            = true;
                    foreach (ConfigurationConstraint constraint in constraints)
                    {
                        if (!constraint.Compatible(action))
                        {
                            compatible = false;
                            break;
                        }
                    }

                    if (compatible)
                    {
                        toBeAdded.Add(action);
                        mustAdd--;
                    }

                    availableServers.RemoveAt(0);
                    if (mustAdd > 0 && availableServers.Count == 0)
                    {
                        throw new Exception("There are not enough servers to enforce this constraint.");
                    }
                }

                toBeAdded.ForEach(a => newActions.Add(a));
            }

            if (currentReplicaFactor > MaxReplicationFactor)
            {
                //The asumption for the minimum replication factor does not hold here.
                //I.e., there can be an action in newActions list that is adding a new replica, hence total  number of replicas has become more than the maximum allowed.
                //Therefore, instead of creating a new action to remove a replica, we first need to remove addReplica action from the newActions list.

                int mustRemove = currentReplicaFactor - MaxReplicationFactor;

                List <ConfigurationAction> toBeRemoved = new List <ConfigurationAction>();

                //first, we try to remove a secondary replica to meet the constraint.
                List <RemoveSecondaryServer> removeActions = new List <RemoveSecondaryServer>();

                // TODO: Make sure that this is doing the right thing.  This code seems strange to me.
                // Why only the first SLA?  And why remove all secondaries?

                ServiceLevelAgreement firstSLA = SLAs.First();
                string clientName = "";
                foreach (ClientUsageData usage in clientData.Values)
                {
                    if (usage.SLAs.Contains(firstSLA))
                    {
                        clientName = usage.ClientName;
                        break;
                    }
                }

                foreach (string server in Configuration.SecondaryServers)
                {
                    RemoveSecondaryServer action = new RemoveSecondaryServer(containerName, server, 0, null, ConfigurationActionSource.Constraint, clientData[clientName].NumberOfReads, clientData[clientName].NumberOfWrites);
                    action.Clients.Add(clientName);
                    removeActions.Add(action);
                }

                foreach (string client in clientData.Keys)
                {
                    foreach (ServiceLevelAgreement sla in clientData[client].SLAs)
                    {
                        foreach (ConfigurationAction action in removeActions)
                        {
                            if (!action.OriginatingSLAs.Contains(sla.Id) || !action.Clients.Contains(client))
                            {
                                ActionSelector.CheckAction(action, sla, clientData[client], Configuration);
                            }
                        }
                    }
                }

                removeActions.Sort(new ConfigurationActionComparer());
                float totalLostUtility = 0;
                float totalGainUtility = 0;
                newActions.ForEach(a => totalGainUtility += a.GainedUtility);

                foreach (RemoveSecondaryServer action in removeActions)
                {
                    if (action.GainedUtility + totalLostUtility + totalGainUtility > 0)
                    {
                        //we need one final test.
                        //we need to make sure that this action does not violate any other constraint.
                        bool compatible = true;
                        foreach (ConfigurationConstraint cc in constraints)
                        {
                            if (!cc.Compatible(action))
                            {
                                compatible = false;
                                break;
                            }
                        }
                        if (compatible)
                        {
                            totalLostUtility += action.GainedUtility;
                            mustRemove--;
                            newActions.Add(action);
                        }
                    }
                    if (mustRemove == 0)
                    {
                        return;
                    }
                }


                //then, we adding a new replica in newactions
                foreach (ConfigurationAction action in newActions)
                {
                    if (action.Source == ConfigurationActionSource.NonConstraint && action.NumberOfAddingReplica() > 0)
                    {
                        toBeRemoved.Add(action);
                        mustRemove--;
                    }

                    if (mustRemove == 0)
                    {
                        break;
                    }
                }

                newActions.RemoveAll(r => toBeRemoved.Contains(r));

                if (mustRemove == 0)
                {
                    return;
                }

                List <ConfigurationAction> toBeAdded = new List <ConfigurationAction>();
                //Removing configurator actions does not suffice to ensure the constraint.
                //Hence, we need to start removing secondary replicas.
                while (mustRemove > 0 && Configuration.SecondaryServers.Count > 0)
                {
                    string serverName          = Configuration.SecondaryServers.First();
                    ConfigurationAction action = new RemoveSecondaryServer(Configuration.Name, serverName, 0, null, ConfigurationActionSource.Constraint);
                    bool compatible            = true;
                    foreach (ConfigurationConstraint constraint in constraints)
                    {
                        if (!constraint.Compatible(action))
                        {
                            compatible = false;
                            break;
                        }
                    }

                    if (compatible)
                    {
                        toBeAdded.Add(action);
                        mustRemove--;
                    }
                }
                toBeAdded.ForEach(a => newActions.Add(a));

                if (mustRemove == 0)
                {
                    return;
                }

                //Removing secondaries was not enough either. we have to start removing primaries.
                toBeAdded = new List <ConfigurationAction>();
                while (mustRemove > 0 && Configuration.PrimaryServers.Count > 1)
                {
                    string serverName           = Configuration.PrimaryServers.Last();
                    ConfigurationAction action1 = new DowngradePrimary(Configuration.Name, serverName, 0, null, ConfigurationActionSource.Constraint);
                    ConfigurationAction action2 = new RemoveSecondaryServer(Configuration.Name, serverName, 0, null, ConfigurationActionSource.Constraint);
                    bool compatible             = true;
                    foreach (ConfigurationConstraint constraint in constraints)
                    {
                        if (!constraint.Compatible(action1) || !constraint.Compatible(action2))
                        {
                            compatible = false;
                            break;
                        }
                    }

                    if (compatible)
                    {
                        toBeAdded.Add(action1);
                        toBeAdded.Add(action2);
                        mustRemove--;
                    }
                }
                Debug.Assert(mustRemove == 0, "mustRemove should be zero by now. Something is wrong");
                toBeAdded.ForEach(a => newActions.Add(a));
            }
        }
 public void OnActionClick(ActionSelector actionSelector)
 {
     Debug.Log(actionSelector.action.name + " clicked");
     gameObject.SetActive(false);
 }
 public ReactiveActions()
 {
     m_actionTendencies = new ActionSelector<ActionTendency>(null);
 }
Esempio n. 28
0
 public ReactiveActions()
 {
     m_actionTendencies = new ActionSelector <ActionTendency>((tendency, set) => !tendency.IsCoolingdown);
 }
 protected virtual bool TryFindActionDescriptor(string actionName, ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, out ActionDescriptor actionDescriptor)
 {
     actionDescriptor = null;
     try
     {
         var actionSelector = new ActionSelector();
         actionDescriptor = actionSelector.FindAction(controllerContext, controllerDescriptor, actionName);
         if (actionDescriptor != null)
             return true;
     }
     catch
     {
         return false;
     }
     return false;
 }
Esempio n. 30
0
 public static void Do(ActionSelector selectedAction, GameObject enemyObject, Enemy enemy)
 {
     Actions[(int)selectedAction](enemyObject, enemy);
 }
        private void runActivateIssueActionsWorker(Action onFinish)
        {
            JiraServer server = JiraServerModel.Instance.getServer(new Guid(CurrentActiveIssue.ServerGuid));

            if (server != null)
            {
                try {
                    int       mods  = 0;
                    JiraIssue issue = SmartJiraServerFacade.Instance.getIssue(server, CurrentActiveIssue.Key);
                    if (issue != null)
                    {
                        string me = CredentialUtils.getUserNameWithoutDomain(server.UserName);
                        if (issue.Assignee == null || issue.Assignee.Equals("Unknown") || !issue.Assignee.Equals(me))
                        {
                            jiraStatus.setInfo("Assigning issue to me...");
                            JiraField assignee = new JiraField("assignee", null)
                            {
                                Values = new List <string> {
                                    me
                                },
                                SettablePropertyName = "name"
                            };
                            var rawIssueObject = SmartJiraServerFacade.Instance.getRawIssueObject(issue);
                            assignee.setRawIssueObject(rawIssueObject);
                            SmartJiraServerFacade.Instance.updateIssue(issue, new List <JiraField> {
                                assignee
                            });
                            ++mods;
                        }
                        List <JiraNamedEntity> actions = SmartJiraServerFacade.Instance.getActionsForIssue(issue);
                        JiraNamedEntity        action  = actions.Find(a => a.Id.Equals(START_PROGRESS_ACTION_ID));
                        if (action == null)
                        {
                            container.safeInvoke(new MethodInvoker(delegate {
                                ActionSelector sel = new ActionSelector(actions);
                                if (sel.ShowDialog() == DialogResult.OK)
                                {
                                    action = sel.SelectedAction;
                                }
                            }));
                        }
//                        foreach (JiraNamedEntity action in actions.Where(action => action.Id.Equals(START_PROGRESS_ACTION_ID))) {
                        if (action != null)
                        {
                            jiraStatus.setInfo("Setting issue in progress...");
                            SmartJiraServerFacade.Instance.runIssueActionWithoutParams(issue, action);
                            ++mods;
                        }
                        if (mods > 0)
                        {
                            issue = SmartJiraServerFacade.Instance.getIssue(server, CurrentActiveIssue.Key);
                        }
                    }
                    jiraStatus.setInfo("Work on issue " + CurrentActiveIssue.Key + " started");
                    container.safeInvoke(new MethodInvoker(() => {
                        JiraIssueListModelImpl.Instance.updateIssue(issue);
                        onFinish();
                    }));
                } catch (Exception e) {
                    CurrentActiveIssue = null;
                    jiraStatus.setError(FAILED_TO_START_WORK, e);
                    container.safeInvoke(new MethodInvoker(() => PlvsUtils.showError(FAILED_TO_START_WORK, e)));
                }
            }
            else
            {
                container.safeInvoke(new MethodInvoker(
                                         () => PlvsUtils.showError(FAILED_TO_START_WORK, new Exception("Unknown JIRA server"))));
            }
        }
 public WebhookActionSelector(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider, ActionConstraintCache actionConstraintCache, ILoggerFactory loggerFactory)
 {
     _defaultSelector = new ActionSelector(actionDescriptorCollectionProvider, actionConstraintCache, loggerFactory);
 }
Esempio n. 33
0
 public void Initialize()
 {
     _selector = GameObject.Find("ActionSelector").GetComponent <ActionSelector>();
     _selector.RegisterActions(this, _actions);
 }