System.Collections.Generic.Dictionary.ContainsKey(int)

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

3459 Examples 7

19 Source : StringsOnXAxis.xaml.cs
with MIT License
from ABTSoftware

public override string FormatLabel(IComparable dataValue)
        {
            int labelValue = (int)Convert.ChangeType(dataValue, typeof(int));
            return _labelsMap.ContainsKey(labelValue) ? _labelsMap[labelValue] : labelValue + " Not in map!";
        }

19 Source : StringsOnXAxis.xaml.cs
with MIT License
from ABTSoftware

public override string FormatCursorLabel(IComparable dataValue)
        {
            int labelValue = (int)Convert.ChangeType(dataValue, typeof(int));
            return _labelsMap.ContainsKey(labelValue) ? _labelsMap[labelValue] : labelValue + " Not in map!";
        }

19 Source : ParticleManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

public int CreateBlockingParticleEmitter(PhysicsObj obj, uint emitterInfoID, int partIdx, AFrame offset, int emitterID)
        {
            if (emitterID != 0)
            {
                if (ParticleTable.ContainsKey(emitterID))
                    return 0;
            }
            return CreateBlockingParticleEmitter(obj, emitterInfoID, partIdx, offset, emitterID);
        }

19 Source : POParser.cs
with MIT License
from adams85

private bool TryReadEntry(bool allowHeaderEntry, out IPOEntry result)
        {
            if (_line == null)
            {
                result = null;
                return false;
            }

            var entryLocation = new TextLocation(_lineIndex, _columnIndex);

            List<POComment> comments = _commentBuffer != null ? ParseComments() : null;
            Dictionary<int, string> translations = null;
            string id = null, pluralId = null, contextId = null;
            IPOEntry entry = null;
            EntryTokens expectedTokens = EntryTokens.Id | EntryTokens.PluralId | EntryTokens.ContextId;
            do
            {
                EntryTokens token = DetectEntryToken(out int tokenLength) & expectedTokens;
                if (token == EntryTokens.None)
                {
                    if (!(expectedTokens == EntryTokens.Translation && entry is POPluralEntry))
                    {
                        AddError(GetUnexpectedCharDiagnosticCode(DiagnosticCodes.UnexpectedToken), new TextLocation(_lineIndex, _columnIndex));
                        result = null;
                        return false;
                    }
                    else
                        break;
                }

                _columnIndex += tokenLength;
                switch (token)
                {
                    case EntryTokens.Id:
                        _columnIndex = FindNextTokenInLine(requireWhiteSpace: true);
                        if (_columnIndex < 0 || !TryReadPOString(_keyStringNewLine, out id))
                        {
                            result = null;
                            return false;
                        }

                        expectedTokens &= ~EntryTokens.Id;
                        expectedTokens |= EntryTokens.Translation;
                        break;
                    case EntryTokens.PluralId:
                        _columnIndex = FindNextTokenInLine(requireWhiteSpace: true);
                        if (_columnIndex < 0 || !TryReadPOString(_keyStringNewLine, out pluralId))
                        {
                            result = null;
                            return false;
                        }
                        expectedTokens &= ~EntryTokens.PluralId;
                        break;
                    case EntryTokens.ContextId:
                        _columnIndex = FindNextTokenInLine(requireWhiteSpace: true);
                        if (_columnIndex < 0 || !TryReadPOString(_keyStringNewLine, out contextId))
                        {
                            result = null;
                            return false;
                        }
                        expectedTokens &= ~EntryTokens.ContextId;
                        break;
                    case EntryTokens.Translation:
                        var originalColumnIndex = _columnIndex;
                        TryReadPluralIndex(out int? pluralIndex);

                        _columnIndex = FindNextTokenInLine(requireWhiteSpace: true);
                        if (_columnIndex < 0 || !TryReadPOString(_translationStringNewLine, out string value))
                        {
                            result = null;
                            return false;
                        }

                        if (entry == null && id.Length == 0)
                        {
                            if (!(pluralId == null && contextId == null))
                            {
                                AddWarning(DiagnosticCodes.EntryHasEmptyId, entryLocation);
                            }
                            else if (!allowHeaderEntry)
                            {
                                AddError(DiagnosticCodes.InvalidEntryKey, entryLocation);
                                result = null;
                                return false;
                            }
                        }

                        // plural
                        if (pluralId != null)
                        {
                            if (pluralIndex != null)
                            {
                                if (pluralIndex < 0 || (_catalog.PluralFormCount > 0 && pluralIndex >= _catalog.PluralFormCount))
                                {
                                    AddError(DiagnosticCodes.InvalidPluralIndex, new TextLocation(_lineIndex, originalColumnIndex));
                                    break;
                                }
                            }
                            else
                            {
                                AddWarning(DiagnosticCodes.MissingPluralIndex, new TextLocation(_lineIndex, originalColumnIndex));
                                pluralIndex = 0;
                            }

                            if (entry == null)
                            {
                                entry = new POPluralEntry(new POKey(id, pluralId, contextId))
                                {
                                    Comments = comments,
                                };

                                translations = new Dictionary<int, string>();
                            }

                            if (translations.ContainsKey(pluralIndex.Value))
                                AddWarning(DiagnosticCodes.DuplicatePluralForm, entryLocation, pluralIndex.Value);

                            translations[pluralIndex.Value] = value;

                            expectedTokens = EntryTokens.Translation;
                        }
                        // singular
                        else
                        {
                            if (pluralIndex != null)
                                if (pluralIndex != 0)
                                {
                                    AddError(DiagnosticCodes.InvalidPluralIndex, new TextLocation(_lineIndex, originalColumnIndex));
                                    break;
                                }
                                else
                                    AddWarning(DiagnosticCodes.UnnecessaryPluralIndex, new TextLocation(_lineIndex, originalColumnIndex));

                            entry = new POSingularEntry(new POKey(id, null, contextId))
                            {
                                Comments = comments,
                                Translation = value
                            };

                            expectedTokens = EntryTokens.None;
                        }

                        break;
                }

                SeekNextToken();
            }
            while (_line != null && expectedTokens != EntryTokens.None);

            if (entry == null)
            {
                if (_columnIndex >= 0)
                    AddError(GetUnexpectedCharDiagnosticCode(DiagnosticCodes.IncompleteEntry), entryLocation);

                result = null;
                return false;
            }

            if (entry is POPluralEntry pluralEntry)
            {
                var n =
                    _catalog.PluralFormCount > 0 ? _catalog.PluralFormCount :
                    translations.Count > 0 ? translations.Keys.Max() + 1 :
                    0;

                for (var i = 0; i < n; i++)
                    if (translations.TryGetValue(i, out string value))
                        pluralEntry.Add(value);
                    else
                    {
                        pluralEntry.Add(null);
                        AddWarning(DiagnosticCodes.MissingPluralForm, entryLocation, i);
                    }
            }

            result = entry;
            return true;
        }

19 Source : CoverletCoverageResults.cs
with MIT License
from ademanuele

public Dictionary<int, int> CoverageForFile(string path)
    {
      Dictionary<int, int> fileCoverage = new Dictionary<int, int>();

      foreach (var module in result.Modules)
        foreach (var doreplacedent in module.Value)
          if (doreplacedent.Key == path)
            foreach (var c in doreplacedent.Value)
              foreach (var method in c.Value)
                foreach (var line in method.Value.Lines)
                {
                  if (!fileCoverage.ContainsKey(line.Key))
                    fileCoverage[line.Key] = 0;
                  fileCoverage[line.Key] += line.Value;
                }

      return fileCoverage;
    }

19 Source : WebResourceHandler.cs
with MIT License
from Adoxio

private string GetMimeType(Enreplacedy webResource)
		{
			var key = webResource.GetAttributeValue<OptionSetValue>("webresourcetype").Value;

			return _webResourceTypes.ContainsKey(key)
				? _webResourceTypes[key]
				: "text/plain";
		}

19 Source : InbuiltAudioOutput.cs
with MIT License
from adrenak

public void Feed
        (int index, int frequency, int channelCount, float[] audioSamples) {
            // If we already have this index, don't bother
            // It's been preplaceded already without playing.
            if (segments.ContainsKey(index)) return;

            int locIdx = (int)(AudioSource.Position() * AudioBuffer.SegCount);
            locIdx = Mathf.Clamp(locIdx, 0, AudioBuffer.SegCount - 1);

            var bufferIndex = AudioBuffer.GetNormalizedIndex(index);

            // Don't write to the same segment index that we are reading
            if (locIdx == bufferIndex) return;

            // Finally write into the buffer 
            segments.Add(index, Status.Ahead);
            AudioBuffer.Write(index, audioSamples);
        }

19 Source : CoverFlow.cs
with GNU General Public License v3.0
from aduskin

private void UpdateShowRange()
        {
            if (this.ItemsSource == null)
             return;
            var newFirstShowIndex = Math.Max(PageIndex - MaxShowCountHalf, 0);
            var newLastShowIndex = Math.Min(PageIndex + MaxShowCountHalf, Count - 1);

            if (_firstShowIndex < newFirstShowIndex)
            {
                for (var i = _firstShowIndex; i < newFirstShowIndex; i++)
                {
                    Remove(i);
                }
            }
            else if (newLastShowIndex < _lastShowIndex)
            {
                for (var i = newLastShowIndex; i < _lastShowIndex; i++)
                {
                    Remove(i);
                }
            }

            for (var i = newFirstShowIndex; i <= newLastShowIndex; i++)
            {
                if (!_itemShowList.ContainsKey(i))
                {
                    var cover = CreateCoverFlowItem(i, (ItemsSource as IList)[i]);
                    _itemShowList[i] = cover;
                    _visualParent.Children.Add(cover);
                }
            }

            _firstShowIndex = newFirstShowIndex;
            _lastShowIndex = newLastShowIndex;

        }

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

private void GameLoop_GameLaunched(object sender, StardewModdingAPI.Events.GameLaunchedEventArgs e)
        {
            CustomChestTypeData data;
            CustomChestTypeConfig conf = new CustomChestTypeConfig();
            int id = 424000;
            Dictionary<int, string> existingPSIs = new Dictionary<int, string>();
            foreach (IContentPack contentPack in Helper.ContentPacks.GetOwned())
            {
                conf = contentPack.ReadJsonFile<CustomChestTypeConfig>("config.json") ?? new CustomChestTypeConfig();
                foreach (KeyValuePair<string, int> psi in conf.parentSheetIndexes)
                {
                    existingPSIs.Add(psi.Value, psi.Key);
                }

            }
            foreach (IContentPack contentPack in Helper.ContentPacks.GetOwned())
            {
                try
                {
                    int add = 0;
                    Monitor.Log($"Reading content pack: {contentPack.Manifest.Name} {contentPack.Manifest.Version} from {contentPack.DirectoryPath}");
                    data = contentPack.ReadJsonFile<CustomChestTypeData>("content.json");
                    conf = contentPack.ReadJsonFile<CustomChestTypeConfig>("config.json") ?? new CustomChestTypeConfig();
                    foreach (CustomChestType chestInfo in data.chestTypes)
                    {
                        try
                        {
                            if (conf.parentSheetIndexes.ContainsKey(chestInfo.name))
                            {
                                chestInfo.id = conf.parentSheetIndexes[chestInfo.name];
                                Monitor.Log($"Got existing parentSheetIndex {chestInfo.id} for chest type {chestInfo.name} from content pack {contentPack.Manifest.Name}", LogLevel.Debug);
                            }
                            else
                            {
                                while (existingPSIs.ContainsKey(id))
                                    id++;
                                chestInfo.id = id++;
                                Monitor.Log($"Set new parentSheetIndex {chestInfo.id} for chest type {chestInfo.name} from content pack {contentPack.Manifest.Name}", LogLevel.Debug);
                            }
                            for (int frame = 1; frame <= chestInfo.frames; frame++)
                            {
                                var texturePath = chestInfo.texturePath.Replace("{frame}", frame.ToString());
                                chestInfo.texture.Add(contentPack.Loadreplacedet<Texture2D>(texturePath));
                            }
                            customChestTypesDict.Add(chestInfo.id, chestInfo);
                            conf.parentSheetIndexes[chestInfo.name] = chestInfo.id;
                            add++;
                        }
                        catch (Exception ex)
                        {
                            Monitor.Log($"Error parsing chest {chestInfo.name}: {ex}", LogLevel.Error);
                        }
                    }
                    Monitor.Log($"Got {add} chest types from content pack {contentPack.Manifest.Name}", LogLevel.Debug);
                    contentPack.WriteJsonFile("config.json", conf);
                    Monitor.Log($"Wrote ids to config for content pack {contentPack.Manifest.Name}", LogLevel.Debug);
                }
                catch (Exception ex)
                {
                    SMonitor.Log($"Error processing content.json in content pack {contentPack.Manifest.Name} {ex}", LogLevel.Error);
                }
            }
            Monitor.Log($"Got {customChestTypesDict.Count} chest types total", LogLevel.Debug);
        }

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

private static bool Debris_collect_Prefix(Debris __instance, ref bool __result, NetObjectShrinkList<Chunk> ___chunks, Farmer farmer, Chunk chunk)
        {
            if (chunk == null)
            {
                if (___chunks.Count <= 0)
                {
                    return false;
                }
                chunk = ___chunks[0];
            }

            if (!customChestTypesDict.ContainsKey(chunk.debrisType) && !customChestTypesDict.ContainsKey(-chunk.debrisType))
                return true;

            SMonitor.Log($"collecting {chunk.debrisType}");

            if (farmer.addItemToInventoryBool(new Object(Vector2.Zero, -chunk.debrisType, false), false))
            {
                __result = true;
                return false;
            }
            return true;
        }

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

private static void Chest_Postfix(Chest __instance, int parent_sheet_index)
        {
            if (!customChestTypesDict.ContainsKey(parent_sheet_index))
                return;
            __instance.Name = $"{customChestTypesDict[parent_sheet_index].name}";
            SMonitor.Log($"Created chest {__instance.Name}"); 
        }

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

private void GameLoop_GameLaunched(object sender, StardewModdingAPI.Events.GameLaunchedEventArgs e)
        {
            customOreNodesList.Clear();
            CustomOreData data;
            int id = 42424000;
            Dictionary<int, int> existingPSIs = new Dictionary<int, int>();
            CustomOreConfig conf = Helper.Data.ReadJsonFile<CustomOreConfig>("ore_config.json") ?? new CustomOreConfig();
            foreach (KeyValuePair<int, int> psi in conf.parentSheetIndexes)
            {
                existingPSIs[psi.Value] = psi.Key;
            }
            foreach (IContentPack contentPack in Helper.ContentPacks.GetOwned())
            {
                conf = contentPack.ReadJsonFile<CustomOreConfig>("ore_config.json") ?? new CustomOreConfig();
                foreach (KeyValuePair<int, int> psi in conf.parentSheetIndexes)
                {
                    existingPSIs[psi.Value] = psi.Key;
                }

            }
            try
            {
                if(File.Exists(Path.Combine(Helper.DirectoryPath, "custom_ore_nodes.json")))
                {
                    int add = 0;
                    try
                    {
                        data = Helper.Content.Load<CustomOreData>("custom_ore_nodes.json", ContentSource.ModFolder);

                    }
                    catch
                    {
                        var tempData = Helper.Content.Load<CustomOreDataOld>("custom_ore_nodes.json", ContentSource.ModFolder);
                        data = new CustomOreData();
                        for (int i = 0; i < tempData.nodes.Count; i++)
                        {
                            data.nodes.Add(new CustomOreNode(tempData.nodes[i]));
                        }
                        Monitor.Log($"Rewriting custom_ore_nodes.json", LogLevel.Debug);
                        Helper.Data.WriteJsonFile("custom_ore_nodes.json", data);
                    }
                    conf = Helper.Data.ReadJsonFile<CustomOreConfig>("ore_config.json") ?? new CustomOreConfig();
                    foreach (object nodeObj in data.nodes)
                    {
                        CustomOreNode node = (CustomOreNode) nodeObj;

                        if (node.spriteType == "mod")
                        {
                            node.texture = Helper.Content.Load<Texture2D>(node.spritePath, ContentSource.ModFolder);
                        }
                        else
                        {
                            node.texture = Helper.Content.Load<Texture2D>(node.spritePath, ContentSource.GameContent);
                        }
                        if (conf.parentSheetIndexes.ContainsKey(add))
                        {
                            node.parentSheetIndex = conf.parentSheetIndexes[add];
                        }
                        else
                        {
                            while (existingPSIs.ContainsKey(id))
                                id++;
                            node.parentSheetIndex = id++;
                        }
                        conf.parentSheetIndexes[add] = node.parentSheetIndex;

                        customOreNodesList.Add(node);
                        add++;
                    }
                    Monitor.Log($"Got {customOreNodesList.Count} ores from mod", LogLevel.Debug);
                    Helper.Data.WriteJsonFile("ore_config.json", conf);

                }
                else
                {
                    SMonitor.Log("No custom_ore_nodes.json in mod directory.");
                }
            }
            catch(Exception ex)
            {
                SMonitor.Log("Error processing custom_ore_nodes.json: "+ex, LogLevel.Error);
            }

            foreach (IContentPack contentPack in Helper.ContentPacks.GetOwned()) 
            {
                try
                {
                    int add = 0;
                    conf = contentPack.ReadJsonFile<CustomOreConfig>("ore_config.json") ?? new CustomOreConfig();
                    Monitor.Log($"Reading content pack: {contentPack.Manifest.Name} {contentPack.Manifest.Version} from {contentPack.DirectoryPath}");

                    try
                    {
                        data = contentPack.ReadJsonFile<CustomOreData>("custom_ore_nodes.json");
                    }
                    catch(Exception ex)
                    {
                        Monitor.Log($"exception {ex}", LogLevel.Error);
                        var tempData = contentPack.ReadJsonFile<CustomOreDataOld>("custom_ore_nodes.json");
                        data = new CustomOreData();
                        for (int i = 0; i < tempData.nodes.Count; i++)
                        {
                            data.nodes.Add(new CustomOreNode(tempData.nodes[i]));
                        }
                        Monitor.Log($"Rewriting custom_ore_nodes.json", LogLevel.Debug);
                        contentPack.WriteJsonFile("custom_ore_nodes.json", data);
                    }

                    foreach (CustomOreNode node in data.nodes)
                    {
                        if (node.spriteType == "mod")
                        {
                            node.texture = contentPack.Loadreplacedet<Texture2D>(node.spritePath);

                        }
                        else
                        {
                            node.texture = Helper.Content.Load<Texture2D>(node.spritePath, ContentSource.GameContent);

                        }
                        if (conf.parentSheetIndexes.ContainsKey(add))
                        {
                            node.parentSheetIndex = conf.parentSheetIndexes[add];
                        }
                        else
                        {
                            while (existingPSIs.ContainsKey(id))
                                id++;
                            node.parentSheetIndex = id++;
                        }
                        conf.parentSheetIndexes[add] = node.parentSheetIndex;
                        customOreNodesList.Add(node);
                        add++;
                    }
                    contentPack.WriteJsonFile("ore_config.json", conf);
                    Monitor.Log($"Got {data.nodes.Count} ores from content pack {contentPack.Manifest.Name}", LogLevel.Debug);
                }
                catch(Exception ex)
                {
                    SMonitor.Log($"Error processing custom_ore_nodes.json in content pack {contentPack.Manifest.Name} {ex}", LogLevel.Error);
                }
            }
            Monitor.Log($"Got {customOreNodesList.Count} ores total", LogLevel.Debug);
        }

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

public static void CheckForAchievements()
        {
            var sound = false;
            using (var dict = Game1.content.Load<Dictionary<string, CustomAcheivementData>>(PHelper.Content.GetActualreplacedetKey(dictPath, ContentSource.GameContent)).GetEnumerator())
            {
                while (dict.MoveNext())
                {
                    var a = dict.Current.Value;
                    int hash = a.name.GetHashCode();
                    if (currentAchievements.ContainsKey(hash) && !currentAchievements[hash].achieved && a.achieved)
                    {
                        PMonitor.Log($"Achievement {a.name} achieved!", LogLevel.Debug);
                        currentAchievements[hash].achieved = true;
                        if (!sound)
                        {
                            Game1.playSound("achievement");
                            sound = true;
                        }
                        Game1.addHUDMessage(new HUDMessage(a.name, true));
                    }
                }
            }
        }

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

private static void ItemGrabMenu_Prefix(ref IList<Item> inventory, object context)
        {
            if (!(context is FishingRod))
                return;

            FishingRod fr = context as FishingRod;
            int fish = SHelper.Reflection.GetField<int>(fr, "whichFish").GetValue();
            bool treasure = false;
            foreach (Item item in inventory)
            {
                if (item.parentSheetIndex != fish)
                    treasure = true;
            }
            if (!treasure)
                return;

            Dictionary<int, string> data = Game1.content.Load<Dictionary<int, string>>("Data\\Fish");
            int difficulty = 5;
            if(data.ContainsKey(fish))
                int.TryParse(data[fish].Split('/')[1], out difficulty);

            int coins = advancedLootFrameworkApi.GetChestCoins(difficulty, Config.IncreaseRate, Config.CoinBaseMin, Config.CoinBaseMax);

			IList<Item> items = advancedLootFrameworkApi.GetChesreplacedems(treasuresList, Config.ItemListChances, Config.MaxItems, Config.MinItemValue, Config.MaxItemValue, difficulty, Config.IncreaseRate, Config.ItemsBaseMaxValue);

			bool vanilla = Game1.random.NextDouble() < Config.VanillaLootChance / 100f;
			foreach (Item item in inventory)
			{
				if (item.parentSheetIndex == fish || vanilla) 
                    items.Add(item);
            }

			if (Game1.random.NextDouble() <= 0.33 && Game1.player.team.SpecialOrderRuleActive("DROP_QI_BEANS", null))
			{
				items.Add(new Object(890, Game1.random.Next(1, 3) + ((Game1.random.NextDouble() < 0.25) ? 2 : 0), false, -1, 0));
			}

			inventory = items;
            Game1.player.Money += coins;
            SMonitor.Log($"chest contains {coins} gold");
        }

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

private static async void HereFishyFishy(Farmer who, int x, int y)
        {
            hereFishying = true;
            if (fishySound != null)
            {
                fishySound.Play();
            }
            who.completelyStopAnimatingOrDoingAction();
            who.jitterStrength = 2f;
            List<FarmerSprite.AnimationFrame> animationFrames = new List<FarmerSprite.AnimationFrame>(){
                new FarmerSprite.AnimationFrame(94, 100, false, false, null, false).AddFrameAction(delegate (Farmer f)
                {
                    f.jitterStrength = 2f;
                })
            };
            who.FarmerSprite.setCurrentAnimation(animationFrames.ToArray());
            who.FarmerSprite.PauseForSingleAnimation = true;
            who.FarmerSprite.loop = true;
            who.FarmerSprite.loopThisAnimation = true;
            who.Sprite.currentFrame = 94;

            await System.Threading.Tasks.Task.Delay(1793);

            canPerfect = true;
            perfect = false;

            who.synchronizedJump(8f);

            await System.Threading.Tasks.Task.Delay(100);

            canPerfect = false;

            await System.Threading.Tasks.Task.Delay(900);

            who.stopJittering();
            who.completelyStopAnimatingOrDoingAction();
            who.forceCanMove();

            hereFishying = false;

            await System.Threading.Tasks.Task.Delay(Game1.random.Next(500, 1000));

            Object o = who.currentLocation.getFish(0, -1, 1, who, 0, new Vector2(x, y), who.currentLocation.Name);
            if (o == null || o.ParentSheetIndex <= 0)
            {
                o = new Object(Game1.random.Next(167, 173), 1, false, -1, 0);
            }


            int parentSheetIndex = o.parentSheetIndex;
            animations.Clear();
            float t;
            lastUser = who;
            whichFish = parentSheetIndex;
            Dictionary<int, string> data = Game1.content.Load<Dictionary<int, string>>("Data\\Fish");
            string[] datas = null;
            if (data.ContainsKey(whichFish))
            {
                datas = data[whichFish].Split('/');
            }


            bool non_fishable_fish = false;
            if (o is Furniture)
            {
                non_fishable_fish = true;
            }
            else if (Utility.IsNormalObjectAtParentSheetIndex(o, o.ParentSheetIndex) && data.ContainsKey(o.ParentSheetIndex))
            {
                string[] array = data[o.ParentSheetIndex].Split(new char[]
                {
                            '/'
                });
                int difficulty = -1;
                if (!int.TryParse(array[1], out difficulty))
                {
                    non_fishable_fish = true;
                }
            }
            else
            {
                non_fishable_fish = true;
            }


            float fs = 1f;
            int minimumSizeContribution = 1 + who.FishingLevel / 2;
            fs *= (float)Game1.random.Next(minimumSizeContribution, Math.Max(6, minimumSizeContribution)) / 5f;
            fs *= 1.2f;
            fs *= 1f + (float)Game1.random.Next(-10, 11) / 100f;
            fs = Math.Max(0f, Math.Min(1f, fs));
            if(datas != null && !non_fishable_fish)
            {
                try
                {
                    int minFishSize = int.Parse(datas[3]);
                    int maxFishSize = int.Parse(datas[4]);
                    fishSize = (int)((float)minFishSize + (float)(maxFishSize - minFishSize) * fishSize);
                    fishSize++;
                    fishQuality = (((double)fishSize < 0.33) ? 0 : (((double)fishSize < 0.66) ? 1 : 2));
                    if (perfect)
                        fishQuality *= 2;
                }
                catch 
                {
                    context.Monitor.Log($"Error getting fish size from {data[whichFish]}", LogLevel.Error);
                }
            }
            bossFish = FishingRod.isFishBossFish(whichFish);
            caughtDoubleFish = !bossFish && Game1.random.NextDouble() < 0.1 + Game1.player.DailyLuck / 2.0;

            context.Monitor.Log($"pulling fish {whichFish} {fishSize} {who.Name} {x},{y}");

            if (who.IsLocalPlayer)
            {
                if (datas != null && !non_fishable_fish)
                {
                    fishDifficulty = int.Parse(datas[1]);

                }
                else
                    fishDifficulty = 0;
                
                int experience = Math.Max(1, (fishQuality + 1) * 3 + fishDifficulty / 3);
                if (bossFish)
                {
                    experience *= 5;
                }
                
                if(perfect)
                    experience += (int)((float)experience * 1.4f);
                
                who.gainExperience(1, experience);
            }

            if (who.FacingDirection == 1 || who.FacingDirection == 3)
            {
                float distance = Vector2.Distance(new Vector2(x, y), who.Position);
                float gravity = 0.001f;
                float height = 128f - (who.Position.Y - y + 10f);
                double angle = 1.1423973285781066;
                float yVelocity = (float)((double)(distance * gravity) * Math.Tan(angle) / Math.Sqrt((double)(2f * distance * gravity) * Math.Tan(angle) - (double)(2f * gravity * height)));
                if (float.IsNaN(yVelocity))
                {
                    yVelocity = 0.6f;
                }
                float xVelocity = (float)((double)yVelocity * (1.0 / Math.Tan(angle)));
                t = distance / xVelocity;
                animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x,y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                {
                    motion = new Vector2((float)((who.FacingDirection == 3) ? -1 : 1) * -xVelocity, -yVelocity),
                    acceleration = new Vector2(0f, gravity),
                    timeBasedMotion = true,
                    endFunction = new TemporaryAnimatedSprite.endBehavior(playerCaughtFishEndFunction),
                    extraInfoForEndBehavior = parentSheetIndex,
                    endSound = "tinyWhip"
                });
                if (caughtDoubleFish)
                {
                    distance = Vector2.Distance(new Vector2(x, y), who.Position);
                    gravity = 0.0008f;
                    height = 128f - (who.Position.Y - y + 10f);
                    angle = 1.1423973285781066;
                    yVelocity = (float)((double)(distance * gravity) * Math.Tan(angle) / Math.Sqrt((double)(2f * distance * gravity) * Math.Tan(angle) - (double)(2f * gravity * height)));
                    if (float.IsNaN(yVelocity))
                    {
                        yVelocity = 0.6f;
                    }
                    xVelocity = (float)((double)yVelocity * (1.0 / Math.Tan(angle)));
                    t = distance / xVelocity;
                    animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                    {
                        motion = new Vector2((float)((who.FacingDirection == 3) ? -1 : 1) * -xVelocity, -yVelocity),
                        acceleration = new Vector2(0f, gravity),
                        timeBasedMotion = true,
                        endSound = "fishSlap",
                        Parent = who.currentLocation
                    });
                }
            }
            else
            {
                float distance2 = y - (float)(who.getStandingY() - 64);
                float height2 = Math.Abs(distance2 + 256f + 32f);
                if (who.FacingDirection == 0)
                {
                    height2 += 96f;
                }
                float gravity2 = 0.003f;
                float velocity = (float)Math.Sqrt((double)(2f * gravity2 * height2));
                t = (float)(Math.Sqrt((double)(2f * (height2 - distance2) / gravity2)) + (double)(velocity / gravity2));
                float xVelocity2 = 0f;
                if (t != 0f)
                {
                    xVelocity2 = (who.Position.X - x) / t;
                }
                animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                {
                    motion = new Vector2(xVelocity2, -velocity),
                    acceleration = new Vector2(0f, gravity2),
                    timeBasedMotion = true,
                    endFunction = new TemporaryAnimatedSprite.endBehavior(playerCaughtFishEndFunction),
                    extraInfoForEndBehavior = parentSheetIndex,
                    endSound = "tinyWhip"
                });
                if (caughtDoubleFish)
                {
                    distance2 = y - (float)(who.getStandingY() - 64);
                    height2 = Math.Abs(distance2 + 256f + 32f);
                    if (who.FacingDirection == 0)
                    {
                        height2 += 96f;
                    }
                    gravity2 = 0.004f;
                    velocity = (float)Math.Sqrt((double)(2f * gravity2 * height2));
                    t = (float)(Math.Sqrt((double)(2f * (height2 - distance2) / gravity2)) + (double)(velocity / gravity2));
                    xVelocity2 = 0f;
                    if (t != 0f)
                    {
                        xVelocity2 = (who.Position.X - x) / t;
                    }
                    animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                    {
                        motion = new Vector2(xVelocity2, -velocity),
                        acceleration = new Vector2(0f, gravity2),
                        timeBasedMotion = true,
                        endSound = "fishSlap",
                        Parent = who.currentLocation
                    });
                }
            }
        }

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

public void LoadAdvancedMeleeWeapons()
        {
            advancedMeleeWeapons.Clear();
            advancedMeleeWeaponsByType[1].Clear();
            advancedMeleeWeaponsByType[2].Clear();
            advancedMeleeWeaponsByType[3].Clear();
            foreach (IContentPack contentPack in Helper.ContentPacks.GetOwned())
            {
                Monitor.Log($"Reading content pack: {contentPack.Manifest.Name} {contentPack.Manifest.Version} from {contentPack.DirectoryPath}", LogLevel.Debug);
                try
                {
                    AdvancedMeleeWeaponData json = contentPack.ReadJsonFile<AdvancedMeleeWeaponData>("content.json") ?? null;
                    WeaponPackConfigData config = contentPack.ReadJsonFile<WeaponPackConfigData>("config.json") ?? new WeaponPackConfigData();

                    if (json != null)
                    {
                        if (json.weapons != null && json.weapons.Count > 0)
                        {
                            foreach (AdvancedMeleeWeapon weapon in json.weapons)
                            {
                                foreach(KeyValuePair<string, string> kvp in weapon.config)
                                {
                                    FieldInfo fi = weapon.GetType().GetField(kvp.Key);

                                    if(fi == null)
                                    {
                                        Monitor.Log($"Error getting field {kvp.Key} in AdvancedMeleeWeapon clreplaced.", LogLevel.Error);
                                        continue;
                                    }

                                    if (config.variables.ContainsKey(kvp.Value))
                                    {
                                        var val = config.variables[kvp.Value];
                                        if (val.GetType() == typeof(Int64))
                                            fi.SetValue(weapon, Convert.ToInt32(config.variables[kvp.Value]));
                                        else
                                            fi.SetValue(weapon, config.variables[kvp.Value]);
                                    }
                                    else
                                    {
                                        config.variables.Add(kvp.Value, fi.GetValue(weapon));
                                    }
                                }
                                foreach(MeleeActionFrame frame in weapon.frames)
                                {
                                    foreach (KeyValuePair<string, string> kvp in frame.config)
                                    {
                                        FieldInfo fi = frame.GetType().GetField(kvp.Key);

                                        if (fi == null)
                                        {
                                            Monitor.Log($"Error getting field {kvp.Key} in MeleeActionFrame clreplaced.", LogLevel.Error);
                                            continue;
                                        }

                                        if (config.variables.ContainsKey(kvp.Value))
                                        {
                                            fi.SetValue(frame, config.variables[kvp.Value]);
                                        }
                                        else
                                        {
                                            config.variables.Add(kvp.Value, fi.GetValue(frame));
                                        }
                                    }
                                    foreach (AdvancedWeaponProjectile entry in frame.projectiles)
                                    {
                                        foreach (KeyValuePair<string, string> kvp in entry.config)
                                        {
                                            FieldInfo fi = entry.GetType().GetField(kvp.Key);

                                            if (fi == null)
                                            {
                                                Monitor.Log($"Error getting field {kvp.Key} in AdvancedWeaponProjectile clreplaced.", LogLevel.Error);
                                                continue;
                                            }

                                            if (config.variables.ContainsKey(kvp.Value))
                                            {
                                                fi.SetValue(entry, config.variables[kvp.Value]);
                                            }
                                            else
                                            {
                                                config.variables.Add(kvp.Value, fi.GetValue(entry));
                                            }
                                        }
                                    }
                                    if(frame.special != null)
                                    {
                                        foreach (KeyValuePair<string, string> kvp in frame.special.config)
                                        {
                                            if (!frame.special.parameters.ContainsKey(kvp.Key))
                                            {
                                                Monitor.Log($"Error getting key {kvp.Key} in SpecialEffects.parameters", LogLevel.Error);
                                                continue;
                                            }
                                            if (config.variables.ContainsKey(kvp.Value))
                                            {
                                                frame.special.parameters[kvp.Key] = config.variables[kvp.Value].ToString();
                                            }
                                            else
                                            {
                                                config.variables.Add(kvp.Value, frame.special.parameters[kvp.Key]);
                                            }

                                        }
                                    }
                                }
                                foreach (AdvancedEnchantmentData entry in weapon.enchantments)
                                {
                                    int count = 0;
                                    foreach (KeyValuePair<string, string> kvp in entry.config)
                                    {
                                        if (!entry.parameters.ContainsKey(kvp.Key))
                                        {
                                            Monitor.Log($"Error getting key {kvp.Key} in AdvancedEnchantmentData.parameters", LogLevel.Error);
                                            continue;
                                        }

                                        if (config.variables.ContainsKey(kvp.Value))
                                        {
                                            entry.parameters[kvp.Key]  = config.variables[kvp.Value].ToString();
                                        }
                                        else
                                        {
                                            config.variables.Add(kvp.Value, entry.parameters[kvp.Key]);
                                        }
                                    }
                                    advancedEnchantments[entry.name] = entry;
                                    count++;
                                }
                                if (config.variables.Any())
                                {
                                    contentPack.WriteJsonFile("config.json", config);
                                }


                                if (weapon.type == 0)
                                {
                                    Monitor.Log($"Adding specific weapon {weapon.id}");
                                    if (!int.TryParse(weapon.id, out int id))
                                    {
                                        Monitor.Log($"Got name instead of id {weapon.id}");
                                        try
                                        {
                                            id = Helper.Content.Load<Dictionary<int, string>>("Data/weapons", ContentSource.GameContent).First(p => p.Value.StartsWith($"{weapon.id}/")).Key;
                                            Monitor.Log($"Got name-based id {id}");
                                        }
                                        catch (Exception ex)
                                        {
                                            if (mJsonreplacedets != null)
                                            {
                                                id = mJsonreplacedets.GetWeaponId(weapon.id);
                                                if(id == -1)
                                                {
                                                    Monitor.Log($"error getting JSON replacedets weapon {weapon.id}\n{ex}", LogLevel.Error);
                                                    continue;
                                                }
                                                Monitor.Log($"Added JA weapon {weapon.id}, id {id}");
                                            }
                                            else
                                            {
                                                Monitor.Log($"error getting weapon {weapon.id}\n{ex}", LogLevel.Error);
                                                continue;
                                            }
                                        }
                                        
                                    }
                                    if (!advancedMeleeWeapons.ContainsKey(id))
                                        advancedMeleeWeapons[id] = new List<AdvancedMeleeWeapon>();
                                    advancedMeleeWeapons[id].Add(weapon);
                                }
                                else
                                {
                                    advancedMeleeWeaponsByType[weapon.type].Add(weapon);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Monitor.Log($"error reading content.json file in content pack {contentPack.Manifest.Name}.\r\n{ex}", LogLevel.Error);
                }
            }
            Monitor.Log($"Total advanced melee weapons: {advancedMeleeWeapons.Count}", LogLevel.Debug);
            Monitor.Log($"Total advanced melee dagger attacks: {advancedMeleeWeaponsByType[1].Count}", LogLevel.Debug);
            Monitor.Log($"Total advanced melee club attacks: {advancedMeleeWeaponsByType[2].Count}", LogLevel.Debug);
            Monitor.Log($"Total advanced melee sword attacks: {advancedMeleeWeaponsByType[3].Count}", LogLevel.Debug);
        }

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

private static void GetSurroundingOffsets(OverlaidDictionary objects, List<Vector2> tiles, Dictionary<int, List<Vector2>> offsets, Vector2 tile)
        {
            if (!tiles.Contains(tile))
                tiles.Add(tile);
            int offset = GetSetOffset(objects[tile].parentSheetIndex);
            if (!offsets.ContainsKey(offset))
                offsets.Add(offset, new List<Vector2>() { tile });
            else
                offsets[offset].Add(tile);

            if(!tiles.Contains(tile + new Vector2(-1, 0)) && IsRock(objects, (int)tile.X - 1, (int)tile.Y))
                GetSurroundingOffsets(objects, tiles, offsets, tile + new Vector2(-1, 0));
            if(!tiles.Contains(tile + new Vector2(1, 0)) && IsRock(objects, (int)tile.X + 1, (int)tile.Y))
                GetSurroundingOffsets(objects, tiles, offsets, tile + new Vector2(1, 0));
            if(!tiles.Contains(tile + new Vector2(0, -1)) && IsRock(objects, (int)tile.X, (int)tile.Y - 1))
                GetSurroundingOffsets(objects, tiles, offsets, tile + new Vector2(0, -1));
            if(!tiles.Contains(tile + new Vector2(0, 1)) && IsRock(objects, (int)tile.X, (int)tile.Y + 1))
                GetSurroundingOffsets(objects, tiles, offsets, tile + new Vector2(0, 1));
        }

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

private static async void HereFishyFishy(Farmer who, int x, int y)
        {
            hereFishying = true;
            if (fishySound != null)
            {
                fishySound.Play();
            }
            who.completelyStopAnimatingOrDoingAction();
            who.jitterStrength = 2f;
            List<FarmerSprite.AnimationFrame> animationFrames = new List<FarmerSprite.AnimationFrame>(){
                new FarmerSprite.AnimationFrame(94, 100, false, false, null, false).AddFrameAction(delegate (Farmer f)
                {
                    f.jitterStrength = 2f;
                })
            };
            who.FarmerSprite.setCurrentAnimation(animationFrames.ToArray());
            who.FarmerSprite.PauseForSingleAnimation = true;
            who.FarmerSprite.loop = true;
            who.FarmerSprite.loopThisAnimation = true;
            who.Sprite.currentFrame = 94;

            await System.Threading.Tasks.Task.Delay(1793);

            canPerfect = true;
            perfect = false;

            who.synchronizedJump(8f);

            await System.Threading.Tasks.Task.Delay(100);

            canPerfect = false;

            await System.Threading.Tasks.Task.Delay(900);

            who.stopJittering();
            who.completelyStopAnimatingOrDoingAction();
            who.forceCanMove();

            hereFishying = false;

            await System.Threading.Tasks.Task.Delay(Game1.random.Next(500, 1000));

            Object o = who.currentLocation.getFish(0, -1, 1, who, 0, new Vector2(x, y), who.currentLocation.Name);
            if (o == null || o.ParentSheetIndex <= 0)
            {
                o = new Object(Game1.random.Next(167, 173), 1, false, -1, 0);
            }


            int parentSheetIndex = o.parentSheetIndex;
            animations.Clear();
            float t;
            lastUser = who;
            whichFish = parentSheetIndex;
            Dictionary<int, string> data = Game1.content.Load<Dictionary<int, string>>("Data\\Fish");
            string[] datas = null;
            if (data.ContainsKey(whichFish))
            {
                datas = data[whichFish].Split('/');
            }


            bool non_fishable_fish = false;
            if (o is Furniture)
            {
                non_fishable_fish = true;
            }
            else if (Utility.IsNormalObjectAtParentSheetIndex(o, o.ParentSheetIndex) && data.ContainsKey(o.ParentSheetIndex))
            {
                string[] array = data[o.ParentSheetIndex].Split(new char[]
                {
                            '/'
                });
                int difficulty = -1;
                if (!int.TryParse(array[1], out difficulty))
                {
                    non_fishable_fish = true;
                }
            }
            else
            {
                non_fishable_fish = true;
            }


            float fs = 1f;
            int minimumSizeContribution = 1 + who.FishingLevel / 2;
            fs *= (float)Game1.random.Next(minimumSizeContribution, Math.Max(6, minimumSizeContribution)) / 5f;
            fs *= 1.2f;
            fs *= 1f + (float)Game1.random.Next(-10, 11) / 100f;
            fs = Math.Max(0f, Math.Min(1f, fs));
            if(datas != null && !non_fishable_fish)
            {
                try
                {
                    int minFishSize = int.Parse(datas[3]);
                    int maxFishSize = int.Parse(datas[4]);
                    fishSize = (int)((float)minFishSize + (float)(maxFishSize - minFishSize) * fishSize);
                    fishSize++;
                    fishQuality = (((double)fishSize < 0.33) ? 0 : (((double)fishSize < 0.66) ? 1 : 2));
                    if (perfect)
                        fishQuality *= 2;
                }
                catch 
                {
                    context.Monitor.Log($"Error getting fish size from {data[whichFish]}", LogLevel.Error);
                }
            }
            bossFish = FishingRod.isFishBossFish(whichFish);
            caughtDoubleFish = !bossFish && Game1.random.NextDouble() < 0.1 + Game1.player.DailyLuck / 2.0;

            context.Monitor.Log($"pulling fish {whichFish} {fishSize} {who.Name} {x},{y}");

            if (who.IsLocalPlayer)
            {
                if (datas != null && !non_fishable_fish)
                {
                    fishDifficulty = int.Parse(datas[1]);

                }
                else
                    fishDifficulty = 0;
                
                int experience = Math.Max(1, (fishQuality + 1) * 3 + fishDifficulty / 3);
                if (bossFish)
                {
                    experience *= 5;
                }
                
                if(perfect)
                    experience += (int)((float)experience * 1.4f);
                
                who.gainExperience(1, experience);
            }

            if (who.FacingDirection == 1 || who.FacingDirection == 3)
            {
                float distance = Vector2.Distance(new Vector2(x, y), who.Position);
                float gravity = 0.001f;
                float height = 128f - (who.Position.Y - y + 10f);
                double angle = 1.1423973285781066;
                float yVelocity = (float)((double)(distance * gravity) * Math.Tan(angle) / Math.Sqrt((double)(2f * distance * gravity) * Math.Tan(angle) - (double)(2f * gravity * height)));
                if (float.IsNaN(yVelocity))
                {
                    yVelocity = 0.6f;
                }
                float xVelocity = (float)((double)yVelocity * (1.0 / Math.Tan(angle)));
                t = distance / xVelocity;
                animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x,y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                {
                    motion = new Vector2((float)((who.FacingDirection == 3) ? -1 : 1) * -xVelocity, -yVelocity),
                    acceleration = new Vector2(0f, gravity),
                    timeBasedMotion = true,
                    endFunction = new TemporaryAnimatedSprite.endBehavior(playerCaughtFishEndFunction),
                    extraInfoForEndBehavior = parentSheetIndex,
                    endSound = "tinyWhip"
                });
                if (caughtDoubleFish)
                {
                    distance = Vector2.Distance(new Vector2(x, y), who.Position);
                    gravity = 0.0008f;
                    height = 128f - (who.Position.Y - y + 10f);
                    angle = 1.1423973285781066;
                    yVelocity = (float)((double)(distance * gravity) * Math.Tan(angle) / Math.Sqrt((double)(2f * distance * gravity) * Math.Tan(angle) - (double)(2f * gravity * height)));
                    if (float.IsNaN(yVelocity))
                    {
                        yVelocity = 0.6f;
                    }
                    xVelocity = (float)((double)yVelocity * (1.0 / Math.Tan(angle)));
                    t = distance / xVelocity;
                    animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                    {
                        motion = new Vector2((float)((who.FacingDirection == 3) ? -1 : 1) * -xVelocity, -yVelocity),
                        acceleration = new Vector2(0f, gravity),
                        timeBasedMotion = true,
                        endSound = "fishSlap",
                        Parent = who.currentLocation
                    });
                }
            }
            else
            {
                float distance2 = y - (float)(who.getStandingY() - 64);
                float height2 = Math.Abs(distance2 + 256f + 32f);
                if (who.FacingDirection == 0)
                {
                    height2 += 96f;
                }
                float gravity2 = 0.003f;
                float velocity = (float)Math.Sqrt((double)(2f * gravity2 * height2));
                t = (float)(Math.Sqrt((double)(2f * (height2 - distance2) / gravity2)) + (double)(velocity / gravity2));
                float xVelocity2 = 0f;
                if (t != 0f)
                {
                    xVelocity2 = (who.Position.X - x) / t;
                }
                animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                {
                    motion = new Vector2(xVelocity2, -velocity),
                    acceleration = new Vector2(0f, gravity2),
                    timeBasedMotion = true,
                    endFunction = new TemporaryAnimatedSprite.endBehavior(playerCaughtFishEndFunction),
                    extraInfoForEndBehavior = parentSheetIndex,
                    endSound = "tinyWhip"
                });
                if (caughtDoubleFish)
                {
                    distance2 = y - (float)(who.getStandingY() - 64);
                    height2 = Math.Abs(distance2 + 256f + 32f);
                    if (who.FacingDirection == 0)
                    {
                        height2 += 96f;
                    }
                    gravity2 = 0.004f;
                    velocity = (float)Math.Sqrt((double)(2f * gravity2 * height2));
                    t = (float)(Math.Sqrt((double)(2f * (height2 - distance2) / gravity2)) + (double)(velocity / gravity2));
                    xVelocity2 = 0f;
                    if (t != 0f)
                    {
                        xVelocity2 = (who.Position.X - x) / t;
                    }
                    animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
                    {
                        motion = new Vector2(xVelocity2, -velocity),
                        acceleration = new Vector2(0f, gravity2),
                        timeBasedMotion = true,
                        endSound = "fishSlap",
                        Parent = who.currentLocation
                    });
                }
            }
        }

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

private static void Billboard_Postfix(Billboard __instance, bool dailyQuest, Dictionary<ClickableTextureComponent, List<string>> ____upcomingWeddings)
        {
            if (dailyQuest || Game1.dayOfMonth < 29)
                return;
            __instance.calendarDays = new List<ClickableTextureComponent>();
            Dictionary<int, NPC> birthdays = new Dictionary<int, NPC>();
            foreach (NPC i in Utility.getAllCharacters())
            {
                if (i.isVillager() && i.Birthday_Season != null && i.Birthday_Season.Equals(Game1.currentSeason) && !birthdays.ContainsKey(i.Birthday_Day) && (Game1.player.friendshipData.ContainsKey(i.Name) || (!i.Name.Equals("Dwarf") && !i.Name.Equals("Sandy") && !i.Name.Equals("Krobus"))))
                {
                    birthdays.Add(i.Birthday_Day, i);
                }
            }
            int startDate = (Game1.dayOfMonth - 1) / 28 * 28 + 1;
            for (int j = startDate; j <= startDate + 27; j++)
            {
                int l = (j - 1) % 28 + 1;
                string festival = "";
                string birthday = "";
                NPC npc = birthdays.ContainsKey(j) ? birthdays[j] : null;
                if (Utility.isFestivalDay(j, Game1.currentSeason))
                {
                    festival = Game1.temporaryContent.Load<Dictionary<string, string>>("Data\\Festivals\\" + Game1.currentSeason + j.ToString())["name"];
                }
                else if (npc != null)
                {
                    if (npc.displayName.Last<char>() == 's' || (LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.de && (npc.displayName.Last<char>() == 'x' || npc.displayName.Last<char>() == 'ß' || npc.displayName.Last<char>() == 'z')))
                    {
                        birthday = Game1.content.LoadString("Strings\\UI:Billboard_SBirthday", npc.displayName);
                    }
                    else
                    {
                        birthday = Game1.content.LoadString("Strings\\UI:Billboard_Birthday", npc.displayName);
                    }
                }
                Texture2D character_texture = null;
                if (npc != null)
                {
                    try
                    {
                        character_texture = Game1.content.Load<Texture2D>("Characters\\" + npc.getTextureName());
                    }
                    catch (Exception)
                    {
                        character_texture = npc.Sprite.Texture;
                    }
                }
                ClickableTextureComponent calendar_day = new ClickableTextureComponent(festival, new Rectangle(__instance.xPositionOnScreen + 152 + (l - 1) % 7 * 32 * 4, __instance.yPositionOnScreen + 200 + (l - 1) / 7 * 32 * 4, 124, 124), festival, birthday, character_texture, (npc != null) ? new Rectangle(0, 0, 16, 24) : Rectangle.Empty, 1f, false)
                {
                    myID = l,
                    rightNeighborID = ((l % 7 != 0) ? (l + 1) : -1),
                    leftNeighborID = ((l % 7 != 1) ? (l - 1) : -1),
                    downNeighborID = l + 7,
                    upNeighborID = ((l > 7) ? (l - 7) : -1)
                };
                HashSet<Farmer> traversed_farmers = new HashSet<Farmer>();
                foreach (Farmer farmer in Game1.getOnlineFarmers())
                {
                    if (!traversed_farmers.Contains(farmer) && farmer.isEngaged() && !farmer.hasCurrentOrPendingRoommate())
                    {
                        string spouse_name = null;
                        WorldDate wedding_date = null;
                        if (Game1.getCharacterFromName(farmer.spouse, true, false) != null)
                        {
                            wedding_date = farmer.friendshipData[farmer.spouse].WeddingDate;
                            spouse_name = Game1.getCharacterFromName(farmer.spouse, true, false).displayName;
                        }
                        else
                        {
                            long? spouse = farmer.team.GetSpouse(farmer.UniqueMultiplayerID);
                            if (spouse != null)
                            {
                                Farmer spouse_farmer = Game1.getFarmerMaybeOffline(spouse.Value);
                                if (spouse_farmer != null && Game1.getOnlineFarmers().Contains(spouse_farmer))
                                {
                                    wedding_date = farmer.team.GetFriendship(farmer.UniqueMultiplayerID, spouse.Value).WeddingDate;
                                    traversed_farmers.Add(spouse_farmer);
                                    spouse_name = spouse_farmer.Name;
                                }
                            }
                        }
                        if (!(wedding_date == null))
                        {
                            if (wedding_date.TotalDays < Game1.Date.TotalDays)
                            {
                                wedding_date = new WorldDate(Game1.Date);
                                wedding_date.TotalDays++;
                            }
                            if (wedding_date != null && wedding_date.TotalDays >= Game1.Date.TotalDays && Utility.getSeasonNumber(Game1.currentSeason) == wedding_date.SeasonIndex && j == wedding_date.DayOfMonth)
                            {
                                if (!____upcomingWeddings.ContainsKey(calendar_day))
                                {
                                    ____upcomingWeddings[calendar_day] = new List<string>();
                                }
                                traversed_farmers.Add(farmer);
                                ____upcomingWeddings[calendar_day].Add(farmer.Name);
                                ____upcomingWeddings[calendar_day].Add(spouse_name);
                            }
                        }
                    }
                }
                __instance.calendarDays.Add(calendar_day);
            }
        }

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

private static void Billboard_Postfix(Billboard __instance, bool dailyQuest, Dictionary<ClickableTextureComponent, List<string>> ____upcomingWeddings)
        {
            if (dailyQuest || Game1.dayOfMonth < 29)
                return;
            __instance.calendarDays = new List<ClickableTextureComponent>();
            Dictionary<int, NPC> birthdays = new Dictionary<int, NPC>();
            foreach (NPC i in Utility.getAllCharacters())
            {
                if (i.isVillager() && i.Birthday_Season != null && i.Birthday_Season.Equals(Game1.currentSeason) && !birthdays.ContainsKey(i.Birthday_Day) && (Game1.player.friendshipData.ContainsKey(i.Name) || (!i.Name.Equals("Dwarf") && !i.Name.Equals("Sandy") && !i.Name.Equals("Krobus"))))
                {
                    birthdays.Add(i.Birthday_Day, i);
                }
            }
            int startDate = (Game1.dayOfMonth - 1) / 28 * 28 + 1;
            for (int j = startDate; j <= startDate + 27; j++)
            {
                int l = (j - 1) % 28 + 1;
                string festival = "";
                string birthday = "";
                NPC npc = birthdays.ContainsKey(j) ? birthdays[j] : null;
                if (Utility.isFestivalDay(j, Game1.currentSeason))
                {
                    festival = Game1.temporaryContent.Load<Dictionary<string, string>>("Data\\Festivals\\" + Game1.currentSeason + j.ToString())["name"];
                }
                else if (npc != null)
                {
                    if (npc.displayName.Last<char>() == 's' || (LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.de && (npc.displayName.Last<char>() == 'x' || npc.displayName.Last<char>() == 'ß' || npc.displayName.Last<char>() == 'z')))
                    {
                        birthday = Game1.content.LoadString("Strings\\UI:Billboard_SBirthday", npc.displayName);
                    }
                    else
                    {
                        birthday = Game1.content.LoadString("Strings\\UI:Billboard_Birthday", npc.displayName);
                    }
                }
                Texture2D character_texture = null;
                if (npc != null)
                {
                    try
                    {
                        character_texture = Game1.content.Load<Texture2D>("Characters\\" + npc.getTextureName());
                    }
                    catch (Exception)
                    {
                        character_texture = npc.Sprite.Texture;
                    }
                }
                ClickableTextureComponent calendar_day = new ClickableTextureComponent(festival, new Rectangle(__instance.xPositionOnScreen + 152 + (l - 1) % 7 * 32 * 4, __instance.yPositionOnScreen + 200 + (l - 1) / 7 * 32 * 4, 124, 124), festival, birthday, character_texture, (npc != null) ? new Rectangle(0, 0, 16, 24) : Rectangle.Empty, 1f, false)
                {
                    myID = l,
                    rightNeighborID = ((l % 7 != 0) ? (l + 1) : -1),
                    leftNeighborID = ((l % 7 != 1) ? (l - 1) : -1),
                    downNeighborID = l + 7,
                    upNeighborID = ((l > 7) ? (l - 7) : -1)
                };
                HashSet<Farmer> traversed_farmers = new HashSet<Farmer>();
                foreach (Farmer farmer in Game1.getOnlineFarmers())
                {
                    if (!traversed_farmers.Contains(farmer) && farmer.isEngaged() && !farmer.hasCurrentOrPendingRoommate())
                    {
                        string spouse_name = null;
                        WorldDate wedding_date = null;
                        if (Game1.getCharacterFromName(farmer.spouse, true, false) != null)
                        {
                            wedding_date = farmer.friendshipData[farmer.spouse].WeddingDate;
                            spouse_name = Game1.getCharacterFromName(farmer.spouse, true, false).displayName;
                        }
                        else
                        {
                            long? spouse = farmer.team.GetSpouse(farmer.UniqueMultiplayerID);
                            if (spouse != null)
                            {
                                Farmer spouse_farmer = Game1.getFarmerMaybeOffline(spouse.Value);
                                if (spouse_farmer != null && Game1.getOnlineFarmers().Contains(spouse_farmer))
                                {
                                    wedding_date = farmer.team.GetFriendship(farmer.UniqueMultiplayerID, spouse.Value).WeddingDate;
                                    traversed_farmers.Add(spouse_farmer);
                                    spouse_name = spouse_farmer.Name;
                                }
                            }
                        }
                        if (!(wedding_date == null))
                        {
                            if (wedding_date.TotalDays < Game1.Date.TotalDays)
                            {
                                wedding_date = new WorldDate(Game1.Date);
                                wedding_date.TotalDays++;
                            }
                            if (wedding_date != null && wedding_date.TotalDays >= Game1.Date.TotalDays && Utility.getSeasonNumber(Game1.currentSeason) == wedding_date.SeasonIndex && j == wedding_date.DayOfMonth)
                            {
                                if (!____upcomingWeddings.ContainsKey(calendar_day))
                                {
                                    ____upcomingWeddings[calendar_day] = new List<string>();
                                }
                                traversed_farmers.Add(farmer);
                                ____upcomingWeddings[calendar_day].Add(farmer.Name);
                                ____upcomingWeddings[calendar_day].Add(spouse_name);
                            }
                        }
                    }
                }
                __instance.calendarDays.Add(calendar_day);
            }
        }

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

public static AdvancedMeleeWeapon GetAdvancedWeapon(MeleeWeapon weapon, Farmer user)
        {
            AdvancedMeleeWeapon advancedMeleeWeapon = null;
            if (advancedMeleeWeapons.ContainsKey(weapon.InitialParentTileIndex))
            {
                int skillLevel = -1;
                foreach (AdvancedMeleeWeapon amw in advancedMeleeWeapons[weapon.initialParentTileIndex])
                {
                    if (user == null || (amw.skillLevel <= user.getEffectiveSkillLevel(4) && amw.skillLevel > skillLevel))
                    {
                        skillLevel = amw.skillLevel;
                        advancedMeleeWeapon = amw;
                    }
                }
            }
            if (advancedMeleeWeapon == null && advancedMeleeWeaponsByType.ContainsKey(weapon.type) && user != null)
            {
                int skillLevel = -1;
                foreach(AdvancedMeleeWeapon amw in advancedMeleeWeaponsByType[weapon.type])
                {
                    if(amw.skillLevel <= user.getEffectiveSkillLevel(4) && amw.skillLevel > skillLevel)
                    {
                        skillLevel = amw.skillLevel;
                        advancedMeleeWeapon = amw;
                    }
                }
            }

            return advancedMeleeWeapon;
        }

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

private static bool GameLocation_isCollidingPosition_Prefix(GameLocation __instance, Rectangle position, ref bool __result)
        {
            foreach (KeyValuePair<Vector2, Object> obj in __instance.objects.Pairs)
            {
                if (customChestTypesDict.ContainsKey(obj.Value.ParentSheetIndex) &&  obj.Value.boundingBox.Value.Intersects(position))
                {
                    __result = true;
                    return false;
                }
            }
            
            return true;
        }

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

private static bool Object_loadDisplayName_Prefix(Object __instance, ref string __result)
        {
            if (!customChestTypesDict.ContainsKey(__instance.ParentSheetIndex))
                return true;
            __result = customChestTypesDict[__instance.ParentSheetIndex].name;
            return false;
        }

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

private void LogColors()
        {
            for (int j = 1; j < 13; j++)
            {
                Texture2D sprite = this.Helper.Content.Load<Texture2D>("replacedets/work/hairs/" + j + ".png");
                Color[] data = new Color[sprite.Width * sprite.Height];
                sprite.GetData(data);
                Dictionary<int,string> tempList = new Dictionary<int,string>();
                for (int i = 0; i < data.Length; i++)
                {
                    if (data[i] != Color.Transparent)
                    {
                        int total = (int)data[i].R + (int)data[i].G + (int)data[i].B;
                        string c = string.Join(" ", new string[] { data[i].R.ToString(), data[i].G.ToString(), data[i].B.ToString() });
                        if (!tempList.ContainsKey(total))
                        {
                            tempList.Add(total,c);
                        }
                        else if(tempList[total] != c)
                        {
                            while (tempList.ContainsKey(total))
                            {
                                total++;
                                if (!tempList.ContainsKey(total))
                                {
                                    tempList.Add(total, c);
                                }
                                else if (tempList[total] == c)
                                    break;
                            }
                        }
                    }

                }
                var keys = tempList.Keys.ToList();
                keys.Sort();
                keys.Reverse();

                var outList = new List<string>();
                foreach(var key in keys)
                {
                    outList.Add(tempList[key]);
                }
                Alert(string.Join("^", outList));
            }
        }

19 Source : GUIPanel.cs
with GNU General Public License v3.0
from aelariane

private void CheckPageChange()
        {
            if (oldPageSelection == pageSelection)
            {
                return;
            }
            if (!allPages.ContainsKey(pageSelection))
            {
                currentPage = typeof(GUIPanel).GetMethod(nameof(EmptyPage), BindingFlags.NonPublic | BindingFlags.Instance);
                if (allDisableMethods.ContainsKey(oldPageSelection))
                {
                    allDisableMethods[oldPageSelection].Invoke(this, parameters);
                }

                oldPageSelection = pageSelection;
                return;
            }

            OnBeforePageChanged();
            if (allDisableMethods.ContainsKey(oldPageSelection))
            {
                allDisableMethods[oldPageSelection].Invoke(this, parameters);
            }

            OnAnyPageDisabled();

            if (allEnableMethods.ContainsKey(pageSelection))
            {
                allEnableMethods[pageSelection].Invoke(this, parameters);
            }

            OnAnyPageEnabled();

            currentPage = allPages[pageSelection];
            oldPageSelection = pageSelection;
        }

19 Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu

public static void RegisterUpdateHandler(int enreplacedyId, IDataUpdateTrigger handler)
        {
            if (Triggers.ContainsKey(enreplacedyId))
                Triggers[enreplacedyId].Add(handler);
            else
                Triggers.Add(enreplacedyId, new List<IDataUpdateTrigger> {handler});
        }

19 Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu

public static void UnRegisterUpdateHandler(int enreplacedyId, IDataUpdateTrigger handler)
        {
            if (Triggers.ContainsKey(enreplacedyId))
                Triggers[enreplacedyId].Remove(handler);
        }

19 Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu

internal static void OnPrepareSave(EditDataObject enreplacedy, DataOperatorType operatorType)
        {
            if (Triggers.ContainsKey(enreplacedy.__Struct.EnreplacedyType))
                foreach (var trigger in Triggers[enreplacedy.__Struct.EnreplacedyType])
                    trigger.OnPrepareSave(enreplacedy, operatorType);
            if (Triggers.ContainsKey(0))
                foreach (var trigger in Triggers[0])
                    trigger.OnPrepareSave(enreplacedy, operatorType);
        }

19 Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu

internal static void OnPrepareSave(EditDataObject enreplacedy, DataOperatorType operatorType)
        {
            if (Triggers.ContainsKey(enreplacedy.__Struct.EnreplacedyType))
                foreach (var trigger in Triggers[enreplacedy.__Struct.EnreplacedyType])
                    trigger.OnPrepareSave(enreplacedy, operatorType);
            if (Triggers.ContainsKey(0))
                foreach (var trigger in Triggers[0])
                    trigger.OnPrepareSave(enreplacedy, operatorType);
        }

19 Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu

internal static void OnDataSaved(EditDataObject enreplacedy, DataOperatorType operatorType)
        {
            if (Triggers.ContainsKey(enreplacedy.__Struct.EnreplacedyType))
                foreach (var trigger in Triggers[enreplacedy.__Struct.EnreplacedyType])
                    trigger.OnDataSaved(enreplacedy, operatorType);
            if (Triggers.ContainsKey(0))
                foreach (var trigger in Triggers[0])
                    trigger.OnDataSaved(enreplacedy, operatorType);
        }

19 Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu

internal static void OnDataSaved(EditDataObject enreplacedy, DataOperatorType operatorType)
        {
            if (Triggers.ContainsKey(enreplacedy.__Struct.EnreplacedyType))
                foreach (var trigger in Triggers[enreplacedy.__Struct.EnreplacedyType])
                    trigger.OnDataSaved(enreplacedy, operatorType);
            if (Triggers.ContainsKey(0))
                foreach (var trigger in Triggers[0])
                    trigger.OnDataSaved(enreplacedy, operatorType);
        }

19 Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu

internal static void OnOperatorExecuting(int enreplacedyId, string condition, IEnumerable<MySqlParameter> args,
            DataOperatorType operatorType)
        {
            var mySqlParameters = args as MySqlParameter[] ?? args.ToArray();
            if (Triggers.ContainsKey(enreplacedyId))
                foreach (var trigger in Triggers[enreplacedyId])
                    trigger.OnOperatorExecuting(enreplacedyId, condition, mySqlParameters, operatorType);
            if (Triggers.ContainsKey(0))
                foreach (var trigger in Triggers[0])
                    trigger.OnOperatorExecuting(enreplacedyId, condition, mySqlParameters, operatorType);
        }

19 Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu

internal static void OnOperatorExecutd(int enreplacedyId, string condition, IEnumerable<MySqlParameter> args,
            DataOperatorType operatorType)
        {
            var mySqlParameters = args as MySqlParameter[] ?? args.ToArray();
            if (Triggers.ContainsKey(enreplacedyId))
                foreach (var trigger in Triggers[enreplacedyId])
                    trigger.OnOperatorExecutd(enreplacedyId, condition, mySqlParameters, operatorType);
            if (Triggers.ContainsKey(0))
                foreach (var trigger in Triggers[0])
                    trigger.OnOperatorExecutd(enreplacedyId, condition, mySqlParameters, operatorType);
        }

19 Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu

public static void RegisterUpdateHandler(int enreplacedyId, IDataUpdateTrigger handler)
        {
            lock (Triggers)
            {
                if (Triggers == null)
                    Triggers = new Dictionary<int, List<IDataUpdateTrigger>>();
                if (!Triggers.ContainsKey(enreplacedyId))
                    Triggers.Add(enreplacedyId, new List<IDataUpdateTrigger> {handler});
                else
                {
                    if (Triggers[enreplacedyId].All(p => p.GetType() != handler.GetType()))
                        Triggers[enreplacedyId].Add(handler);
                }
            }
        }

19 Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu

public static void UnRegisterUpdateHandler(int enreplacedyId, IDataUpdateTrigger handler)
        {
            lock (Triggers)
            {
                if (Triggers == null || !Triggers.ContainsKey(enreplacedyId))
                    return;
                Triggers[enreplacedyId].Remove(handler);
                if (Triggers[enreplacedyId].Count == 0)
                    Triggers.Remove(enreplacedyId);
                if (Triggers.Count == 0)
                    Triggers = null;
            }
        }

19 Source : TraceMessage.cs
with Mozilla Public License 2.0
from agebullhu

private void WriteTrace(string message, bool time = false)
        {
            BeginInvokeInUiThread(p =>
            {
                if (_threadIndex.ContainsKey(Thread.CurrentThread.ManagedThreadId))
                {
                    var idx = _threadIndex[Thread.CurrentThread.ManagedThreadId] + 1;
                    if (idx >= _trace.Count)
                    {
                        _trace.Add(time ? $"{DateTime.Now}:{p}" : p);
                        _threadIndex[Thread.CurrentThread.ManagedThreadId] = _trace.Count;
                    }
                    else
                    {
                        _trace.Insert(idx, time ? $"{DateTime.Now}:{p}" : p);
                        _threadIndex[Thread.CurrentThread.ManagedThreadId] = idx;
                    }
                }
                else
                {
                    _trace.Add(time ? $"{DateTime.Now}:{p}" : p);
                    _threadIndex.Add(Thread.CurrentThread.ManagedThreadId, _trace.Count - 1);
                }
                RaisePropertyChanged(() => Track);
                LastMessageIndex = _trace.Count - 1;
            }, message);
        }

19 Source : ProcessExtensions.cs
with GNU General Public License v3.0
from aglab2

public static ProcessModuleWow64Safe[] ModulesWow64Safe(this Process p)
        {
            if (ModuleCache.Count > 100)
                ModuleCache.Clear();

            const int LIST_MODULES_ALL = 3;
            const int MAX_PATH = 260;

            var hModules = new IntPtr[1024];

            uint cb = (uint)IntPtr.Size*(uint)hModules.Length;
            uint cbNeeded;

            if (!WinAPI.EnumProcessModulesEx(p.Handle, hModules, cb, out cbNeeded, LIST_MODULES_ALL))
                throw new Win32Exception();
            uint numMods = cbNeeded / (uint)IntPtr.Size;

            int hash = p.StartTime.GetHashCode() + p.Id + (int)numMods;
            if (ModuleCache.ContainsKey(hash))
                return ModuleCache[hash];

            var ret = new List<ProcessModuleWow64Safe>();

            // everything below is fairly expensive, which is why we cache!
            var sb = new StringBuilder(MAX_PATH);
            for (int i = 0; i < numMods; i++)
            {
                sb.Clear();
                if (WinAPI.GetModuleFileNameEx(p.Handle, hModules[i], sb, (uint)sb.Capacity) == 0)
                    throw new Win32Exception();
                string fileName = sb.ToString();

                sb.Clear();
                if (WinAPI.GetModuleBaseName(p.Handle, hModules[i], sb, (uint)sb.Capacity) == 0)
                    throw new Win32Exception();
                string baseName = sb.ToString();

                var moduleInfo = new WinAPI.MODULEINFO();
                if (!WinAPI.GetModuleInformation(p.Handle, hModules[i], out moduleInfo, (uint)Marshal.SizeOf(moduleInfo)))
                    throw new Win32Exception();

                ret.Add(new ProcessModuleWow64Safe()
                {
                    FileName = fileName,
                    BaseAddress = moduleInfo.lpBaseOfDll,
                    ModuleMemorySize = (int)moduleInfo.SizeOfImage,
                    EntryPointAddress = moduleInfo.EntryPoint,
                    ModuleName = baseName
                });
            }

            ModuleCache.Add(hash, ret.ToArray());

            return ret.ToArray();
        }

19 Source : PagingComponent.cs
with GNU General Public License v3.0
from agolaszewski

public bool Next()
        {
            if (PagedChoices.ContainsKey(_page + 1))
            {
                _page += 1;
                return true;
            }

            return false;
        }

19 Source : AssertConsole.cs
with GNU General Public License v3.0
from agolaszewski

public void PositionWrite(string text, int x = 0, int y = 0, ConsoleColor color = ConsoleColor.White)
        {
            _currentY = y;
            if (!buffer.ContainsKey(y))
            {
                buffer.Add(y, string.Empty);
            }
            buffer[_currentY] = buffer[y].Insert(x, text);
        }

19 Source : AssertConsole.cs
with GNU General Public License v3.0
from agolaszewski

public void PositionWriteLine(string text, int x = 0, int y = 0, ConsoleColor color = ConsoleColor.White)
        {
            _currentY = y;
            if (!buffer.ContainsKey(y + 1))
            {
                buffer.Add(y + 1, string.Empty);
            }
            buffer[_currentY] = buffer[y + 1].Insert(x, text);
        }

19 Source : AssertConsole.cs
with GNU General Public License v3.0
from agolaszewski

public void Write(string text, ConsoleColor color = ConsoleColor.White)
        {
            if (!buffer.ContainsKey(_currentY))
            {
                buffer.Add(_currentY, string.Empty);
            }

            buffer[_currentY] = buffer[_currentY].Insert(0, text);
        }

19 Source : AssertConsole.cs
with GNU General Public License v3.0
from agolaszewski

public void WriteError(string error)
        {
            if (!buffer.ContainsKey(_currentY))
            {
                buffer.Add(_currentY, string.Empty);
            }
            buffer[_currentY] = buffer[_currentY].Insert(0, error);
        }

19 Source : AssertConsole.cs
with GNU General Public License v3.0
from agolaszewski

public void WriteLine(string text = " ", ConsoleColor color = ConsoleColor.White)
        {
            _currentY += 1;

            if (!buffer.ContainsKey(_currentY))
            {
                buffer.Add(_currentY, string.Empty);
            }

            buffer[_currentY] = buffer[_currentY].Insert(0, text);
        }

19 Source : MainPage.xaml.cs
with MIT License
from AgoraIO-Community

public async Task NavigateFromMenu(int id)
        {
            if (Device.RuntimePlatform == Device.macOS && id == (int)MenuItemType.About)
            {
                // see https://github.com/xamarin/Xamarin.Forms/issues/4300 and other similar mac-related crashes with navigation
                DisplayAlert("About",
@"Xamarin.Forms sample for Agora SDK

Proudly presented by Agora and DreamTeam Mobile

https://agora.io

https://drmtm.us", "OK");
                return;

            }
            if (!_menuPages.ContainsKey(id))
            {
                switch (id)
                {
                    case (int)MenuItemType.Call:
                        _menuPages.Add(id, new NavigationPage(new ConnectPage()));
                        break;
                    case (int)MenuItemType.About:
                        _menuPages.Add(id, new NavigationPage(new AboutPage()));
                        break;
                }
            }

            var newPage = _menuPages[id];
            if (newPage != null && Detail != newPage)
            {
                Detail = newPage;
                if (Device.RuntimePlatform == Device.Android)
                {
                    await Task.Delay(100); //auto-hide menu on Android
                }
                IsPresented = false;
            }
        }

19 Source : Map.cs
with GNU General Public License v3.0
from AHeroicLlama

static int DrawLegend(Font font, Graphics imageGraphic)
		{
			if (FormMaster.legendItems.Count == 0)
			{
				return 0;
			}

			Dictionary<int, string> overridingLegendText = FormMaster.GatherOverriddenLegendTexts();
			List<int> drawnGroups = new List<int>();

			// Calculate the total height of all legend strings with their plot icons beside, combined
			int legendTotalHeight = 0;
			foreach (MapItem mapItem in FormMaster.legendItems)
			{
				// Skip legend groups that are merged/overridden and have already been accounted for
				if (drawnGroups.Contains(mapItem.legendGroup) && overridingLegendText.ContainsKey(mapItem.legendGroup))
				{
					continue;
				}

				legendTotalHeight += Math.Max(
					(int)Math.Ceiling(imageGraphic.MeasureString(mapItem.GetLegendText(false), font, legendBounds).Height),
					SettingsPlot.IsIconOrTopographic() ? SettingsPlotIcon.iconSize : 0);

				drawnGroups.Add(mapItem.legendGroup);
			}

			int skippedLegends = 0; // How many legend items did not fit onto the map

			// The initial Y coord where first legend item should be written, in order to Y-center the entire legend
			int legendCaretHeight = (mapDimension / 2) - (legendTotalHeight / 2);

			// Reset the drawn groups list, as we need to iterate over the items again
			drawnGroups = new List<int>();

			// Loop over every MapItem and draw the legend
			foreach (MapItem mapItem in FormMaster.legendItems)
			{
				// Skip legend groups that are merged/overridden and have already been drawn
				if (drawnGroups.Contains(mapItem.legendGroup) && overridingLegendText.ContainsKey(mapItem.legendGroup))
				{
					continue;
				}

				// Calculate positions and color for legend text (plus icon)
				int fontHeight = (int)Math.Ceiling(imageGraphic.MeasureString(mapItem.GetLegendText(false), font, legendBounds).Height);

				PlotIcon icon = mapItem.GetIcon();
				Image plotIconImg = SettingsPlot.IsIconOrTopographic() ? icon.GetIconImage() : null;

				Color legendColor = SettingsPlot.IsTopographic() ? SettingsPlotTopograph.legendColor : mapItem.GetLegendColor();
				Brush textBrush = new SolidBrush(legendColor);

				int iconHeight = SettingsPlot.IsIconOrTopographic() ?
					plotIconImg.Height :
					0;

				int legendHeight = Math.Max(fontHeight, iconHeight);

				// If the icon is taller than the text, offset the text it so it sits Y-centrally against the icon
				int textOffset = 0;
				if (iconHeight > fontHeight)
				{
					textOffset = (iconHeight - fontHeight) / 2;
				}

				// If the legend text/item fits on the map vertically
				if (legendCaretHeight > 0 && legendCaretHeight + legendHeight < mapDimension)
				{
					if (SettingsPlot.IsIconOrTopographic())
					{
						imageGraphic.DrawImage(plotIconImg, (float)(legendIconX - (plotIconImg.Width / 2d)), (float)(legendCaretHeight - (plotIconImg.Height / 2d) + (legendHeight / 2d)));
					}

					imageGraphic.DrawString(mapItem.GetLegendText(false), font, textBrush, new RectangleF(legendXMin, legendCaretHeight + textOffset, legendWidth, legendHeight));
				}
				else
				{
					skippedLegends++;
				}

				drawnGroups.Add(mapItem.legendGroup);
				legendCaretHeight += legendHeight; // Move the 'caret' down for the next item, enough to fit the icon and the text
			}

			GC.Collect();
			return skippedLegends;
		}

19 Source : PlotIcon.cs
with GNU General Public License v3.0
from AHeroicLlama

public static PlotIcon GetIconForGroup(int group)
		{
			int colorTotal = SettingsPlotIcon.paletteColor.Count;
			int shapeTotal = SettingsPlotIcon.paletteShape.Count;

			if (SettingsPlot.IsTopographic())
			{
				colorTotal = 1; // Force a unique shape per group in topography mode, as color becomes indistinguishable
			}

			// Reduce the group number to find repeating icons
			// For example, 3 shapes and 5 colors makes 15 icons. Group 15 is therefore the same as group 0.
			group %= colorTotal * shapeTotal;

			// Return this ploticon if it has already been generated.
			if (plotIconCache.ContainsKey(group))
			{
				return plotIconCache[group];
			}

			// Identify which item from each palette should be used.
			// First iterate through every color, then every palette, and repeat.
			int colorIndex = group % colorTotal;
			int shapeIndex = (group / colorTotal) % shapeTotal;

			// Generate the PlotIcon
			Color color = SettingsPlot.IsTopographic() ? SettingsPlotTopograph.legendColor : SettingsPlotIcon.paletteColor[colorIndex];
			PlotIconShape shape = SettingsPlotIcon.paletteShape[shapeIndex];
			PlotIcon plotIcon = new PlotIcon(color, shape);

			// Register the icon in the cache and return it - Don't cache topography icons as they override the color
			if (!SettingsPlot.IsTopographic())
			{
				plotIconCache.Add(group, plotIcon);
			}

			return plotIcon;
		}

19 Source : CodePath.cs
with GNU General Public License v3.0
from ahmed605

public bool IsInstructionOffsetInPathTree(int offset)
        {
            bool found = false;

            if (InstructionMap.ContainsKey(offset))
            {
                found = true;
            }
            else if (ParentCodePath != null)
            {
                found = ParentCodePath.IsInstructionOffsetInPathTree(offset);
            }

            return found;
        }

19 Source : CodePath.cs
with GNU General Public License v3.0
from ahmed605

public HLInstruction GetInstruction(int offset)
        {
            if (InstructionMap.ContainsKey(offset))
            {
                return InstructionMap[offset];
            }
            return null;
        }

19 Source : ControlFlowAnalyzer.cs
with GNU General Public License v3.0
from ahmed605

private void replacedyzeSwitchBranch(HLInstruction branchInstruction)
        {
            var sw = branchInstruction.Instruction as InstructionSwitch;

            CodePath parentPath = branchInstruction.ParentCodePath;

            var swMap = new Dictionary<int, CodePath>();
            bool allWereReturns = true;

            HLInstruction switchExitInstruction = branchInstruction.NextInstruction.NextInstruction;

            foreach (var item in sw.SwitchTable)
            {
                if (swMap.ContainsKey(item.Value))
                {
                    // Deal with multiple values leading to the same code path
                    branchInstruction.BranchCodesPaths.Add(item.Key, swMap[item.Value]);
                }
                else
                {
                    CodePath branchCodePath = CreateCodePath("sw_case_" + item.Key, item.Value, parentPath);
                    branchCodePath.ParentExitInstruction = branchInstruction;

                    branchInstruction.BranchCodesPaths.Add(item.Key, branchCodePath);
                    swMap.Add(item.Value, branchCodePath);

                    replacedyzeCodePath(branchCodePath);

                    if (branchCodePath.ParentEntryInstruction != null)
                    {
                        allWereReturns = false;
                        switchExitInstruction = branchCodePath.ParentEntryInstruction;
                    }
                }
            }

            if (allWereReturns)
            {
                switchExitInstruction = null;
            }

            if (switchExitInstruction != branchInstruction.NextInstruction.NextInstruction)
            {
                // Crappy... got a default case statement that we need to extract

                CodePath branchDefaultCodePath = ExtractPath("sw_case_default", parentPath, branchInstruction, branchInstruction.NextInstruction, switchExitInstruction);

                branchInstruction.BranchCodesPaths.Add(new object(), branchDefaultCodePath);
            }
        }

19 Source : NodeParallel.cs
with MIT License
from aillieo

public override BTState Update(float deltaTime)
        {
            int nodeCount = Children.Count;
            for(int i = 0; i < nodeCount; ++i)
            {
                if (!nodeStates.ContainsKey(i))
                {
                    var ret = NodeTick(Children[i], deltaTime);
                    if(ret != BTState.Running)
                    {
                        nodeStates.Add(i, ret);
                    }
                }
            }

            return CheckTarget();
        }

See More Examples