コード例 #1
0
 /// <summary>
 /// Only checks if any of the Picked requirements are matched (used for checking id card(s)). Much simpler and a bit different than HasRequiredItems.
 /// </summary>
 public virtual bool HasAccess(Character character)
 {
     if (character.IsBot && item.IgnoreByAI(character))
     {
         return(false);
     }
     if (!item.IsInteractable(character))
     {
         return(false);
     }
     if (requiredItems.None())
     {
         return(true);
     }
     if (character.Inventory != null)
     {
         foreach (Item item in character.Inventory.AllItems)
         {
             if (requiredItems.Any(ri => ri.Value.Any(r => r.Type == RelatedItem.RelationType.Picked && r.MatchesItem(item))))
             {
                 return(true);
             }
         }
     }
     return(false);
 }
コード例 #2
0
        public static Path FindLargestCommon(this IEnumerable <Path> paths)
        {
            Dictionary <Path, Path[]> ancestors = paths.ToDictionary(p => p, p => new[] { p }.Concat(p.GetAncestors()).ToArray());

            if (ancestors.None())
            {
                return(null);
            }
            if (ancestors.Count == 1)
            {
                return(ancestors.Single().Key);
            }
            int  maxIndex = ancestors.Min(kvp => kvp.Value.Length);
            Path largestCommonAncestor = null;

            for (int i = 1; i <= maxIndex; i++)
            {
                Path[] testAncestors     = ancestors.Select(kvp => kvp.Value[kvp.Value.Length - i]).ToArray();
                Path[] distinctAncestors = testAncestors.Distinct().Take(2).ToArray();
                if (distinctAncestors.Length == 1)
                {
                    largestCommonAncestor = distinctAncestors.Single();
                }
                else
                {
                    return(largestCommonAncestor);
                }
            }
            return(largestCommonAncestor);
        }
コード例 #3
0
            private void RemoveCore(PointerCaptureTarget target, PointerCaptureKind kinds)
            {
                global::System.Diagnostics.Debug.Assert(
                    kinds != PointerCaptureKind.None,
                    "The capture kind must be set to release pointer captures.");

                if (this.Log().IsEnabled(LogLevel.Information))
                {
                    this.Log().Info($"{target.Element.GetDebugName()}: Releasing ({kinds}) capture of pointer {Pointer}");
                }

                // If we remove an explicit capture, we update the _localExplicitCaptures of the target element
                if (kinds.HasFlag(PointerCaptureKind.Explicit) &&
                    target.Kind.HasFlag(PointerCaptureKind.Explicit))
                {
                    target.Element._localExplicitCaptures.Remove(Pointer);
                }

                target.Kind &= ~kinds;

                // The element is no longer listening for events, remove it.
                if (target.Kind == PointerCaptureKind.None)
                {
                    _targets.Remove(target.Element);
                }

                IsImplicitOnly = _targets.None(t => t.Value.Kind.HasFlag(PointerCaptureKind.Explicit));

                // Validate / update the state of this capture
                EnsureEffectiveCaptureState();
            }
コード例 #4
0
            public ExpressionInfo FindIn(Expression expression)
            {
                Visit(expression);

                if (_nestedAccessesByPath.None() && _multiInvocations.NoneOrNull())
                {
                    return(EmptyExpressionInfo);
                }

                var nestedAccessChecks = GetNestedAccessChecks();

                var multiInvocations = _multiInvocations?.Any() == true
                    ? _multiInvocations.OrderBy(inv => inv.ToString()).ToArray()
                    : Enumerable <Expression> .EmptyArray;

                return(new ExpressionInfo(nestedAccessChecks, multiInvocations));
            }
コード例 #5
0
        /// <summary>
        /// Only checks if any of the Picked requirements are matched (used for checking id card(s)). Much simpler and a bit different than HasRequiredItems.
        /// </summary>
        public bool HasAccess(Character character)
        {
            if (character.Inventory == null)
            {
                return(false);
            }
            if (requiredItems.None())
            {
                return(true);
            }

            foreach (Item item in character.Inventory.Items)
            {
                if (requiredItems.Any(ri => ri.Value.Any(r => r.Type == RelatedItem.RelationType.Picked && r.MatchesItem(item))))
                {
                    return(true);
                }
            }
            return(false);
        }
コード例 #6
0
ファイル: NoneTest.cs プロジェクト: VitorSouza23/pandemonium
        public void Should_Be_False_Given_Existing_Keys()
        {
            var dictionary = new Dictionary <int, string>()
            {
                [0] = "0",
                [1] = "1"
            };

            bool result = dictionary.None(0, 1);

            Assert.False(result);
        }
コード例 #7
0
ファイル: NoneTest.cs プロジェクト: VitorSouza23/pandemonium
        public void Should_Be_True_Given_A_Non_Existing_Key()
        {
            var dictionary = new Dictionary <int, string>()
            {
                [0] = "0",
                [1] = "1"
            };

            bool result = dictionary.None(2);

            Assert.True(result);
        }
コード例 #8
0
        public static TExpression Replace <TExpression>(
            this TExpression expression,
            Dictionary <Expression, Expression> replacementsByTarget)
            where TExpression : Expression
        {
            if (replacementsByTarget.None())
            {
                return(expression);
            }

            var replacer = new ExpressionReplacer(replacementsByTarget);
            var replaced = replacer.ReplaceIn(expression);

            return((TExpression)replaced);
        }
コード例 #9
0
        public IList <DerivedTypePair> GetDerivedTypePairsFor(IQualifiedMemberContext context)
        {
            LookForDerivedTypePairs(context);

            if (_typePairsByTargetType.None())
            {
                return(Enumerable <DerivedTypePair> .EmptyArray);
            }

            if (_typePairsByTargetType.TryGetValue(context.TargetType, out var typePairs))
            {
                return(typePairs.FilterToArray(context, (ctx, tp) => tp.AppliesTo(ctx)));
            }

            return(Enumerable <DerivedTypePair> .EmptyArray);
        }
コード例 #10
0
        protected override IReadOnlyDictionary<string, object> GetEntries()
        {
            Dictionary<string, object> driverNames = new Dictionary<string, object>();

            foreach (var driverName in AsioOut.GetDriverNames())
            {
                //the return dictionary holds the names of the entries as key with an optional "tag"
                //here the tag is null but you can provide any object that you want to associate with the entry
                driverNames[driverName] = null;
            }

            if (driverNames.None())
                driverNames["No ASIO!? -> get yours from http://www.asio4all.org/"] = null; 

            return driverNames;
        }
コード例 #11
0
        public IList <DerivedTypePair> GetDerivedTypePairsFor(
            IBasicMapperData mapperData,
            MapperContext mapperContext)
        {
            LookForDerivedTypePairs(mapperData, mapperContext);

            if (_typePairsByTargetType.None())
            {
                return(Enumerable <DerivedTypePair> .EmptyArray);
            }

            if (_typePairsByTargetType.TryGetValue(mapperData.TargetType, out var typePairs))
            {
                return(typePairs.Filter(tp => tp.AppliesTo(mapperData)).ToArray());
            }

            return(Enumerable <DerivedTypePair> .EmptyArray);
        }
コード例 #12
0
 public override void Update(AIObjectiveManager objectiveManager, float deltaTime)
 {
     base.Update(objectiveManager, deltaTime);
     if (IgnoreListClearInterval > 0)
     {
         if (ignoreListTimer > IgnoreListClearInterval)
         {
             Reset();
         }
         else
         {
             ignoreListTimer += deltaTime;
         }
     }
     if (targetUpdateTimer >= TargetUpdateInterval)
     {
         targetUpdateTimer = 0;
         UpdateTargets();
     }
     else
     {
         targetUpdateTimer += deltaTime;
     }
     // Sync objectives, subobjectives and targets
     foreach (var objective in objectives)
     {
         var target = objective.Key;
         if (!objective.Value.CanBeCompleted)
         {
             ignoreList.Add(target);
             targetUpdateTimer = TargetUpdateInterval;
         }
         if (!targets.Contains(target))
         {
             subObjectives.Remove(objective.Value);
         }
     }
     SyncRemovedObjectives(objectives, GetList());
     if (objectives.None() && targets.Any())
     {
         CreateObjectives();
     }
 }
コード例 #13
0
        public static TExpression Replace <TExpression>(
            this TExpression expression,
            Dictionary <Expression, Expression> replacementsByTarget)
            where TExpression : Expression
        {
            if ((expression == null) || replacementsByTarget.None())
            {
                return(expression);
            }

            var replacer = replacementsByTarget.HasOne()
                ? new ExpressionReplacer(
                replacementsByTarget.Keys.First(),
                replacementsByTarget.Values.First(),
                replacementsByTarget.Comparer)
                : new ExpressionReplacer(replacementsByTarget);

            return(replacer.Replace <TExpression>(expression));
        }
コード例 #14
0
        // Returns null if the report is empty
        protected static string GenerateReport(
            Alert alert,
            string htmlTemplate,
            IEnumerable <DataModelIssue> issues,
            IEnumerable <string> inputFiles,
            ExpressionUntriaged untriagedExpression)
        {
            IEnumerable <DataModelIssue> matchingIssues = alert.Query.Evaluate(issues);
            var untriagedFlagsMap = new Dictionary <DataModelIssue, ExpressionUntriaged.Flags>();

            foreach (DataModelIssue issue in matchingIssues)
            {
                ExpressionUntriaged.Flags flags = untriagedExpression.GetUntriagedFlags(issue);
                if (flags != 0)
                {
                    untriagedFlagsMap[issue] = flags;
                }
            }

            if (untriagedFlagsMap.None())
            {
                Console.WriteLine("    No untriaged issues, skipping.");
                Console.WriteLine();
                return(null);
            }

            string text = htmlTemplate;

            text = text.Replace("%UNTRIAGED_ISSUES_START%", "");
            text = text.Replace("%UNTRIAGED_ISSUES_END%", "");

            text = text.Replace("%UNTRIAGED_ISSUES_LINKED_COUNTS%",
                                AlertReport.GetLinkedCount("is:issue is:open", untriagedFlagsMap.Keys));

            IEnumerable <IssueEntry> untriagedIssueEntries = untriagedFlagsMap.Keys.Select(issue => new IssueEntry(issue));

            text = text.Replace("%UNTRIAGED_ISSUES_TABLE%", FormatIssueTable(untriagedFlagsMap));

            text = text.Replace("%INPUT_FILES_LIST%", FormatInputFilesList(inputFiles));

            return(text);
        }
コード例 #15
0
        public Expression[] FindIn(Expression expression, bool targetCanBeNull)
        {
            Expression[] memberAccesses;

            lock (_syncLock)
            {
                _includeTargetNullChecking = targetCanBeNull;

                Visit(expression);

                memberAccesses = _memberAccessesByPath.None()
                    ? _noMemberAccesses
                    : _memberAccessesByPath.Values.Reverse().ToArray();

                _stringMemberAccessSubjects.Clear();
                _nullCheckSubjects.Clear();
                _memberAccessesByPath.Clear();
            }

            return(memberAccesses);
        }
コード例 #16
0
 protected override void Act(float deltaTime)
 {
     SyncRemovedObjectives(extinguishObjectives, Hull.hullList);
     if (character.Submarine == null)
     {
         return;
     }
     foreach (Hull hull in Hull.hullList)
     {
         if (hull.FireSources.None())
         {
             continue;
         }
         if (hull.Submarine == null)
         {
             continue;
         }
         if (hull.Submarine.TeamID != character.TeamID)
         {
             continue;
         }
         // If the character is inside, only take connected hulls into account.
         if (character.Submarine != null && !character.Submarine.IsEntityFoundOnThisSub(hull, true))
         {
             continue;
         }
         if (!extinguishObjectives.TryGetValue(hull, out AIObjectiveExtinguishFire objective))
         {
             objective = new AIObjectiveExtinguishFire(character, hull);
             extinguishObjectives.Add(hull, objective);
             AddSubObjective(objective);
         }
     }
     if (extinguishObjectives.None())
     {
         character?.Speak(TextManager.Get("DialogNoFire"), null, 3.0f, "nofire", 30.0f);
     }
 }
コード例 #17
0
        private static void AddUnmappedTargetMembersInfo(
            Dictionary <QualifiedMember, IDataSourceSet> unmappedMembers,
            StringBuilder failureMessage,
            IMemberMapperData rootData)
        {
            if (unmappedMembers.None())
            {
                return;
            }

            failureMessage
            .AppendLine(" Unmapped target members - fix by ignoring or configuring a custom source member or data source:")
            .AppendLine();

            foreach (var unmappedMember in unmappedMembers)
            {
                var targetMemberPath = unmappedMember.Key.GetFriendlyTargetPath(rootData);

                failureMessage.Append("  - ").AppendLine(targetMemberPath);
            }

            failureMessage.AppendLine();
        }
コード例 #18
0
ファイル: ModuleInfoModule.cs プロジェクト: pjmagee/Nircbot
        /// <summary>
        /// Lists the modules.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="channel">The channel.</param>
        /// <param name="messageType">Type of the message.</param>
        /// <param name="messageFormat">The message format.</param>
        /// <param name="message">The message.</param>
        /// <param name="arguments">The arguments.</param>
        private void ListModules(User user, string channel, MessageType messageType, MessageFormat messageFormat, string message, Dictionary<string, string> arguments)
        {
            var targets = new[] { user.Nick };

            if (arguments.None())
            {
                this.SendCommandUsageExamples(this, targets, messageType, messageFormat);
            }

            foreach (var key in arguments.Keys)
            {
                AccessLevel level;

                if (Enum.TryParse(key, ignoreCase: true, result: out level))
                {
                    foreach (var module in this.IrcClient.Modules.Where(m => m.Commands.Any(c => c.LevelRequired <= level && c.LevelRequired <= user.AccessLevel)))
                    {
                        var moduleInfoResponse = new Response("{0}: {1}".FormatWith(module.Name, module.Description), targets, MessageFormat.Notice, messageType);
                        this.SendResponse(moduleInfoResponse);
                    }
                }
            }

            if (arguments.ContainsKey("list"))
            {
                #region Send all Module descriptions

                foreach (var module in this.IrcClient.Modules.Where(m => m.Commands.Any(c => c.LevelRequired <= user.AccessLevel)))
                {
                    var moduleInfoResponse = new Response("{0}: {1}".FormatWith(module.Name, module.Description), targets, MessageFormat.Notice, messageType);
                    this.SendResponse(moduleInfoResponse);
                }

                #endregion

                this.GetMoreInformation(messageType, targets);
            }

            if (arguments.ContainsKey("examples"))
            {
                // For each module where the module has a command that is accessible by this user
                foreach (var module in this.IrcClient.Modules.Where(m => m.Commands.Any(c => c.LevelRequired <= user.AccessLevel)))
                {
                    #region Module Description

                    var response = new Response("{0}: {1}".FormatWith(module.Name, module.Description), targets, MessageFormat.Notice, messageType);
                    this.SendResponse(response);

                    #endregion

                    #region Usage Examples

                    response.Message = "Usage Examples: ";
                    this.SendResponse(response);
                    this.SendCommandUsageExamples(module, targets, messageType, MessageFormat.Notice);

                    #endregion
                }
            }
        }
コード例 #19
0
        private static void Place(IEnumerable <Submarine> subs)
        {
            if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
            {
                DebugConsole.ThrowError("Clients are not allowed to use AutoItemPlacer.\n" + Environment.StackTrace.CleanupStackTrace());
                return;
            }

            int itemCountApprox         = MapEntityPrefab.List.Count() / 3;
            var containers              = new List <ItemContainer>(70 + 30 * subs.Count());
            var prefabsWithContainer    = new List <ItemPrefab>(itemCountApprox / 3);
            var prefabsWithoutContainer = new List <ItemPrefab>(itemCountApprox);
            var removals = new List <ItemPrefab>();

            foreach (Item item in Item.ItemList)
            {
                if (!subs.Contains(item.Submarine))
                {
                    continue;
                }
                if (item.GetRootInventoryOwner() is Character)
                {
                    continue;
                }
                containers.AddRange(item.GetComponents <ItemContainer>());
            }
            containers.Shuffle(Rand.RandSync.Server);

            foreach (MapEntityPrefab prefab in MapEntityPrefab.List)
            {
                if (!(prefab is ItemPrefab ip))
                {
                    continue;
                }

                if (ip.ConfigElement.Elements().Any(e => string.Equals(e.Name.ToString(), typeof(ItemContainer).Name.ToString(), StringComparison.OrdinalIgnoreCase)))
                {
                    prefabsWithContainer.Add(ip);
                }
                else
                {
                    prefabsWithoutContainer.Add(ip);
                }
            }

            spawnedItems.Clear();
            var validContainers = new Dictionary <ItemContainer, PreferredContainer>();

            prefabsWithContainer.Shuffle(Rand.RandSync.Server);
            // Spawn items that have an ItemContainer component first so we can fill them up with items if needed (oxygen tanks inside the spawned diving masks, etc)
            for (int i = 0; i < prefabsWithContainer.Count; i++)
            {
                var itemPrefab = prefabsWithContainer[i];
                if (itemPrefab == null)
                {
                    continue;
                }
                if (SpawnItems(itemPrefab))
                {
                    removals.Add(itemPrefab);
                }
            }
            // Remove containers that we successfully spawned items into so that they are not counted in in the second pass.
            removals.ForEach(i => prefabsWithContainer.Remove(i));
            // Another pass for items with containers because also they can spawn inside other items (like smg magazine)
            prefabsWithContainer.ForEach(i => SpawnItems(i));
            // Spawn items that don't have containers last
            prefabsWithoutContainer.Shuffle(Rand.RandSync.Server);
            prefabsWithoutContainer.ForEach(i => SpawnItems(i));

            if (OutputDebugInfo)
            {
                var subNames = subs.Select(s => s.Info.Name).ToList();
                DebugConsole.NewMessage($"Automatically placed items in { string.Join(", ", subNames) }:");
                foreach (string itemName in spawnedItems.Select(it => it.Name).Distinct())
                {
                    DebugConsole.NewMessage(" - " + itemName + " x" + spawnedItems.Count(it => it.Name == itemName));
                }
            }

            if (GameMain.GameSession?.Level != null &&
                GameMain.GameSession.Level.Type == LevelData.LevelType.Outpost &&
                GameMain.GameSession.StartLocation?.TakenItems != null)
            {
                foreach (Location.TakenItem takenItem in GameMain.GameSession.StartLocation.TakenItems)
                {
                    var matchingItem = spawnedItems.Find(it => takenItem.Matches(it));
                    if (matchingItem == null)
                    {
                        continue;
                    }
                    var containedItems = spawnedItems.FindAll(it => it.ParentInventory?.Owner == matchingItem);
                    matchingItem.Remove();
                    spawnedItems.Remove(matchingItem);
                    foreach (Item containedItem in containedItems)
                    {
                        containedItem.Remove();
                        spawnedItems.Remove(containedItem);
                    }
                }
            }
#if SERVER
            foreach (Item spawnedItem in spawnedItems)
            {
                Entity.Spawner.CreateNetworkEvent(spawnedItem, remove: false);
            }
#endif
            bool SpawnItems(ItemPrefab itemPrefab)
            {
                if (itemPrefab == null)
                {
                    string errorMsg = "Error in AutoItemPlacer.SpawnItems - itemPrefab was null.\n" + Environment.StackTrace.CleanupStackTrace();
                    DebugConsole.ThrowError(errorMsg);
                    GameAnalyticsManager.AddErrorEventOnce("AutoItemPlacer.SpawnItems:ItemNull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                    return(false);
                }
                bool success = false;

                foreach (PreferredContainer preferredContainer in itemPrefab.PreferredContainers)
                {
                    if (preferredContainer.SpawnProbability <= 0.0f || preferredContainer.MaxAmount <= 0)
                    {
                        continue;
                    }
                    validContainers = GetValidContainers(preferredContainer, containers, validContainers, primary: true);
                    if (validContainers.None())
                    {
                        validContainers = GetValidContainers(preferredContainer, containers, validContainers, primary: false);
                    }
                    foreach (var validContainer in validContainers)
                    {
                        if (SpawnItem(itemPrefab, containers, validContainer))
                        {
                            success = true;
                        }
                    }
                }
                return(success);
            }
        }
コード例 #20
0
        // Returns null if the report is empty
        protected static string GenerateReport(
            Alert alert,
            string htmlTemplate,
            IEnumerable <DataModelIssue> issues,
            IEnumerable <DataModelIssue> comments)
        {
            // Create a Dictionary mapping issues to comments for that issue
            Dictionary <int, List <DataModelIssue> > issueComments  = new Dictionary <int, List <DataModelIssue> >();
            Dictionary <int, DataModelIssue>         issuesMap      = new Dictionary <int, DataModelIssue>();
            IEnumerable <DataModelIssue>             matchingIssues = alert.Query.Evaluate(issues);

            if (matchingIssues.None())
            {
                Console.WriteLine("    No changes to the query, skipping.");
                Console.WriteLine();
                return(null);
            }
            foreach (DataModelIssue issue in matchingIssues)
            {
                issueComments.Add(issue.Number, new List <DataModelIssue>());
                issuesMap.Add(issue.Number, issue);
            }
            foreach (DataModelIssue comment in comments)
            {
                int startIndex = comment.HtmlUrl.IndexOf("/issues/") + 8;
                if (startIndex < 8)
                {
                    startIndex = comment.HtmlUrl.IndexOf("/pull/") + 6;
                }
                int endIndex = comment.HtmlUrl.IndexOf("#");

                string issueString = comment.HtmlUrl.Substring(startIndex, endIndex - startIndex);
                int    issueID     = int.Parse(issueString);
                if (issueComments.ContainsKey(issueID))
                {
                    issueComments[issueID].Add(comment);
                }
            }

            // Filter our issues to ones that haven't had an owner response after our grace waiting period
            Dictionary <DataModelIssue, TimeSpan?> needsResponse = new Dictionary <DataModelIssue, TimeSpan?>();

            foreach (KeyValuePair <int, List <DataModelIssue> > pair in issueComments)
            {
                TimeSpan?lastComment;
                // First check if there are no comments and the issue was opened past the threshold.
                if (pair.Value.Count == 0 && ((lastComment = (DateTime.Now - issuesMap[pair.Key].CreatedAt)) > _acceptableResponseDelay))
                {
                    needsResponse.Add(issuesMap[pair.Key], lastComment);
                }

                // Next check if the last issue occurred past the threshold
                else if (pair.Value.Count > 0 && ((lastComment = (DateTime.Now - pair.Value.Max((issue) => issue.CreatedAt))) > _acceptableResponseDelay))
                {
                    needsResponse.Add(issuesMap[pair.Key], lastComment);
                }
            }

            if (needsResponse.None())
            {
                Console.WriteLine("    No changes to the query, skipping.");
                Console.WriteLine();
                return(null);
            }

            string text = htmlTemplate;

            text = text.Replace("%NEEDSMSRESPONSE_ACCEPTABLE_RESPONSE_DELAY%", _acceptableResponseDelay.Days.ToString());

            text = text.Replace("%NEEDSMSRESPONSE_ISSUES_START%", "");
            text = text.Replace("%NEEDSMSRESPONSE_ISSUES_END%", "");

            text = text.Replace("%NEEDSMSRESPONSE_ISSUES_LINKED_COUNTS%",
                                AlertReport.GetLinkedCount("is:issue is:open", needsResponse.Keys));
            text = text.Replace("%NEEDSMSRESPONSE_ISSUES_COUNT%", needsResponse.Count().ToString());

            text = text.Replace("%NEEDSMSRESPONSE_ISSUES_TABLE%", FormatIssueTable(needsResponse.OrderByDescending((pair) => pair.Value.Value.Days)));

            return(text);
        }
コード例 #21
0
 private static string BuildParameterList(Dictionary<string, ObjectOutput> properties)
 {
     return properties.None() ? "no properties "
         : properties
             .Select(kv => "{0} [{1}]".FormatWith(kv.Key, GetTypeName(kv.Value.GetTypedValue())))
             .Join(", ");
 }