Пример #1
0
 // To protect from overposting attacks, please enable the specific properties you want to bind to, for
 // more details see https://aka.ms/RazorPagesCRUD.
 public IActionResult OnGet(string propName = "propaneTank")
 {
     if (propName == "propaneTank")
     {
         PList  = _pMgr.GetRecentToLastList();
         PEquip = Settings.ActiveEquip.Where(e => e.IsPropane()).ToList();
         if (PEquip.Count > 0)
         {
             var Props = PEquip[0].GetProps();
             if ((Props != null) && Props.Count >= 2)
             {
                 KeyValuePair <string, double> kvp = Props.Find(k => k.Key.Contains("Tank"));
                 if (!kvp.Equals(new KeyValuePair <string, double>()))
                 {
                     TankSize = kvp.Value;
                 }
                 kvp = Props.Find(k => k.Key.Contains("Price"));
                 if (!kvp.Equals(new KeyValuePair <string, double>()))
                 {
                     PricePerGal = kvp.Value;
                 }
             }
         }
     }
     return(Page());
 }
Пример #2
0
    private void IdleState()
    {
        idle = (fsm, gameObj) => {
            List <KeyValuePair <string, object> > worldState = goapAgent.GetWorldState();

            KeyValuePair <string, object> goal = goapAgent.GetSubGoals();
            planner.Reset();
            if (!goal.Equals(new KeyValuePair <string, object>()))
            {
                Queue <GoapAction> plan = planner.Plan(availableActions, worldState, goal);

                if (plan != null)
                {
                    // we have a plan, hooray!
                    currentActions = plan;
                    goapAgent.PlanFound(goal, plan);

                    fsm.popState();
                    fsm.pushState(act);
                }
                else
                {
                    goapAgent.PlanFailed(goal);
                    fsm.popState();
                    fsm.pushState(idle);
                }
            }
            else
            {
                goapAgent.GameFinished();
            }
        };
    }
Пример #3
0
        private async Task <bool> TryPlayPreviousAsync(bool ignoreLoopOne)
        {
            this.isPlayingPreviousTrack = true;

            if (this.GetCurrentTime.Seconds > 3)
            {
                // If we're more than 3 seconds into the Track, try to
                // jump to the beginning of the current Track.
                this.player.Skip(0);
                return(true);
            }

            // When "loop one" is enabled and ignoreLoopOne is true, act like "loop all".
            LoopMode loopMode = this.LoopMode == LoopMode.One && ignoreLoopOne ? LoopMode.All : this.LoopMode;

            KeyValuePair <string, PlayableTrack> previousTrack = await this.queueManager.PreviousTrackAsync(loopMode);

            if (previousTrack.Equals(default(KeyValuePair <string, PlayableTrack>)))
            {
                this.Stop();
                return(true);
            }

            return(await this.TryPlayAsync(previousTrack));
        }
Пример #4
0
        /// <summary>
        /// 根据模板分析,并且返回已替换内容
        /// </summary>
        /// <param name="content"></param>
        /// <param name="regex"></param>
        /// <param name="modelInfo"></param>
        /// <param name="TransferFactory"></param>
        /// <returns></returns>
        public string AnalyAndReplace(string content, string regex, EntityInfo entity, Object obj, IExTransferFactory TransferFactory)
        {
            string Result = "";

            Dictionary<int, string> expresses = content.RegBaseDic(@regex); ;
            
            Dictionary<int, int> patternS_E = AnaUtil.Instance().GetKeyIndVal(expresses);

            Result += patternS_E.Count > 0 ? content.Substring(0, patternS_E.ElementAt(0).Key) : "";

            KeyValuePair<int, int> S_EPair = new KeyValuePair<int, int>();
            KeyValuePair<int, int> S_EPair2 = new KeyValuePair<int, int>();
            for (int i = 0; i < expresses.Count; i++)
            {
                Result += TransferFactory.CreateTransfer(expresses.ElementAt(i).Value).Transfer(expresses.ElementAt(i).Value, entity, obj);
                S_EPair = patternS_E.ElementAt(i);
                S_EPair2 = patternS_E.Count > (i + 1) ? patternS_E.ElementAt(i + 1) : patternS_E.ElementAt(i);

                Result += S_EPair2.Equals(S_EPair) ? "" : content.Substring(S_EPair.Value, S_EPair2.Key - S_EPair.Value);
            }
            Result += patternS_E.Count > 0 ? content.Substring(S_EPair.Value, content.Length - S_EPair.Value) : "";

            Result = patternS_E.Count == 0 ? content : Result;

            return Result;
        }
        public virtual void TestEntryType()
        {
            Ref a = NewRef("refs/heads/A", ID_ONE);
            Ref b = NewRef("refs/heads/B", ID_TWO);

            packed = ToList(a, b);
            RefMap map = new RefMap("refs/heads/", packed, loose, resolved);
            Iterator <KeyValuePair <string, Ref> > itr   = map.EntrySet().Iterator();
            KeyValuePair <string, Ref>             ent_a = itr.Next();
            KeyValuePair <string, Ref>             ent_b = itr.Next();

//			NUnit.Framework.Assert.AreEqual(ent_a.GetHashCode(), "A".GetHashCode());
            NUnit.Framework.Assert.IsTrue(ent_a.Equals(ent_a));
            NUnit.Framework.Assert.IsFalse(ent_a.Equals(ent_b));
            NUnit.Framework.Assert.AreEqual(a.ToString(), ent_a.Value.ToString());
        }
Пример #6
0
 public NumberEnumParameter(string name, LocalizedString dialogTitle, LocalizedString dialogLabel, int upperLimit, int lowerLimit, int defaultValue, IEnumerable <KeyValuePair <int, LocalizedString> > displayValues) : base(name, dialogTitle, dialogLabel, defaultValue.ToString())
 {
     if (upperLimit < lowerLimit || defaultValue > upperLimit || defaultValue < lowerLimit)
     {
         base.Values = null;
     }
     else
     {
         IEnumerable <EnumValue> source = Enumerable.Range(lowerLimit, upperLimit - lowerLimit + 1).Select(delegate(int currentNum)
         {
             string displayText = currentNum.ToString();
             if (displayValues != null)
             {
                 KeyValuePair <int, LocalizedString> keyValuePair = displayValues.FirstOrDefault((KeyValuePair <int, LocalizedString> f) => f.Key == currentNum);
                 if (!keyValuePair.Equals(default(KeyValuePair <int, LocalizedString>)))
                 {
                     displayText = keyValuePair.Value;
                 }
             }
             return(new EnumValue(displayText, currentNum.ToString()));
         });
         base.Values = source.ToArray <EnumValue>();
     }
     base.FormletType = typeof(EnumComboBoxModalEditor);
 }
        /// <inheritdoc />
        public override void OnActionExecuting([NotNull] ActionExecutingContext actionContext)
        {
            KeyValuePair <string, StringValues> parameter =
                actionContext.HttpContext
                .Request
                .Query
                .SingleOrDefault(x => _name.Equals(x.Key));

            bool check0 = !parameter.Equals(default(KeyValuePair <string, StringValues>));

            bool check1 =
                parameter.Value
                .SelectMany(y => y.Split(','))
                .All(y => _options.Contains(y, StringComparer.OrdinalIgnoreCase));

            if (check0 && check1)
            {
                return;
            }

            actionContext.Result =
                new ContentResult
            {
                StatusCode  = (int)HttpStatusCode.BadRequest,
                ContentType = "text/plain",
                Content     = $"Parameter '{_name}' is required to be from the set {{ {string.Join(", ", _options)} }}."
            };
        }
        public string GetRestriction(string value, string OtherConstraintsAccess = "")
        {
            KeyValuePair <string, string> dic = ListOfRestrictionValues.Where(p => p.Key == value).FirstOrDefault();

            if (!dic.Equals(default(KeyValuePair <String, String>)))
            {
                value = dic.Value;
            }

            Dictionary <string, string> inspire = GetInspireAccessRestrictions();

            if (value == "restricted")
            {
                value = inspire["https://inspire.ec.europa.eu/metadata-codelist/LimitationsOnPublicAccess/INSPIRE_Directive_Article13_1b"];
            }
            if (value == "no restrictions" || OtherConstraintsAccess == "no restrictions")
            {
                value = inspire["http://inspire.ec.europa.eu/metadata-codelist/LimitationsOnPublicAccess/noLimitations"];
            }
            else if (value == "norway digital restricted" || OtherConstraintsAccess == "norway digital restricted")
            {
                value = inspire["https://inspire.ec.europa.eu/metadata-codelist/LimitationsOnPublicAccess/INSPIRE_Directive_Article13_1d"];
            }

            return(value);
        }
Пример #9
0
    public void callSong(NetworkPlayer player, string name, string subtitle, int step, int difficulty, int level)
    {
        if(!isSearching)
        {
            var theSIP = new SongInfoProfil(name, subtitle, step, (Difficulty)difficulty, level);
            if(lastSongChecked.Equals(default(KeyValuePair<Difficulty, Dictionary<Difficulty, Song>>)) || !lastSongChecked.Value[lastSongChecked.Key].sip.CompareId(theSIP))
            {
                for(int i=0; i < LANManager.Instance.players.Count; i++)
                {
                    LANManager.Instance.players.ElementAt(i).Value.songChecked = 0;
                }
                isSearching = true;
                networkView.RPC("setSearching", RPCMode.Others, true);
                networkView.RPC ("checkSong", RPCMode.Others, name, subtitle, step, difficulty, level);
                playerSearching = player;
                lastSongChecked = LoadManager.Instance.FindSong(theSIP);
                LANManager.Instance.players[Network.player].songChecked = lastSongChecked.Equals(default(KeyValuePair<Difficulty, Dictionary<Difficulty, Song>>)) ? 2 : 1;

            }else
            {
                isSearching = true;
                playerSearching = player;
            }

        }
    }
Пример #10
0
        private void DoPseudoBoost(object sender, System.EventArgs e)
        {
            Messages.ShowInfo(HostShip.PilotInfo.PilotName + " is resolving Boost as a maneuver");

            SavedManeuver = HostShip.AssignedManeuver;

            SavedManeuverColors = new Dictionary <string, MovementComplexity>();
            foreach (var changedManeuver in ChangedManeuversCodes)
            {
                KeyValuePair <ManeuverHolder, MovementComplexity> existingManeuver = (HostShip.DialInfo.PrintedDial.FirstOrDefault(n => n.Key.ToString() == changedManeuver));
                SavedManeuverColors.Add(changedManeuver, (existingManeuver.Equals(default(KeyValuePair <ManeuverHolder, MovementComplexity>))) ? MovementComplexity.None : existingManeuver.Value);
                HostShip.Maneuvers[changedManeuver] = MovementComplexity.Normal;
            }

            // Direction from action
            HostShip.SetAssignedManeuver(
                ShipMovementScript.MovementFromString(
                    ManeuverFromBoostTemplate(
                        (ActionToRevert as BoostAction).SelectedBoostTemplate
                        )
                    )
                );

            HostShip.AssignedManeuver.IsRevealDial = false;
            HostShip.AssignedManeuver.GrantedBy    = HostShip.PilotInfo.PilotName;
            ShipMovementScript.LaunchMovement(FinishAbility);
        }
Пример #11
0
    public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        List <MemberInfo> members = new List <MemberInfo>();

        members.AddRange(type.GetFields());
        members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));

        object obj = Activator.CreateInstance(type);

        foreach (MemberInfo member in members)
        {
            JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));

            if (jsonProperty != null && dictionary.ContainsKey(jsonProperty.Name))
            {
                SetMemberValue(serializer, member, obj, dictionary[jsonProperty.Name]);
            }
            else if (dictionary.ContainsKey(member.Name))
            {
                SetMemberValue(serializer, member, obj, dictionary[member.Name]);
            }
            else
            {
                KeyValuePair <string, object> kvp = dictionary.FirstOrDefault(x => string.Equals(x.Key, member.Name, StringComparison.InvariantCultureIgnoreCase));
                if (!kvp.Equals(default(KeyValuePair <string, object>)))
                {
                    SetMemberValue(serializer, member, obj, kvp.Value);
                }
            }
        }
        return(obj);
    }
Пример #12
0
        // Configure is called after ConfigureServices is called.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddProvider(new DebugLoggerProvider());

            app.Use((httpContext, next) =>
            {
                KeyValuePair <string, StringValues> header = httpContext.Request.Headers.FirstOrDefault(h => h.Key == "Authorization");
                if (header.Equals(default(KeyValuePair <string, StringValues>)))
                {
                    return(null);
                }
                if (!header.Value.Any() || !header.Value.First().StartsWith("Basic "))
                {
                    return(null);
                }
                string headerValue        = header.Value.First().Substring(6);
                byte[] valueBytes         = Convert.FromBase64String(headerValue);
                string[] usernamePassword = Encoding.UTF8.GetString(valueBytes, 0, valueBytes.Length).Split(':');
                if (usernamePassword[0] == "Gekctek" && usernamePassword[1] == "Welc0me!")
                {
                    return(next());
                }
                return(null);
            });

            app.UseJsonRpc(config =>
            {
                config.RoutePrefix = "RpcApi";
                config.RegisterClassToRpcRoute <RpcMath>();
                config.RegisterClassToRpcRoute <RpcString>("Strings");
                config.RegisterClassToRpcRoute <RpcCommands>("Commands");
                config.RegisterClassToRpcRoute <RpcMath>("Math");
            });
        }
Пример #13
0
        private void OnMarkerClick(object sender, GoogleMap.MarkerClickEventArgs e)
        {
            var selectedMarker = e.Marker;

            if (selectedMarker == null || !_isUserInteractionEnabled)
            {
                // If user interaction is disabled, don't show info window
                e.Handled = true;
                return;
            }

            KeyValuePair <string, Marker> keyPair = GetPushpinMappedMarker(e.Marker);

            // Check if this is a incident marker
            if (keyPair.Equals(default(KeyValuePair <string, Marker>)))
            {
                return;
            }

            CustomPin pin = FormsMap.Pushpins?.Where(i => i.Id == keyPair.Key)
                            .FirstOrDefault();

            if (pin != null)
            {
                OnPushpinSelected(pin);
            }

            _infoWindowAdapter.Duration = pin.Duration;

            // Mark as unhandled (to let info window appear)
            e.Handled = false;
        }
Пример #14
0
        private void ValidateFieldDataConfigValue <TValidate>(KeyValuePair <string, KeyValuePair <Type, object> > config)
        {
            if (config.Equals(default(KeyValuePair <string, KeyValuePair <Type, object> >)))
            {
                config = _query.FieldDataConfig.First();
            }

            var pair = config.Value;

            if (pair.Key != typeof(TValidate))
            {
                throw new Exception(Messages.InvalidMapping);
            }

            if (!(pair.Value is FieldDataConfig <TValidate>))
            {
                throw new Exception(Messages.InvalidMapping);
            }


            var mapping = (FieldDataConfig <TValidate>)pair.Value;

            if (!mapping.Properties.HasItems())
            {
                throw new Exception(Messages.InvalidMapping);
            }
        }
        /// <summary>
        /// Backtrack obstaclesAndBackTrack dictionary to find the path
        /// </summary>
        /// <param name="obstaclesAndBackTrack"></param>
        /// <param name="startVertex"></param>
        /// <param name="endVertex"></param>
        /// <returns></returns>
        private List <GraphVertex> BackTrackToGetThePath(Dictionary <GraphVertex, List <KeyValuePair <GraphVertex, int> > > obstaclesAndBackTrack, GraphVertex startVertex, GraphVertex endVertex)
        {
            List <GraphVertex> path = new List <GraphVertex>();

            path.Add(endVertex);
            if (obstaclesAndBackTrack.ContainsKey(endVertex))
            {
                // This check is needed to make sure that there is a path. if there is no path we will return an empty list
                KeyValuePair <GraphVertex, int> currentPair = obstaclesAndBackTrack[endVertex][0];
                int previousObstacleVal = currentPair.Value;
                while (!currentPair.Equals(default(KeyValuePair <GraphVertex, int>)))
                {
                    path.Add(currentPair.Key);
                    KeyValuePair <GraphVertex, int> nextPair = default(KeyValuePair <GraphVertex, int>);
                    if (currentPair.Key != null)
                    {
                        foreach (KeyValuePair <GraphVertex, int> pathPair in obstaclesAndBackTrack[currentPair.Key])
                        {
                            if (pathPair.Value == previousObstacleVal)
                            {
                                nextPair = pathPair;
                                break;
                            }
                        }
                        if (currentPair.Key.IsObstacle)
                        {
                            previousObstacleVal--;
                        }
                    }
                    currentPair = nextPair;
                }
                path.Reverse();
            }
            return(path);
        }
Пример #16
0
            public U this[string tag]
            {
                get
                {
                    KeyValuePair <T, U> pair = innerDict.FirstOrDefault(t => (t.Key as Common.IHaveTag).Tag == tag);

                    if (pair.Equals(default(KeyValuePair <T, U>)))
                    {
                        return(null);
                    }

                    return(pair.Value);
                }
                set
                {
                    KeyValuePair <T, U> pair = innerDict.FirstOrDefault(t => (t.Key as Common.IHaveTag).Tag == tag);

                    if (pair.Equals(default(KeyValuePair <T, U>)))
                    {
                        return;
                    }

                    innerDict[pair.Key] = value;
                    vehicle.Vehicle_massTotalChanged();
                }
            }
Пример #17
0
 private void UnstuckIfNeeded(WowPoint playerLoc, DoActionType currentAction)
 {
     if (currentAction == DoActionType.Move)
     {
         unstuckDictionary.Add(DateTime.UtcNow, playerLoc);
         if (unstuckDictionary.Count >= 2)
         {
             if (unstuckDictionary.Count > 100) // sufficiently big value (until this method is called once per second)
             {
                 unstuckDictionary.Remove(unstuckDictionary.Keys.First());
             }
             KeyValuePair <DateTime, WowPoint> last  = unstuckDictionary.Last();
             KeyValuePair <DateTime, WowPoint> first = unstuckDictionary.LastOrDefault(l => (last.Key - l.Key).TotalSeconds >= 5);
             if (!first.Equals(default(KeyValuePair <DateTime, WowPoint>)))
             {
                 if (last.Value.Distance(first.Value) < 1f)
                 {
                     this.LogPrint($"We are stuck at {playerLoc}. Trying to unstuck...");
                     game.Jump();
                 }
             }
         }
     }
     else
     {
         unstuckDictionary.Clear();
     }
 }
Пример #18
0
        private Boolean StartSFC()
        {
            KeyValuePair <string, ShopOrderModel> shopOrder = dictGSFCCache.Where(order => order.Value.sFCState == SFCState.New).FirstOrDefault();

            if (shopOrder.Equals(default(KeyValuePair <string, ShopOrderModel>)))
            {
                return(false);
            }
            //Assumption is there will be no routing steps with status other than "New"
            int         RoutingStepID = Int32.MaxValue;
            XElement    RoutingStep   = null;
            XmlNodeList RoutingSteps  = shopOrder.Value.Routing.SelectNodes("/SFC/RoutingStep");

            foreach (XmlNode RoutingStepNode in RoutingSteps)
            {
                if (RoutingStepID > Convert.ToInt32(RoutingStepNode.Attributes["ID"].Value))
                {
                    RoutingStepID = Convert.ToInt32(RoutingStepNode.Attributes["ID"].Value);
                    RoutingStep   = XElement.Parse(RoutingStepNode.OuterXml);
                }
            }
            ThreadedExecuter <Tuple <XElement, String>, Tuple <XElement, string> > threadedExecuter =
                new ThreadedExecuter <Tuple <XElement, string>, Tuple <XElement, string> >(DelegateWork, null);

            threadedExecuter.Start(new Tuple <XElement, string>(RoutingStep, shopOrder.Value.Product));
            shopOrder.Value.sFCState = SFCState.InProcess;
            shopOrder.Value.Routing.DocumentElement.Attributes["Status"].Value = OperationState.InProcess.ToString();
            //ManageGSFCCache();
            return(true);
        }
Пример #19
0
        private static bool FindMoveToTime(IEnumerable <KeyValuePair <DateTime, double> > dataPoints, KeyValuePair <DateTime, double> outOfRangePoint, double minLevel, double maxLevel, out DateTime moveToTime)
        {
            moveToTime = DateTime.MaxValue;

            //Find the first point after overshoot/undershoot that is inside the allowed range or outside but in the opposite direction
            KeyValuePair <DateTime, double> candidatePoint = dataPoints.FirstOrDefault(kv => (kv.Key > outOfRangePoint.Key) && (((outOfRangePoint.Value < minLevel) && (kv.Value >= minLevel)) || ((outOfRangePoint.Value > maxLevel) && (kv.Value <= maxLevel))));

            if (candidatePoint.Equals(default(KeyValuePair <DateTime, double>)))
            {
                return(false);
            }

            //Check if the found point lies on the maxLevel or minLevel line depending on what we have (overshoot or undershoot)
            if (((candidatePoint.Value == maxLevel) && (outOfRangePoint.Value > maxLevel)) || ((candidatePoint.Value == minLevel) && (outOfRangePoint.Value < minLevel)))
            {
                moveToTime = candidatePoint.Key;
            }
            else
            {
                //Point is inside allowed range, so calculate where the graph crosses the maxLevel or minLevel line, it must be earlier in time
                KeyValuePair <DateTime, double> onLimitPoint = dataPoints.LastOrDefault(kv => kv.Key < candidatePoint.Key);
                if (onLimitPoint.Equals(default(KeyValuePair <DateTime, double>)))
                {
                    return(false);
                }
                moveToTime = onLimitPoint.Key.AddHours((candidatePoint.Key - onLimitPoint.Key).TotalHours * ((onLimitPoint.Value - (outOfRangePoint.Value > maxLevel ? maxLevel : minLevel)) / (onLimitPoint.Value - candidatePoint.Value)));
            }

            return(true);
        }
Пример #20
0
        /// <summary>
        /// Removes the specified kv.
        /// </summary>
        /// <param name="kv">The kv.</param>
        /// <returns>True, if the collection modified, otherwise False.</returns>
        public bool Remove(KeyValuePair <TKey, TValue> kv)
        {
            DoDisposeCheck();
            if (ReferenceEquals(kv, null))
            {
                ThrowHelper.ThrowArgumentNullException("kv");
            }

            bool result = false;

            lock (mLockObject)
            {
                for (int i = 0; i < this.Count; i++)
                {
                    KeyValuePair <TKey, TValue> item = GetItem(i);
                    if (kv.Equals(item))
                    {
                        this.RemoveItem(item);
                        result = true;
                        break;
                    }
                }
            }

            return(result);
        }
Пример #21
0
        private void InitializeToSelectedPlayer()
        {
            List <DynamicColumn> columns = SelectedGameStatistics.Players.Select(x => new DynamicColumn
            {
                Name        = x.PlayerName,
                DisplayName = x.PlayerName,
                Type        = typeof(int),
                IsReadOnly  = true,
            }).ToList();
            List <Specials>             specials = SelectedGameStatistics.Players.Where(p => p.SpecialsUsed != null).SelectMany(p => p.SpecialsUsed.Select(kv => kv.Key)).Distinct().ToList();
            List <SpecialStatisticsRow> rows     = specials.Select(x => new SpecialStatisticsRow
            {
                Special = x
            }).ToList();

            foreach (GameStatisticsByPlayer statsByPlayer in SelectedGameStatistics.Players)
            {
                foreach (SpecialStatisticsRow row in rows)
                {
                    int value = 0;
                    if (statsByPlayer.SpecialsUsed != null && statsByPlayer.SpecialsUsed.ContainsKey(row.Special))
                    {
                        KeyValuePair <string, int> kv = statsByPlayer.SpecialsUsed[row.Special].FirstOrDefault(x => x.Key == SelectedPlayer);
                        value = kv.Equals(default(KeyValuePair <string, int>)) ? 0 : kv.Value;
                    }
                    row.TryAddProperty(statsByPlayer.PlayerName, value);
                }
            }
            SpecialsToSelectedPlayerGrid = new DynamicGrid <SpecialStatisticsRow, DynamicColumn>(rows, columns);
        }
Пример #22
0
        /// <summary>
        /// Returns True if the table refers that view
        /// </summary>
        /// <param name="viewName"></param>
        /// <returns></returns>
        internal protected bool IsViewReferenced(string viewName)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                return(false);
            }

            if (!string.IsNullOrEmpty(ViewName) &&
                ViewName.Equals(viewName, StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            // Check partition map
            if (string.IsNullOrEmpty(PartitionOnProperty) ||
                PartitionsToViewMap == null)
            {
                return(false);
            }

            KeyValuePair <string, string>
            entry = PartitionsToViewMap.FirstOrDefault(x => x.Value.Equals(viewName, StringComparison.OrdinalIgnoreCase));

            if (entry.Equals(default(KeyValuePair <string, string>)))
            {
                return(false);
            }

            return(!string.IsNullOrEmpty(entry.Key));
        }
Пример #23
0
        public bool Remove(KeyValuePair <K, V> item)
        {
            int         hash = TKeyed.hash(item.Key);
            Transaction outer = current_();
            Transaction inner = startWrite_(outer);
            bool        ok = false, result = false;

            try
            {
                TKeyedEntry entry = getEntry(inner, (K)item.Key, hash);

                if (item.Equals(new KeyValuePair <K, V>((K)entry.getKey(), (V)entry.getValue())))
                {
                    remove(entry.getKey());
                    result = true;
                }

                ok = true;
            }
            finally
            {
                endWrite_(outer, inner, ok);
            }

            return(result);
        }
Пример #24
0
    private void RpcRemovePart(Vector3 position)
    {
        // Remove on clients
        if (isServer)
        {
            return;
        }

        // Searching for a Part in Parts
        KeyValuePair <Vector3Int, Part> keyValuePair = Parts.First(p => p.Key == Vector3Int.RoundToInt(position));

        // If a Part was not found
        if (keyValuePair.Equals(default(KeyValuePair <Vector3Int, Part>)))
        {
            return;
        }

        // Removing from Parts
        Parts.Remove(keyValuePair.Key);

        // Destroying gameObject
        Destroy(keyValuePair.Value.gameObject);

        // Removing from PartsData
        partsData.Remove(partsData.First(p => Vector3Int.RoundToInt(p.Position) == keyValuePair.Key));

        // Invoking event (for server already invoked in Command)
        if (PartsChanged != null)
        {
            PartsChanged(this, EventArgs.Empty);
        }
    }
Пример #25
0
 public string this[string field]
 {
     get {
         KeyValuePair <string, string> kvp = Fields.Where(k => k.Key == field).FirstOrDefault();
         return((!kvp.Equals(default(KeyValuePair <string, string>))) ? kvp.Value : null);
     }
 }
Пример #26
0
    public void FadeCanvasGroupOut(CanvasGroup canvasGroup, Action callback)
    {
        // Find out if the renderer we want to fade is already fading
        KeyValuePair <CanvasGroup, Coroutine> existingFade = Instance.FadingRenderers.Find(renderCoroutinePair => renderCoroutinePair.Key == canvasGroup);

        // If it's already fading, stop the fade
        if (existingFade.Equals(default(KeyValuePair <CanvasRenderer, Coroutine>)) && existingFade.Value != null)
        {
            Instance.StopCoroutine(existingFade.Value);
        }

        // Setup a new fade routine for the renderer
        Coroutine fade = null;
        KeyValuePair <CanvasGroup, Coroutine> replacementFade = new KeyValuePair <CanvasGroup, Coroutine>(canvasGroup, fade);

        Action completionAction = () => {
            Instance.FadingRenderers.Remove(replacementFade);
            Instance.CurrentOverlays.Remove(canvasGroup);
            if (callback != null)
            {
                callback();
            }
        };

        fade = Instance.StartCoroutine(FadeUtility.UIAlphaFade(canvasGroup, canvasGroup.alpha, 0f, FadeDuration, FadeUtility.EaseType.InOut, completionAction));

        Instance.FadingRenderers.Remove(existingFade);  // Remove the previous fade
        Instance.FadingRenderers.Add(replacementFade);  // Add the new fade
    }
Пример #27
0
        private App GetBestInstance()
        {
            var connectionOrdered = requestsCounter.OrderBy(x => x.Value)
                                    .ToDictionary(x => x.Key, x => x.Value);

            var empty = new KeyValuePair <string, long>();
            KeyValuePair <string, long> item = new KeyValuePair <string, long>();

            for (int i = 0; i < connectionOrdered.Count; i++)
            {
                //Verificar se o IIS fechou a coneção
                // validações
                item = connectionOrdered.ElementAt(i);
                if (item.Value >= 25)
                {
                    break;
                }
            }

            if (item.Equals(empty))
            {
                var instance = new App();

                requestsCounter.Add(instance.SessionId, 0);
                connections.Add(instance.SessionId, instance);
                item = new KeyValuePair <string, long>(instance.SessionId, 0);
            }

            requestsCounter[item.Key] = requestsCounter[item.Key] + 1;
            return(connections[item.Key]);
        }
Пример #28
0
    private void CmdRemovePart(Vector3 position)
    {
        // Searching for a Part in Parts
        KeyValuePair <Vector3Int, Part> keyValuePair = Parts.First(p => p.Key == Vector3Int.RoundToInt(position));

        // If a Part was found
        if (!keyValuePair.Equals(default(KeyValuePair <Vector3Int, Part>)))
        {
            // Removing from Parts
            Parts.Remove(keyValuePair.Key);

            // Removing from PartsData
            partsData.Remove(partsData.First(p => Vector3Int.RoundToInt(p.Position) == keyValuePair.Key));

            // Destroying gameObject
            Destroy(keyValuePair.Value.gameObject);

            RpcRemovePart(position);
            // Invoking event
            if (PartsChanged != null)
            {
                PartsChanged(this, EventArgs.Empty);
            }
        }
        else
        {
            // Display warning if there's no Part in this position (server only warning)
            Debug.LogWarning("Trying to remove a non-existent Part (check if removal position is correct).");
        }
    }
Пример #29
0
        public static ODataMetadataLevel GetMetadataLevel(string mediaType, IEnumerable <KeyValuePair <string, string> > parameters)
        {
            if (mediaType == null)
            {
                return(ODataMetadataLevel.Minimal);
            }

            if (!String.Equals(ODataMediaTypes.ApplicationJson, mediaType,
                               StringComparison.Ordinal))
            {
                return(ODataMetadataLevel.Minimal);
            }

            Contract.Assert(parameters != null);
            KeyValuePair <string, string> odataParameter =
                parameters.FirstOrDefault(
                    (p) => String.Equals("odata.metadata", p.Key, StringComparison.OrdinalIgnoreCase));

            if (!odataParameter.Equals(default(KeyValuePair <string, string>)))
            {
                if (String.Equals("full", odataParameter.Value, StringComparison.OrdinalIgnoreCase))
                {
                    return(ODataMetadataLevel.Full);
                }
                if (String.Equals("none", odataParameter.Value, StringComparison.OrdinalIgnoreCase))
                {
                    return(ODataMetadataLevel.None);
                }
            }

            // Minimal is the default metadata level
            return(ODataMetadataLevel.Minimal);
        }
        public long?Disconnect(string connectionId)
        {
            lock (_userIdToConnectionsIdMap)
            {
                KeyValuePair <long, HashSet <string> > userIdAndConnectionStrings
                    = _userIdToConnectionsIdMap.FirstOrDefault(x => x.Value.Contains(connectionId));
                if (userIdAndConnectionStrings.Equals(default(KeyValuePair <long, HashSet <string> >)))
                {
                    return(null);
                }

                long userId = userIdAndConnectionStrings.Key;
                if (_userIdToConnectionsIdMap[userId].Count == 1)
                {
                    _userIdToConnectionsIdMap.Remove(userId);
                }
                else
                {
                    _userIdToConnectionsIdMap[userId].Remove(connectionId);
                }

                if (_connectionToTasksMap.ContainsKey(connectionId))
                {
                    _connectionToTasksMap.Remove(connectionId);
                    _connectionToSubscriptionsMap.Remove(connectionId);
                }

                return(userId);
            }
        }
        /// <summary>
        /// Creates an instance of <see cref="EncounterMonsterDialogViewModel"/>
        /// </summary>
        public EncounterMonsterDialogViewModel(EncounterMonsterModel encounterMonster)
        {
            _encounterCreatureModel = encounterMonster;

            _monsterOptions.Clear();
            _monsterOptions.Add(new KeyValuePair <MonsterModel, string>(null, "None"));
            foreach (MonsterModel monsterModel in _compendium.Monsters)
            {
                _monsterOptions.Add(new KeyValuePair <MonsterModel, string>(monsterModel, monsterModel.Name));
            }

            if (encounterMonster.MonsterModel != null)
            {
                _selectedMonsterOption = _monsterOptions.FirstOrDefault(x => x.Key != null && x.Key.Id == encounterMonster.MonsterModel.Id);
            }

            if (_selectedMonsterOption.Equals(default(KeyValuePair <MonsterModel, string>)))
            {
                _selectedMonsterOption = _monsterOptions[0];
            }

            _searchMonstersCommand = new RelayCommand(obj => true, obj => SearchMonsters());
            _viewMonsterCommand    = new RelayCommand(obj => true, obj => ViewMonster());
            _acceptCommand         = new RelayCommand(obj => true, obj => OnAccept());
            _rejectCommand         = new RelayCommand(obj => true, obj => OnReject());
        }
Пример #32
0
        public bool AddResource(ResourceDetails resourceDetails)
        {
            if (!resourceDetails.IsOnline)
            {
                KeyValuePair <string, ResourceDetails> Resource = dictRegisteredResources.
                                                                  Where(resource => resource.Value.ResourceUrl.Equals(resourceDetails.ResourceUrl)).
                                                                  FirstOrDefault();

                if (!Resource.Equals(default(KeyValuePair <string, ResourceDetails>)))
                {
                    Resource.Value.IsOnline = false;
                }
                return(false);
            }

            if (!dictRegisteredResources.ContainsKey(resourceDetails.Name))
            {
                dictRegisteredResources.Add(resourceDetails.Name, resourceDetails);
                return(true);
            }
            else
            {
                dictRegisteredResources[resourceDetails.Name] = resourceDetails;
            }
            return(false);
        }
 public bool ContactKeyValueIsNull(KeyValuePair<string, Contact> contactKeyValue)
 {
     if (contactKeyValue.Equals(new KeyValuePair<string, Contact>())) return true;
     return false;
 }
Пример #34
0
        private void AddListItemForPair(XElement xKey, XElement xValue)
        {
            ValueEditor keyEditor = ValueEditor.CreateEditor(dictionaryValueType.KeyType, new ValueValidatorAttribute[0], xDefaultKey);
            keyEditor.ReadFromXElement(xKey);
            keyEditor.ValueChanged += delegate { RaiseValueChanged(); };

            ValueEditor valueEditor = ValueEditor.CreateEditor(dictionaryValueType.ValueType, new ValueValidatorAttribute[0], xDefaultValue);
            valueEditor.ReadFromXElement(xValue);
            valueEditor.ValueChanged += delegate { RaiseValueChanged(); };

            var editorsPair = new KeyValuePair<ValueEditor, ValueEditor>(keyEditor, valueEditor);

            Button uiRemove = new Button {
                Content = new Image {
                    Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("pack://application:,,,/ObjectConfigurator;component/Resources/delete.png")),
                    Width = 12,
                    Margin = new Thickness(1)
                },
                Margin = new Thickness(2, 0, 0, 0)
            };
            uiRemove.Click += delegate {
                Border itemToRemove = uiItems.Children.OfType<Border>().First(i => editorsPair.Equals(i.Tag));
                uiItems.Children.Remove(itemToRemove);
                CheckErrors();
                RaiseValueChanged();
            };
            Grid.SetColumn(uiRemove, 2);

            Grid.SetColumn(valueEditor.Representation, 1);
            valueEditor.Representation.Margin = new Thickness(5, 0, 0, 0);
            Border item = new Border {
                Tag = editorsPair,
                Child = new Grid {
                    ColumnDefinitions = {
                        new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                        new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                        new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) },
                    },
                    Children = {
                        keyEditor.Representation,
                        valueEditor.Representation,
                        uiRemove
                    }
                },
                Margin = new Thickness(2, 2, 2, 2)
            };
            uiItems.Children.Insert(uiItems.Children.Count - 1, item);
        }
Пример #35
0
        /// <summary>
        /// As the user types we want to filter the processes to those that contain the users search
        /// If its less than two characters, search for title starting with those characters for a "fast switch" type feel
        /// </summary>
        private void filter_Processes(object sender, FilterEventArgs e)
        {
            KeyValuePair<IntPtr, string> p = new KeyValuePair<IntPtr,string>();
            try
            {
                p = (KeyValuePair<IntPtr, string>)e.Item;
            }
            catch
            {
                e.Accepted = false;
                return;
            }

            Debug.Assert(!p.Equals(default(KeyValuePair<IntPtr, string>)));
            if (string.IsNullOrEmpty(ProcessUserInput)) { e.Accepted = true; return; }

            e.Accepted = ProcessUserInput.Length < 2 ? p.Value.ToUpper().StartsWith(ProcessUserInput.ToUpper()) : p.Value.ToUpper().Contains(ProcessUserInput.ToUpper());
        }
Пример #36
0
 public void Test_Find_ShouldReturnEqualKeyValue()
 {
     hashTable.Add(key1, value1);
     var result = hashTable.Find(key1);
     var pair = new KeyValuePair<string, string>(key1, value1);
     Assert.IsTrue(pair.Equals(result), "Hash table find() should return equal key when found.");
 }
Пример #37
0
        private static bool KeyHasValue(KeyValuePair<string, string> kvp)
        {
            if (!kvp.Equals(default(KeyValuePair<string, string>)) && !string.IsNullOrEmpty(kvp.Value))
            {
                return true;
            }

            return false;
        }
Пример #38
0
        private bool TryFindByKey( string key, out KeyValuePair<string, string> header )
        {
            header = default( KeyValuePair<string, string> );

            if ( _headers != null )
            {
                header =
                    _headers.FirstOrDefault(
                        s => s.Key.Equals( key, StringComparison.InvariantCultureIgnoreCase ) );
            }

            return !header.Equals( default( KeyValuePair<string, string> ) );
        }
Пример #39
0
 void checkSong(string name, string subtitle, int step, int difficulty, int level)
 {
     lastSongChecked = LoadManager.Instance.FindSong(new SongInfoProfil(name, subtitle, step, (Difficulty)difficulty, level));
     var getSong = !lastSongChecked.Equals(default(KeyValuePair<Difficulty, Dictionary<Difficulty, Song>>));
     networkView.RPC("getSongCheckResult", RPCMode.Server, Network.player, getSong);
 }
Пример #40
0
        public Task<Message[]> FindClosestBirthday(Channel channel)
        {
            Server s = channel.Server;
            if (Miku_Bot.birthdays[s].Count == 0)
            {
                return client.SendMessage(channel, "No birthday has been added for this server");
            }

            else
            {
                DateTime today = DateTime.Today;
                List<KeyValuePair<string, DateTime>> same = new List<KeyValuePair<string, DateTime>>();
                List<KeyValuePair<string, DateTime>> same2 = new List<KeyValuePair<string, DateTime>>();
                KeyValuePair<string, DateTime> next = new KeyValuePair<string, DateTime>("", DateTime.MaxValue);
                KeyValuePair<string, DateTime> min = new KeyValuePair<string, DateTime>("", DateTime.MaxValue);

                foreach (KeyValuePair<string, DateTime> bday in Miku_Bot.birthdays[s])
                {
                    DateTime temp = new DateTime(today.Year, bday.Value.Month, bday.Value.Day);
                    Console.Write($"{bday.Key}");
                    if (temp.Month > today.Month)
                    {

                        if (temp.Month == next.Value.Month && temp.Day == next.Value.Day)
                        {
                            same.Add(bday);
                        }

                        else if (temp.Month < next.Value.Month)
                        {
                            next = bday;
                            same.Clear();
                            same.Add(next);
                        }

                        else if (temp.Month == next.Value.Month && temp.Day < next.Value.Day)
                        {
                            next = bday;
                            same.Clear();
                            same.Add(next);
                        }
                    }

                    else if (temp.Month == today.Month && temp.Day > today.Day)
                    {
                        if (temp.Month == next.Value.Month && temp.Day == next.Value.Day)
                        {
                            same.Add(bday);
                        }

                        else if (temp.Month < next.Value.Month)
                        {
                            next = bday;
                            same.Clear();
                            same.Add(next);
                        }

                        else if (temp.Month == next.Value.Month && temp.Day < next.Value.Day)
                        {
                            next = bday;
                            same.Clear();
                            same.Add(next);
                        }
                    }

                    if (temp.Month == min.Value.Month && temp.Day == min.Value.Day)
                    {
                        same2.Add(bday);
                    }

                    else if (temp.Month < min.Value.Month)
                    {
                        min = bday;
                        same2.Clear();
                        same2.Add(min);
                    }

                    else if (temp.Month == min.Value.Month && temp.Day < min.Value.Day)
                    {
                        min = bday;
                        same2.Clear();
                        same2.Add(min);
                    }
                }

                if (next.Value == DateTime.MaxValue)
                {
                    next = min;
                }

                string message = "Next birthday is";
                if (!next.Equals(min))
                {
                    if (same2.Count == 1)
                    {
                        message += $" {same2[0].Key} on {same2[0].Value.Month}/{same2[0].Value.Day}";
                    }
                    else
                    {
                        message += ":";
                        foreach (KeyValuePair<string, DateTime> s1 in same2)
                        {
                            message += "\n";
                            message += $"・{s1.Key} on {s1.Value.Month}/{s1.Value.Day}";
                        }
                    }
                }
                else
                {
                    if (same.Count == 1)
                    {
                        message += $" {same[0].Key} on {same[0].Value.Month}/{same[0].Value.Day}";
                    }
                    else
                    {
                        message += ":";
                        foreach (KeyValuePair<string, DateTime> s1 in same)
                        {
                            message += "\n";
                            message += $"・{s1.Key} on {s1.Value.Month}/{s1.Value.Day}";
                        }
                    }
                }

                return client.SendMessage(channel, message);
            }

        }
Пример #41
0
 //=======================================================================
 // Support functions
 //=======================================================================
 /// <summary>
 /// Test if the item is last in the collection
 /// </summary>
 /// <returns>True if it is last</returns>
 private bool Last( 
     KeyValuePair<string, string> item, 
     KeyValuePair<string, string>[] collection )
 {
     int collectionCount = collection.Length;
     if ( item.Equals( collection[ collectionCount - 1 ] ) )
         return true;
     return false;
 }
Пример #42
0
 private static bool FindOutOfRangePoint(IEnumerable<KeyValuePair<DateTime, double>> dataPoints, double minLevel, double maxLevel, out KeyValuePair<DateTime, double> outOfRangePoint)
 {
     outOfRangePoint = dataPoints.FirstOrDefault(kv => (kv.Value < minLevel) || (kv.Value > maxLevel));
     if (outOfRangePoint.Equals(default(KeyValuePair<DateTime, double>)))
         return false;
     else
         return true;
 }
        private static bool HaveCodeMatch(string codeToMatch, KeyValuePair<string, string> codeResponse)
        {
            if (!codeResponse.Equals(default(KeyValuePair<string, string>)))
            {
                return codeResponse.Key.Equals(codeToMatch, StringComparison.InvariantCultureIgnoreCase) || codeResponse.Value.Equals(codeToMatch, StringComparison.InvariantCultureIgnoreCase);
            }

            return false;
        }
Пример #44
0
        private List<string> GetReferencedVariablesForStatement(KeyValuePair<int, List<VariableLine>> statementLinesMapping)
        {
            if (statementLinesMapping.Equals(null))
                throw new ArgumentNullException("statementLinesMapping");

            List<string> referencedVariable = new List<string>();
            foreach (VariableLine statementLine in statementLinesMapping.Value)
                referencedVariable.Add(statementLine.variable);
            return referencedVariable;
        }