Exemplo n.º 1
0
        public PodGroup Load(Control murpleControl, string filename)
        {
            PodGroup newPodGroup = new PodGroup();

            StreamReader streamReader = new StreamReader (filename);
            XmlReader xmlReader = XmlReader.Create (streamReader);
            XmlDocument document = new XmlDocument ();

            document.Load (xmlReader);

            XmlNodeList allPodsAsXml = document.GetElementsByTagName ("Pod");

            foreach(XmlNode thisPodAsXml in allPodsAsXml)
            {
                XmlNode podNameNode = thisPodAsXml.Attributes.GetNamedItem("name");
                string podType = podNameNode.Value;

                Pod newPod = new Pod();

                if(murpleControl.IsInDefinition(podType) == true)
                {
                    newPod = murpleControl.AddMurpleFromDefinition(podType);
                    System.Guid podUUID = XmlToPod(murpleControl, thisPodAsXml, ref newPod, filename);
                    newPod.UUID = podUUID;
                    murpleControl.AddPod(podUUID, newPod, filename);
                }
            }
            streamReader.Close();

            return newPodGroup;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Converts a <see cref="T:HospitalAllocation.Data.Allocation.StaffGroups.Pod"/>
        /// to a <see cref="T:HospitalAllocation.Providers.Allocation.Database.Model.PodAllocation"/>.
        /// </summary>
        /// <param name="allocation">The allocation to convert.</param>
        /// <returns>The converted allocation.</returns>
        public TeamAllocation PodToModel(Pod allocation)
        {
            var positions = new List <Position>();

            foreach (var bed in allocation.Beds)
            {
                positions.Add(BedToModel(bed.Key, bed.Value));
            }

            positions.Add(PositionToModel(allocation.Consultant, PositionType.Consultant));
            positions.Add(PositionToModel(allocation.TeamLeader, PositionType.TeamLeader));
            positions.Add(PositionToModel(allocation.Registrar, PositionType.Registrar));
            positions.Add(PositionToModel(allocation.Resident, PositionType.Resident));
            positions.Add(PositionToModel(allocation.PodCa, PositionType.PodCa));
            positions.Add(PositionToModel(allocation.CaCleaner, PositionType.CaCleaner));

            return(new TeamAllocation
            {
                Type = TeamTypeToModel(allocation.TeamType),
                Positions = positions,
            });
        }
Exemplo n.º 3
0
        public ActionResult Delete(int?id)
        {
            var user = db.Employees.Find(User.Identity.GetUserId());

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Pod pod = db.Pods.Find(id);

            if (pod == null)
            {
                return(HttpNotFound());
            }

            if (pod.Station.CompanyId != user.CompanyId)
            {
                return(HttpNotFound());
            }

            return(View(pod));
        }
        private async Task CreateServicesForPod(CancellationToken cancellationToken, Pod pod)
        {
            var services = GetPodServices(pod).ToList();
            var timeout  = TimeSpan.FromSeconds(_configuration.ConsulServiceTtlSeconds);

            Logger.Info($"Pod '{pod.Namespace}/{pod.Name}' is ready, adding {services.Count} services.");
            foreach (var podService in services)
            {
                try
                {
                    var serviceId = await _consulClient.RegisterPodServiceAsync(podService, timeout, cancellationToken);

                    Logger.Info($"Pod service '{serviceId}' was created with a TTL of {timeout.Seconds}s.");
                }
                catch (Exception e)
                {
                    Logger.Warn(e, "A handled exception occurred while registering pod service.");
                }
            }

            await _podServicesContainer.UpsertPodServicesAsync(pod, services, cancellationToken);
        }
Exemplo n.º 5
0
        public async Task <bool> FixUpdate()
        {
            bool updated = false;

            foreach (var onePod in getAllPods())
            {
                NextUpdate = onePod.NextUpdate;
                int interval = Int32.Parse(onePod.Frequency);

                if (onePod.podUpdate)
                {
                    onePod.NextUpdate = DateTime.Now.AddSeconds(interval);
                    int            index    = GetPodIndexOfName(onePod.Name);
                    List <Episode> episodes = await podRepository.getEpisodes(onePod.PodUrl);

                    Pod newPod = new Pod(onePod.Name, onePod.PodUrl, onePod.Frequency, onePod.Category, onePod.NextUpdate, episodes);
                    podRepository.Update(index, newPod);
                    updated = true;
                }
            }
            return(updated);
        }
Exemplo n.º 6
0
        public Pod AddMurpleFromDefinition(string definitionName)
        {
            Pod newPod = new Pod ();
            Definition murpleDefinition = GetMurpleDefinition(definitionName);

            newPod.AddDefinition(murpleDefinition);

            foreach (KeyValuePair<string, StatBase> definitionNodeBase in murpleDefinition.Definitions)
            {
                string statName = definitionNodeBase.Key;
                StatBase statValue = definitionNodeBase.Value;

                StatBase newStat = (StatBase)mStatHelper.Create(statValue.StatTypeSystem, statValue);
                newPod.AddStat(statName, newStat);
            }

            newPod.UUID = Pod.GenerateUUID();

            //mMurples.Add(murpleName, newPod);

            return newPod;
        }
Exemplo n.º 7
0
        private void BundleStored(InputStation iStation, Bot bot, Pod pod, ItemBundle bundle)
        {
            // Skip callback, if inactive
            if (!_instance.SettingConfig.MonitorWellSortedness)
            {
                return;
            }
            // Return if not in use yet
            if (_podsContainingItems == null)
            {
                return;
            }
            // --> Add pod to the list of pods containing / offering the respective item
            _podsAvailableItems[bundle.ItemDescription].Add(pod);
            _podsContainingItems[bundle.ItemDescription].Add(pod);
            // --> Update pod utility
            int itemDemand  = _instance.StockInfo.GetCurrentDemand(bundle.ItemDescription);
            int beforeCount = pod.CountContained(bundle.ItemDescription) - bundle.ItemCount;

            // Add either rest of demand that now can be supplied by the pod or simply the content of the bundle
            if (beforeCount < itemDemand)
            {
                _podUtility[pod] += Math.Min(itemDemand - beforeCount, bundle.ItemCount);
                // Update max value
                if (_podUtility[pod] > PodUtilityMax)
                {
                    PodUtilityMax     = _podUtility[pod];
                    _podUtilityMaxPod = pod;
                }
            }
            // --> Update pod speed
            _podSpeed[pod] += bundle.ItemCount * _instance.FrequencyTracker.GetStaticFrequency(bundle.ItemDescription);
            if (_podSpeed[pod] > PodSpeedMax)
            {
                PodSpeedMax     = _podSpeed[pod];
                _podSpeedMaxPod = pod;
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Selects a pod for the bundle according to the desired class.
        /// </summary>
        /// <param name="classId">The class of the desired pod.</param>
        /// <param name="bundle">The bundle to assign to a pod.</param>
        /// <returns>The pod for the given bundle or <code>null</code> in case it does not fit any pod.</returns>
        private Pod ChoosePodByConfig(int classId, ItemBundle bundle)
        {
            Pod chosenPod = null;

            // See whether we can recycle the last pod
            if (_lastChosenPodByClass.ContainsKey(classId) && _lastChosenPodByClass[classId].FitsForReservation(bundle))
            {
                chosenPod = _lastChosenPodByClass[classId];
            }
            else
            {
                // We can not recycle the last pod
                if (_config.EmptiestInsteadOfRandom)
                {
                    // Find the new emptiest pod
                    chosenPod = _classManager.GetClassPods(classId)
                                .Where(b => b.FitsForReservation(bundle))
                                .OrderBy(b => (b.CapacityInUse + b.CapacityReserved) / b.Capacity)
                                .FirstOrDefault();
                }
                else
                {
                    // Find a new random pod
                    chosenPod = _classManager.GetClassPods(classId)
                                .Where(b => b.FitsForReservation(bundle))
                                .OrderBy(b => b.Instance.Randomizer.NextDouble())
                                .FirstOrDefault();
                }
                // Remember the pod for next time
                if (chosenPod != null)
                {
                    _lastChosenPodByClass[classId]          = chosenPod;
                    _lastChosenPodByClassReverse[chosenPod] = classId;
                }
            }
            // Return the choice
            return(chosenPod);
        }
Exemplo n.º 9
0
        private Type[] tests(Pod pod, string testName)
        {
            // named test
            if (testName != "*")
            {
                return new Type[] { pod.type(testName, true) }
            }
            ;

            // all types which subclass Test
            List      all = pod.types();
            ArrayList acc = new ArrayList();

            for (int i = 0; i < all.sz(); i++)
            {
                Type x = (Type)all.get(i);
                if (x.@is(Sys.TestType) && !x.isAbstract())
                {
                    acc.Add(x);
                }
            }
            return((Type[])acc.ToArray(System.Type.GetType("Fan.Sys.Type")));
        }
Exemplo n.º 10
0
        public PodEditModel Create(Pod pod, IEnumerable <Territory> territories, IEnumerable <OrderedPair <long, string> > podTerritories, IEnumerable <PodStaff> podStaff, IEnumerable <OrderedPair <long, string> > idNamePairs,
                                   IEnumerable <StaffEventRole> eventRoles, IEnumerable <PodRoom> podRooms, IEnumerable <PodRoomTest> podRoomTests, IEnumerable <Test> tests)
        {
            var model = new PodEditModel
            {
                AssignedToFranchiseeid = pod.AssignedToFranchiseeid,
                DataRecoderMetaData    = pod.DataRecorderMetaData,
                Description            = pod.Description,
                Id   = pod.Id,
                Name = pod.Name,
                ProcessingCapacity = pod.ProcessingCapacity,
                VanId = pod.VanId,
                AssignedTerritories  = territories.Select(t => t.Id),
                Territories          = podTerritories,
                DefaultStaffAssigned = _staffEditModelFactory.Create(pod.Id, podStaff, idNamePairs, eventRoles),
                Tests = tests,
                Rooms = GetPodRoomEditModels(podRooms, podRoomTests),
                EnableKynIntegration    = pod.EnableKynIntegration,
                IsBloodworkFormAttached = pod.IsBloodworkFormAttached
            };

            return(model);
        }
Exemplo n.º 11
0
        public void NsPodsMapTests()
        {
            KanoVerifier verifier = new KanoVerifier();
            Pod          p1       = new Pod("default");
            Pod          p2       = new Pod("ns1");
            Pod          p3       = new Pod("ns2");
            Pod          p4       = new Pod("ns2");
            var          output   = verifier.createNSMatrix(new Pod[] { p1, p2, p3, p4 });
            var          actual   = new Dictionary <string, BitArray>()
            {
                { "default", new BitArray(new bool[4] {
                        true, false, false, false
                    }) },
                { "ns1", new BitArray(new bool[4] {
                        false, true, false, false
                    }) },
                { "ns2", new BitArray(new bool[4] {
                        false, false, true, true
                    }) },
            };

            Assert.IsTrue(new DictionaryComparer <string, BitArray>(new BitArrayComparer()).Equals(output, actual));
        }
Exemplo n.º 12
0
        private bool DoExtractTaskWithPod(Bot bot, Pod pod)
        {
            // Bring items to the randomly selected first fitting station
            foreach (var oStation in Instance.OutputStations.OrderBy(s => GetOrderValue(s, bot)))
            {
                // Search for requests matching the items of the pod
                List <ExtractRequest> fittingRequests = GetPossibleRequests(pod, oStation, PodSelectionExtractRequestFilteringMode.AssignedOnly);
                if (fittingRequests.Any())
                {
                    // Simply execute the next task with the pod
                    EnqueueExtract(
                        bot,              // The bot itself
                        oStation,         // The random station
                        pod,              // Keep the pod
                        fittingRequests); // The requests to serve

                    // Finished search for next task
                    return(true);
                }
            }
            // No fitting request
            return(false);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Creates a pod with the given characteristics.
        /// </summary>
        /// <param name="id">The ID of the pod.</param>
        /// <param name="tier">The initial position (tier).</param>
        /// <param name="x">The initial position (x-coordinate).</param>
        /// <param name="y">The initial position (y-coordinate).</param>
        /// <param name="radius">The radius of the pod.</param>
        /// <param name="orientation">The initial orientation of the pod.</param>
        /// <param name="capacity">The capacity of the pod.</param>
        /// <returns>The newly created pod.</returns>
        public Pod CreatePod(int id, Tier tier, double x, double y, double radius, double orientation, double capacity)
        {
            // Consider override values
            if (SettingConfig.OverrideConfig != null && SettingConfig.OverrideConfig.OverridePodCapacity)
            {
                capacity = SettingConfig.OverrideConfig.OverridePodCapacityValue;
            }
            // Create the pod
            Pod pod = new Pod(this)
            {
                ID = id, Tier = tier, Radius = radius, X = x, Y = y, Orientation = orientation, Capacity = capacity
            };

            Pods.Add(pod);
            tier.AddPod(pod);
            _idToPods[pod.ID] = pod;
            // Set volatile ID
            SetVolatileIDForPod(pod);
            // Notify listeners
            NewPod(pod);
            // Return it
            return(pod);
        }
Exemplo n.º 14
0
        public ActionResult Edit([Bind(Include = "PodId, StationId,Id")] Pod pod)
        {
            var company = db.Employees.Find(User.Identity.GetUserId()).Company;
            Pod temp    = db.Pods.Find(pod.Id);

            temp.PodId = pod.PodId;

            if (temp.Station.Id != pod.StationId)
            {
                return(RedirectToAction("Index"));
            }

            if (ModelState.IsValid)
            {
                db.Entry(temp).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.PodId     = new SelectList(db.PodTypes, "Id", "Name", pod.PodId);
            ViewBag.StationId = new SelectList(company.Stations, "Id", "ComercialName", pod.StationId);
            return(View(pod));
        }
        public void ReachabilityMatrix_TwoDirection()
        {
            Zen <Pod>[] pods = new Zen <Pod>[]
            {
                Pod.Create("default", EmptyDict <string, string>().Add("k0", "v0"), EmptyList <string>().AddBack("k0")),
                Pod.Create("ns1", EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k1")),
            };
            Zen <Namespace>[] namespaces = new Zen <Namespace>[]
            {
                Namespace.Create("default", EmptyDict <string, string>().Add("k0", "v0"), EmptyList <string>().AddBack("k0")),
                Namespace.Create("ns1", EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k1"))
            };
            Zen <Policy>[] policies = new Zen <Policy>[]
            {
                // only ingress is allowed
                Policy.Create("default", EmptyDict <string, string>().Add("k0", "v0"),
                              EmptyDict <string, string>(), EmptyDict <string, string>().Add("k1", "v1"),
                              EmptyList <string>().AddBack("k0"), EmptyList <string>(), EmptyList <string>().AddBack("k1")),

                // only egress is allowed
                Policy.Create("ns1", EmptyDict <string, string>().Add("k1", "v1"),
                              EmptyDict <string, string>(), EmptyDict <string, string>().Add("k0", "v0"),
                              EmptyList <string>().AddBack("k1"), EmptyList <string>(), EmptyList <string>().AddBack("k0"),
                              False(), False()),
            };
            var ingress = Algorithms.CreateReachMatrix(pods, policies, namespaces).ingressMatrix;
            var r0      = EmptyList <bool>().AddBack(true).AddBack(true);
            var r1      = EmptyList <bool>().AddBack(false).AddBack(true);

            TestHelper.AssertMatrixEqual(ingress, new Zen <IList <bool> >[] { r0, r1 }, "Happy path(ingress matrix)");

            var egress = Algorithms.CreateReachMatrix(pods, policies, namespaces).egressMatrix;

            r0 = EmptyList <bool>().AddBack(true).AddBack(false);
            r1 = EmptyList <bool>().AddBack(true).AddBack(true);
            TestHelper.AssertMatrixEqual(egress, new Zen <IList <bool> >[] { r0, r1 }, "Happy path(egress matrix)");
        }
        public void Reachabilitymatrix_DenyAll()
        {
            Zen <Pod>[] pods = new Zen <Pod>[]
            {
                Pod.Create("default", EmptyDict <string, string>().Add("k0", "v0"), EmptyList <string>().AddBack("k0")),
                Pod.Create("default", EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k1")),
                Pod.Create("ns1", EmptyDict <string, string>().Add("k2", "v2"), EmptyList <string>().AddBack("k2")),
                Pod.Create("ns1", EmptyDict <string, string>().Add("k3", "v3"), EmptyList <string>().AddBack("k3"))
            };
            Zen <Namespace>[] namespaces = new Zen <Namespace>[]
            {
                Namespace.Create("default", EmptyDict <string, string>().Add("k0", "v0"), EmptyList <string>().AddBack("k0")),
                Namespace.Create("ns1", EmptyDict <string, string>().Add("k1", "v1"), EmptyList <string>().AddBack("k1"))
            };
            Zen <Policy>[] policies = new Zen <Policy>[]
            {
                Policy.Create("default", EmptyDict <string, string>(),
                              EmptyDict <string, string>().Add("k1", "v1"), EmptyDict <string, string>().Add("k0", "v0"),
                              EmptyList <string>(), EmptyList <string>().AddBack("k1"), EmptyList <string>().AddBack("k0"),
                              True(), True()),
            };
            var ingress = Algorithms.CreateReachMatrix(pods, policies, namespaces).ingressMatrix;
            var r0      = EmptyList <bool>().AddBack(true).AddBack(false).AddBack(false).AddBack(false);
            var r1      = EmptyList <bool>().AddBack(false).AddBack(true).AddBack(false).AddBack(false);
            var r2      = EmptyList <bool>().AddBack(false).AddBack(false).AddBack(true).AddBack(true);
            var r3      = EmptyList <bool>().AddBack(false).AddBack(false).AddBack(true).AddBack(true);

            TestHelper.AssertMatrixEqual(ingress, new Zen <IList <bool> >[] { r0, r1, r2, r3 }, "Reachability_Matrix_Test_Deny_All(ingress matrix)");

            var egress = Algorithms.CreateReachMatrix(pods, policies, namespaces).egressMatrix;

            r0 = EmptyList <bool>().AddBack(true).AddBack(false).AddBack(false).AddBack(false);
            r1 = EmptyList <bool>().AddBack(false).AddBack(true).AddBack(false).AddBack(false);
            r2 = EmptyList <bool>().AddBack(false).AddBack(false).AddBack(true).AddBack(true);
            r3 = EmptyList <bool>().AddBack(false).AddBack(false).AddBack(true).AddBack(true);
            TestHelper.AssertMatrixEqual(egress, new Zen <IList <bool> >[] { r0, r1, r2, r3 }, "Reachability_Matrix_Test_Deny_All(egress matrix)");
        }
Exemplo n.º 17
0
        public ActionResult Create(Planner planner)
        {
            if (planner.PodExists == 1)
            {
                var pod             = _context.Pods.Where(p => p.PodName == planner.PodName && p.PodPassword == planner.PodPassword).SingleOrDefault();
                var foundingPlanner = _context.Planners.Where(p => p.UserName == pod.FoundingUserName).SingleOrDefault();
                planner.IdentityUserId      = GetLoggedInUser();
                planner.PodId               = pod.PodId;
                planner.SpoonacularUserName = foundingPlanner.SpoonacularUserName;
                planner.UserHash            = foundingPlanner.UserHash;

                _context.Add(planner);
                _context.SaveChanges();

                return(RedirectToAction(nameof(Index)));
            }
            else if (planner.PodExists == 2)
            {
                Pod pod = new Pod();
                pod.PodName          = planner.PodName;
                pod.PodPassword      = planner.PodPassword;
                pod.FoundingUserName = planner.UserName;

                _context.Add(pod);
                _context.SaveChanges();

                var selectedPod = _context.Pods.Where(p => p.PodName == planner.PodName && p.PodPassword == planner.PodPassword).FirstOrDefault();
                planner.PodId          = pod.PodId;
                planner.IdentityUserId = GetLoggedInUser();
                _context.Add(planner);
                _context.SaveChanges();

                return(RedirectToAction(nameof(Index)));
            }

            return(RedirectToAction("Create"));
        }
Exemplo n.º 18
0
        public override object get(Uri uri, object @base)
        {
            // don't support anything but relative fan: URIs right now
            if (uri.auth() == null)
            {
                throw ArgErr.make("Invalid format for fan: URI - " + uri).val;
            }

            // lookup pod
            string podName = (string)uri.auth();
            Pod    pod     = Pod.find(podName, false);

            if (pod == null)
            {
                throw UnresolvedErr.make(uri.toStr()).val;
            }
            if (uri.pathStr().Length == 0)
            {
                return(pod);
            }

            // dive into file of pod
            return(pod.file(uri));
        }
Exemplo n.º 19
0
        /// <summary>
        /// using     := usingPod | usingType | usingAs
        /// usingPod  := "using" podName
        /// usingType := "using" podName::typeName
        /// usingAs   := "using" podName::typeName "as" name
        /// </summary>
        private Using readUsing()
        {
            consume();
            int line = tokenizer.m_line;

            string podName = consumeId("Expecting pod name");
            Pod    pod     = Pod.find(podName, false);

            if (pod == null)
            {
                throw err("Unknown pod: " + podName);
            }
            if (curt != Token.DOUBLE_COLON)
            {
                endOfStmt(line);
                return(new UsingPod(pod));
            }

            consume();
            string typeName = consumeId("Expecting type name");
            Type   t        = pod.type(typeName, false);

            if (t == null)
            {
                throw err("Unknown type: " + podName + "::" + typeName);
            }

            if (curt == Token.AS)
            {
                consume();
                typeName = consumeId("Expecting using as name");
            }

            endOfStmt(line);
            return(new UsingType(t, typeName));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Returns a suitable storage location for the given pod.
        /// </summary>
        /// <param name="pod">The pod to fetch a storage location for.</param>
        /// <returns>The storage location to use.</returns>
        protected override Waypoint GetStorageLocationForPod(Pod pod)
        {
            // Ensure init
            if (_bestCandidateSelector == null)
            {
                Init();
            }
            // Get output station this pod is coming from (it has to be the nearest one)
            _currentStation = Instance.OutputStations.ArgMin(s => Distances.CalculateEuclid(s, pod, Instance.WrongTierPenaltyDistance));
            // Get current pod location (pod has to be at station's position right now)
            _currentPodLocation = _currentStation.Waypoint;
            // Determine whether the pod should be put in the cache
            double cacheUtilityValue =
                Instance.SharedControlElements.StoragePartitioner.GetCacheValue(pod, _currentStation, _config.WeightSpeed, _config.WeightUtility);
            double cacheFill =
                (double)Instance.SharedControlElements.StoragePartitioner.CachePartitions[_currentStation].Count(c => c.Pod != null) /
                Instance.SharedControlElements.StoragePartitioner.CachePartitions[_currentStation].Count;

            _currentCacheable = ((1 - cacheFill) * _config.WeightCacheFill + cacheUtilityValue * _config.WeightCacheUtility) / 2.0 > _config.PodCacheableThreshold;
            // Get best storage location
            _bestCandidateSelector.Recycle();
            Waypoint bestStorageLocation = null;

            foreach (var storageLocation in Instance.ResourceManager.UnusedPodStorageLocations)
            {
                // Update current candidate
                _currentStorageLocation = storageLocation;
                // Assess new candidate
                if (_bestCandidateSelector.Reassess())
                {
                    bestStorageLocation = _currentStorageLocation;
                }
            }
            // Return it
            return(bestStorageLocation);
        }
Exemplo n.º 21
0
        public int solution(int[] A)
        {
            int n    = A.Length;
            var pods = new Pod[n];

            for (var i = 0; i < n; i++)
            {
                pods[i] = new Pod {
                    Val = A[i], Index = i
                };
            }
            Array.Sort(pods);

            var nodes = new Node[n];

            for (var i = 0; i < n; i++)
            {
                nodes[i] = new Node {
                };
            }

            var total = 0;
            var count = 0;

            for (var i = n - 1; i >= 0; i--, count++)
            {
                var pod    = pods[i];
                var offset = GetIndexAndUpdate(nodes, pod.Index);
                total += i - pod.Index + offset;
                if (total > 1000000000)
                {
                    return(-1);
                }
            }
            return(total);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Finds the best delivery task for the specified pod.
        /// Sets <code>bestDeliveryRequest</code> to null if none found, otherwise <code>bestDeliveryRequest</code> and <code>bestTimeForDeliveryRequest</code> are initialized.
        /// </summary>
        /// <param name="bot">The bot to consider.</param>
        /// <param name="pod">Pod to take.</param>
        /// <param name="podLocation">Current location of the pod.</param>
        /// <param name="bestExtractTask">The best extract task set by this method.</param>
        /// <param name="bestDistanceForExtract">The distance of the best extract set by this method.</param>
        void GetBestTaskForPod(Bot bot, Pod pod, Waypoint podLocation,
                               out ExtractRequest bestExtractTask, out double bestDistanceForExtract)
        {
            bestExtractTask        = null;
            bestDistanceForExtract = 0.0;

            bestExtractTask = null;
            if (pod == null || podLocation == null)
            {
                return;
            }

            bestDistanceForExtract = double.PositiveInfinity;

            // Check all tasks
            foreach (var delivery in Instance.ResourceManager.AvailableAndAssignedExtractRequests)
            {
                // If it has the item
                if (pod.IsContained(delivery.Item))
                {
                    // See how long it would take to get to the output-station
                    // Choose the worst of delivering or waiting
                    Waypoint sw = delivery.Station.Waypoint; // fixed per item
                                                             //double distance = Math.Max(Estimators.EstimateTravelTimeEuclid(bot, podLocation, sw), Estimators.EstimateOutputStationWaitTime(bot, sw));
                    double distance = (bot.GetDistance(sw) + ((bot.Tier == sw.Tier) ? 0 : bot.Instance.WrongTierPenaltyDistance));
                    //double waitDistance = ((ws.ItemTransferTime + 5 * 2 * bot.Radius) / bot.MaxVelocity) * w.BotCountOverall * w.BotCountOverall; // TODO this time estimate cannot hold when transferring multiple items at once

                    // If it's the best, then use it
                    if (distance < bestDistanceForExtract)
                    {
                        bestExtractTask        = delivery;
                        bestDistanceForExtract = distance;
                    }
                }
            }
        }
Exemplo n.º 23
0
        private IEnumerable <PodService> GetPodServices(Pod pod)
        {
            var serviceAnnotations = pod.PodAnnotations.Where(x => x.Key.StartsWith(KubernetesConstants.ServicePrefixAnnotation));

            foreach (var annotation in serviceAnnotations)
            {
                if (_serviceAnnotationMapper.TryMap(annotation.Key, annotation.Value, pod.PodPorts, out var parsedPodServiceAnnotation, out var parseErrors))
                {
                    yield return(new PodService(
                                     pod.Uid,
                                     parsedPodServiceAnnotation.ServiceName,
                                     parsedPodServiceAnnotation.Port,
                                     parsedPodServiceAnnotation.Tags,
                                     parsedPodServiceAnnotation.Scope
                                     ));
                }

                if (parseErrors.Count > 0)
                {
                    var errors = string.Join(", ", parseErrors.GetErrorMessages());
                    Logger.Warn($"Errors occured while parsing the annotation '{annotation.Key}' '{annotation.Value}' on pod '{pod.Name}': {errors}.");
                }
            }
        }
Exemplo n.º 24
0
        static int FindFirstNoLess(Pod root, int t, int c, bool rev, int len)
        {
            var lastp = root;
            int lastMax = 0;
            for (var p = root; p != null;)
            {
                if (p.MaxSt[c] > 0)
                {
                    lastMax = p.MaxSt[c];
                    var cmp = t.CompareTo(lastMax);
                    lastp = (rev ^ (cmp > 0)) ? GetRightmost(p) : GetLeftmost(p);
                    break;
                }
                else
                {
                    lastMax = p.Max[c];
                    var cmp = t.CompareTo(lastMax);
                    lastp = p;
                    p = (rev ^ (cmp > 0)) ? p.Right : p.Left;
                }
            }

            return (lastMax < t) ? (rev ? lastp.Index - 1 : lastp.Index + 1) : lastp.Index;
        }
Exemplo n.º 25
0
        public async Task FullQueryTest2()
        {
            FullResultRequest req = new FullResultRequest("Pi");

            FullResultResponse resp = await Client.FullResultAsync(req).ConfigureAwait(false);

            Assert.True(resp.IsSuccess);
            Assert.False(resp.IsError);

            Pod    inputPod    = resp.Pods.Single(x => x.Title == "Input");
            SubPod inputSubPod = Assert.Single(inputPod.SubPods);

            //Check if we can represent symbols correctly
            Assert.Equal("π", inputSubPod.Plaintext);

            Pod altRepresent = resp.Pods.Single(x => x.Title == "Alternative representations");

            Assert.Equal(4, altRepresent.Infos.Count);

            State state = Assert.Single(altRepresent.States);

            Assert.Equal("More", state.Name);
            Assert.Equal("AlternativeRepresentations:MathematicalFunctionIdentityData__More", state.Input);
        }
Exemplo n.º 26
0
        private static async Task RunCounters(Pod pod, CountersMode?mode, string[]?extraArgs)
        {
            try
            {
                await Kubectl.ExecEmbeddedSingleLineShellScript(pod, "install-dotnet-counters.sh");

                var countersArguments = new List <string>()
                {
                    "dotnet", "/diagnostics/dotnet-counters/tools/netcoreapp2.1/any/dotnet-counters.dll"
                };

                if (mode != null)
                {
                    switch (mode.Value)
                    {
                    case CountersMode.Monitor:
                        countersArguments.AddRange(new[] { "monitor", "--process-id", "1" });
                        break;

                    case CountersMode.Collect:
                        countersArguments.AddRange(new[] { "collect", "--process-id", "1" });
                        break;
                    }
                }

                if (extraArgs != null)
                {
                    countersArguments.AddRange(extraArgs);
                }

                await Kubectl.Exec(pod, true, countersArguments);
            }
            catch (KubectlException)
            {
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Determine whether the target SDK needs to be updated based upon pod
        /// dependencies.
        /// </summary>
        /// <returns>Key value pair of minimum SDK version (key) and
        /// a list of pod names that require it (value) if the currently
        /// selected target SDK version does not satify pod requirements, the list
        /// (value) is null otherwise.</returns>
        private static KeyValuePair <int, List <string> > TargetSdkNeedsUpdate()
        {
            var kvpair            = new KeyValuePair <int, List <string> >(0, null);
            var podListsByVersion = Pod.BucketByMinSdkVersion(pods.Values);

            if (podListsByVersion.Count == 0)
            {
                return(kvpair);
            }
            KeyValuePair <int, List <string> > minVersionAndPodName = kvpair;

            foreach (var versionAndPodList in podListsByVersion)
            {
                minVersionAndPodName = versionAndPodList;
                break;
            }
            int currentVersion = TargetSdkVersion;

            if (currentVersion >= minVersionAndPodName.Key)
            {
                return(kvpair);
            }
            return(minVersionAndPodName);
        }
Exemplo n.º 28
0
        /// <summary>
        /// <c>kubectl cp demo-global-admin-processor-58dd4cbcff-fmfgw:/app/processor/trace.speedscope.json /temp/trace.speedscope.json</c>
        /// </summary>
        public static async Task <string> DownloadFile(Pod pod, string containerPath)
        {
            var index    = containerPath.LastIndexOf('/');
            var fileName = index == -1
                ? containerPath
                : containerPath.Substring(index + 1);

            var localPath = Path.Combine(Path.GetTempPath(), fileName);

            Console.WriteLine($"Downloading {containerPath} to {localPath}");

            var arguments = new List <string>()
            {
                "cp",
                pod.Namespace == null
                    ? $"{pod.Name}:{containerPath}"
                    : $"{pod.Namespace}/{pod.Name}:{containerPath}",
                fileName
            };

            await Run(false, arguments);

            return(localPath);
        }
Exemplo n.º 29
0
        string calculateSluggerThrust(List <Pod> pods, List <Tuple <int, int> > checkpoints)
        {
            int e1Progress = getProgress(pods[2]);
            int e2Progress = getProgress(pods[3]);

            Pod    pod  = e1Progress >= e2Progress ? pods[2] : pods[3];
            Vector podV = pod.position.sub(position);

            for (int i = 2; i < 4; i++)
            {
                if (willCollide(pods[i]))
                {
                    return("0 0 SHIELD");
                }
            }
            if (podV.length() > 3000)
            {
                return(checkpoints[pod.nextCheckpointId].Item1 + " " + checkpoints[pod.nextCheckpointId].Item2 + " 100");
            }
            else
            {
                return((pod.position.x + pod.speed.x) + " " + (pod.position.y + pod.speed.y) + " 100");
            }
        }
        public IActionResult CreatePod(Pod pod)
        {
            _logger.LogInformation($"CreatePod: {pod.Metadata.Namespace}:{pod.Metadata.Name}");
            // update state so that we show as running!
            pod.Status.Phase      = PodPhase.Running;
            pod.Status.Conditions = new[] {
                new PodCondition {
                    Type = PodConditionType.PodScheduled, Status = PodConditionStatus.True
                },
                new PodCondition {
                    Type = PodConditionType.Initialized, Status = PodConditionStatus.True
                },
                new PodCondition {
                    Type = PodConditionType.Ready, Status = PodConditionStatus.True
                },
            };
            pod.Status.ContainerStatuses = pod.Spec.Containers
                                           .Select(container => new ContainerStatus
            {
                Name  = container.Name,
                Image = container.Image,
                Ready = true,
                State = new ContainerState
                {
                    Running = new ContainerStateRunning
                    {
                        StartedAt = DateTime.UtcNow
                    }
                }
            })
                                           .ToArray();

            _podStore.AddPod(pod);

            return(Ok());
        }
Exemplo n.º 31
0
 public GameMove GetMoveHit(Pod[] pods, Pod[] opps, int ind)
 {
     Pod[] allPods = new Pod[] { pods[0], pods[1], opps[0], opps[1] };
     return GetMoveHit(allPods, ind);
 }
Exemplo n.º 32
0
 public GameMove DefendCP(Pod pod, Pod opp, int CP)
 {
     return DefendCP(pod, opp, cp[CP]);
 }
Exemplo n.º 33
0
        static public void UpdateAngle(Pod[] pod, GameMove[] move)
        {
            for (int i = 0; i < 4; i++)
            {
                double angle1 = SpeedAngle(move[i].Destination - pod[i].p);
                double angleDiff = angle1 - pod[i].Angle;
                if (angleDiff > 180) angleDiff -= 360;
                else if (angleDiff < -180) angleDiff += 360;

                if (angleDiff > 18) angleDiff = 18;
                else if (angleDiff < -18) angleDiff = -18;
                pod[i].Angle = (int)Math.Round(pod[i].Angle + angleDiff) % 360;
                if (pod[i].Angle < 0) pod[i].Angle += 360;
            }
            //for (int i = 0; i < 2; i++)
            //{
            //    Console.Error.WriteLine("New angle = {0}", pod[i].Angle);
            //}
        }
Exemplo n.º 34
0
 public Settings(Pod associatedPod)
 {
     mAssociatedPod = associatedPod;
     mAssociatedPod.AddFunction("OnTick", OnTick);
 }
Exemplo n.º 35
0
        /*
        public bool IsDatabaseEntry(string groupName)
        {
            foreach (KeyValuePair<string, MurpleDefinition> murpleDefinition in mDefinitions)
            {
                MurpleDefinition value = murpleDefinition.Value;

                foreach (KeyValuePair<string, StatBase> definitionNode in value.mDefinition)
                {
                    string nodeKey = definitionNode.Key;
                    StatBase nodeValue = definitionNode.Value;

                    if (nodeKey == groupName && (nodeValue.mType == Type.Database || nodeValue.mType == Type.DatabaseList))
                    {
                        return true;
                    }
                }
            }

            return false;// mDatabase.IsGroupName(groupName);
        }

        public MURPLE.Pod GetPod(string murpleID)
        {
            MURPLE.Pod murple = null;

            if (HasPOD(murpleID))
            {
                murple = mMurples[murpleID];
            }

            return murple;
        }

        public void AddBaseMurple(string baseMurpleName)
        {
            DebugUtils.Assert(mBaseMurpleNames.Contains(baseMurpleName) == false, string.Format("Duplicate base murple name: {0}", baseMurpleName));

            if (mBaseMurpleNames.Contains(baseMurpleName) == false)
                mBaseMurpleNames.Add(baseMurpleName);
        }
        */
        /*
        public void AddPod(string podName, Pod newPod, string podGroupName)
        {
            if (HasPod(podName) == true)
                mPods[podName] = newPod;
            else
                mPods.Add(podName, newPod);

            if (mPodGroups.ContainsKey(podGroupName) == false)
                mPodGroups.Add(podGroupName, new PodGroup());
            if(mPodGroups[podGroupName].ContainsPod(podName) == false)
                mPodGroups[podGroupName].AddPod(podName);
        }
        */
        public void AddPod(System.Guid podUUID, Pod newPod, string podGroupName)
        {
            if (HasPod(podUUID) == true)
                mPods[podUUID] = newPod;
            else
                mPods.Add(podUUID, newPod);

            if (mPodGroups.ContainsKey(podGroupName) == false)
                mPodGroups.Add(podGroupName, new PodGroup());
            if (mPodGroups[podGroupName].ContainsPod(podUUID) == false)
                mPodGroups[podGroupName].AddPod(podUUID);
        }
Exemplo n.º 36
0
        public GameMove GetMove(Pod pod)
        {
            double distanceToGoal = Math.Sqrt(Dist(cp[pod.NextCP], pod.p));
            //Console.Error.WriteLine("Distance to goal = {0}", distanceToGoal);
            double distanceFromGoalToSpeedLine = DistFromPointToLine(pod.p,
                new Point(pod.X + pod.VX, pod.Y + pod.VY), cp[pod.NextCP]);
            //Console.Error.WriteLine("Distance from goal to speedline = {0}", distanceFromGoalToSpeedLine);

            bool shield = false;
            int thrust = 0;
            Point destPoint;
            destPoint = Destination(pod.p, cp[pod.NextCP], new Point(pod.X + pod.VX * 3, pod.Y + pod.VY * 3));

            bool lastCP = (pod.Lap == laps) && (pod.NextCP == 0);

            double speedAngle = SpeedAngle(pod.v);
            Point goalVector, nextGoalVector;
            goalVector.x = cp[pod.NextCP].x - pod.X;
            goalVector.y = cp[pod.NextCP].y - pod.Y;
            //nextGoalVector.x = cp[(pod.NextCP + 1) % C].x - pod.X;
            //nextGoalVector.y = cp[(pod.NextCP + 1) % C].y - pod.Y;
            nextGoalVector.x = cp[(pod.NextCP + 1) % C].x - cp[pod.NextCP].x;
            nextGoalVector.y = cp[(pod.NextCP + 1) % C].y - cp[pod.NextCP].y;
            double goalAngle = SpeedAngle(goalVector);
            double nextGoalAngle = SpeedAngle(nextGoalVector);
            //Console.Error.WriteLine("Speed Angle = {0}", speedAngle);
            //Console.Error.WriteLine("Goal Angle = {0}", goalAngle);
            double ourAngle = Math.Min(Math.Abs(speedAngle - goalAngle),
                Math.Min(Math.Abs(speedAngle - goalAngle - 360.0),
                Math.Abs(speedAngle - goalAngle + 360.0)));
            double anglediff = AngleDiff(goalAngle, nextGoalAngle);
            if (ourAngle > 90) destPoint = cp[pod.NextCP];

            //Console.Error.WriteLine(ourAngle);
            //double angle = Angle(cp[pod.NextCP], pod.p, pod.angle);
            double angle = Math.Min(Math.Abs(pod.Angle - goalAngle),
                Math.Min(Math.Abs(pod.Angle - goalAngle - 360.0),
                Math.Abs(pod.Angle - goalAngle + 360.0)));
            //Console.Error.WriteLine(angle);
            //Console.Error.WriteLine("Our angle = {0}", pod.Angle);
            if (lastCP)
            {
                //destPoint.Print();
                thrust = 220 - (int)(angle * angle) / 24;
                if (thrust < 80) thrust = 80;
                if (thrust > 200) thrust = 200;
                //return new GameMove(destPoint, thrust);
            }
            else if (distanceFromGoalToSpeedLine < 480)
            {

                //Console.Error.WriteLine("Next Goal Angle = {0}", nextGoalAngle);
                double angle2 = AngleDiff(nextGoalAngle, pod.Angle);
                double timeToStart = Math.Abs(angle2) / 18.0;
                double V = pod.v.Module();
                //bool toBrake = 
                //double actualTime = distanceToGoal /
                //    Math.Sqrt(pod.VX * pod.VX + pod.VY * pod.VY);
                double actualTime = Double.MaxValue;
                if (0.15 * distanceToGoal < V)
                    actualTime = (-6.153) * Math.Log(1 - 0.15 * (distanceToGoal - 450) / V) + 0.2;
                //Console.Error.WriteLine("{0} {1}", timeToStart, actualTime);

                //double threshold = 0.85;
                //if (angle2 > 105) threshold = 0.5;
                //else if (angle2 < 30) threshold = 1.05;
                if (timeToStart > actualTime)
                {
                    // start braking
                    thrust = 0;
                    destPoint = cp[(pod.NextCP + 1) % C];
                    pod.braking = true;
                    if (actualTime > 4 && distanceFromGoalToSpeedLine < 380) shield = true;
                }
                else
                {
                    thrust = 220 - (int)(angle * angle) / 13;
                    if (thrust < 65) thrust = 65;
                    if (thrust > 200) thrust = 200;
                    pod.braking = false;
                }
            }
            else {
                thrust = 225 - (int)(angle * angle) / 13;
                if (thrust < 65) thrust = 65;
                if (thrust > 200) thrust = 200;
                pod.braking = false;
            }
            return new GameMove(destPoint, thrust, shield);
        }
Exemplo n.º 37
0
 public Situation(Pod myPod1, Pod myPod2, Pod oppPod1, Pod oppPod2)
 {
     pods = new Pod[] { myPod1, myPod2, oppPod1, oppPod2 };
 }
Exemplo n.º 38
0
 public Situation(Pod[] myPod, Pod[] oppPod)
 {
     pods = new Pod[] { myPod[0], myPod[1], oppPod[0], oppPod[1] };
 }
Exemplo n.º 39
0
 public Pod(Pod oldPod) : this(oldPod.X, oldPod.Y, oldPod.VX, oldPod.VY, oldPod.Angle, oldPod.NextCP)
 {
     Lap = oldPod.Lap; WaitToThrust = oldPod.WaitToThrust;
 }
Exemplo n.º 40
0
 static public bool Collision(Pod pod1, Pod pod2)
 {
     var dX = pod1.X - pod2.X; var dY = pod1.Y - pod2.Y;
     return dX * dX + dY * dY <= 640000; // 640000 = (2*radius)^2
 }
Exemplo n.º 41
0
        static public void ProcessCollision(ref Pod pod1, ref Pod pod2, GameMove move1, GameMove move2, double alpha)
        {
            //Console.Error.WriteLine("pre: speed1 ({0},{1}), speed2 ({2},{3})", pod1.VX, pod1.VY, pod2.VX, pod2.VY);
            pod1.p += new Point(pod1.v * alpha);
            pod2.p += new Point(pod2.v * alpha);
            //double d = Math.Sqrt(Math.Pow(pod1.X - pod2.X, 2) + Math.Pow(pod1.Y - pod2.Y, 2));
            double d = (pod1.p - pod2.p).Module();
            PointD n = (pod2.p - pod1.p) * (1.0 / d);
            int m1 = 1 + (move1.Shield ? 9 : 0); int m2 = 1 + (move2.Shield ? 9 : 0);
            double p = 2.0 * (pod1.v * n - pod2.v * n) / (m1 + m2);
            PointD deltaV1 = n * (p * m2);
            PointD deltaV2 = n * (p * m1);
            double deltaImpulse = Math.Sqrt(deltaV1.x * deltaV1.x + deltaV1.y * deltaV1.y);
            if (deltaImpulse < 240)
            {
                double beta = ((240 - deltaImpulse) / 2.0) / deltaImpulse;
                p += p * beta;
            }
            PointD w1 = pod1.v - deltaV1;
            PointD w2 = pod2.v + deltaV2;

            pod1.v = new Point(w1);
            pod2.v = new Point(w2);

            pod1.p += new Point(pod1.v * (1 - alpha));
            pod2.p += new Point(pod2.v * (1 - alpha));
        }
Exemplo n.º 42
0
        static public void UpdatePos(Pod[] pod, GameMove[] move)
        {
            for (int i = 0; i < 4; i++)
            {
                if (move[i].Shield) pod[i].WaitToThrust = 3;
                else pod[i].WaitToThrust--;
                if (pod[i].WaitToThrust > 0) move[i].Thrust = 0;
            }
            // 1. Target:
            UpdateAngle(pod, move);
            // 2. Thrust:
            PointD[] dV = new PointD[4];
            for (int i = 0; i < 4; i++)
            {
                // possible optimization - pump Sin values for all degrees 0..90 into array
                // + transformation to get all 0..360
                dV[i] = GetVector(pod[i].Angle, move[i].Thrust);
                pod[i].v += new Point(dV[i]);
            }
            bool[] collided = new bool[4];
            // 3. Movement (+collision):
            // TODO: multiple simultaneous collisions case
            for (int i = 0; i < 3; i++)
            {
                for (int j = i + 1; j < 4; j++)
                {
                    Point pos1 = pod[i].p + (pod[i].v - pod[j].v);
                    long denom = Dist(pod[i].p, pos1);
                    long b = (pod[i].VX - pod[j].VX) * (pod[i].X - pod[j].X) +
                        (pod[i].VY - pod[j].VY) * (pod[i].Y - pod[j].Y);
                    double sD = Math.Sqrt(b * b - denom * (Dist(pod[i].p, pod[j].p) - 640000));
                    double alpha1 = (-b + sD) / denom;
                    double alpha2 = (-b - sD) / denom;
                    bool bam = true;
                    if (alpha1 > 0 && alpha1 < 1)
                    {
                        if (alpha2 > 0 && alpha2 < alpha1)
                        {
                            // alpha2 - point of collision
                            ProcessCollision(ref pod[i], ref pod[j], move[i], move[j], alpha2);
                        }
                        else
                        {
                            // alpha1 - point of collision
                            ProcessCollision(ref pod[i], ref pod[j], move[i], move[j], alpha1);
                        }
                    }
                    else if (alpha2 > 0 && alpha2 < 1)
                    {
                        // alpha2 - point of collision
                        ProcessCollision(ref pod[i], ref pod[j], move[i], move[j], alpha2);
                    }
                    else
                    {
                        bam = false;
                    }
                    //no collision

                    if (bam)
                    {
                        collided[i] = true; collided[j] = true;
                        //Console.Error.WriteLine("pod {0} and pod {1} collided; bf speed 1:({2},{3}), 2:({4},{5})",
                        //    i, j, pod[i].VX, pod[i].VY, pod[j].VX, pod[j].VY);
                    }
                }
            }

            for (int i = 0; i < 4; i++)
            {
                if (!collided[i])
                {
                    pod[i].p += pod[i].v;
                }

                if (pod[i].CrossedCP(100 * ((3 - i) / 2)))
                {
                    if (pod[i].NextCP == 0)
                    {
                        pod[i].Lap++;
                        //if (pod[i].Lap > laps)
                        //{
                        //    // game over
                        //    // pod[i] is winner
                        //}
                    }
                    pod[i].NextCP = (pod[i].NextCP + 1) % C;
                }
            }

            // 4. Friction:
            for (int i = 0; i < 4; i++)
            {
                pod[i].VX = (int)Math.Truncate(pod[i].VX * Friction);
                pod[i].VY = (int)Math.Truncate(pod[i].VY * Friction);
            }

        }
Exemplo n.º 43
0
        public GameMove GetMoveHit(Pod[] pods, int ind)
        {
            double u1 = pods[2].Utility();
            double u2 = pods[3].Utility();
            int toHunt = 2;
            //Console.Error.WriteLine("u1 = {0}, u2 = {1}", u1, u2);
            if (u2 > u1) toHunt = 3;
            double toNextCP = Math.Sqrt(Dist(pods[toHunt].p, cp[pods[toHunt].NextCP]));
            //double toNextCP1 = Math.Sqrt(Dist(pods[ind].p, cp[pods[toHunt].NextCP]));
            double toNextCP1 = DistFromPointToLine2(pods[toHunt].p, cp[pods[toHunt].NextCP], pods[ind].p);
            double distToOpp = Math.Sqrt(Dist(pods[ind].p, pods[toHunt].p));
            
            bool shield = false;
            Point dest = PointOnLineSegment(pods[toHunt].p, cp[pods[toHunt].NextCP], pods[ind].p);
            double angleDiff = AngleDiff(pods[ind].Angle, SpeedAngle(dest - pods[ind].p));
            int thrust = 80;
            string message = "";
            // can make better condition:
            if ((toNextCP1 < 0.7 * toNextCP && angleDiff < 140)|| distToOpp < 950)
            {
                message = "Hitting you " + toNextCP + " " + toNextCP1;

                if (distToOpp < 1500) shield = true;
                
                dest = new Point((dest*2 + cp[pods[toHunt].NextCP] + pods[toHunt].p) * 0.25);


                Point goalVector = dest - pods[ind].p;
                double goalAngle = SpeedAngle(goalVector);
                double angle = Math.Min(Math.Abs(pods[ind].Angle - goalAngle),
                    Math.Min(Math.Abs(pods[ind].Angle - goalAngle - 360.0),
                    Math.Abs(pods[ind].Angle - goalAngle + 360.0)));
                thrust = 215 - (int)(angle * angle) / 15;
                if (thrust < 80) thrust = 80;
                if (thrust > 200) thrust = 200;
                //if (toNextCP1 < 0.36 * toNextCP)
                //{
                //    dest = (dest + pods[toHunt].p) / 2.0;
                //    thrust -= 20;
                //}
                if (toNextCP1 < 0.22 * toNextCP)
                {
                    dest = pods[toHunt].p;
                    //thrust -= 50;
                }
            }
            else
            {
                double dist2 = Math.Sqrt(Dist(pods[ind].p, cp[pods[toHunt].NextCP]));
                
                //dest = pods[toHunt].p;
                Point pointToDefend = (cp[pods[toHunt].NextCP] * 4 + cp[(pods[toHunt].NextCP + 1) % C]*0 + pods[toHunt].p) / 5.0;
                
                //double alpha = 1 - toNextCP / Math.Sqrt(Dist(cp[(pods[toHunt].NextCP + C - 1) % C], cp[pods[toHunt].NextCP]));
                message = "Getting ready to hit you ";// + alpha;
                //if (dist2 * 0.17 < toNextCP)
                //{
                //    message = "; flying to other one";
                //    pointToDefend = (cp[pods[toHunt].NextCP] + cp[(pods[toHunt].NextCP + 1) % C] * 4 + pods[toHunt].p * 0) / 5.0;
                //}
                //double alpha2 = toNextCP1 / Math.Sqrt(Dist(cp[(pods[toHunt].NextCP + C - 1) % C], cp[pods[toHunt].NextCP]));
                //if (alpha > 0.7)
                //{
                //    alpha = 0.6;
                //    pointToDefend = (cp[pods[toHunt].NextCP] * (int)(1000*(1 - alpha)) + cp[(pods[toHunt].NextCP + 1) % C] * (int)(1000*alpha)) / 1000.0;
                //}
                if (pods[toHunt].NextCP == 0 && pods[toHunt].Lap == laps)
                {
                    pointToDefend = cp[0];
                }
                //GameMove res = DefendCP(pods[ind], pods[toHunt], pods[toHunt].NextCP);
                //GameMove res = DefendCP(pods[ind], pods[toHunt],
                //    (cp[pods[toHunt].NextCP] * 4 + cp[(pods[toHunt].NextCP + 1) % C]) / 5.0);
                //GameMove res = DefendCP(pods[ind], pods[toHunt],
                //    (pods[toHunt].p + cp[(pods[toHunt].NextCP + 1) % C]) / 2.0);
                GameMove res = DefendCP(pods[ind], pods[toHunt], pointToDefend);
                res.msg = message;
                return res;
                //dest = cp[(pods[toHunt].NextCP + 1) % C];

            }

         //   Console.Error.WriteLine("distToOpp = {0}", distToOpp);

            return new GameMove(dest, thrust, shield, message);
        }
Exemplo n.º 44
0
 public GameMove[] GetMoves(Pod[] pod, Pod[] opp)
 {
     GameMove[] moves = new GameMove[4];
     moves[0] = GetMove(pod[0]);
     moves[1] = GetMove(pod[1]);
     return moves;
 }
Exemplo n.º 45
0
 public Situation(Pod[] pod)
 {
     pods = pod;
 }
Exemplo n.º 46
0
 /// <summary>
 /// Update the iOS target SDK if it's lower than the minimum SDK
 /// version specified by the pod.
 /// </summary>
 /// <param name="pod">Pod to query for the minimum supported version.
 /// </param>
 /// <param name="notifyUser">Whether to write to the log to notify the
 /// user of a build setting change.</param>
 /// <returns>true if the SDK version was changed, false
 /// otherwise.</returns>
 private static bool UpdateTargetSdk(Pod pod,
                                     bool notifyUser = true) {
     int currentVersion = TargetSdkVersion;
     int minVersion = pod.MinTargetSdkToVersion();
     if (currentVersion >= minVersion) {
         return false;
     }
     if (notifyUser) {
         string oldSdk = TargetSdk;
         TargetSdkVersion = minVersion;
         Log("iOS Target SDK changed from " + oldSdk + " to " +
             TargetSdk + " required by the " + pod.name + " pod");
     }
     return true;
 }
Exemplo n.º 47
0
        public Situation SimulateHR(Pod pod1, Pod pod2, Pod opp1, Pod opp2, GameMove[] moves, int runner)
        {
            var strategy = new SimpleStrategy();

            Console.SetError(StreamWriter.Null);
            var fastStrat = new FastStrategy(OppDepth);

            moves[2] = strategy.GetMove(opp1);
            moves[3] = strategy.GetMove(opp2);

            var standardError = new StreamWriter(Console.OpenStandardError());
            standardError.AutoFlush = true;
            Console.SetError(standardError);

            Pod[] sPod = new Pod[4];
            sPod[0] = new Pod(pod1); sPod[1] = new Pod(pod2);
            sPod[2] = new Pod(opp1); sPod[3] = new Pod(opp2);
            Pod.UpdatePos(sPod, moves);

            GameMove[] moves2 = new GameMove[4];

            GameMove.Copy(moves, moves2, 4);

            for (int i = 0; i < SimpleSimDepth; i++)
            {
                moves2[runner] = strategy.GetMove(sPod[runner]);
                moves2[runner ^ 1] = strategy.GetMoveHit(sPod, runner ^ 1);

                moves2[2] = strategy.GetMove(sPod[2]);
                moves2[3] = strategy.GetMove(sPod[3]);
                Pod.UpdatePos(sPod, moves2);
            }

            return new Situation(sPod);
        }
Exemplo n.º 48
0
 /// <summary>
 /// Tells the app what pod dependencies are needed.
 /// This is called from a deps file in each API to aggregate all of the
 /// dependencies to automate the Podfile generation.
 /// </summary>
 /// <param name="podName">pod path, for example "Google-Mobile-Ads-SDK" to
 /// be included</param>
 /// <param name="version">Version specification.  See Pod.version.</param>
 /// <param name="bitcodeEnabled">Whether the pod was compiled with bitcode
 /// enabled.  If this is set to false on a pod, the entire project will
 /// be configured with bitcode disabled.</param>
 /// <param name="minTargetSdk">Minimum SDK revision required by this
 /// pod.</param>
 public static void AddPod(string podName, string version = null,
                           bool bitcodeEnabled = true,
                           string minTargetSdk = null) {
     Log("AddPod - name: " + podName +
         " version: " + (version ?? "null") +
         " bitcode: " + bitcodeEnabled.ToString() +
         " sdk: " + (minTargetSdk ?? "null"),
         verbose: true);
     var pod = new Pod(podName, version, bitcodeEnabled, minTargetSdk);
     pods[podName] = pod;
     UpdateTargetSdk(pod);
 }
Exemplo n.º 49
0
 /// <summary>
 /// Retrieves the time after which buffered bundles will be allocated even if they do not meet the threshold criterion.
 /// </summary>
 /// <param name="pod">The pod to get the timeout value for.</param>
 /// <returns>The buffer timeout.</returns>
 protected override double GetStorageBufferTimeout(Pod pod)
 {
     return(_classBufferTimeout[_classManager.DetermineStorageClass(pod)]);
 }
Exemplo n.º 50
0
        public Situation Simulate(Pod pod1, Pod pod2, Pod opp1, Pod opp2, GameMove[] moves, bool Opp = false)
        {
            var strategy = new SimpleStrategy();

            Console.SetError(StreamWriter.Null);
            var fastStrat = new FastStrategy(OppDepth);

            if (!Opp)
            {
                moves[2] = strategy.GetMove(opp1);
                moves[3] = strategy.GetMove(opp2);
            }
            else
            {
                GameMove[] oppMoves = fastStrat.GetMoves(new Pod[] { opp1, opp2 }, new Pod[] { pod1, pod2 });
                moves[2] = oppMoves[0];
                moves[3] = oppMoves[1];
            }

            var standardError = new StreamWriter(Console.OpenStandardError());
            standardError.AutoFlush = true;
            Console.SetError(standardError);

            Pod[] sPod = new Pod[4];
            sPod[0] = new Pod(pod1); sPod[1] = new Pod(pod2);
            sPod[2] = new Pod(opp1); sPod[3] = new Pod(opp2);
            Pod.UpdatePos(sPod, moves);

            GameMove[] moves2 = new GameMove[4];

            GameMove.Copy(moves, moves2, 4);

            for (int i = 0; i < SimpleSimDepth; i++)
            {
                moves2[0] = strategy.GetMove(sPod[0]);
                moves2[1] = strategy.GetMove(sPod[1]);
                moves2[2] = strategy.GetMove(sPod[2]);
                moves2[3] = strategy.GetMove(sPod[3]);
                Pod.UpdatePos(sPod, moves2);
            }

            return new Situation(sPod);
        }
Exemplo n.º 51
0
 static List<Point> cp = new List<Point>(); // checkpoints
 static void InitialInput()
 {
     laps = int.Parse(Console.ReadLine());
     C = int.Parse(Console.ReadLine());
     for (int i = 0; i < C; i++)
     {
         inputs = Console.ReadLine().Split(' ');
         Point point;
         point.x = int.Parse(inputs[0]);
         point.y = int.Parse(inputs[1]);
         cp.Add(point);
     }
     pod[0] = new Pod(); pod[1] = new Pod();
     opp[0] = new Pod(); opp[1] = new Pod();
 }
Exemplo n.º 52
0
 /// <summary>
 /// Retrieves the threshold value above which buffered decisions for that respective pod are submitted to the system.
 /// </summary>
 /// <param name="pod">The pod to get the threshold value for.</param>
 /// <returns>The threshold value above which buffered decisions are submitted. Use 0 to immediately submit decisions.</returns>
 protected override double GetStorageBufferThreshold(Pod pod)
 {
     return(_classReservedCapacityPercentageForRefill[_classManager.DetermineStorageClass(pod)]);
 }
Exemplo n.º 53
0
        public GameMove[] GetMoves(Pod[] pod, Pod[] opp)
        {
            GameMove[] moves = new GameMove[4];
            moves = (new SimpleStrategy()).GetMoves(pod, opp);

            List<GameMove[]> altMoves = GameMove.GenerateMoves(moves);

            Simulator sim = new Simulator();
            double maxU = Double.MinValue;
            int maxInd = 0;
            for (int i = 0; i < altMoves.Count; i++)
            {
                Situation situation = sim.Simulate(pod[0], pod[1], opp[0], opp[1], altMoves[i], Opp);

                //Console.Error.WriteLine("thrust1: {0}, thrust2: {1}", altMoves[i][0].Thrust, altMoves[i][1].Thrust);
                //situation.Print();
                double utility = situation.Utility();
                //Console.Error.WriteLine("Utility {0} = {1}", i, utility);
                if (utility > maxU)
                {
                    maxU = utility; maxInd = i;
                }
            }
            GameMove moveWithShield = GameMove.MoveWithShield(altMoves[maxInd][0]);
            Situation sit = sim.Simulate(pod[0], pod[1], opp[0], opp[1], new GameMove[] {
                moveWithShield, altMoves[maxInd][1], altMoves[maxInd][2], altMoves[maxInd][3]});
            if (sit.Utility() > maxU + 30 && !(pod[0].Lap == laps && pod[0].NextCP == 0))
            {
                //moveWithShield.Print();
                altMoves[maxInd][0] = moveWithShield;
            }

            moveWithShield = GameMove.MoveWithShield(altMoves[maxInd][1]);
            sit = sim.Simulate(pod[0], pod[1], opp[0], opp[1], new GameMove[] {
                altMoves[maxInd][0], moveWithShield, altMoves[maxInd][2], altMoves[maxInd][3]});
            if (sit.Utility() > maxU + 40 && !(pod[1].Lap == laps && pod[1].NextCP == 0))
            {
                //moveWithShield.Print();
                altMoves[maxInd][1] = moveWithShield;
            }

            return altMoves[maxInd];
        }
Exemplo n.º 54
0
 public GameMove GetMove(Pod pod)
 {
     var strategy = new SimpleStrategy();
     //
     return strategy.GetMove(pod);
 }
Exemplo n.º 55
0
        private System.Guid XmlToPod(Control murpleControl, XmlNode thisPodAsXml, ref Pod newPod, string filename)
        {
            //DebugUtils.Assert (newPod != null, "Pod has not been created.");
            System.Guid podUUID = System.Guid.Empty;
            XmlNodeList allChildren = thisPodAsXml.ChildNodes;
            bool uuidFound = false;

            foreach(XmlNode thisChild in allChildren)
            {
                string name = thisChild.Name;
                XmlNode statTypeNode = thisChild.Attributes.GetNamedItem("statType");
                string statType = statTypeNode.Value;
                string statValue = thisChild.InnerText;

                if (name == "UUID")
                {
                    uuidFound = true;
                    // Can't do this in .Net 3.5 (Unity)
                    //if( System.Guid.TryParse(statValue, out podUUID) == false)
                    //{
                    //    podUUID = Pod.GenerateUUID();
                    //}
                    if (thisChild.InnerText == "")
                    {
                        podUUID = System.Guid.NewGuid();
                    }
                    else
                    {
                        podUUID = new System.Guid(thisChild.InnerText);    // Have to do this non-safe way :(
                    }

                    if (murpleControl.HasPod(podUUID) == true)
                    {
                        newPod = murpleControl.GetPod(podUUID);
                    }

                }
                else if (newPod.Stats.ContainsKey(name) == true)
                {
                    System.Diagnostics.Debug.Assert(uuidFound == true);

                    StatBase thisStatBase = newPod.Stats[name];

                    // FILLMEIN
                    if (thisStatBase.IsStatType(StatHelper.StatType.DatabaseType))
                        XmlToDatabase(thisChild, ref thisStatBase);
                    else if (thisStatBase.IsStatType(StatHelper.StatType.StringList))
                        XmlToStringList(thisChild, ref thisStatBase);
                    else if (thisStatBase.IsStatType(StatHelper.StatType.StringIntDictionary))
                        XmlToStringIntDictionary(thisChild, ref thisStatBase);
                    else if (thisStatBase.IsStatType(StatHelper.StatType.Pod))
                    {
                        Stat<Pod> newChildPod = GetPod(murpleControl, thisChild, filename, name);

                        //System.Guid childPodUUID = System.Guid.Parse(thisChild.InnerText);
                        System.Guid childPodUUID = new System.Guid(thisChild.InnerText);

                        System.Diagnostics.Debug.Assert(childPodUUID != System.Guid.Empty);

                        murpleControl.AddPod(childPodUUID, newChildPod.Value, filename);
                        thisStatBase = newChildPod;

                        /*
                        // The Xml has a reference to the name of the pod, we can create a dummy one here to be filled in later.
                        // Or if the Pod is already loaded than we will link it here.
                        Stat<Pod> newChildPod = new Stat<Pod>(new Pod());
                        string childPodName = thisChild.InnerText;

                        if (murpleControl.HasPod(childPodName))
                            newChildPod.Value = murpleControl.GetPod(childPodName);
                        else
                            newChildPod.Value = murpleControl.AddMurpleFromDefinition(name); ;

                        murpleControl.AddPod(childPodName, newChildPod.Value, filename);
                        thisStatBase = newChildPod;
                        */
                    }
                    else if (thisStatBase.IsStatType(StatHelper.StatType.PodList))
                    {
                        List<Pod> podList = new List<Pod>();
                        Stat<List<Pod>> podListStat = new Stat<List<Pod>>(podList);

                        XmlNodeList podListChildren = thisChild.ChildNodes;

                        foreach(XmlNode podChild in podListChildren)
                        {
                            string childPodType = podChild.Name;
                            string childStatType = podChild.Attributes.GetNamedItem("statType").Value;
                            System.Diagnostics.Debug.Assert(childStatType == "pod");

                            Stat <Pod> newChildPod = GetPod(murpleControl, podChild, filename, childPodType);

                            /*
                            if (murpleControl.HasPod(childPodUUID) == false)
                            {
                                murpleControl.AddPod(childPodUUID, newChildPod.Value, filename);
                            }
                            else
                            {
                                newChildPod.                                 = murpleControl.GetPod(childPodUUID);
                            }
                             * */

                            podList.Add(newChildPod.Value);

                        }

                        podListStat.Value = podList;
                        thisStatBase = podListStat;
                    }
                    else if (thisStatBase.IsStatType(StatHelper.StatType.Image))
                    {
                        XmlToImage(thisChild, ref thisStatBase);
                    }
                    else if (statValue != "")
                    {
                        thisStatBase.SetValueFromString(statValue);

                        // If it's a name then add a helper string for name for quick getting instead of having to go through the stats.
                        if (newPod.Name == "" && StatHelper.IsStatType(thisStatBase, StatHelper.StatType.String) && name.ToLower() == "name")
                        {
                            newPod.Name = statValue;
                        }

                    }
                    else
                        System.Diagnostics.Debug.Assert(false, string.Format("You haven't provided a way to extract a {0} from XML yet.", thisStatBase.GetType().ToString()));

                    newPod.Stats[name] = thisStatBase;

                }
            }
            return podUUID;
        }