System.Collections.Generic.List.FindAll(System.Predicate)

Here are the examples of the csharp api System.Collections.Generic.List.FindAll(System.Predicate) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

706 Examples 7

19 Source : ZooKeeperServiceDiscovery.cs
with MIT License
from 1100100

private void RefreshNodes(string serviceName, List<ServiceNodeInfo> currentNodes)
        {
            if (ServiceNodes.TryGetValue(serviceName, out var nodes))
            {
                if (!currentNodes.Any())
                    nodes.Clear();

                var leavedNodes = nodes.Where(p => currentNodes.All(c => c.ServiceId != p.ServiceId)).Select(p => p.ServiceId).ToList();
                if (leavedNodes.Any())
                {
                    Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
                    OnNodeLeave?.Invoke(serviceName, leavedNodes);
                    nodes.RemoveAll(p => currentNodes.All(c => c.ServiceId != p.ServiceId));
                }

                var addedNodes = currentNodes.FindAll(p => nodes.All(c => c.ServiceId != p.ServiceId));
                if (addedNodes.Any())
                {
                    nodes.AddRange(addedNodes);
                    Logger.LogTrace(
                        $"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
                    OnNodeJoin?.Invoke(serviceName, addedNodes);
                }
            }
            else
            {
                if (!currentNodes.Any())
                    ServiceNodes.TryAdd(serviceName, currentNodes);
            }
        }

19 Source : RegisterCrossBindingAdaptorHelper.cs
with MIT License
from 404Lcc

public static void RegisterCrossBindingAdaptor(AppDomain appdomain)
        {
            foreach (Type item in typeof(Init).replacedembly.GetTypes().ToList().FindAll(item => item.IsSubclreplacedOf(typeof(CrossBindingAdaptor))))
            {
                object obj = Activator.CreateInstance(item);
                if (!(obj is CrossBindingAdaptor))
                {
                    continue;
                }
                appdomain.RegisterCrossBindingAdaptor((CrossBindingAdaptor)obj);
            }
        }

19 Source : SimpleGraphBackend.cs
with Apache License 2.0
from activey

public List<AbstractGraphEdge> FindEdges(long nodeId) {
			return AllGraphEdges.FindAll (edge => {
				AbstractGraphNode startNode = edge.GetStartGraphNode();
				AbstractGraphNode endNode = edge.GetEndGraphNode();
				return startNode.GetId() == nodeId || endNode.GetId() == nodeId;
			});
		}

19 Source : SimpleGraphBackend.cs
with Apache License 2.0
from activey

public List<AbstractGraphEdge> FindEdges(long startOrEndNodeId, long endOrStartNodeId) {
			return AllGraphEdges.FindAll (edge => {
				AbstractGraphNode startNode = edge.GetStartGraphNode();
				AbstractGraphNode endNode = edge.GetEndGraphNode();
			
				return (startNode.GetId() == startOrEndNodeId && endNode.GetId() == endOrStartNodeId) 
					|| (startNode.GetId() == endOrStartNodeId && endNode.GetId() == startOrEndNodeId);
			});
		}

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private void Input_ButtonPressed(object sender, StardewModdingAPI.Events.ButtonPressedEventArgs e)
        {
            if (!Config.Enabled || !Context.IsWorldReady)
                return;

            Dictionary<string, string> npcDic;
            List<string> npcKeys;

            // check for click on dialogue

            if (Game1.activeClickableMenu != null && Game1.player?.currentLocation?.lastQuestionKey?.StartsWith("DialogueTrees_") == true)
            {
                IClickableMenu menu = Game1.activeClickableMenu;
                if (menu == null || menu.GetType() != typeof(DialogueBox))
                    return;

                DialogueBox db = menu as DialogueBox;
                int resp = db.selectedResponse;
                List<Response> resps = db.responses;

                if (resp < 0 || resps == null || resp >= resps.Count || resps[resp] == null)
                    return;

                string[] parts = resps[resp].responseKey.Split('#');
                string npcName = parts[1];
                string topicID = parts[2];
                string responseID = parts[3];
                npcDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{npcName}", ContentSource.GameContent);
                npcKeys = npcDic.Keys.ToList();

                if (Game1.player.currentLocation.lastQuestionKey == "DialogueTrees_Player_Question")
                {
                    Monitor.Log($"asking {npcName} about {loadedTopicNames[topicID]}");
                    var possibleResponses = npcKeys.FindAll(k => k.StartsWith("DialogueTrees_response_" + topicID + "_"));
                    NPC n = Game1.getCharacterFromName(npcName);
                    Game1.drawDialogue(n, npcDic[possibleResponses[myRand.Next(possibleResponses.Count)]]);

                    string nextTopicID = GetNextTopicID(topicID, "any");

                    if (nextTopicID != null && loadedDialogues.ContainsKey(nextTopicID) && npcKeys.Exists(k => k.StartsWith("DialogueTrees_response_" + nextTopicID + "_")))
                    {
                        if (responseData != null)
                        {
                            responseData.lastTopic = loadedDialogues[topicID];
                            responseData.nextTopic = loadedDialogues[nextTopicID];
                            responseData.npc = n;
                            responseData.topicResponses[topicID] = responseID;
                        }
                        else
                            responseData = new DialogueTreeResponse(loadedDialogues[topicID], loadedDialogues[nextTopicID], n, responseID);
                    }
                }
                else if(Game1.player.currentLocation.lastQuestionKey == "DialogueTrees_NPC_Question")
                {
                    Monitor.Log($"{npcName} is asking player about {loadedTopicNames[topicID]}, player response: {loadedResponseStrings[responseID]}");

                    var possibleReactions = npcKeys.FindAll(k => k.StartsWith("DialogueTrees_reaction_" + topicID + "_" + responseID + "_"));

                    if (!possibleReactions.Any())
                    {
                        Monitor.Log($"{npcName} has no reaction to {loadedTopicNames[topicID]} response {loadedResponseStrings[responseID]}! Check the [DT] content pack.", LogLevel.Warn);
                    }
                    else
                    {
                        NPC n = Game1.getCharacterFromName(npcName);
                        Game1.drawDialogue(n, npcDic[possibleReactions[myRand.Next(possibleReactions.Count)]]);
                        if (npcDic.ContainsKey("DialogueTrees_friendship_" + topicID + "_" + responseID) && int.TryParse(npcDic["DialogueTrees_friendship_" + topicID + "_" + responseID], out int amount))
                        {
                            Monitor.Log($"changing friendship with {n.Name} by {amount}");
                            Game1.player.changeFriendship(amount, n);
                        }

                        string nextTopicID = GetNextTopicID(topicID, responseID);

                        if (nextTopicID != null && loadedDialogues.ContainsKey(nextTopicID))
                        {
                            Monitor.Log($"Preparing followup dialogue {nextTopicID}");
                            if (responseData != null)
                            {
                                Monitor.Log($"Adding to existing responseData");

                                responseData.lastTopic = loadedDialogues[topicID];
                                responseData.nextTopic = loadedDialogues[nextTopicID];
                                responseData.npc = n;
                                responseData.topicResponses[topicID] = responseID;
                            }
                            else
                                responseData = new DialogueTreeResponse(loadedDialogues[topicID], loadedDialogues[nextTopicID], n, responseID);
                        }
                        else
                        {
                            if(responseData != null)
                                Monitor.Log("No next topic, erasing response data");
                            responseData = null;
                        }
                    }
                }
                
                Game1.player.currentLocation.lastQuestionKey = "";
                return;
            }

            // check for click on NPC

            if (Game1.activeClickableMenu != null || !Context.CanPlayerMove || (Config.ModButton != SButton.None && !Helper.Input.IsDown(Config.ModButton)) || (e.Button != Config.AskButton && e.Button != Config.AnswerButton))
                return;

            Monitor.Log($"Pressed modkey + {e.Button}");

            Rectangle tileRect = new Rectangle((int)Game1.currentCursorTile.X * 64, (int)Game1.currentCursorTile.Y * 64, 64, 64);

            NPC npc = null;

            foreach (NPC i in Game1.currentLocation.characters)
            {
                if (i != null && !i.IsMonster && (!Game1.player.isRidingHorse() || !(i is Horse)) && i.GetBoundingBox().Intersects(tileRect) && !i.IsInvisible && !i.checkAction(Game1.player, Game1.currentLocation))
                {
                    npc = i;
                    break;
                }
            }

            if (npc == null)
                return;
            try
            {
                npcDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{npc.Name}", ContentSource.GameContent);

            }
            catch
            {
                Monitor.Log($"No dialogue file for {npc.Name}", LogLevel.Warn);

                return;
            }
            npcKeys = npcDic.Keys.ToList();

            if (e.Button == Config.AskButton)
            {

                Monitor.Log($"Asking question of {npc.Name}");

                var shuffled = loadedDialogues.Values.ToList().FindAll(d => d.isStarter && d.playerCanAsk && npcKeys.Exists(k => k.StartsWith("DialogueTrees_response_" + d.topicID+"_")));

                if(!shuffled.Any())
                {
                    Monitor.Log($"No questions that {npc.Name} has a response to! Check the [DT] content pack.", LogLevel.Warn);
                    return;
                }
                Monitor.Log($"{shuffled.Count} questions that {npc.Name} has a response to.");

                ShuffleList(shuffled);
                var questions = shuffled.Take(Config.MaxPlayerQuestions);
                List<Response> responses = new List<Response>();
                foreach(var q in questions)
                {
                    Monitor.Log(q.topicID);
                    responses.Add(new Response($"DialogueTrees_Response#{npc.Name}#{q.topicID}", string.Format(loadedQuestionStrings[q.questionIDs[myRand.Next(q.questionIDs.Count)]], loadedTopicNames[q.topicID])));
                }

                Game1.player.currentLocation.createQuestionDialogue(string.Format(Helper.Translation.Get("ask-npc"), npc.Name), responses.ToArray(), "DialogueTrees_Player_Question");
            }
            else if (e.Button == Config.AnswerButton)
            {
                Monitor.Log($"Answering {npc.Name}'s question");

                var possibleQuestions = loadedDialogues.Values.ToList().FindAll(d => d.isStarter && npcKeys.Exists(k => k.StartsWith("DialogueTrees_reaction_" + d.topicID+"_")));

                if (!possibleQuestions.Any())
                {
                    Monitor.Log($"No questions that {npc.Name} can ask (no reactions)! Check the [DT] content pack.", LogLevel.Warn);
                    return;
                }

                DialogueTree p = possibleQuestions[myRand.Next(possibleQuestions.Count)];

                Monitor.Log($"Asking about {loadedTopicNames[p.topicID]}");

                List<Response> responses = new List<Response>();
                foreach(var r in p.responseIDs)
                {
                    Monitor.Log(r);

                    responses.Add(new Response($"DialogueTrees_Response#{npc.Name}#{p.topicID}#{r}", string.Format(loadedResponseStrings[r], loadedTopicNames[p.topicID])));
                }
                string qid = p.questionIDs[myRand.Next(p.questionIDs.Count)];

                List<string> possibleQuestionStrings = npcDic.Keys.ToList().FindAll(k => k.StartsWith("DialogueTrees_question_" + qid + "_"));
                string questionString = possibleQuestionStrings.Any() ? npcDic[possibleQuestionStrings[myRand.Next(possibleQuestionStrings.Count)]] : loadedQuestionStrings[qid];

                Game1.player.currentLocation.createQuestionDialogue(string.Format(questionString, loadedTopicNames[p.topicID]), responses.ToArray(), "DialogueTrees_NPC_Question");
                Game1.objectDialoguePortraitPerson = npc;
            }
        }

19 Source : HelperEvents.cs
with GNU General Public License v3.0
from aedenthorn

public static void GameLoop_OneSecondUpdateTicked(object sender, OneSecondUpdateTickedEventArgs e)
        {
            if (!Config.EnableMod)
                return;

            foreach (GameLocation location in Game1.locations)
            {

                if (location is FarmHouse)
                {
                    FarmHouse fh = location as FarmHouse;
                    if (fh.owner == null)
                        continue;

                    List<string> allSpouses = Misc.GetSpouses(fh.owner, 1).Keys.ToList();
                    List<string> bedSpouses = Misc.ReorderSpousesForSleeping(allSpouses.FindAll((s) => ModEntry.config.RoommateRomance || !fh.owner.friendshipData[s].RoommateMarriage));

                    using(IEnumerator<NPC> characters = fh.characters.GetEnumerator())
                    {
                        while (characters.MoveNext())
                        {
                            var character = characters.Current;
                            if (!(character.currentLocation == fh))
                            {
                                character.farmerPreplacedesThrough = false;
                                character.HideShadow = false;
                                character.isSleeping.Value = false;
                                continue;
                            }

                            if (allSpouses.Contains(character.Name))
                            {

                                if (Misc.IsInBed(fh, character.GetBoundingBox()))
                                {
                                    character.farmerPreplacedesThrough = true;
                                    if (!character.isMoving() && (Integrations.kissingAPI == null || Integrations.kissingAPI.LastKissed(character.Name) > 2))
                                    {
                                        Vector2 bedPos = Misc.GetSpouseBedPosition(fh, character.Name);
                                        if (Game1.timeOfDay >= 2000 || Game1.timeOfDay <= 600)
                                        {
                                            character.position.Value = bedPos;

                                            if (Game1.timeOfDay >= 2200)
                                            {
                                                character.ignoreScheduleToday = true;
                                            }
                                            if (!character.isSleeping.Value)
                                            {
                                                character.isSleeping.Value = true;

                                            }
                                            if (character.Sprite.CurrentAnimation == null)
                                            {
                                                if (!Misc.HreplacedleepingAnimation(character.Name))
                                                {
                                                    character.Sprite.StopAnimation();
                                                    character.faceDirection(0);
                                                }
                                                else
                                                {
                                                    character.playSleepingAnimation();
                                                }
                                            }
                                        }
                                        else
                                        {
                                            character.faceDirection(3);
                                            character.isSleeping.Value = false;
                                        }
                                    }
                                    else
                                    {
                                        character.isSleeping.Value = false;
                                    }
                                    character.HideShadow = true;
                                }
                                else if (Game1.timeOfDay < 2000 && Game1.timeOfDay > 600)
                                {
                                    character.farmerPreplacedesThrough = false;
                                    character.HideShadow = false;
                                    character.isSleeping.Value = false;
                                }
                            }
                        }
                    }
                }
            }
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public void Edit<T>(IreplacedetData replacedet)
        {
            Monitor.Log("Editing replacedet " + replacedet.replacedetName);
            if (replacedet.replacedetNameEquals("Data/Events/HaleyHouse"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;

                data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"] = Regex.Replace(data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 3", "");
                data["choseToExplain"] = Regex.Replace(data["choseToExplain"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
                data["lifestyleChoice"] = Regex.Replace(data["lifestyleChoice"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
            }
            else if (replacedet.replacedetNameEquals("Data/Events/Saloon"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;

                string aData = data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"];
                data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 3", "");
                aData = data["choseToExplain"];
                data["choseToExplain"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"", $"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
                aData = data["crying"];
                data["crying"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
            }
            else if (replacedet.replacedetNameEquals("Strings/StringsFromCSFiles"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                data["NPC.cs.3985"] = Regex.Replace(data["NPC.cs.3985"],  @"\.\.\.\$s.+", $"$n#$b#$c 0.5#{data["ResourceCollectionQuest.cs.13681"]}#{data["ResourceCollectionQuest.cs.13683"]}");
                Monitor.Log($"NPC.cs.3985 is set to \"{data["NPC.cs.3985"]}\"");
            }
            else if (replacedet.replacedetNameEquals("Data/animationDescriptions"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                List<string> sleepKeys = data.Keys.ToList().FindAll((s) => s.EndsWith("_Sleep"));
                foreach(string key in sleepKeys)
                {
                    if (!data.ContainsKey(key.ToLower()))
                    {
                        Monitor.Log($"adding {key.ToLower()} to animationDescriptions");
                        data.Add(key.ToLower(), data[key]);
                    }
                }
            }
            else if (replacedet.replacedetNameEquals("Data/EngagementDialogue"))
            {
                if (!config.RomanceAllVillagers)
                    return;
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                Farmer f = Game1.player;
                if (f == null)
                {
                    return;
                }
                foreach (string friend in f.friendshipData.Keys)
                {
                    if (!data.ContainsKey(friend+"0"))
                    {
                        data[friend + "0"] = "";
                    }
                    if (!data.ContainsKey(friend+"1"))
                    {
                        data[friend + "1"] = "";
                    }
                }
            }
            else if (replacedet.replacedetName.StartsWith("Characters/schedules") || replacedet.replacedetName.StartsWith("Characters\\schedules"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                List<string> keys = new List<string>(data.Keys);
                foreach (string key in keys)
                {
                    if(!data.ContainsKey($"marriage_{key}"))
                        data[$"marriage_{key}"] = data[key]; 
                }
            }
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public void Edit<T>(IreplacedetData replacedet)
        {
            Monitor.Log("Editing replacedet " + replacedet.replacedetName);
            if (replacedet.replacedetNameEquals("Data/Events/HaleyHouse"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;

                data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"] = Regex.Replace(data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 3", "");
                data["choseToExplain"] = Regex.Replace(data["choseToExplain"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
                data["lifestyleChoice"] = Regex.Replace(data["lifestyleChoice"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
            }
            else if (replacedet.replacedetNameEquals("Data/Events/Saloon"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;

                string aData = data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"];
                data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 3", "");
                aData = data["choseToExplain"];
                data["choseToExplain"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"", $"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
                aData = data["crying"];
                data["crying"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
            }
            else if (replacedet.replacedetNameEquals("Strings/StringsFromCSFiles"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                data["NPC.cs.3985"] = Regex.Replace(data["NPC.cs.3985"],  @"\.\.\.\$s.+", $"$n#$b#$c 0.5#{data["ResourceCollectionQuest.cs.13681"]}#{data["ResourceCollectionQuest.cs.13683"]}");
                Monitor.Log($"NPC.cs.3985 is set to \"{data["NPC.cs.3985"]}\"");
            }
            else if (replacedet.replacedetNameEquals("Data/animationDescriptions"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                List<string> sleepKeys = data.Keys.ToList().FindAll((s) => s.EndsWith("_Sleep"));
                foreach(string key in sleepKeys)
                {
                    if (!data.ContainsKey(key.ToLower()))
                    {
                        Monitor.Log($"adding {key.ToLower()} to animationDescriptions");
                        data.Add(key.ToLower(), data[key]);
                    }
                }
            }
            else if (replacedet.replacedetNameEquals("Data/EngagementDialogue"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                if (!config.RomanceAllVillagers)
                    return;
                Farmer f = Game1.player;
                if (f == null)
                {
                    return;
                }
                foreach (string friend in f.friendshipData.Keys)
                {
                    if (!data.ContainsKey(friend+"0"))
                    {
                        data[friend + "0"] = "";
                    }
                    if (!data.ContainsKey(friend+"1"))
                    {
                        data[friend + "1"] = "";
                    }
                }
            }
            else if (replacedet.replacedetName.StartsWith("Characters/schedules") || replacedet.replacedetName.StartsWith("Characters\\schedules"))
            {


                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                List<string> keys = new List<string>(data.Keys);
                foreach (string key in keys)
                {
                    if(!data.ContainsKey($"marriage_{key}"))
                        data[$"marriage_{key}"] = data[key]; 
                }
            }
        }

19 Source : LocationPatches.cs
with GNU General Public License v3.0
from aedenthorn

public static void FarmHouse_performTenMinuteUpdate_Postfix(FarmHouse __instance, int timeOfDay)
        {
            try
            {
                if (__instance.owner == null)
                    return;

                List<string> mySpouses = Misc.GetSpouses(__instance.owner, 1).Keys.ToList();
                if (Game1.IsMasterGame && Game1.timeOfDay >= 2200 && Game1.IsMasterGame)
                {
                    int upgradeLevel = __instance.upgradeLevel;
                    List<string> roomSpouses = mySpouses.FindAll((s) => Maps.roomIndexes.ContainsKey(s) || Maps.tmxSpouseRooms.ContainsKey(s));
                    List<string> bedSpouses = mySpouses.FindAll((s) => ModEntry.config.RoommateRomance || !__instance.owner.friendshipData[s].RoommateMarriage);
                    foreach (NPC c in __instance.characters)
                    {
                        if (c.isMarried())
                        {
                            string spouseName = c.Name;

                            if (Misc.GetSpouses(Game1.player,1).ContainsKey(spouseName))
                            {
                                c.checkForMarriageDialogue(timeOfDay, __instance);
                            }

                            Point bedSpot;
                            if (timeOfDay >= 2200)
                            {
                                if (!bedSpouses.Contains(c.Name))
                                {
                                    if (!roomSpouses.Exists((n) => n == spouseName))
                                    {
                                        bedSpot = __instance.getRandomOpenPointInHouse(ModEntry.myRand);
                                    }
                                    else
                                    {
                                        int offset = roomSpouses.IndexOf(spouseName) * 7;
                                        Vector2 spot = (upgradeLevel == 1) ? new Vector2(32f, 5f) : new Vector2(38f, 14f);
                                        bedSpot = new Point((int)spot.X + offset, (int)spot.Y);
                                    }

                                }
                                else
                                {
                                    int bedWidth = Misc.GetBedWidth(__instance);
                                    bool up = upgradeLevel > 1;

                                    Point bedStart = __instance.GetSpouseBed().GetBedSpot();
                                    int x = 1 + (int)(bedSpouses.IndexOf(spouseName) / (float)(bedSpouses.Count) * (bedWidth - 1));
                                    bedSpot = new Point(bedStart.X + x, bedStart.Y);

                                }

                                c.controller = null;
                                if (c.Position != Misc.GetSpouseBedPosition(__instance, bedSpouses, c.Name) && (!Misc.IsInBed(__instance,c.GetBoundingBox()) || !Kissing.kissingSpouses.Contains(c.Name)))
                                {
                                    c.controller = new PathFindController(c, __instance, bedSpot, 0, new PathFindController.endBehavior(FarmHouse.spouseSleepEndFunction));
                                    if (c.controller.pathToEndPoint == null || !__instance.isTileOnMap(c.controller.pathToEndPoint.Last<Point>().X, c.controller.pathToEndPoint.Last<Point>().Y))
                                    {
                                        c.controller = null;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(FarmHouse_performTenMinuteUpdate_Postfix)}:\n{ex}", LogLevel.Error);
            }
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private void GameLoop_UpdateTicked(object sender, StardewModdingAPI.Events.UpdateTickedEventArgs e)
        {

            // check for followup dialogue

            if (Game1.activeClickableMenu == null && responseData != null)
            {
                DialogueTree p = responseData.nextTopic;

                Monitor.Log($"Asking about followup topic {loadedTopicNames[p.topicID]}");

                Dictionary<string, string> npcDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{responseData.npc.name}", ContentSource.GameContent);
                List<string> npcKeys = npcDic.Keys.ToList();

                List<Response> responses = new List<Response>();
                foreach (var r in p.responseIDs)
                {
                    Monitor.Log(r);
                    responses.Add(new Response($"DialogueTrees_Response#{responseData.npc.Name}#{p.topicID}#{r}", string.Format(loadedResponseStrings[r], loadedTopicNames[p.topicID])));
                }
                string qid = p.questionIDs[myRand.Next(p.questionIDs.Count)];
                List<string> possibleQuestionStrings = npcDic.Keys.ToList().FindAll(k => k.StartsWith("DialogueTrees_question_" + qid + "_"));
                string questionString = possibleQuestionStrings.Any() ? npcDic[possibleQuestionStrings[myRand.Next(possibleQuestionStrings.Count)]] : loadedQuestionStrings[qid];

                Game1.player.currentLocation.createQuestionDialogue(string.Format(questionString, loadedTopicNames[p.topicID]), responses.ToArray(), "DialogueTrees_NPC_Question");
                Game1.objectDialoguePortraitPerson = responseData.npc;
            }
        }

19 Source : Misc.cs
with GNU General Public License v3.0
from aedenthorn

public static List<string> GetBedSpouses(FarmHouse fh)
        {
            if (ModEntry.config.RoommateRomance)
                return GetSpouses(fh.owner, 1).Keys.ToList();

            return GetSpouses(fh.owner, 1).Keys.ToList().FindAll(s => !fh.owner.friendshipData[s].RoommateMarriage);
        }

19 Source : HelperEvents.cs
with GNU General Public License v3.0
from aedenthorn

public static void GameLoop_OneSecondUpdateTicked(object sender, OneSecondUpdateTickedEventArgs e)
        {
            foreach(GameLocation location in Game1.locations)
            {

                if(location is FarmHouse)
                {
                    FarmHouse fh = location as FarmHouse;
                    if (fh.owner == null)
                        continue;

                    List<string> allSpouses = Misc.GetSpouses(fh.owner, 1).Keys.ToList();
                    List<string> bedSpouses = Misc.ReorderSpousesForSleeping(allSpouses.FindAll((s) => ModEntry.config.RoommateRomance || !fh.owner.friendshipData[s].RoommateMarriage));

                    foreach (NPC character in fh.characters)
                    {
                        if (!(character.currentLocation == fh))
                            continue;

                        if (allSpouses.Contains(character.Name))
                        {

                            if (Misc.IsInBed(fh, character.GetBoundingBox()))
                            {
                                character.farmerPreplacedesThrough = true;
                                if (!character.isMoving() && !Kissing.kissingSpouses.Contains(character.Name))
                                {
                                    Vector2 bedPos = Misc.GetSpouseBedPosition(fh, bedSpouses, character.Name);
                                    if(Game1.timeOfDay >= 2000 || Game1.timeOfDay <= 600)
                                    {
                                        character.position.Value = bedPos;
                                        character.ignoreScheduleToday = true;
                                        if (!character.isSleeping.Value)
                                        {
                                            Monitor.Log($"putting {character.Name} to sleep");
                                            character.isSleeping.Value = true;

                                        }
                                        if(character.Sprite.CurrentAnimation == null)
                                        {
                                            if (!Misc.HreplacedleepingAnimation(character.Name))
                                            {
                                                character.Sprite.StopAnimation();
                                                character.faceDirection(0);
                                            }
                                            else
                                            {
                                                character.playSleepingAnimation();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        character.faceDirection(3);
                                        character.isSleeping.Value = false;
                                    }
                                }
                                else
                                {
                                    character.isSleeping.Value = false;
                                }
                                character.HideShadow = true;
                            }
                            else if (Game1.timeOfDay < 2000 && Game1.timeOfDay > 600)
                            {
                                character.farmerPreplacedesThrough = false;
                                character.HideShadow = false;
                                character.isSleeping.Value = false;
                            }
                        }
                    }
                    if (location == Game1.player.currentLocation && ModEntry.config.AllowSpousesToKiss)
                    {
                        Kissing.TrySpousesKiss();
                    }
                }
            }
        }

19 Source : Misc.cs
with GNU General Public License v3.0
from aedenthorn

public static void PlaceSpousesInFarmhouse(FarmHouse farmHouse)
        {
            Farmer farmer = farmHouse.owner;

            if (farmer == null)
                return;

            List<NPC> allSpouses = GetSpouses(farmer, 1).Values.ToList();

            if (allSpouses.Count == 0)
            {
                Monitor.Log("no spouses");
                return;
            }

            ShuffleList(ref allSpouses);

            List<string> bedSpouses = new List<string>();
            string kitchenSpouse = null;

            foreach (NPC spouse in allSpouses)
            {

                int type = ModEntry.myRand.Next(0, 100);

                Monitor.Log($"spouse rand {type}, bed: {ModEntry.config.PercentChanceForSpouseInBed} kitchen {ModEntry.config.PercentChanceForSpouseInKitchen}");
                
                if(type < ModEntry.config.PercentChanceForSpouseInBed)
                {
                    if (bedSpouses.Count < GetBedWidth(farmHouse) - 1 && (ModEntry.config.RoommateRomance || !farmer.friendshipData[spouse.Name].IsRoommate()) && HreplacedleepingAnimation(spouse.Name))
                    {
                        Monitor.Log("made bed spouse: " + spouse.Name);
                        bedSpouses.Add(spouse.Name);
                    }

                }
                else if(type < ModEntry.config.PercentChanceForSpouseInBed + ModEntry.config.PercentChanceForSpouseInKitchen)
                {
                    if (kitchenSpouse == null)
                    {
                        Monitor.Log("made kitchen spouse: " + spouse.Name);
                        kitchenSpouse = spouse.Name;
                    }
                }
                else if(type < ModEntry.config.PercentChanceForSpouseInBed + ModEntry.config.PercentChanceForSpouseInKitchen + ModEntry.config.PercentChanceForSpouseAtPatio)
                {
                    if (!Game1.isRaining && !Game1.IsWinter && !spouse.Name.Equals("Krobus") && spouse.Schedule == null)
                    {
                        Monitor.Log("made patio spouse: " + spouse.Name);
                        spouse.setUpForOutdoorPatioActivity();
                    }
                }
            }

            List<string> allBedSpouses = new List<string>(GetSpouses(farmer, 1).Keys.ToList());

            List<string> roomSpouses = ReorderSpousesForRooms(GetSpouses(farmer, -1).Keys.ToList().FindAll(s => (Maps.roomIndexes.ContainsKey(s) || Maps.tmxSpouseRooms.ContainsKey(s)) && !farmer.friendshipData[s].IsEngaged()));

            foreach (NPC j in allSpouses) { 
                Monitor.Log("placing " + j.Name);

                Point kitchenSpot = farmHouse.getKitchenStandingSpot();
                Vector2 spouseRoomSpot = (farmHouse.upgradeLevel == 1) ? new Vector2(32f, 5f) : new Vector2(38f, 14f);

                if (!farmHouse.Equals(j.currentLocation))
                {
                    Monitor.Log("not in farm house");
                    continue;
                }

                Monitor.Log("in farm house");
                j.shouldPlaySpousePatioAnimation.Value = false;

                Vector2 spot = (farmHouse.upgradeLevel == 1) ? new Vector2(32f, 5f) : new Vector2(38f, 14f);


                if (bedSpouses.Count > 0 && (IsInBed(farmHouse, j.GetBoundingBox()) || bedSpouses.Contains(j.Name)))
                {
                    Monitor.Log($"putting {j.Name} in bed");
                    j.position.Value = GetSpouseBedPosition(farmHouse, allBedSpouses, j.Name);

                    if (HreplacedleepingAnimation(j.Name) && Game1.timeOfDay >= 2000)
                    {
                        j.playSleepingAnimation();
                    }
                }
                else if (kitchenSpouse == j.Name)
                {
                    Monitor.Log($"{j.Name} is in kitchen");
                    j.setTilePosition(farmHouse.getKitchenStandingSpot());
                    j.setRandomAfternoonMarriageDialogue(Game1.timeOfDay, farmHouse, false);
                }
                else if (!ModEntry.config.BuildAllSpousesRooms && farmer.spouse != j.Name)
                {
                    j.setTilePosition(farmHouse.getRandomOpenPointInHouse(ModEntry.myRand));
                    j.setRandomAfternoonMarriageDialogue(Game1.timeOfDay, farmHouse, false);
                }
                else if(ModEntry.config.BuildAllSpousesRooms && roomSpouses.Contains(j.Name))
                {
                    int offset = roomSpouses.IndexOf(j.Name) * 7;
                    if (j.Name == "Sebastian" && Game1.netWorldState.Value.hasWorldStateID("sebastianFrog"))
                        j.setTilePosition((int)spot.X + offset - 1, (int)spot.Y + 1);
                    else
                        j.setTilePosition((int)spot.X + offset, (int)spot.Y);
                    j.faceDirection(ModEntry.myRand.Next(0, 4));
                    j.setSpouseRoomMarriageDialogue();
                    Monitor.Log($"{j.Name} loc: {(spot.X + offset)},{spot.Y}");
                }
                else
                {
                    j.setTilePosition(farmHouse.getRandomOpenPointInHouse(ModEntry.myRand));
                    j.faceDirection(ModEntry.myRand.Next(0, 4));
                    Monitor.Log($"{j.Name} spouse random loc");
                    j.setRandomAfternoonMarriageDialogue(Game1.timeOfDay, farmHouse, false);
                }
            }

        }

19 Source : Misc.cs
with GNU General Public License v3.0
from aedenthorn

internal static Point GetSpouseRoomTilePosition(NPC npc, FarmHouse farmHouse)
        {
            List<string> roomSpouses = ReorderSpousesForRooms(GetSpouses(npc.getSpouse(), -1).Keys.ToList().FindAll(s => (Maps.roomIndexes.ContainsKey(s) || Maps.tmxSpouseRooms.ContainsKey(s)) && !npc.getSpouse().friendshipData[s].IsEngaged()));

            Point spot = (farmHouse.upgradeLevel == 1) ? new Point(32, 5) : new Point(38, 14);
            int offset = roomSpouses.IndexOf(npc.Name) * 7;
            return new Point(spot.X + offset, spot.Y);
        }

19 Source : MainViewModel.cs
with MIT License
from ahopper

public void Search()
        {
            if (SearchText == "")
            {
                FilteredIcons = Icons;
            }
            else
            {
                FilteredIcons = Icons.FindAll(x => x.Name.Contains(SearchText, StringComparison.OrdinalIgnoreCase));
            }
        }

19 Source : ArrayUtilities.cs
with Apache License 2.0
from aivclab

public static List<T> FindAll<T>(T[] array, Predicate<T> match)
        {
            var list = new List<T>(collection : array);
            return list.FindAll(match : match);
        }

19 Source : Util.cs
with MIT License
from ajayyy

public static List<T> FindAndRemove<T>( List<T> list, System.Predicate<T> match )
		{
			List<T> retVal = list.FindAll( match );
			list.RemoveAll( match );
			return retVal;
		}

19 Source : UnitMakerSpawnPointSelector.cs
with GNU General Public License v3.0
from akaAgar

internal int GetFreeParkingSpot(int airbaseID, out Coordinates parkingSpotCoordinates, Coordinates? lastSpotCoordinates = null, bool requiresOpenAirParking = false)
        {
            parkingSpotCoordinates = new Coordinates();
            if (!AirbaseParkingSpots.ContainsKey(airbaseID) || (AirbaseParkingSpots[airbaseID].Count == 0)) return -1;
            DBEntryAirbase[] airbaseDB = (from DBEntryAirbase ab in TheaterDB.GetAirbases() where ab.DCSID == airbaseID select ab).ToArray();
            if (airbaseDB.Length == 0) return -1; // No airbase with proper DCSID
            DBEntryAirbaseParkingSpot? parkingSpot = null;
            if (lastSpotCoordinates != null) //find nearest spot distance wise in attempt to cluster
                parkingSpot = AirbaseParkingSpots[airbaseID].FindAll(x => (!requiresOpenAirParking || x.ParkingType != ParkingSpotType.HardenedAirShelter))
                    .ToList()
                    .Aggregate((acc, x) => acc.Coordinates.GetDistanceFrom(lastSpotCoordinates.Value) > x.Coordinates.GetDistanceFrom(lastSpotCoordinates.Value) && x.Coordinates.GetDistanceFrom(lastSpotCoordinates.Value) != 0 ? x : acc);
            else
                parkingSpot = Toolbox.RandomFrom(AirbaseParkingSpots[airbaseID]);
            AirbaseParkingSpots[airbaseID].Remove(parkingSpot.Value);
            parkingSpotCoordinates = parkingSpot.Value.Coordinates;
            return parkingSpot.Value.DCSID;
        }

19 Source : PrimaryKeyIndex.cs
with MIT License
from AlenToma

internal void ClearAndRenderValues(List<LightDataTableRow> rows, string key)
        {
            _savedIndexes.Clear();
            if (string.IsNullOrEmpty(key)) return;
            if (rows.Any())
                _savedIndexes = rows.GroupBy(x => x[key]).Select(x => x.First()).ToList().FindAll(x => x[key] != null).ToDictionary(x => x[key], x => x);
        }

19 Source : LightDataRowCollection.cs
with MIT License
from AlenToma

public LightDataRowCollection DistinctByColumn(string columnName, Predicate<LightDataTableRow> func = null)
        {
            var r = new LightDataRowCollection(this.GroupBy(x => x[columnName]).Select(x => x.First()).ToList());
            if (r.Any() && func != null)
                r = new LightDataRowCollection(r.FindAll(func));

            return r;
        }

19 Source : Workspace.cs
with GNU General Public License v3.0
from alexgracianoarj

private bool RemoveAll(bool saveConfirmation)
		{
			if (saveConfirmation)
			{
				ICollection<Project> unsavedProjects = projects.FindAll(
					delegate(Project project) { return project.IsDirty; }
				);

				if (unsavedProjects.Count > 0)
				{
					string message = Strings.AskSaveChanges + "\n";
					foreach (Project project in unsavedProjects)
						message += "\n" + project.Name;

					DialogResult result = MessageBox.Show(message, Strings.Confirmation,
						MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

					if (result == DialogResult.Yes)
					{
						if (!SaveAllUnsavedProjects())
							return false;
					}
					else if (result == DialogResult.Cancel)
					{
						return false;
					}
				}
			}

			while (HasProject)
			{
				int lastIndex = projects.Count - 1;
				Project project = projects[lastIndex];
				project.CloseItems();
				projects.RemoveAt(lastIndex);
				OnProjectRemoved(new ProjectEventArgs(project));
			}
			ActiveProject = null;
			return true;
		}

19 Source : DealStaticticGenerator.cs
with Apache License 2.0
from AlexWan

public static List<string> GetStatisticNew(List<Position> positions, bool withPunkt)
        {
            if (positions == null)
            {
                return null;
            }

            List<Position> positionsNew = positions.FindAll((
                position => position.State != PositionStateType.OpeningFail 
                            && position.EntryPrice != 0 && position.ClosePrice != 0));

            if (positionsNew.Count == 0)
            {
                return null;
            }

            Position[] deals = positionsNew.ToArray();

            List<string> report = new List<string>();
            /*
                 Чистый П\У
                 Чистый П\У %
                 Количество сделок

                 Сред. П\У по сделке
                 Сред. П\У % по сделке
                 Сред. П\У на капитал
                 Сред. П\У % на капитал

                 Прибыльных  сделок
                 Прибыльных %
                 Сред. П\У по сделке
                 Сред. П\У % по сделке
                 Сред. П\У на капитал
                 Сред. П\У % на капитал
                 Максимум подряд

                 Убыточных сделок
                 Убыточных  %
                 Сред. П\У по сделке
                 Сред. П\У % по сделке
                 Сред. П\У на капитал
                 Сред. П\У % на капитал
                 Максимум подряд

                 Макс просадка %
                 Размер комиссии
            */
            /*Net Profit/Loss
                Net Profit/Loss
                Number of transactions

                Average. Profit/Loss on the deal
                Average. Profit/Loss % of the transaction
                Average. Profit/Loss for capital
                Average. Profit/Loss % for capital

                Profitable deals
                Profitable %
                Average. Profit/Loss on the deal
                Average. Profit/Loss % of the transaction
                Average. Profit/Loss for capital
                Average. Profit/Loss % for capital
                At most in a row.

                Loss transactions
                Losses.
                Average. Profit/Loss on the deal
                Average. Profit/Loss % of the transaction
                Average. Profit/Loss for capital
                Average. Profit/Loss % for capital
                At most in a row.

                Max drawdown %
                Comission amount
            */


            report.Add(Convert.ToDouble(GetAllProfitInPunkt(deals)).ToString(new CultureInfo("ru-RU"))); //Net profit
            report.Add(Math.Round(GetAllProfitPersent(deals), 6).ToString(new CultureInfo("ru-RU")));//Net profti %
            report.Add(deals.Length.ToString(new CultureInfo("ru-RU")));// Number of transactions
            report.Add(Math.Round(GetProfitFactor(deals), 6).ToString(new CultureInfo("ru-RU")));   //Profit Factor
            report.Add(Math.Round(GetRecovery(deals), 6).ToString(new CultureInfo("ru-RU")));   // Recovery
            report.Add("");

            report.Add(Convert.ToDouble(GetMidleProfitInPunkt(deals)).ToString(new CultureInfo("ru-RU"))); //average profit
            report.Add(Math.Round(GetMidleProfitInPersent(deals), 6).ToString(new CultureInfo("ru-RU"))); //average profit in %
            report.Add(Convert.ToDouble(GetMidleProfitInPunktToDepozit(deals)).ToString(new CultureInfo("ru-RU"))); //average profit
            report.Add(Math.Round(GetMidleProfitInPersentToDepozit(deals), 6).ToString(new CultureInfo("ru-RU"))); //average profit in %

            report.Add(""); // 11
            report.Add(GetProfitDial(deals).ToString(new CultureInfo("ru-RU"))); //wining trades/выигрышных сделок
            report.Add(Math.Round(GetProfitDialPersent(deals), 6).ToString(new CultureInfo("ru-RU")));//wining trade in %/выигрышных сделок в %
            //report += Convert.ToDouble(GetAllProfitInProfitInPunkt(deals)).ToString(new CultureInfo("ru-RU")) + "\r\n"; //total profit margins/общий профит выигрышных сделок
            report.Add(Convert.ToDouble(GetAllMidleProfitInProfitInPunkt(deals)).ToString(new CultureInfo("ru-RU"))); //Average profit in winning trades/средний профит в выигрышных сделках
            report.Add(Math.Round(GetAllMidleProfitInProfitInPersent(deals), 6).ToString(new CultureInfo("ru-RU"))); //Average profit as a percentage of winning trades/средний профит в процентах в выигрышных сделках
            report.Add(Convert.ToDouble(GetAllMidleProfitInProfitInPunktOnDepozit(deals)).ToString(new CultureInfo("ru-RU"))); //Average profit in winning trades/средний профит в выигрышных сделках
            report.Add(Math.Round(GetAllMidleProfitInProfitInPersentOnDepozit(deals), 6).ToString(new CultureInfo("ru-RU")));//Average profit as a percentage of winning trades/средний профит в процентах в выигрышных сделках
            report.Add(GetMaxProfitSeries(deals).ToString(new CultureInfo("ru-RU"))); //maximum series of winning trades/максимальная серия выигрышных сделок

            report.Add("");
            report.Add(GetLossDial(deals).ToString(new CultureInfo("ru-RU"))); //losing trades/проигрышных сделок
            report.Add(Math.Round(GetLossDialPersent(deals), 6).ToString(new CultureInfo("ru-RU"))); //losing deals in/проигрышных сделок в %
            //report += Convert.ToDouble(GetAllLossInLossInPunkt(deals)).ToString(new CultureInfo("ru-RU")) + "\r\n"; //loss-making total profit/общий профит проигрышных сделок
            report.Add(Convert.ToDouble(GetAllMidleLossInLossInPunkt(deals)).ToString(new CultureInfo("ru-RU")));//average profit in losing trades/средний профит в проигрышных сделках
            report.Add(Math.Round(GetAllMidleLossInLossInPersent(deals), 6).ToString(new CultureInfo("ru-RU")));//Average profit as a percentage in losing trades/средний профит в процентах в проигрышных сделках
            report.Add(Convert.ToDouble(GetAllMidleLossInLossInPunktOnDepozit(deals)).ToString(new CultureInfo("ru-RU"))); //Average profit in winning trades/средний профит в выигрышных сделках
            report.Add(Math.Round(GetAllMidleLossInLossInPersentOnDepozit(deals), 6).ToString(new CultureInfo("ru-RU")));//Average profit as a percentage of winning trades/средний профит в процентах в выигрышных сделках
            report.Add(GetMaxLossSeries(deals).ToString(new CultureInfo("ru-RU")));//maximum series of winning trades/максимальная серия выигрышных сделок
            report.Add("");
            report.Add(Math.Round(GetMaxDownPersent(deals), 6).ToString(new CultureInfo("ru-RU"))); //maximum drawdown in percent/максимальная просадка в процентах
            report.Add(Math.Round(GetCommissionAmount(deals), 6).ToString(new CultureInfo("ru-RU"))); //maximum drawdown in percent/максимальная просадка в процентах

            /*report += Math.Round(GetSharp(), 2).ToString(new CultureInfo("ru-RU"));
            */
            return report;
        }

19 Source : Journal.cs
with Apache License 2.0
from AlexWan

public decimal GetProfitFromThatDayInPersent()
        {
            try
            {
                List<Position> deals = _positionController.AllPositions;

                if (deals == null)
                {
                    return 0;
                }

                List<Position> dealsToDay = deals.FindAll(
                    position => position.OpenOrders[0].TimeCreate.Day == DateTime.Now.Day
                    );

                decimal profit = 0;

                for (int i = 0; i < dealsToDay.Count; i++)
                {
                    profit += dealsToDay[i].ProfitOperationPersent;
                }
                return profit;
            }
            catch (Exception error)
            {
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
            return 0;
        }

19 Source : ServerMasterPortfoliosPainter.cs
with Apache License 2.0
from AlexWan

private void RePaintPortfolio()
        {
            try
            {
                if (_positionHost.Child == null)
                {
                    return;
                }

                if (_portfolios == null)
                {
                    return;
                }

                try
                {
                    for (int i = 0; i < _portfolios.Count; i++)
                    {
                        List<Portfolio> portfolios =
                            _portfolios.FindAll(p => p.Number == _portfolios[i].Number);

                        if (portfolios.Count > 1)
                        {
                            _portfolios.RemoveAt(i);
                            break;
                        }
                    }
                }
                catch
                {
                    // ignore
                }

                if (!_positionHost.CheckAccess())
                {
                    _positionHost.Dispatcher.Invoke(RePaintPortfolio);
                    return;
                }

                if (_portfolios == null)
                {
                    _gridPosition.Rows.Clear();
                    return;
                }

                int curUpRow = 0;
                int curSelectRow = 0;

                if (_gridPosition.RowCount != 0)
                {
                    curUpRow = _gridPosition.FirstDisplayedScrollingRowIndex;
                }

                if (_gridPosition.SelectedRows.Count != 0)
                {
                    curSelectRow = _gridPosition.SelectedRows[0].Index;
                }

                _gridPosition.Rows.Clear();

                // send portfolios to draw
                // отправляем портфели на прорисовку
                for (int i = 0; _portfolios != null && i < _portfolios.Count; i++)
                {
                    try
                    {
                        PaintPortfolio(_portfolios[i]);
                    }
                    catch (Exception)
                    {
                        
                    }
                }

               /* int curUpRow = 0;
                int curSelectRow = 0;*/

               if (curUpRow != 0 && curUpRow != -1)
               {
                   _gridPosition.FirstDisplayedScrollingRowIndex = curUpRow;
               }

               if (curSelectRow != 0 &&
                   _gridPosition.Rows.Count > curSelectRow
                   && curSelectRow != -1)
               {
                   _gridPosition.Rows[curSelectRow].Selected = true;
               }

            }
            catch (Exception error)
            {
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 Source : ServerMasterUi.xaml.cs
with Apache License 2.0
from AlexWan

private void RePaintSourceGrid()
        {
            if (_gridSources.InvokeRequired)
            {
                _gridSources.Invoke(new Action(RePaintSourceGrid));
                return;
            }

            _gridSources.Rows.Clear();

            List<IServer> servers = ServerMaster.GetServers();

            if (servers != null)
            {
                servers = servers.FindAll(s => s != null && s.ServerType != ServerType.Optimizer);
            }

            List<ServerType> serverTypes = ServerMaster.ServersTypes;

            for (int i = 0; servers != null && i < servers.Count; i++)
            {
                DataGridViewRow row1 = new DataGridViewRow();
                row1.Cells.Add(new DataGridViewTextBoxCell());
                row1.Cells[0].Value = servers[i].ServerType;
                row1.Cells.Add(new DataGridViewTextBoxCell());
                row1.Cells[1].Value = servers[i].ServerStatus;
                _gridSources.Rows.Add(row1);

                serverTypes.Remove(serverTypes.Find(s => s == servers[i].ServerType));

                if (servers[i].ServerStatus == ServerConnectStatus.Connect)
                {
                    DataGridViewCellStyle style = new DataGridViewCellStyle();
                    style.BackColor = Color.MediumSeaGreen;
                    style.SelectionBackColor = Color.Green;
                    style.ForeColor = Color.Black;
                    style.SelectionForeColor = Color.Black;
                    row1.Cells[1].Style = style;
                    row1.Cells[0].Style = style;
                }
                else
                {
                    DataGridViewCellStyle style = new DataGridViewCellStyle();
                    style.BackColor = Color.Coral;
                    style.SelectionBackColor = Color.Chocolate;
                    style.ForeColor = Color.Black;
                    style.SelectionForeColor = Color.Black;
                    row1.Cells[1].Style = style;
                    row1.Cells[0].Style = style;
                }
            }

            for (int i = 0; i < serverTypes.Count; i++)
            {
                DataGridViewRow row1 = new DataGridViewRow();
                row1.Cells.Add(new DataGridViewTextBoxCell());
                row1.Cells[0].Value = serverTypes[i].ToString();
                row1.Cells.Add(new DataGridViewTextBoxCell());
                row1.Cells[1].Value = "Disabled";
                _gridSources.Rows.Add(row1);
            }
        }

19 Source : QuikDde.cs
with Apache License 2.0
from AlexWan

private void PortfolioSpotUpdated(long id, object[,] table)
        {
             int countElem = table.GetLength(0);

            if (countElem == 0)
            {
                return;
            }

            for (int i = 0; i < countElem; i++)
            {
                string firm = table[i, 0].ToString();

                if (firm.Length != firm.Replace("SPBFUT", "").Length)
                {
                    return;
                }
                
                decimal valueBegin = ToDecimal(table[i, 1]);

                decimal profitLoss = ToDecimal(table[i, 3]);
                decimal valueCurrent = valueBegin + profitLoss;

                decimal valueBlock = valueCurrent - ToDecimal(table[i, 2]);

                if (valueBegin == 0 &&
                    valueBlock == 0 &&
                    profitLoss == 0)
                {
                    return;
                }

                string portfolioClient = table[i, 4].ToString();

                QuikPortfolio data = _portfoliosQuik.Find(port => port.Firm == firm);

                if (data == null)
                {
                    PortfolioReturner r = new PortfolioReturner();
                    r.Long = id;
                    r.Objects = table;
                    r.PortfolioUpdate += PortfolioSpotUpdated;
                    Thread worker = new Thread(r.Start);
                    worker.IsBackground = true;
                    worker.Start();
                    return;
                }

                Portfolio portfolioWithoutClient = _portfolios.Find(portfolio => portfolio.Number == data.Number);

                if (portfolioWithoutClient != null)
                {
                    portfolioWithoutClient.Number = data.Number + "@" + portfolioClient;
                }

                Portfolio myPortfolio = _portfolios.Find(portfolio => portfolio.Number == data.Number + "@" + portfolioClient);

                if (myPortfolio == null)
                {
                    continue;
                }

                myPortfolio.ValueBegin = valueBegin;
                myPortfolio.ValueCurrent = valueCurrent;
                myPortfolio.ValueBlocked = valueBlock;
                myPortfolio.Profit = profitLoss;
            }

            for (int i = 0; i < _portfolios.Count; i++)
            {
                List<Portfolio> portfolios = _portfolios.FindAll(p => p.Number == _portfolios[i].Number);

                if (portfolios.Count > 1)
                {
                    _portfolios.RemoveAt(i);
                    break;
                }
            }

            if (UpdatePortfolios != null)
            {
                UpdatePortfolios(_portfolios);
            }
        }

19 Source : QuikDdeServer.cs
with Apache License 2.0
from AlexWan

private void PfnOrderStatusCallback(int nMode, int dwTransId, ulong nOrderNum, string clreplacedCode, string secCode,
            double dPrice, long l, double dValue, int nIsSell, int nStatus, IntPtr pOrderDescriptor)
        {
            try
            {
                if (dwTransId == 0)
                {
                    return;
                }
                Order order = new Order();

                order.SecurityNameCode = secCode;
                order.ServerType = ServerType.QuikDde;
                order.Price = (decimal)dPrice;
                //order.Volume = (int)dValue;

                Order oldOrder = GetOrderFromUserId(dwTransId.ToString());

                if (oldOrder != null)
                {
                    order.Volume = oldOrder.Volume;
                }

                order.NumberUser = dwTransId;
                order.NumberMarket = nOrderNum.ToString();
                order.SecurityNameCode = secCode;

                Order originOrder = _allOrders.Find(ord => ord.NumberUser == order.NumberUser);

                if (originOrder != null)
                {
                    order.PortfolioNumber = originOrder.PortfolioNumber;
                }

                if (ServerTime != DateTime.MinValue)
                {
                    order.TimeCallBack = ServerTime;
                }
                else
                {
                    order.TimeCallBack = DateTime.Now;
                }

                if (nIsSell == 0)
                {
                    order.Side = Side.Buy;
                }
                else
                {
                    order.Side = Side.Sell;
                }

                if (nStatus == 1)
                {
                    order.State = OrderStateType.Activ;
                }
                else if (nStatus == 2)
                {
                    order.State = OrderStateType.Cancel;
                    order.TimeCancel = order.TimeCallBack;
                }
                else
                {
                    order.State = OrderStateType.Done;
                    order.TimeDone = order.TimeCallBack;
                }

                SetOrder(order);

                if (MyOrderEvent != null)
                {
                    MyOrderEvent(order);
                }

                if (_myTrades != null &&
                        _myTrades.Count != 0)
                {
                    List<MyTrade> myTrade =
                        _myTrades.FindAll(trade => trade.NumberOrderParent == order.NumberMarket);

                    for (int tradeNum = 0; tradeNum < myTrade.Count; tradeNum++)
                    {
                        if (MyTradeEvent != null)
                        {
                            MyTradeEvent(myTrade[tradeNum]);
                        }
                    }
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 Source : Robot.cs
with Apache License 2.0
from AlexWan

public void CheckOtherStates()
        {
            var errors = Log.FindAll(l => l.Type == LogMessageType.Error);
            if (errors.Count != 0)
            {
                LogStatus = Status.Danger;
            }
            else
            {
                LogStatus = Status.Ok;
            }
        }

19 Source : ContactEventHandler.cs
with Apache License 2.0
from Algoryx

public void Remove( System.Predicate<ContactListener> predicate )
    {
      if ( m_isPerformingCallbacks ) {
        var listenersToRemove = m_listeners.FindAll( listener => predicate( listener ) );
        listenersToRemove.ForEach( listener => listener.IsRemoved = true );
        m_listenersToRemove.AddRange( listenersToRemove );
      }
      else
        m_listeners.RemoveAll( listener => predicate( listener ) && listener.OnDestroy( this ) );
    }

19 Source : GpuState.cs
with Apache License 2.0
from anadventureisu

public void UpdateAverages()
        {
            FiveMinHashAvg = GetAverage(Samples.FindAll(x => DateTime.Now - x.Timestamp < TimeSpan.FromMinutes(5)));
            OneHourHashAvg = GetAverage(Samples.FindAll(x => DateTime.Now - x.Timestamp < TimeSpan.FromMinutes(60)));
        }

19 Source : Edge.cs
with MIT License
from anderm

public static List<Edge> SelectEdgesForSitePoint(Vector2f coord, List<Edge> edgesToTest) {
			return edgesToTest.FindAll(
			delegate(Edge e) {
				if (e.LeftSite != null) {
					if (e.LeftSite.Coord == coord) return true;
				}
				if (e.RightSite != null) {
					if (e.RightSite.Coord == coord) return true;
				}
				return false;
			});
		}

19 Source : Voronoi.cs
with MIT License
from anderm

public List<Edge> HullEdges() {
			return edges.FindAll(edge=>edge.IsPartOfConvexHull());
		}

19 Source : DirectoryInfoExtensions.cs
with GNU General Public License v3.0
from AndreiFedarets

public static FileInfo[] GetFilesFixed(this DirectoryInfo directoryinfo, string searchPattern)
        {
            if (((searchPattern.Length - (searchPattern.LastIndexOf('.') + 1)) == 3) && !
            searchPattern.Substring(searchPattern.LastIndexOf('.')).Contains('*'))
                return directoryinfo.GetFiles(searchPattern).ToList().FindAll
                (F => F.Extension.Length == 4).ToArray();
            return directoryinfo.GetFiles(searchPattern);
        }

19 Source : DirectoryInfoExtensions.cs
with GNU General Public License v3.0
from AndreiFedarets

public static FileInfo[] GetFilesFixed(this DirectoryInfo directoryinfo, string searchPattern, SearchOption searchOption)
        {
            if (((searchPattern.Length - (searchPattern.LastIndexOf('.') + 1)) == 3) && !
            searchPattern.Substring(searchPattern.LastIndexOf('.')).Contains('*'))
                return directoryinfo.GetFiles(searchPattern, searchOption).ToList().FindAll
                (f => f.Extension.Length == 4).ToArray();
            return directoryinfo.GetFiles(searchPattern);
        }

19 Source : FieldList.cs
with MIT License
from AnkiTools

public string ToJSON()
        {
            var json = from field in base.FindAll(x => x != null)
                       select field.ToJSON();

            return String.Join(",\n", json.ToArray());
        }

19 Source : ExcelDataValidationCollection.cs
with Apache License 2.0
from Appdynamics

public IEnumerable<IExcelDataValidation> FindAll(Predicate<IExcelDataValidation> match)
        {
            return _validations.FindAll(match);
        }

19 Source : ExcelDataValidationCollection.cs
with Apache License 2.0
from Appdynamics

public void RemoveAll(Predicate<IExcelDataValidation> match)
        {
            var matches = _validations.FindAll(match);
            foreach (var m in matches)
            {
                if (!(m is ExcelDataValidation))
                {
                    throw new InvalidCastException("The supplied item must inherit OfficeOpenXml.DataValidation.ExcelDataValidation");
                }
                TopNode.RemoveChild(((ExcelDataValidation)m).TopNode);
                //var dvNode = TopNode.SelectSingleNode(DataValidationPath.TrimStart('/'), NameSpaceManager);
                //if (dvNode != null)
                //{
                //    dvNode.RemoveChild(((ExcelDataValidation)m).TopNode);
                //}
            }
            _validations.RemoveAll(match);
            OnValidationCountChanged();
        }

19 Source : DepartmentControllerTest.cs
with MIT License
from appsonsf

[TestMethod]
        public async Task TestSearch()
        {
            var dep0 = new DepartmentListOutput
            {
                Id = Guid.NewGuid(),
                Name = "sclq",
            };
            var dep1 = new DepartmentListOutput
            {
                Id = Guid.NewGuid(),
                Name = "sclq-jt",
                ParentId = dep0.Id,
            };
            var dep2 = new DepartmentListOutput
            {
                Id = Guid.NewGuid(),
                Name = "sclq-gs",
                ParentId = dep0.Id,
            };
            var dep3 = new DepartmentListOutput
            {
                Id = Guid.NewGuid(),
                Name = "sclq-jt-jg",
                ParentId = dep1.Id,
            };
            var departments = new List<DepartmentListOutput>(new[] { dep0, dep1, dep2, dep3 });

            var departmentAppService = Subsreplacedute.For<IDepartmentAppService>();
            departmentAppService.GetAllListAsync()
                .Returns(Task.FromResult(departments));
            var searchResult = departments.FindAll(o => o.Name.Contains("jt"));
            departmentAppService.SearchByKeywordAsync("jt")
                .Returns(Task.FromResult(searchResult));


            var target = new DepartmentController(
                CreateMemoryCache(),
                CreateMapper(),
                departmentAppService,
                Subsreplacedute.For<IPositionAppService>());

            var result = await target.Search("jt");

            var data = result.Value;
            data.Count.Should().Be(2);
            data[0].Id.Should().Be(dep1.Id);
            data[1].Id.Should().Be(dep3.Id);
        }

19 Source : MahjongLogic.cs
with MIT License
from ArcturusZhang

public static IEnumerable<OpenMeld> GetKongs(IList<Tile> handTiles, Tile discardTile, MeldSide side)
        {
            var result = new HashSet<Meld>(Meld.MeldConsiderColorEqualityComparer);
            var tileList = new List<Tile>(handTiles) { discardTile };
            var handCount = CountTiles(handTiles);
            int index = Tile.GetIndex(discardTile);
            if (handCount[index] == 3)
            {
                var tiles = tileList.FindAll(t => Tile.GetIndex(t) == index);
                result.Add(new Meld(true, tiles.ToArray()));
            }
            return result.Select(meld => new OpenMeld
            {
                Meld = meld,
                Tile = discardTile,
                Side = side
            });
        }

19 Source : MahjongLogic.cs
with MIT License
from ArcturusZhang

public static IEnumerable<OpenMeld> GetSelfKongs(IList<Tile> handTiles, Tile lastDraw)
        {
            var result = new HashSet<Meld>(Meld.MeldConsiderColorEqualityComparer);
            var testTiles = new List<Tile>(handTiles) { lastDraw };
            var handCount = CountTiles(testTiles);
            for (int i = 0; i < handCount.Length; i++)
            {
                replacedert.IsTrue(handCount[i] <= 4);
                if (handCount[i] == 4)
                {
                    var tiles = testTiles.FindAll(tile => Tile.GetIndex(tile) == i);
                    result.Add(new Meld(false, tiles.ToArray()));
                }
            }
            return result.Select(meld => new OpenMeld
            {
                Meld = meld,
                Side = MeldSide.Self
            });
        }

19 Source : MahjongLogic.cs
with MIT License
from ArcturusZhang

public static IEnumerable<OpenMeld> GetPongs(IList<Tile> handTiles, Tile discardTile, MeldSide side)
        {
            var result = new HashSet<Meld>(Meld.MeldConsiderColorEqualityComparer);
            var handTileList = new List<Tile>(handTiles);
            var particularTiles = handTileList.FindAll(tile => tile.EqualsIgnoreColor(discardTile));
            var combination = Combination(particularTiles, 2);
            foreach (var item in combination)
            {
                item.Add(discardTile);
                result.Add(new Meld(true, item.ToArray()));
            }
            return result.Select(meld => new OpenMeld
            {
                Meld = meld,
                Tile = discardTile,
                Side = side
            });
        }

19 Source : MahjongLogic.cs
with MIT License
from ArcturusZhang

private static void GetChows1(List<Tile> handTiles, Tile discardTile, HashSet<Meld> result)
        {
            Tile first, second;
            if (Tile.TryTile(discardTile.Suit, discardTile.Rank - 2, out first) && Tile.TryTile(discardTile.Suit, discardTile.Rank - 1, out second))
            {
                var firstTiles = handTiles.FindAll(tile => tile.EqualsIgnoreColor(first));
                if (firstTiles.Count == 0) return;
                var secondTiles = handTiles.FindAll(tile => tile.EqualsIgnoreColor(second));
                if (secondTiles.Count == 0) return;
                foreach (var pair in CartesianJoin(firstTiles, secondTiles))
                {
                    result.Add(new Meld(true, pair.Key, pair.Value, discardTile));
                }
            }
        }

19 Source : MahjongLogic.cs
with MIT License
from ArcturusZhang

private static void GetChows2(List<Tile> handTiles, Tile discardTile, HashSet<Meld> result)
        {
            Tile first, second;
            if (Tile.TryTile(discardTile.Suit, discardTile.Rank - 1, out first) && Tile.TryTile(discardTile.Suit, discardTile.Rank + 1, out second))
            {
                var firstTiles = handTiles.FindAll(tile => tile.EqualsIgnoreColor(first));
                if (firstTiles.Count == 0) return;
                var secondTiles = handTiles.FindAll(tile => tile.EqualsIgnoreColor(second));
                if (secondTiles.Count == 0) return;
                foreach (var pair in CartesianJoin(firstTiles, secondTiles))
                {
                    result.Add(new Meld(true, pair.Key, pair.Value, discardTile));
                }
            }
        }

19 Source : MahjongLogic.cs
with MIT License
from ArcturusZhang

private static void GetChows3(List<Tile> handTiles, Tile discardTile, HashSet<Meld> result)
        {
            Tile first, second;
            if (Tile.TryTile(discardTile.Suit, discardTile.Rank + 1, out first) && Tile.TryTile(discardTile.Suit, discardTile.Rank + 2, out second))
            {
                var firstTiles = handTiles.FindAll(tile => tile.EqualsIgnoreColor(first));
                if (firstTiles.Count == 0) return;
                var secondTiles = handTiles.FindAll(tile => tile.EqualsIgnoreColor(second));
                if (secondTiles.Count == 0) return;
                foreach (var pair in CartesianJoin(firstTiles, secondTiles))
                {
                    result.Add(new Meld(true, pair.Key, pair.Value, discardTile));
                }
            }
        }

19 Source : GridInformation.cs
with MIT License
from Aroueterra

public Vector3Int[] GetAllPositions(string propertyName)
        {
            return m_PositionProperties.Keys.ToList().FindAll(x => x.name == propertyName).Select(x => x.position).ToArray();
        }

19 Source : ERC20Account.cs
with GNU General Public License v3.0
from atomex-me

private async Task<IEnumerable<SelectedWalletAddress>> SelectUnspentAddresses(
            List<WalletAddress> from,
            decimal amount,
            decimal fee,
            decimal feePrice,
            FeeUsagePolicy feeUsagePolicy,
            AddressUsagePolicy addressUsagePolicy,
            BlockchainTransactionType transactionType)
        {
            var erc20 = Erc20Config;
            var eth = EthConfig;

            if (addressUsagePolicy == AddressUsagePolicy.UseMinimalBalanceFirst)
            {
                from = from.ToList().SortList((a, b) => a.AvailableBalance().CompareTo(b.AvailableBalance()));
            }
            else if (addressUsagePolicy == AddressUsagePolicy.UseMaximumBalanceFirst)
            {
                from = from.ToList().SortList((a, b) => b.AvailableBalance().CompareTo(a.AvailableBalance()));
            }
            else if (addressUsagePolicy == AddressUsagePolicy.UseMaximumChainBalanceFirst)
            {
                var ethUnspentAddresses = (await DataRepository
                    .GetUnspentAddressesAsync(eth.Name)
                    .ConfigureAwait(false))
                    .ToList();

                if (!ethUnspentAddresses.Any())
                {
                    Log.Debug("Unsufficient ETH ammount for ERC20 token processing");
                    return Enumerable.Empty<SelectedWalletAddress>();
                }

                ethUnspentAddresses = ethUnspentAddresses.SortList((a, b) => b.AvailableBalance().CompareTo(a.AvailableBalance()));

                from = from.FindAll(
                    a => ethUnspentAddresses.Select(b => b.Address)
                        .ToList()
                        .Contains(a.Address));
            }

            else if (addressUsagePolicy == AddressUsagePolicy.UseOnlyOneAddress)
            {
                var result = new List<SelectedWalletAddress>();

                var feeInEth = feeUsagePolicy == FeeUsagePolicy.EstimatedFee
                    ? erc20.GetFeeAmount(
                        fee: GasLimitByType(transactionType, isFirstTx: true),
                        feePrice: await eth
                            .GetGasPriceAsync()
                            .ConfigureAwait(false))
                    : erc20.GetFeeAmount(fee, feePrice);

                //take erc20 non zero addresses first
                foreach (var address in from.TakeWhile(x => x.AvailableBalance() >= amount))
                {
                    var ethAddress = await DataRepository
                        .GetWalletAddressAsync(eth.Name, address.Address)
                        .ConfigureAwait(false);
                    
                    if (ethAddress == null || ethAddress.AvailableBalance() < feeInEth)
                    {
                        Log.Debug("Unsufficient ETH ammount for ERC20 token processing on address {@address} with available balance {@balance} and needed amount {@amount}",
                            ethAddress.Address,
                            ethAddress.AvailableBalance(),
                            feeInEth);
                        continue;
                    }

                    result.Add(new SelectedWalletAddress
                    {
                        WalletAddress = address,
                        UsedAmount = amount,
                        UsedFee = feeInEth
                    });
                }

                if (result.Any() || amount != 0m)
                    return result;
                
                //take non zero eth addresses
                var ethUnspentAddresses = (await DataRepository
                    .GetUnspentAddressesAsync(eth.Name)
                    .ConfigureAwait(false))
                    .ToList();

                if(!ethUnspentAddresses.Any())
                {
                    Log.Debug("Unsufficient ETH ammount for ERC20 token processing");
                    return Enumerable.Empty<SelectedWalletAddress>();
                }

                ethUnspentAddresses = ethUnspentAddresses.FindAll(a => a.AvailableBalance() > feeInEth);
                ethUnspentAddresses = ethUnspentAddresses.SortList((a, b) => a.AvailableBalance().CompareTo(b.AvailableBalance()));

                foreach (var address in ethUnspentAddresses)
                {
                    result.Add(new SelectedWalletAddress
                    {
                        WalletAddress = address,
                        UsedAmount = amount,
                        UsedFee = feeInEth
                    });
                }

                return result;
            }

            for (var txCount = 1; txCount <= from.Count; ++txCount)
            {
                var result = new List<SelectedWalletAddress>();
                var requiredAmount = amount;

                var isFirstTx = true;
                var completed = false;

                foreach (var address in from)
                {
                    var availableBalance = address.AvailableBalance();

                    if (!(availableBalance > 0))
                        continue;

                    var ethAddress = await DataRepository
                        .GetWalletAddressAsync(eth.Name, address.Address)
                        .ConfigureAwait(false);

                    var ethAvailableBalance = ethAddress != null ? ethAddress.AvailableBalance() : 0;

                    var txFee = feeUsagePolicy == FeeUsagePolicy.EstimatedFee
                        ? eth.GetFeeAmount(
                            fee: GasLimitByType(transactionType, isFirstTx),
                            feePrice: await eth
                                .GetGasPriceAsync()
                                .ConfigureAwait(false))
                        : feeUsagePolicy == FeeUsagePolicy.FeeForAllTransactions
                            ? Math.Round(eth.GetFeeAmount(fee, feePrice) / txCount, eth.Digits)
                            : eth.GetFeeAmount(fee, feePrice);

                    if (ethAvailableBalance < txFee) // ignore address with balance less than fee
                    {
                        Log.Debug("Unsufficient ETH ammount for ERC20 token processing on address {@address} with available balance {@balance} and needed amount {@amount}",
                            ethAddress.Address,
                            ethAddress.AvailableBalance(),
                            txFee);
                        if (result.Count + from.Count - from.IndexOf(address) <= txCount)
                            break;
                        else
                            continue;
                    }

                    var amountToUse = Math.Min(availableBalance, requiredAmount);

                    result.Add(new SelectedWalletAddress
                    {
                        WalletAddress = address,
                        UsedAmount = amountToUse,
                        UsedFee = txFee
                    });
                    requiredAmount -= amountToUse;

                    if (requiredAmount <= 0)
                    {
                        completed = true;
                        break;
                    }

                    if (result.Count == txCount) // will need more transactions
                        break;

                    if (isFirstTx)
                        isFirstTx = false;
                }

                if (completed)
                    return result;
            }

            return Enumerable.Empty<SelectedWalletAddress>();
        }

19 Source : SequenceUtils.cs
with GNU General Public License v3.0
from az64

public static void RebuildAudioSeq(List<SequenceInfo> SequenceList, OutputSettings _settings)
        {
            // spoiler log output DEBUG
            StringBuilder log = new StringBuilder();
            void WriteOutput(string str)
            {
                Debug.WriteLine(str); // we still want debug output though
                log.AppendLine(str);
            }

            List<MMSequence> OldSeq = new List<MMSequence>();
            int f = RomUtils.GetFileIndexForWriting(Addresses.SeqTable);
            int basea = RomData.MMFileList[f].Addr;

            for (int i = 0; i < 128; i++)
            {
                MMSequence entry = new MMSequence();
                if (i == 0x1E) // intro music when link gets ambushed
                {
                    entry.Addr = 2;
                    entry.Size = 0;
                    OldSeq.Add(entry);
                    continue;
                }

                int entryaddr = Addresses.SeqTable + (i * 16);
                entry.Addr = (int)ReadWriteUtils.Arr_ReadU32(RomData.MMFileList[f].Data, entryaddr - basea);
                entry.Size = (int)ReadWriteUtils.Arr_ReadU32(RomData.MMFileList[f].Data, (entryaddr - basea) + 4);
                if (entry.Size > 0)
                {
                    entry.Data = new byte[entry.Size];
                    Array.Copy(RomData.MMFileList[4].Data, entry.Addr, entry.Data, 0, entry.Size);
                }
                else
                {
                    int j = SequenceList.FindIndex(u => u.Replaces == i);
                    if (j != -1)
                    {
                        if ((entry.Addr > 0) && (entry.Addr < 128))
                        {
                            if (SequenceList[j].Replaces != 0x28) // 28 (fairy fountain)
                            {
                                SequenceList[j].Replaces = entry.Addr;
                            }
                            else
                            {
                                entry.Data = OldSeq[0x18].Data;
                                entry.Size = OldSeq[0x18].Size;
                            }
                        }
                    }
                }
                OldSeq.Add(entry);
            }

            List<MMSequence> NewSeq = new List<MMSequence>();
            int addr = 0;
            byte[] NewAudioSeq = new byte[0];
            for (int i = 0; i < 128; i++)
            {
                MMSequence newentry = new MMSequence();
                if (OldSeq[i].Size == 0)
                {
                    newentry.Addr = OldSeq[i].Addr;
                }
                else
                {
                    newentry.Addr = addr;
                }

                if (SequenceList.FindAll(u => u.Replaces == i).Count > 1)
                {
                    WriteOutput("Error: Slot " + i.ToString("X") + " has multiple songs pointing at it!");
                }

                int p = RomData.PointerizedSequences.FindIndex(u => u.PreviousSlot == i);
                int j = SequenceList.FindIndex(u => u.Replaces == i);
                if (p != -1){ // found song we want to pointerize
                    newentry.Addr = RomData.PointerizedSequences[p].Replaces;
                    newentry.Size = 0;
                }
                else if (j != -1){ // new song to replace old slot found
                    if (SequenceList[j].MM_seq != -1)
                    {
                        newentry.Size = OldSeq[SequenceList[j].MM_seq].Size;
                        newentry.Data = OldSeq[SequenceList[j].MM_seq].Data;
                        WriteOutput("Slot " + i.ToString("X") + " -> " + Path.GetFileName(SequenceList[j].Name));

                    }
                    else if (SequenceList[j].SequenceBinaryList != null && SequenceList[j].SequenceBinaryList[0] != null)
                    {
                        if (SequenceList[j].SequenceBinaryList.Count == 0)
                            throw new Exception("Reached music write without a song to write");
                        if (SequenceList[j].SequenceBinaryList.Count > 1)
                            WriteOutput("Warning: writing song with multiple sequence/bank combos, selecting first available");
                        newentry.Size = SequenceList[j].SequenceBinaryList[0].SequenceBinary.Length;
                        newentry.Data = SequenceList[j].SequenceBinaryList[0].SequenceBinary;
                        WriteOutput("Slot " + i.ToString("X") + " := " + Path.GetFileName(SequenceList[j].Name) + " *");

                    }
                    else // non mm, load file and add
                    {
                        BinaryReader sequence = new BinaryReader(File.Open(SequenceList[j].Name, FileMode.Open));
                        byte[] data = new byte[(int)sequence.BaseStream.Length];
                        sequence.Read(data, 0, data.Length);
                        sequence.Close();

                        // if the sequence is not padded to 16 bytes, the DMA fails
                        //  music can stop from playing and on hardware it will just straight crash
                        if (data.Length % 0x10 != 0)
                            data = data.Concat(new byte[0x10 - (data.Length % 0x10)]).ToArray();

                        // I think this checks if the sequence type is correct for MM
                        //  because DB ripped sequences from SF64/SM64/MK64 without modifying them
                        if (data[1] != 0x20)
                        {
                            data[1] = 0x20;
                        }

                        newentry.Size = data.Length;
                        newentry.Data = data;
                        WriteOutput("Slot " + i.ToString("X") + " := " + Path.GetFileName(SequenceList[j].Name));

                    }
                }
                else // not found, song wasn't touched by rando, just transfer over
                {
                    newentry.Size = OldSeq[i].Size;
                    newentry.Data = OldSeq[i].Data;
                }

                NewSeq.Add(newentry);
                // TODO is there not a better way to write this?
                if (newentry.Data != null)
                {

                    NewAudioSeq = NewAudioSeq.Concat(newentry.Data).ToArray();
                }

                addr += newentry.Size;
            }

            // discovered when MM-only music was fixed, if the audioseq is left in it's old spot
            // audio quality is garbage, sounds like static
            //if (addr > (RomData.MMFileList[4].End - RomData.MMFileList[4].Addr))
            //else
                //RomData.MMFileList[4].Data = NewAudioSeq;

            int index = RomUtils.AppendFile(NewAudioSeq);
            ResourceUtils.ApplyHack(Values.ModsDirectory, "reloc-audio");
            RelocateSeq(index);
            RomData.MMFileList[4].Data = new byte[0];
            RomData.MMFileList[4].Cmp_Addr = -1;
            RomData.MMFileList[4].Cmp_End = -1;

            //update sequence index pointer table
            f = RomUtils.GetFileIndexForWriting(Addresses.SeqTable);
            for (int i = 0; i < 128; i++)
            {
                ReadWriteUtils.Arr_WriteU32(RomData.MMFileList[f].Data, (Addresses.SeqTable + (i * 16)) - basea, (uint)NewSeq[i].Addr);
                ReadWriteUtils.Arr_WriteU32(RomData.MMFileList[f].Data, 4 + (Addresses.SeqTable + (i * 16)) - basea, (uint)NewSeq[i].Size);
            }

            //update inst sets used by each new seq
            // this is NOT the audiobank, its the complementary instrument set value for each sequence
            //   IE, sequence 7 uses instrument set "10", we replaced it with sequnece ae which needs bank "23"
            f = RomUtils.GetFileIndexForWriting(Addresses.InstSetMap);
            basea = RomData.MMFileList[f].Addr;
            for (int i = 0; i < 128; i++)
            {
                // huh? paddr? pointer? padding?
                int paddr = (Addresses.InstSetMap - basea) + (i * 2) + 2;

                int j = -1;
                if (NewSeq[i].Size == 0) // pointer, we need to copy the instrumnet set from the destination
                {
                    j = SequenceList.FindIndex(u => u.Replaces == NewSeq[i].Addr);
                }
                else
                {
                    j = SequenceList.FindIndex(u => u.Replaces == i);
                }

                if (j != -1)
                {
                    RomData.MMFileList[f].Data[paddr] = (byte)SequenceList[j].Instrument;
                }

            }

            // DEBUG spoiler log output
            String dir = Path.GetDirectoryName(_settings.OutputROMFilename);
            String path = $"{Path.GetFileNameWithoutExtension(_settings.OutputROMFilename)}";
            // spoiler log should already be written by the time we reach this far
            if (File.Exists(Path.Combine(dir, path + "_SpoilerLog.txt")))
                path += "_SpoilerLog.txt";
            else // TODO add HTML log compatibility
                path += "_SongLog.txt";

            using (StreamWriter sw = new StreamWriter(Path.Combine(dir, path), append: true))
            {
                sw.WriteLine(""); // spacer
                sw.Write(log);
            }


        }

19 Source : Enemies.cs
with GNU General Public License v3.0
from az64

public static void SwapSceneEnemies(Scene scene, Random rng)
        {
            List<int> Actors = GetSceneEnemyActors(scene);
            if (Actors.Count == 0)
            {
                return;
            }
            List<int> Objects = GetSceneEnemyObjects(scene);
            if (Objects.Count == 0)
            {
                return;
            }
            // if actor doesn't exist but object does, probably spawned by something else
            List<int> ObjRemove = new List<int>();
            foreach (int o in Objects)
            {
                List<Enemy> ObjectMatch = EnemyList.FindAll(u => u.Object == o);
                bool exists = false;
                for (int i = 0; i < ObjectMatch.Count; i++)
                {
                    exists |= Actors.Contains(ObjectMatch[i].Actor);
                }
                if (!exists)
                {
                    ObjRemove.Add(o); ;
                }
            }
            foreach (int o in ObjRemove)
            {
                Objects.Remove(o);
            }
            List<ValueSwap[]> ActorsUpdate = new List<ValueSwap[]>();
            List<ValueSwap> ObjsUpdate;
            List<List<Enemy>> Updates;
            List<List<Enemy>> Matches;
            while (true)
            {
                ObjsUpdate = new List<ValueSwap>();
                Updates = new List<List<Enemy>>();
                Matches = new List<List<Enemy>>();
                int oldsize = 0;
                int newsize = 0;
                for (int i = 0; i < Objects.Count; i++)
                {
                    Updates.Add(EnemyList.FindAll(u => ((u.Object == Objects[i]) && (Actors.Contains(u.Actor)))));
                    Matches.Add(GetMatchPool(Updates[i], rng));
                    int k = rng.Next(Matches[i].Count);
                    int newobj = Matches[i][k].Object;
                    newsize += Matches[i][k].ObjectSize;
                    oldsize += Updates[i][0].ObjectSize;
                    ValueSwap NewObject = new ValueSwap();
                    NewObject.OldV = Objects[i];
                    NewObject.NewV = newobj;
                    ObjsUpdate.Add(NewObject);
                }
                if (newsize <= oldsize)
                {
                    //this should take into account map/scene size and size of all loaded actors...
                    //not really accurate but *should* work for now to prevent crashing
                    break;
                }
            }
            for (int i = 0; i < ObjsUpdate.Count; i++)
            {
                int j = 0;
                while (j != Actors.Count)
                {
                    Enemy Old = Updates[i].Find(u => u.Actor == Actors[j]);
                    if (Old != null)
                    {
                        List<Enemy> SubMatches = Matches[i].FindAll(u => u.Object == ObjsUpdate[i].NewV);
                        int l;
                        while (true)
                        {
                            l = rng.Next(SubMatches.Count);
                            if ((Old.Type == SubMatches[l].Type) && (Old.Stationary == SubMatches[l].Stationary))
                            {
                                break;
                            }
                            else
                            {
                                if ((Old.Type == SubMatches[l].Type) && (rng.Next(5) == 0))
                                {
                                    break;
                                }
                            }
                            if (SubMatches.FindIndex(u => u.Type == Old.Type) == -1)
                            {
                                break;
                            }
                        }
                        ValueSwap NewActor = new ValueSwap();
                        NewActor.OldV = Actors[j];
                        NewActor.NewV = SubMatches[l].Actor;
                        ValueSwap NewVar = new ValueSwap();
                        NewVar.NewV = SubMatches[l].Variables[rng.Next(SubMatches[l].Variables.Count)];
                        ActorsUpdate.Add(new ValueSwap[] { NewActor, NewVar });
                        Actors.RemoveAt(j);
                    }
                    else
                    {
                        j++;
                    }
                }
            }
            SetSceneEnemyActors(scene, ActorsUpdate);
            SetSceneEnemyObjects(scene, ObjsUpdate);
            SceneUtils.UpdateScene(scene);
        }

19 Source : RoleAssignmentHelper.cs
with MIT License
from Azure

private async Task<List<Microsoft.Azure.Management.Graph.RBAC.Fluent.IRolereplacedignment>> CreateRbacRolereplacedignmentsAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            List<IRolereplacedignment> rolereplacedignments = new List<IRolereplacedignment>();
            if (!this.rolesToreplacedign.Any()
                && !this.roleDefinitionsToreplacedign.Any())
            {
                return rolereplacedignments;
            }
            else if (this.idProvider.PrincipalId == null)
            {
                return rolereplacedignments;
            }
            else
            {
                try
                {
                    ResolveCurrentResourceGroupScope();

                    var rolereplacedignments1 = await Task.WhenAll(rolesToreplacedign.Values.Select(async (scopeAndRole) =>
                    {
                        BuiltInRole role = scopeAndRole.Item2;
                        string scope = scopeAndRole.Item1;
                        return await CreateRbacRolereplacedignmentIfNotExistsAsync(role.ToString(), scope, true, cancellationToken);
                    }));
                    rolereplacedignments.AddRange(rolereplacedignments1);

                    var rolereplacedignments2 = await Task.WhenAll(roleDefinitionsToreplacedign.Values.Select(async (scopeAndRole) =>
                    {
                        string roleDefinition = scopeAndRole.Item2;
                        string scope = scopeAndRole.Item1;
                        return await CreateRbacRolereplacedignmentIfNotExistsAsync(roleDefinition, scope, false, cancellationToken);
                    }));
                    rolereplacedignments.AddRange(rolereplacedignments2);
                    return rolereplacedignments.FindAll(rolereplacedignment => rolereplacedignment != null);
                }
                finally
                {
                    this.rolesToreplacedign.Clear();
                    this.roleDefinitionsToreplacedign.Clear();
                }
            }
        }

19 Source : AuthorizationRules.cs
with MIT License
from Azure

public List<AuthorizationRule> GetRules(Predicate<AuthorizationRule> match)
        {
            return ((List<AuthorizationRule>)this.innerCollection).FindAll(match);
        }

See More Examples