System.Collections.Generic.HashSet.Contains(uint)

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

159 Examples 7

19 Source : UiHelper.Data.cs
with GNU Affero General Public License v3.0
from 0ceal0t

public static bool IsGCD(uint action) => GCDs.Contains(action);

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

public bool Search(uint x)
        {
            if (CurrentKey == x)
            {
                return true;
            }
            if (xors.Contains(x))
            {
                return true;
            }
            int g = xors.Count;
            for (int i = 0; i < MaximumEffortLevel - g; i++)
            {
                xors.Add(CurrentKey);
                ConsumeKey(CurrentKey);
                if (CurrentKey == x)
                    return true;
            }
            return false;
        }

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

public void ProcessDropList(Dictionary<uint, WeakReference<Player>> fellowshipMembers, HashSet<uint> fellowGuids)
        {
            foreach (var fellowGuid in fellowGuids)
            {
                var offlinePlayer = PlayerManager.FindByGuid(fellowGuid);
                var offlineName = offlinePlayer != null ? offlinePlayer.Name : "NULL";

                log.Warn($"Dropped fellow: {offlineName}");
                fellowshipMembers.Remove(fellowGuid);
            }
            if (fellowGuids.Contains(FellowshipLeaderGuid))
                replacedignNewLeader(null, null);

            CalculateXPSharing();
            UpdateAllMembers();
        }

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

public static HashSet<uint> GetHousesOwned()
        {
            // select * from biota where weenie_Type=53;

            var housesOwned = DatabaseManager.Shard.BaseDatabase.GetHousesOwned();

            Console.WriteLine($"Owned houses: {housesOwned.Count}");

            // build owned hashset
            var owned = new HashSet<uint>();

            foreach (var house in housesOwned)
            {
                if (owned.Contains(house.Id))
                {
                    Console.WriteLine($"HouseList.GetOwned(): duplicate owned house id {house.Id}");
                    continue;
                }
                owned.Add(house.Id);
            }
            return owned;
        }

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

public static void BuildAvailable(HashSet<uint> housesOwned)
        {
            Available = new Dictionary<HouseType, List<HouseListResults>>();
            Available.Add(HouseType.Apartment, new List<HouseListResults>());
            Available.Add(HouseType.Cottage, new List<HouseListResults>());
            Available.Add(HouseType.Villa, new List<HouseListResults>());
            Available.Add(HouseType.Mansion, new List<HouseListResults>());

            foreach (var house in AllHouses)
            {
                if (housesOwned.Contains(house.LandblockInstance.Guid))
                    continue;

                Available[house.HouseType].Add(house);
            }
        }

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

private float DoCalculateDamage(Creature attacker, Creature defender, WorldObject damageSource)
        {
            var playerAttacker = attacker as Player;
            var playerDefender = defender as Player;

            var pkBattle = playerAttacker != null && playerDefender != null;

            Attacker = attacker;
            Defender = defender;

            CombatType = damageSource.ProjectileSource == null ? CombatType.Melee : CombatType.Missile;

            DamageSource = damageSource;

            Weapon = damageSource.ProjectileSource == null ? attacker.GetEquippedMeleeWeapon() : (damageSource.ProjectileLauncher ?? damageSource.ProjectileAmmo);

            AttackType = attacker.AttackType;
            AttackHeight = attacker.AttackHeight ?? AttackHeight.Medium;

            // check lifestone protection
            if (playerDefender != null && playerDefender.UnderLifestoneProtection)
            {
                LifestoneProtection = true;
                playerDefender.HandleLifestoneProtection();
                return 0.0f;
            }

            if (defender.Invincible)
                return 0.0f;

            // overpower
            if (attacker.Overpower != null)
                Overpower = Creature.GetOverpower(attacker, defender);

            // evasion chance
            if (!Overpower)
            {
                EvasionChance = GetEvadeChance(attacker, defender);
                if (EvasionChance > ThreadSafeRandom.Next(0.0f, 1.0f))
                {
                    Evaded = true;
                    return 0.0f;
                }
            }

            // get base damage
            if (playerAttacker != null)
                GetBaseDamage(playerAttacker);
            else
                GetBaseDamage(attacker, AttackMotion ?? MotionCommand.Invalid, AttackHook);

            if (DamageType == DamageType.Undef && !AllowDamageTypeUndef.Contains(damageSource.WeenieClreplacedId))
            {
                log.Error($"DamageEvent.DoCalculateDamage({attacker?.Name} ({attacker?.Guid}), {defender?.Name} ({defender?.Guid}), {damageSource?.Name} ({damageSource?.Guid})) - DamageType == DamageType.Undef");
                GeneralFailure = true;
            }

            if (GeneralFailure) return 0.0f;

            // get damage modifiers
            PowerMod = attacker.GetPowerMod(Weapon);
            AttributeMod = attacker.GetAttributeMod(Weapon);
            SlayerMod = WorldObject.GetWeaponCreatureSlayerModifier(Weapon, attacker, defender);

            // ratings
            DamageRatingBaseMod = Creature.GetPositiveRatingMod(attacker.GetDamageRating());
            RecklessnessMod = Creature.GetRecklessnessMod(attacker, defender);
            SneakAttackMod = attacker.GetSneakAttackMod(defender);
            HeritageMod = attacker.GetHeritageBonus(Weapon) ? 1.05f : 1.0f;

            DamageRatingMod = Creature.AdditiveCombine(DamageRatingBaseMod, RecklessnessMod, SneakAttackMod, HeritageMod);

            if (pkBattle)
            {
                PkDamageMod = Creature.GetPositiveRatingMod(attacker.GetPKDamageRating());
                DamageRatingMod = Creature.AdditiveCombine(DamageRatingMod, PkDamageMod);
            }

            // damage before mitigation
            DamageBeforeMitigation = BaseDamage * AttributeMod * PowerMod * SlayerMod * DamageRatingMod;

            // critical hit?
            var attackSkill = attacker.GetCreatureSkill(attacker.GetCurrentWeaponSkill());
            CriticalChance = WorldObject.GetWeaponCriticalChance(Weapon, attacker, attackSkill, defender);

            // https://asheron.fandom.com/wiki/Announcements_-_2002/08_-_Atonement
            // It should be noted that any time a character is logging off, PK or not, all physical attacks against them become automatically critical.
            // (Note that spells do not share this behavior.) We hope this will stress the need to log off in a safe place.

            if (playerDefender != null && (playerDefender.IsLoggingOut || playerDefender.PKLogout))
                CriticalChance = 1.0f;

            if (CriticalChance > ThreadSafeRandom.Next(0.0f, 1.0f))
            {
                if (playerDefender != null && playerDefender.AugmentationCriticalDefense > 0)
                {
                    var criticalDefenseMod = playerAttacker != null ? 0.05f : 0.25f;
                    var criticalDefenseChance = playerDefender.AugmentationCriticalDefense * criticalDefenseMod;

                    if (criticalDefenseChance > ThreadSafeRandom.Next(0.0f, 1.0f))
                        CriticalDefended = true;
                }

                if (!CriticalDefended)
                {
                    IsCritical = true;

                    // verify: CriticalMultiplier only applied to the additional crit damage,
                    // whereas CD/CDR applied to the total damage (base damage + additional crit damage)
                    CriticalDamageMod = 1.0f + WorldObject.GetWeaponCritDamageMod(Weapon, attacker, attackSkill, defender);

                    CriticalDamageRatingMod = Creature.GetPositiveRatingMod(attacker.GetCritDamageRating());

                    // recklessness excluded from crits
                    RecklessnessMod = 1.0f;
                    DamageRatingMod = Creature.AdditiveCombine(DamageRatingBaseMod, CriticalDamageRatingMod, SneakAttackMod, HeritageMod);

                    if (pkBattle)
                        DamageRatingMod = Creature.AdditiveCombine(DamageRatingMod, PkDamageMod);

                    DamageBeforeMitigation = BaseDamageMod.MaxDamage * AttributeMod * PowerMod * SlayerMod * DamageRatingMod * CriticalDamageMod;
                }
            }

            // armor rending and cleaving
            var armorRendingMod = 1.0f;
            if (Weapon != null && Weapon.HasImbuedEffect(ImbuedEffectType.ArmorRending))
                armorRendingMod = WorldObject.GetArmorRendingMod(attackSkill);

            var armorCleavingMod = attacker.GetArmorCleavingMod(Weapon);

            var ignoreArmorMod = Math.Min(armorRendingMod, armorCleavingMod);

            // get body part / armor pieces / armor modifier
            if (playerDefender != null)
            {
                // select random body part @ current attack height
                GetBodyPart(AttackHeight);

                // get player armor pieces
                Armor = attacker.GetArmorLayers(playerDefender, BodyPart);

                // get armor modifiers
                ArmorMod = attacker.GetArmorMod(playerDefender, DamageType, Armor, Weapon, ignoreArmorMod);
            }
            else
            {
                // determine height quadrant
                Quadrant = GetQuadrant(Defender, Attacker, AttackHeight, DamageSource);

                // select random body part @ current attack height
                GetBodyPart(Defender, Quadrant);
                if (Evaded)
                    return 0.0f;

                Armor = CreaturePart.GetArmorLayers(PropertiesBodyPart.Key);

                // get target armor
                ArmorMod = CreaturePart.GetArmorMod(DamageType, Armor, Attacker, Weapon, ignoreArmorMod);
            }

            if (Weapon != null && Weapon.HasImbuedEffect(ImbuedEffectType.IgnoreAllArmor))
                ArmorMod = 1.0f;

            // get resistance modifiers
            WeaponResistanceMod = WorldObject.GetWeaponResistanceModifier(Weapon, attacker, attackSkill, DamageType);

            if (playerDefender != null)
            {
                ResistanceMod = playerDefender.GetResistanceMod(DamageType, Attacker, Weapon, WeaponResistanceMod);
            }
            else
            {
                var resistanceType = Creature.GetResistanceType(DamageType);
                ResistanceMod = (float)Math.Max(0.0f, defender.GetResistanceMod(resistanceType, Attacker, Weapon, WeaponResistanceMod));
            }

            // damage resistance rating
            DamageResistanceRatingMod = DamageResistanceRatingBaseMod = defender.GetDamageResistRatingMod(CombatType);

            if (IsCritical)
            {
                CriticalDamageResistanceRatingMod = Creature.GetNegativeRatingMod(defender.GetCritDamageResistRating());

                DamageResistanceRatingMod = Creature.AdditiveCombine(DamageResistanceRatingBaseMod, CriticalDamageResistanceRatingMod);
            }

            if (pkBattle)
            {
                PkDamageResistanceMod = Creature.GetNegativeRatingMod(defender.GetPKDamageResistRating());

                DamageResistanceRatingMod = Creature.AdditiveCombine(DamageResistanceRatingMod, PkDamageResistanceMod);
            }

            // get shield modifier
            ShieldMod = defender.GetShieldMod(attacker, DamageType, Weapon);

            // calculate final output damage
            Damage = DamageBeforeMitigation * ArmorMod * ShieldMod * ResistanceMod * DamageResistanceRatingMod;

            DamageMitigated = DamageBeforeMitigation - Damage;

            return Damage;
        }

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

public bool is_idle_anim()
        {
            return CurrAnim == null || PlayerIdleAnims.Contains(CurrAnim.Value.Anim.ID);
        }

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

public bool HasPermission(Player player)
        {
            // players can loot their own corpses
            if (VictimId == null || player.Guid.Full == VictimId)
                return true;

            // players can loot corpses of creatures they killed or corpses that have previously been looted by killer
            if (KillerId != null && player.Guid.Full == KillerId || IsLooted)
                return true;

            var victimGuid = new ObjectGuid(VictimId.Value);

            // players can /permit other players to loot their corpse if not killed by another player killer.
            if (player.HasLootPermission(victimGuid) && PkLevel != PKLevel.PK)
            {
                if (!PropertyManager.GetBool("permit_corpse_all").Item)
                {
                    // this is the retail default. see the comments for 'permitteeOpened' for an explanation of why this table is needed
                    if (permitteeOpened == null)
                        permitteeOpened = new HashSet<uint>();

                    // these are technically side effects, and HasPermission() is not the best place for this logic to mutate state,
                    // however with the current lone calling pattern for corpse ActOnUse -> TryOpen -> HasPermission -> Open
                    // if HasPermission returns true, the corpse is always opened, ie. there's no chance of 'the corpse is already in use' or any other failure cases,
                    // as those pre-verifications have already happened before this function is called

                    permitteeOpened.Add(player.Guid.Full);

                    player.LootPermission.Remove(victimGuid);
                }
                return true;
            }
            if (permitteeOpened != null && permitteeOpened.Contains(player.Guid.Full))
                return true;

            // all players can loot monster corpses after 1/2 decay time except if corpse generates a rare
            if (TimeToRot != null && TimeToRot < HalfLife && !new ObjectGuid(VictimId.Value).IsPlayer() && !CorpseGeneratedRare)
                return true;

            // players in the same fellowship as the killer w/ loot sharing enabled except if corpse generates a rare
            if (player.Fellowship != null && player.Fellowship.ShareLoot)
            {
                var onlinePlayer = PlayerManager.GetOnlinePlayer(KillerId ?? 0);
                if (onlinePlayer != null && onlinePlayer.Fellowship != null && player.Fellowship == onlinePlayer.Fellowship && !CorpseGeneratedRare && PkLevel != PKLevel.PK)
                    return true;
            }
            return false;
        }

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

public bool ValidateMovement(ACE.Enreplacedy.Position newPosition)
        {
            if (CurrentLandblock == null)
                return false;

            if (!Teleporting && Location.Landblock != newPosition.Cell >> 16)
            {
                if ((Location.Cell & 0xFFFF) >= 0x100 && (newPosition.Cell & 0xFFFF) >= 0x100)
                {
                    if (!buggedCells.Contains(Location.Cell) || !buggedCells.Contains(newPosition.Cell))
                        return false;
                }

                if (CurrentLandblock.IsDungeon)
                {
                    var destBlock = LScape.get_landblock(newPosition.Cell);
                    if (destBlock != null && destBlock.IsDungeon)
                        return false;
                }
            }
            return true;
        }

19 Source : RawInteractionSourcesInput.cs
with MIT License
from anderm

private void SendSourceVisibilityEvents()
        {
            // Send event for new sources that were added
            foreach (uint newSource in newSources)
            {
                inputManager.RaiseSourceDetected(this, newSource);
            }

            // Send event for sources that are no longer visible and remove them from our dictionary
            foreach (uint existingSource in sourceIdToData.Keys)
            {
                if (!currentSources.Contains(existingSource))
                {
                    pendingSourceIdDeletes.Add(existingSource);
                    inputManager.RaiseSourceLost(this, existingSource);
                }
            }

            // Remove pending source IDs
            for (int i = 0; i < pendingSourceIdDeletes.Count; ++i)
            {
                sourceIdToData.Remove(pendingSourceIdDeletes[i]);
            }
            pendingSourceIdDeletes.Clear();
        }

19 Source : EditorHandsInput.cs
with MIT License
from anderm

private void SendHandVisibilityEvents()
        {
            // Send event for new hands that were added.
            foreach (uint newHand in newHands)
            {
                inputManager.RaiseSourceDetected(this, newHand);
            }

            // Send event for hands that are no longer visible and remove them from our dictionary.
            foreach (uint existingHand in handIdToData.Keys)
            {
                if (!currentHands.Contains(existingHand))
                {
                    pendingHandIdDeletes.Add(existingHand);
                    inputManager.RaiseSourceLost(this, existingHand);
                }
            }

            // Remove pending hand IDs.
            for (int i = 0; i < pendingHandIdDeletes.Count; ++i)
            {
                handIdToData.Remove(pendingHandIdDeletes[i]);
            }
            pendingHandIdDeletes.Clear();
        }

19 Source : MOAction.cs
with GNU General Public License v3.0
from attickdoor

private bool CreplacedeAction(StackEntry targ)
        {
            if (targ.target == null || targ.actionID == 0) return false;
            var action = RawActions.SingleOrDefault(row => (ulong)row.RowId == targ.actionID);
            

            for (var i = 0; i < this.pluginInterface.ClientState.Actors.Length; i++)
            {
                var a = this.pluginInterface.ClientState.Actors[i];
                if (a != null && a.ActorId == targ.target.GetTargetActorId())
                {
                    if (Configuration.RangeCheck)
                    {
                        if (UnorthodoxFriendly.Contains((uint)action.RowId))
                        {
                            if (a.YalmDistanceX > 30) return false;
                        }
                        else if ((byte)action.Range < a.YalmDistanceX) return false;
                    }
                    if (a is PlayerCharacter) return action.CanTargetFriendly || action.CanTargetParty 
                            || action.CanTargetSelf
                            || action.RowId == 17055 || action.RowId == 7443;
                    if (a is BattleNpc)
                    {
                        BattleNpc b = (BattleNpc)a;
                        if (b.BattleNpcKind != BattleNpcSubKind.Enemy) return action.CanTargetFriendly || action.CanTargetParty
                                || action.CanTargetSelf
                                || UnorthodoxFriendly.Contains((uint)action.RowId);
                    }
                    return action.CanTargetHostile || UnorthodoxHostile.Contains((uint)action.RowId);
                }
            }
            return false;
        }

19 Source : GLSLLinkProgram.cs
with GNU Lesser General Public License v2.1
from axiom3d

public bool IsAttributeValid(VertexElementSemantic semantic, uint index)
        {
            return this.validAttributes.Contains(GetAttributeIndex(semantic, index));
        }

19 Source : MultiRowDbTableEditorViewModel.cs
with The Unlicense
from BAndysc

private bool ContainsKey(uint key)
        {
            return keys.Contains(key);
        }

19 Source : DatabaseTableModelGenerator.cs
with The Unlicense
from BAndysc

public IDatabaseTableData? CreateDatabaseTable(DatabaseTableDefinitionJson tableDefinition,
            uint[] keys,
            IList<Dictionary<string, (System.Type type, object value)>> fieldsFromDb)
        {
            HashSet<uint> providedKeys = new();

            IList<IConditionLine>? conditions = null;
            List<DatabaseEnreplacedy> rows = new();
            foreach (var enreplacedy in fieldsFromDb)
            {
                uint? key = null;
                Dictionary<string, IDatabaseField> columns = new();
                foreach (var column in enreplacedy)
                {
                    IValueHolder valueHolder = null!;
                    if (column.Value.type == typeof(string))
                    {
                        string? val = column.Value.value as string ?? null;
                        valueHolder = new ValueHolder<string>(val, column.Value.value is DBNull);
                    }
                    else if (column.Value.type == typeof(float))
                    {
                        valueHolder = new ValueHolder<float>(column.Value.value as float? ?? 0, column.Value.value is DBNull);
                    }
                    else if (column.Value.type == typeof(uint))
                    {
                        valueHolder = new ValueHolder<long>(column.Value.value as uint? ?? 0, column.Value.value is DBNull);
                    }
                    else if (column.Value.type == typeof(int))
                    {
                        valueHolder = new ValueHolder<long>(column.Value.value as int? ?? 0, column.Value.value is DBNull);
                    }
                    else if (column.Value.type == typeof(long))
                    {
                        valueHolder = new ValueHolder<long>(column.Value.value as long? ?? 0, column.Value.value is DBNull);
                    }
                    else if (column.Value.type == typeof(ulong))
                    {
                        valueHolder = new ValueHolder<long>((long)(column.Value.value as ulong? ?? 0), column.Value.value is DBNull);
                    }
                    else if (column.Value.type == typeof(byte))
                    {
                        valueHolder = new ValueHolder<long>(column.Value.value as byte? ?? 0, column.Value.value is DBNull);
                    }
                    else if (column.Value.type == typeof(sbyte))
                    {
                        valueHolder = new ValueHolder<long>(column.Value.value as sbyte? ?? 0, column.Value.value is DBNull);
                    }
                    else if (column.Value.type == typeof(ushort))
                    {
                        valueHolder = new ValueHolder<long>(column.Value.value as ushort? ?? 0, column.Value.value is DBNull);
                    }
                    else if (column.Value.type == typeof(short))
                    {
                        valueHolder = new ValueHolder<long>(column.Value.value as short? ?? 0, column.Value.value is DBNull);
                    }
                    else if (column.Value.type == typeof(bool))
                    {
                        valueHolder = new ValueHolder<long>(column.Value.value is DBNull ? 0 : ((bool)column.Value.value ? 1 : 0), column.Value.value is DBNull);
                    }
                    else if (column.Value.type == typeof(IList<IConditionLine>))
                    {
                        conditions = ((IList<IConditionLine>)column.Value.value);
                        continue;
                    }
                    else
                    {
                        throw new NotImplementedException("Unknown column type " + column.Value.type);
                    }

                    if (column.Key == tableDefinition.TablePrimaryKeyColumnName)
                    {
                        if (valueHolder is ValueHolder<long> longKey)
                        {
                            key = (uint)longKey.Value;
                            providedKeys.Add(key.Value);
                        }
                    }
                    
                    columns[column.Key] = databaseFieldFactory.CreateField(column.Key, valueHolder);
                }
                if (key.HasValue)
                    rows.Add(new DatabaseEnreplacedy(true, key.Value, columns, conditions?.ToList<ICondition>()));
            }

            if (!tableDefinition.IsMultiRecord)
            {
                foreach (var key in keys)
                {
                    if (!providedKeys.Contains(key))
                        rows.Add(CreateEmptyEnreplacedy(tableDefinition, key));
                }   
            }

            try
            {
                return new DatabaseTableData(tableDefinition, rows);
            }
            catch (Exception e)
            {
                // in case of throw from DbTableFieldFactory
                ShowLoadingError(e.Message);
            }
            
            return null;
        }

19 Source : GossipExtractProcessor.cs
with The Unlicense
from BAndysc

public async Task<string> Generate()
        {
            var multiQuery = Queries.BeginTransaction();

            await DeleteExisting();

            foreach (var menu in menus.Values)
            {
                foreach (var option in menu.Options)
                {
                    var broadCastTextId = await databaseProvider.GetBroadcastTextByTextAsync(option.Text);
                    if (broadCastTextId != null)
                        option.BroadcastTextId = broadCastTextId.Id;
                    
                    if (option.BoxText != null)
                    {
                        broadCastTextId = await databaseProvider.GetBroadcastTextByTextAsync(option.BoxText);
                        if (broadCastTextId != null)
                            option.BoxTextBroadcastId = broadCastTextId.Id;
                    }
                }
            }

            if (gossiperToFirstMenuId.Count > 0)
            {
                multiQuery.Comment("");
                multiQuery.Comment(" [ Creature templates ] ");
                multiQuery.Comment("");   
            }

            foreach (var menu in gossiperToFirstMenuId
                .Where(entry => !templatesNotExistingInDb.Contains(entry.Key)))
            {
                var template = databaseProvider.GetCreatureTemplate(menu.Key);
                string? comment = template?.Name;
                if (overridenDatabaseGossipMenu.TryGetValue(menu.Key, out var originalMenu))
                    comment = $"{template?.Name} (was {originalMenu} in db)";
                
                multiQuery.Table("creature_template")
                    .Where(row => row.Column<uint>("entry") == menu.Key)
                    .Set("gossip_menu_id", menu.Value)
                    .Update(comment);
            }

            bool first = true;
            foreach (var menu in gossiperToFirstMenuId
                .Where(entry => templatesNotExistingInDb.Contains(entry.Key)))
            {
                if (first)
                {
                    multiQuery.BlankLine();
                    multiQuery.Comment("Entries not existing in creature_template:");
                    first = false;
                }
                multiQuery.Table("creature_template")
                    .Where(row => row.Column<uint>("entry") == menu.Key)
                    .Set("gossip_menu_id", menu.Value)
                    .Update();
            }

            var npcTextsToInsert =
                npcTexts.Where(npcText => databaseProvider.GetNpcText(npcText.entry) == null).ToList();
            if (npcTextsToInsert.Count > 0)
            {
                multiQuery.Comment("");
                multiQuery.Comment(" [ NPC TEXT ]");
                multiQuery.Comment("");
                multiQuery.Table("npc_text")
                    .WhereIn("ID", npcTextsToInsert.Select(npcText => npcText.entry))
                    .Delete();

                var inserts = await npcTextsToInsert.SelectAsync(async npcText =>
                {
                    var bcast1 = await GetBroadcastText(npcText.Item2[0].broadcastText);
                    var bcast2 = await GetBroadcastText(npcText.Item2[1].broadcastText);
                    var bcast3 = await GetBroadcastText(npcText.Item2[2].broadcastText);
                    var bcast4 = await GetBroadcastText(npcText.Item2[3].broadcastText);
                    var bcast5 = await GetBroadcastText(npcText.Item2[4].broadcastText);
                    var bcast6 = await GetBroadcastText(npcText.Item2[5].broadcastText);
                    var bcast7 = await GetBroadcastText(npcText.Item2[6].broadcastText);
                    var bcast8 = await GetBroadcastText(npcText.Item2[7].broadcastText);
                    return new
                    {
                        ID = npcText.entry,
                        text0_0 = bcast1?.Text,
                        text0_1 = bcast1?.Text1,
                        BroadcastTextID0 = bcast1?.Id ?? 0,
                        lang0 = bcast1?.Language ?? 0,
                        Probability0 = npcText.Item2[0].probability,
                        EmoteDelay0_0 = bcast1?.EmoteDelay1 ?? 0,
                        Emote0_0 = bcast1?.EmoteId1 ?? 0,
                        EmoteDelay0_1 = bcast1?.EmoteDelay2 ?? 0,
                        Emote0_1 = bcast1?.EmoteId2 ?? 0,
                        EmoteDelay0_2 = bcast1?.EmoteDelay3 ?? 0,
                        Emote0_2 = bcast1?.EmoteId3 ?? 0,


                        text1_0 = bcast2?.Text,
                        text1_1 = bcast2?.Text1,
                        BroadcastTextID1 = bcast2?.Id ?? 0,
                        lang1 = bcast2?.Language ?? 0,
                        Probability1 = npcText.Item2[1].probability,
                        EmoteDelay1_0 = bcast2?.EmoteDelay1 ?? 0,
                        Emote1_0 = bcast2?.EmoteId1 ?? 0,
                        EmoteDelay1_1 = bcast2?.EmoteDelay2 ?? 0,
                        Emote1_1 = bcast2?.EmoteId2 ?? 0,
                        EmoteDelay1_2 = bcast2?.EmoteDelay3 ?? 0,
                        Emote1_2 = bcast2?.EmoteId3 ?? 0,

                        text2_0 = bcast3?.Text,
                        text2_1 = bcast3?.Text1,
                        BroadcastTextID2 = bcast3?.Id ?? 0,
                        lang2 = bcast3?.Language ?? 0,
                        Probability2 = npcText.Item2[2].probability,
                        EmoteDelay2_0 = bcast3?.EmoteDelay1 ?? 0,
                        Emote2_0 = bcast3?.EmoteId1 ?? 0,
                        EmoteDelay2_1 = bcast3?.EmoteDelay2 ?? 0,
                        Emote2_1 = bcast3?.EmoteId2 ?? 0,
                        EmoteDelay2_2 = bcast3?.EmoteDelay3 ?? 0,
                        Emote2_2 = bcast3?.EmoteId3 ?? 0,


                        text3_0 = bcast4?.Text,
                        text3_1 = bcast4?.Text1,
                        BroadcastTextID3 = bcast4?.Id ?? 0,
                        lang3 = bcast4?.Language ?? 0,
                        Probability3 = npcText.Item2[3].probability,
                        EmoteDelay3_0 = bcast4?.EmoteDelay1 ?? 0,
                        Emote3_0 = bcast4?.EmoteId1 ?? 0,
                        EmoteDelay3_1 = bcast4?.EmoteDelay2 ?? 0,
                        Emote3_1 = bcast4?.EmoteId2 ?? 0,
                        EmoteDelay3_2 = bcast4?.EmoteDelay3 ?? 0,
                        Emote3_2 = bcast4?.EmoteId3 ?? 0,

                        text4_0 = bcast5?.Text,
                        text4_1 = bcast5?.Text1,
                        BroadcastTextID4 = bcast5?.Id ?? 0,
                        lang4 = bcast5?.Language ?? 0,
                        Probability4 = npcText.Item2[3].probability,
                        EmoteDelay4_0 = bcast5?.EmoteDelay1 ?? 0,
                        Emote4_0 = bcast5?.EmoteId1 ?? 0,
                        EmoteDelay4_1 = bcast5?.EmoteDelay2 ?? 0,
                        Emote4_1 = bcast5?.EmoteId2 ?? 0,
                        EmoteDelay4_2 = bcast5?.EmoteDelay3 ?? 0,
                        Emote4_2 = bcast5?.EmoteId3 ?? 0,


                        text5_0 = bcast6?.Text,
                        text5_1 = bcast6?.Text1,
                        BroadcastTextID5 = bcast6?.Id ?? 0,
                        lang5 = bcast6?.Language ?? 0,
                        Probability5 = npcText.Item2[5].probability,
                        EmoteDelay5_0 = bcast6?.EmoteDelay1 ?? 0,
                        Emote5_0 = bcast6?.EmoteId1 ?? 0,
                        EmoteDelay5_1 = bcast6?.EmoteDelay2 ?? 0,
                        Emote5_1 = bcast6?.EmoteId2 ?? 0,
                        EmoteDelay5_2 = bcast6?.EmoteDelay3 ?? 0,
                        Emote5_2 = bcast6?.EmoteId3 ?? 0,


                        text6_0 = bcast7?.Text,
                        text6_1 = bcast7?.Text1,
                        BroadcastTextID6 = bcast7?.Id ?? 0,
                        lang6 = bcast7?.Language ?? 0,
                        Probability6 = npcText.Item2[6].probability,
                        EmoteDelay6_0 = bcast7?.EmoteDelay1 ?? 0,
                        Emote6_0 = bcast7?.EmoteId1 ?? 0,
                        EmoteDelay6_1 = bcast7?.EmoteDelay2 ?? 0,
                        Emote6_1 = bcast7?.EmoteId2 ?? 0,
                        EmoteDelay6_2 = bcast7?.EmoteDelay3 ?? 0,
                        Emote6_2 = bcast7?.EmoteId3 ?? 0,

                        text7_0 = bcast8?.Text,
                        text7_1 = bcast8?.Text1,
                        BroadcastTextID7 = bcast8?.Id ?? 0,
                        lang7 = bcast8?.Language ?? 0,
                        Probability7 = npcText.Item2[7].probability,
                        EmoteDelay7_0 = bcast8?.EmoteDelay1 ?? 0,
                        Emote7_0 = bcast8?.EmoteId1 ?? 0,
                        EmoteDelay7_1 = bcast8?.EmoteDelay2 ?? 0,
                        Emote7_1 = bcast8?.EmoteId2 ?? 0,
                        EmoteDelay7_2 = bcast8?.EmoteDelay3 ?? 0,
                        Emote7_2 = bcast8?.EmoteId3 ?? 0
                    };
                });
                
                multiQuery.Table("npc_text")
                    .BulkInsert(inserts);
            
                multiQuery.BlankLine();
                multiQuery.BlankLine();
            }
            
            multiQuery.Comment("");
            multiQuery.Comment(" [ MENUS ]");
            multiQuery.Comment("");
            DumpGossipMenu(multiQuery, false);

            var poiToAdd = menus.Values
                .SelectMany(menu => menu.Options)
                .Where(option => option.ActionPoi != null)
                .ToList();
            if (poiToAdd.Count > 0)
            {
                var dbPoi = await databaseProvider.GetPointsOfInterestsAsync();
                var freePoiNum = dbPoi.Select(poi => poi.Id).Max() + 1;
                
                multiQuery.Comment("");
                multiQuery.Comment(" [ POINTS OF INTEREST ]");
                multiQuery.Comment("");

                multiQuery.Table("points_of_interest")
                    .WhereIn("ID", Enumerable.Range((int)freePoiNum, poiToAdd.Count))
                    .Delete();

                var id = freePoiNum;
                multiQuery.Table("points_of_interest")
                    .BulkInsert(poiToAdd.Select(option => new
                    {
                        ID = id++,
                        PositionX = option.ActionPoi!.Coordinates.X,
                        PositionY = option.ActionPoi.Coordinates.Y,
                        Icon = option.ActionPoi.Icon,
                        Flags = option.ActionPoi.Flags,
                        Importance = option.ActionPoi.Importance,
                        Name = option.ActionPoi.Name,
                        VerifiedBuild  = 0,
                    }));

                id = freePoiNum;
                foreach (var option in poiToAdd)
                {
                    option.ActionPoiId = id++;
                    option.ActionPoi = null;
                }
            }
            
            multiQuery.Comment("");
            multiQuery.Comment(" [ OPTIONS ]");
            multiQuery.Comment("");

            first = true;
            foreach (var menu in menus.Where(pair => menuOptionsMissingInDb.Contains(pair.Key)))
            {
                if (menu.Value.Options.Count == 0)
                    continue;
                
                if (first)
                {
                    multiQuery.BlankLine();
                    multiQuery.Comment("Missing from the database:");
                    first = false;
                }
                DumpGossipMenuOptions(multiQuery, menu);
            }

            first = true;
            foreach (var menu in menus.Where(pair => !menuOptionsAlreadyInDb.Contains(pair.Key) &&
                                                     !menuOptionsMissingInDb.Contains(pair.Key)))
            {
                if (menu.Value.Options.Count == 0)
                    continue;
                
                if (first)
                {
                    multiQuery.BlankLine();
                    multiQuery.Comment("Partially in the database:");
                    first = false;
                }
                DumpGossipMenuOptions(multiQuery, menu);
            }
            
            multiQuery.BlankLine();
            multiQuery.BlankLine();
            multiQuery.Comment(" [                ]");
            multiQuery.Comment(" [ ALREADY IN DB  ]");
            multiQuery.Comment(" [                ]");
            multiQuery.BlankLine();
            DumpGossipMenu(multiQuery, true);
            
            first = true;
            foreach (var menu in menus.Where(pair => menuOptionsAlreadyInDb.Contains(pair.Key)))
            {
                if (menu.Value.Options.Count == 0)
                    continue;

                if (first)
                {
                    multiQuery.BlankLine();
                    multiQuery.Comment("Existing in the database:");
                    first = false;
                }
                
                DumpGossipMenuOptions(multiQuery, menu);
            }

            return multiQuery.Close().QueryString;
        }

19 Source : GossipExtractProcessor.cs
with The Unlicense
from BAndysc

private void DumpGossipMenu(IMultiQuery multiQuery, bool existing)
        {
            bool any = false;
            foreach (var menu in menus)
            {
                if (menusAlreadyInDb.Contains(menu.Key) != existing)
                    continue;

                any = true;
                multiQuery.Table("gossip_menu")
                    .Where(row => row.Column<uint>("MenuID") == menu.Key)
                    .Delete();
            }

            multiQuery.Table("gossip_menu")
                .BulkInsert(menus
                    .Where(menu => menusAlreadyInDb.Contains(menu.Key) == existing)
                    .SelectMany(menu => menu.Value.TextsId.Select(text => new
                    {
                        MenuID = menu.Key,
                        TextID = text,
                        __comment = (string?)null
                    }).Concat(menu.Value.DatabaseOnlyTextsId.Select(dbText => new
                    {
                        MenuID = menu.Key,
                        TextID = dbText,
                        __comment = (string?)"not in sniff"
                    }))));

            if (any)
            {
                multiQuery.BlankLine();
                multiQuery.BlankLine();
            }
        }

19 Source : TrinityStringsViewModel.cs
with The Unlicense
from BAndysc

private async Task Load()
        {
            IsLoading = true;
            var enums = trinityStringsSourceParser.ParseTrinityStringsEnum();

            var definedList = await databaseProvider.GetStringsAsync();

            var defined = new HashSet<uint>(definedList.Select(d => d.Entry));
            
            TrinityStringsNoDatabase.Clear();
            List<TrinityStringViewModel> temp = new();
            foreach (var e in enums)
            {
                if (defined.Contains(e.Key))
                    continue;
                
                temp.Add(new TrinityStringViewModel(e.Key, e.Value));
            }

            temp.Reverse();
            TrinityStringsNoDatabase.AddRange(temp);
            
            IsLoading = false;
        }

19 Source : GossipExtractProcessor.cs
with The Unlicense
from BAndysc

private async Task DeleteExisting()
        {
            await ResolvePointsOfInterest();
            
            foreach (var entry in gossiperToFirstMenuId.Keys.ToList())
            {
                var template = databaseProvider.GetCreatureTemplate(entry);
                if (template != null)
                {
                    if (template.GossipMenuId == gossiperToFirstMenuId[entry])
                        gossiperToFirstMenuId.Remove(entry);
                    else if (template.GossipMenuId != 0)
                        overridenDatabaseGossipMenu.Add(entry, template.GossipMenuId);
                }
                else
                    templatesNotExistingInDb.Add(entry);
            }

            var databaseMenus = await databaseProvider.GetGossipMenusAsync();
            var databaseGossipMenus = databaseMenus.ToDictionary(o => o.MenuId);
            foreach (var menu in menus)
            {
                if (!databaseGossipMenus.TryGetValue(menu.Key, out var dbMenu))
                {
                    menuMissingInDb.Add(menu.Key);
                    continue;
                }

                foreach (var dbText in dbMenu.Text)
                {
                    if (!menu.Value.TextsId.Contains(dbText.Id))
                        menu.Value.DatabaseOnlyTextsId.Add(dbText.Id);
                }
                
                if (menu.Value.DatabaseOnlyTextsId.Count == 0 &&
                    menu.Value.TextsId.All(text => dbMenu.Text.Any(f => f.Id == text)))
                    menusAlreadyInDb.Add(menu.Key);
            }

            foreach (var menu in menus)
            {
                if (menu.Value.Options.Count == 0)
                    continue;
                
                var existingOptions = await databaseProvider.GetGossipMenuOptionsAsync(menu.Key);

                if (existingOptions.Count == 0)
                {
                    menuOptionsMissingInDb.Add(menu.Key);
                    continue;
                }
                
                bool allInDb = true;
                foreach (var option in menu.Value.Options)
                {
                    var isInDb = existingOptions.Any(db => IsSameOption(option, db));
                    if (!isInDb)
                        allInDb = false;
                }

                foreach (var option in existingOptions)
                {
                    var isInSniff = menu.Value.Options.Any(sniff => IsSameOption(option, sniff));
                    if (!isInSniff)
                    {
                        allInDb = false;
                        menu.Value.AddDatabaseOption(new GossipMenuOption(option));
                    }
                }

                if (allInDb)
                {
                    menuOptionsAlreadyInDb.Add(menu.Key);
                }
            }
        }

19 Source : CommandsDocumentViewModel.cs
with The Unlicense
from BAndysc

private async Task Load()
        {
            IsLoading = true;

            var permissions = await authDatabaseProvider.GetRbacPermissionsAsync();
            var links = await authDatabaseProvider.GetLinkedPermissionsAsync();

            Dictionary<uint, string> rbacEnumMapping = rbacSourceParser.ParseRbacEnum();
            Dictionary<string, uint> reverseRbacEnumMapping =
                rbacEnumMapping.ToDictionary(pair => pair.Value, pair => pair.Key);

            var databaseDefinedRbac = new HashSet<uint>(permissions.Select(p => p.Id));
            
            Dictionary<uint, PermissionViewModel> permissionViewModels = permissions.ToDictionary(p => p.Id, p =>
            {
                rbacEnumMapping.TryGetValue(p.Id, out var enumName);
                return new PermissionViewModel(p.Id, enumName ?? "UNKNOWN_ENUM", p);
            });
            
            PossibleParentPermissions.Clear();
            PossibleParentPermissions.AddRange(permissionViewModels.Values
                .Where(p => p.PermissionReadableName.StartsWith("Role:") && p.PermissionReadableName.EndsWith("Commands")));
            
            foreach (var pair in rbacEnumMapping)
            {
                if (!permissionViewModels.ContainsKey(pair.Key))
                    permissionViewModels[pair.Key] = new PermissionViewModel(pair.Key, pair.Value, "");
            }

            foreach (var link in links)
            {
                var parent = permissionViewModels[link.Id];
                var child = permissionViewModels[link.LinkedId];
                child.Parent = parent;
            }

            Dictionary<string, string?> existing = databaseProvider.GetCommands().ToDictionary(d => d.Name, d => d.Help);

            Commands.Clear();
            CommandsNoRbac.Clear();
            foreach (var cmd in commandsSourceParser.GetAllCommands())
            {
                if (!reverseRbacEnumMapping.TryGetValue(cmd.RbacPermission, out var rbacId))
                    continue;
                
                if (!permissionViewModels.TryGetValue(rbacId, out var permission))
                    continue;

                var hasDatabaseRbac = databaseDefinedRbac.Contains(rbacId);
                var hasDatabaseCommand = existing.ContainsKey(cmd.Command);

                if (!hasDatabaseRbac || !hasDatabaseCommand)
                {
                    var vm = new CommandViewModel(cmd.Command, permission);
                    if (vm.IsRbacDefined)
                        Commands.Add(vm);
                    else
                    {
                        vm.PermissionViewModel.PermissionReadableName = "Command: " + vm.Name;
                        CommandsNoRbac.Add(vm);
                    }
                }
            }
            
            IsLoading = false;
        }

19 Source : EventManagerTests.cs
with Apache License 2.0
from bnoazx005

[Test]
        public void TestSubscribe_MultipleSubscriptionsCreatesNewListener_ReturnsListenerIdentifier()
        {
            replacedert.DoesNotThrow(() =>
            {
                HashSet<uint> createdListenersIds = new HashSet<uint>();

                IEventListener eventListener = Subsreplacedute.For<IEventListener>();

                uint registeredListenerId = 0;

                for (int i = 0; i < 4; ++i)
                {
                    registeredListenerId = mEventManager.Subscribe<TSimpleEvent>(eventListener);

                    // all registered listeners have unique identifiers
                    replacedert.IsFalse(createdListenersIds.Contains(registeredListenerId));

                    createdListenersIds.Add(registeredListenerId);
                }
            });
        }

19 Source : MemoryDebugger.cs
with MIT License
from bryanperris

public bool IsRegAddress(uint address) {
            return s_RegTable.Contains(address);
        }

19 Source : MipsDebugger.cs
with MIT License
from bryanperris

public void AppendInstBreakpointByAddr(uint address)
        {
            if (!m_InstByAddressBreakpoints.Contains(address))
            {
                m_InstByAddressBreakpoints.Add(address);
            }
        }

19 Source : MipsDebugger.cs
with MIT License
from bryanperris

public void AppendInstBreakpointByCode(String asm)
        {
            uint inst = N64replacedembler.replacedembleSingleInstruction(asm);

            if (!m_InstByCodeBreakpoints.Contains(inst))
            {
                m_InstByCodeBreakpoints.Add(inst);
            }
        }

19 Source : MipsDebugger.cs
with MIT License
from bryanperris

public virtual void ActivateDebugger() {
            m_Probe_OnInstruction = (inst) => {
                if (m_BreakActive) return;

                ThrowBreakpoint(m_InstByCodeBreakpoints.Contains(inst.Inst.inst));
                ThrowBreakpoint(m_InstByAddressBreakpoints.Contains((uint)inst.Address));
            };

            m_Probe_OnGprWrite = (i) => {
                if (m_BreakActive) return;

                ThrowBreakpoint(m_GPRWriteBreakpoints.Contains(i));
            };

            m_Probe_OnBranch = (target, taken) => {
                if (m_BreakActive) return;

                if (m_BranchBreakpoints.ContainsKey(target))
                {
                    var kind = m_BranchBreakpoints[target];

                    if (kind == BranchCondition.Any)
                    {
                        ThrowBreakpoint(true);
                    }
                    else if (kind == BranchCondition.Taken && taken)
                    {
                        ThrowBreakpoint(true);
                    }
                    else if (kind == BranchCondition.NotTaken && !taken)
                    {
                        ThrowBreakpoint(true);
                    }
                }
            };
        }

19 Source : MipsDebugger.cs
with MIT License
from bryanperris

public virtual void ActivateDebugger() {
            m_Probe_OnInstruction = (inst) => {
                if (m_BreakActive) return;

                ThrowBreakpoint(m_InstByCodeBreakpoints.Contains(inst.Inst.inst));
                ThrowBreakpoint(m_InstByAddressBreakpoints.Contains((uint)inst.Address));
            };

            m_Probe_OnGprWrite = (i) => {
                if (m_BreakActive) return;

                ThrowBreakpoint(m_GPRWriteBreakpoints.Contains(i));
            };

            m_Probe_OnBranch = (target, taken) => {
                if (m_BreakActive) return;

                if (m_BranchBreakpoints.ContainsKey(target))
                {
                    var kind = m_BranchBreakpoints[target];

                    if (kind == BranchCondition.Any)
                    {
                        ThrowBreakpoint(true);
                    }
                    else if (kind == BranchCondition.Taken && taken)
                    {
                        ThrowBreakpoint(true);
                    }
                    else if (kind == BranchCondition.NotTaken && !taken)
                    {
                        ThrowBreakpoint(true);
                    }
                }
            };
        }

19 Source : FiscalQuarterValidator.cs
with Apache License 2.0
from BuffettCode

public static void Validate(uint maybeFiscalQuarter)
        {
            if (!QUARTERS.Contains(maybeFiscalQuarter))
            {
                throw new ValidationError($"{maybeFiscalQuarter} is not in {QUARTERS}");
            }
        }

19 Source : Party.cs
with GNU General Public License v3.0
from caioavidal

public bool IsInvited(IPlayer player)
        {
            return invites.Contains(player.CreatureId);
        }

19 Source : Vip.cs
with GNU General Public License v3.0
from caioavidal

public bool HasInVipList(uint playerId)
        {
            return VipList.Contains(playerId);
        }

19 Source : Texture.cs
with MIT License
from ChevyRay

internal static void UnbindMarked()
        {
            for (uint i = 0; i < binded.Length; ++i)
            {
                if (binded[i].ID != 0 && unbind.Contains(binded[i].ID))
                {
                    GL.ActiveTexture(i);
                    GL.BindTexture(binded[i].Target, 0);
                    binded[i].ID = 0;
                }
            }
            unbind.Clear();
        }

19 Source : AlbionPalette.cs
with MIT License
from csinkers

public uint[] GetUnambiguousPalette()
        {
            if (_unambiguous == null)
            {
                _unambiguous = new uint[256];
                var used = new HashSet<uint>();
                for (int i = 0; i < 256; i++)
                {
                    uint entry = Entries[i];

                    // Always set full alpha when it's not index 0 so things like item graphics
                    // that should just use the common palette still round-trip correctly if 
                    // they accidentally contain some indices < 192
                    if (i > 0)
                        entry |= 0xff000000; 

                    if (used.Contains(entry))
                        entry = Search(entry, used);

                    _unambiguous[i] = entry;
                    used.Add(entry);
                }
            }

            return _unambiguous;
        }

19 Source : LDA.cs
with MIT License
from curiosity-ai

private static bool ShouldKeepToken(HashSet<uint> stopWords, IToken tk)
        {
            //We keep both NONE when there is no POS tagging on the doreplacedent (i.e. POS == NONE) or the token represents a merged set of tokens (Tokens always return PartOfSpeech.X (i.e. from enreplacedies being captured) - see Tokens.cs

            bool filterPartOfSpeech = !(tk.POS == PartOfSpeech.ADJ || tk.POS == PartOfSpeech.NOUN || tk.POS == PartOfSpeech.PROPN || tk.POS == PartOfSpeech.NONE || tk.POS == PartOfSpeech.X);

            bool skipIfTooSmall = (tk.Length < 3);

            //We ignore skipping non-letter POS = X, as this is due to multiple enreplacedy tokens, and we would like to keep enreplacedies them for the LDA calculation (and they'll probably have whitespaces besides letters/digits)
            bool skipIfNotAllLetterOrDigit = (tk.POS != PartOfSpeech.X) && !(tk.Valuereplacedpan.IsAllLetterOrDigit());

            bool skipIfStopWord = stopWords.Contains(Hash(tk.Valuereplacedpan));

            //Heuristic for ordinal numbers (i.e. 1st, 2nd, 33rd, etc)
            bool skipIfMaybeOrdinal = (tk.Valuereplacedpan.IndexOfAny(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' }, 0) >= 0 &&
                                       tk.Valuereplacedpan.IndexOfAny(new char[] { 't', 'h', 's', 't', 'r', 'd' }, 0) >= 0 &&
                                       tk.Valuereplacedpan.IndexOfAny(new char[] { 'a', 'b', 'c', 'e', 'f', 'g', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'u', 'v', 'w', 'x', 'y', 'z' }, 0) < 0);

            bool skipThisToken = filterPartOfSpeech || skipIfTooSmall || skipIfNotAllLetterOrDigit || skipIfStopWord || skipIfMaybeOrdinal;
            return !skipThisToken;
        }

19 Source : FileReaderV7.cs
with GNU General Public License v3.0
from Cytoid

private HashSet<uint> VisitIndexPages(uint startPageID)
        {
            var toVisit = new HashSet<uint>(new uint[] { startPageID });
            var visited = new HashSet<uint>();

            while(toVisit.Count > 0)
            {
                var indexPageID = toVisit.First();

                toVisit.Remove(indexPageID);

                var indexPage = this.ReadPage(indexPageID);

                if (indexPage == null || indexPage["pageType"] != 3) continue;

                visited.Add(indexPageID);

                foreach(var node in indexPage["nodes"].AsArray)
                {
                    var prev = (uint)node["prev"]["pageID"].AsInt32;
                    var next = (uint)node["next"]["pageID"].AsInt32;

                    if (!visited.Contains(prev)) toVisit.Add(prev);
                    if (!visited.Contains(next)) toVisit.Add(next);
                }
            }

            return visited;
        }

19 Source : WalIndexService.cs
with GNU General Public License v3.0
from Cytoid

private int CheckpointInternal()
        {
            LOG($"checkpoint", "WAL");

            // wait all pages write on disk
            _disk.Queue.Wait();

            var counter = 0;

            ENSURE(_disk.Queue.Length == 0, "no pages on queue when checkpoint");

            // getting all "good" pages from log file to be copied into data file
            IEnumerable<PageBuffer> source()
            {
                foreach (var buffer in _disk.ReadFull(FileOrigin.Log))
                {
                    // read direct from buffer to avoid create BasePage structure
                    var transactionID = buffer.ReadUInt32(BasePage.P_TRANSACTION_ID);

                    // only confied paged can be write on data disk
                    if (_confirmTransactions.Contains(transactionID))
                    {
                        var pageID = buffer.ReadUInt32(BasePage.P_PAGE_ID);

                        // clear isConfirmed/transactionID
                        buffer.Write(uint.MaxValue, BasePage.P_TRANSACTION_ID);
                        buffer.Write(false, BasePage.P_IS_CONFIRMED);

                        buffer.Position = BasePage.GetPagePosition(pageID);

                        counter++;

                        yield return buffer;
                    }
                }
            }

            // write all log pages into data file (sync)
            _disk.Write(source(), FileOrigin.Data);

            // clear log file, clear wal index, memory cache,
            this.Clear();

            return counter;
        }

19 Source : GestureManager.cs
with MIT License
from dag10

private void InteractionManager_SourcePressed(InteractionSourceState state)
        {
            // Make sure we're using a tracked interaction source.
            if (trackedInteractionSource.Contains(state.source.id))
            {
                // Add it to the list of pressed states.
                if (!pressedInteractionSource.Contains(state.source.id))
                {
                    pressedInteractionSource.Add(state.source.id);
                }

                // Don't start another manipulation gesture if one is already underway.
                if (!ManipulationInProgress)
                {
                    // Cache our current source state for use later.
                    currentInteractionSourceState = state;

                    // Gesture Support for Controllers: (i.e. Clicker, Xbox Controller, etc.)
                    if (state.source.kind == InteractionSourceKind.Controller)
                    {
                        OnManipulation(inProgress: true, offset: ManipulationPosition);

                        if (OnManipulationStarted != null)
                        {
                            OnManipulationStarted(state.source.kind);
                        }
                    }
                }
            }
        }

19 Source : GestureManager.cs
with MIT License
from dag10

private void InteractionManager_SourceReleased(InteractionSourceState state)
        {
            // if we currently in a manipulation then stop.
            // Check the current interaction source matches our cached value.
            if (ManipulationInProgress && state.source.id == currentInteractionSourceState.source.id)
            {
                // Gesture Support for Controllers: (i.e. Clicker, Xbox Controller, etc.)
                if (state.source.kind == InteractionSourceKind.Controller)
                {
                    Vector3 replacedulativeDelta = ManipulationOffset - ManipulationPosition;
                    OnManipulation(inProgress: false, offset: replacedulativeDelta);

                    if (OnManipulationCompleted != null)
                    {
                        OnManipulationCompleted(state.source.kind);
                    }
                }
            }

            // Removed our pressed state.
            if (pressedInteractionSource.Contains(state.source.id))
            {
                pressedInteractionSource.Remove(state.source.id);
            }
        }

19 Source : GestureManager.cs
with MIT License
from dag10

private void InteractionManager_SourceLost(InteractionSourceState state)
        {
            // If we currently in a manipulation then stop.
            // Check the current interaction source matches our cached value.
            if (ManipulationInProgress && state.source.id == currentInteractionSourceState.source.id)
            {
                // Gesture Support for Controllers: (i.e. Clicker, Xbox Controller, etc.)
                if (state.source.kind == InteractionSourceKind.Controller)
                {
                    Vector3 replacedulativeDelta = ManipulationOffset - ManipulationPosition;
                    OnManipulation(inProgress: false, offset: replacedulativeDelta);

                    if (OnManipulationCanceled != null)
                    {
                        OnManipulationCanceled(state.source.kind);
                    }
                }
            }

            // Removed our pressed state.
            if (pressedInteractionSource.Contains(state.source.id))
            {
                pressedInteractionSource.Remove(state.source.id);
            }

            // Remove our tracked interaction state.
            if (trackedInteractionSource.Contains(state.source.id))
            {
                trackedInteractionSource.Remove(state.source.id);
            }
        }

19 Source : HandsManager.cs
with MIT License
from dag10

private void InteractionManager_SourcePressed(InteractionSourceState state)
        {
            if (state.source.kind == InteractionSourceKind.Hand)
            {
                if (trackedHands.Contains(state.source.id))
                {
                    currentHandState = state;

                    if(!pressedHands.Contains(state.source.id))
                    {
                        pressedHands.Add(state.source.id);
                    }
                }
            }
        }

19 Source : HandsManager.cs
with MIT License
from dag10

private void InteractionManager_SourceReleased(InteractionSourceState state)
        {
            if (state.source.kind == InteractionSourceKind.Hand)
            {
                if (pressedHands.Contains(state.source.id))
                {
                    pressedHands.Remove(state.source.id);
                }
            }
        }

19 Source : HandsManager.cs
with MIT License
from dag10

private void InteractionManager_SourceLost(InteractionSourceState state)
        {
            InteractionManager_SourceReleased(state);

            if (state.source.kind == InteractionSourceKind.Hand)
            {
                if (trackedHands.Contains(state.source.id))
                {
                    trackedHands.Remove(state.source.id);

                    if (HandInView != null)
                    {
                        HandInView(HandDetected);
                    }
                }
            }
        }

19 Source : TabEditLevelTextures.cs
with MIT License
from DavidSM64

private void loadObjectsOnlyButtonSet()
        {
            List<RadioButtonWithInfo> buttons = new List<RadioButtonWithInfo>();
            HashSet<uint> addresses = new HashSet<uint>();
            HashSet<ushort> modelIDs = level.getModelIDsUsedByObjects();

            foreach (ushort modelID in modelIDs)
            {
                if (level.ModelIDs.ContainsKey(modelID))
                {
                    for (int i = 0; i < level.ModelIDs[modelID].builder.TextureImages.Count; i++)
                    {
                        uint address = level.ModelIDs[modelID].builder.TextureAddresses[i];
                        if (address == 0)
                            continue;
                        if (!addresses.Contains(address))
                        {
                            AddNewImage(ref buttons, level.ModelIDs[modelID].builder.TextureImages[i], address, RadioButtonWithInfo_Click);
                            addresses.Add(address);
                        }
                    }
                }
            }
            lt_objectButtons = buttons.ToArray();
        }

19 Source : TabEditLevelTextures.cs
with MIT License
from DavidSM64

private void loadLevelOnlyButtonSet()
        {
            List<RadioButtonWithInfo> buttons = new List<RadioButtonWithInfo>();
            HashSet<uint> addresses = new HashSet<uint>();
            foreach (Area area in level.Areas)
            {
                for (int i = 0; i < area.AreaModel.builder.TextureImages.Count; i++)
                {
                    uint address = area.AreaModel.builder.TextureAddresses[i];
                    if (address == 0)
                        continue;
                    if (!addresses.Contains(address))
                    {
                        AddNewImage(ref buttons, area.AreaModel.builder.TextureImages[i], address,  RadioButtonWithInfo_Click);
                        addresses.Add(address);
                    }
                }
            }
            lt_levelButtons = buttons.ToArray();
        }

19 Source : TabEditLevelTextures.cs
with MIT License
from DavidSM64

private void loadModelsOnlyButtonSet()
        {
            HashSet<uint> addresses = new HashSet<uint>();
            List<RadioButtonWithInfo> buttons = new List<RadioButtonWithInfo>();
            foreach (KeyValuePair<ushort, Model3D> entry in level.ModelIDs)
            {
                for (int i = 0; i < entry.Value.builder.TextureImages.Count; i++)
                {
                    uint address = entry.Value.builder.TextureAddresses[i];
                    if (address == 0)
                        continue;
                    if (!addresses.Contains(address))
                    {
                        AddNewImage(ref buttons, entry.Value.builder.TextureImages[i], address, RadioButtonWithInfo_Click);
                        addresses.Add(address);
                    }
                }
            }
            lt_modelButtons = buttons.ToArray();
        }

19 Source : Program.cs
with MIT License
from DebugST

static void Scan(uint uIP, int nPort) {
            m_se.WaitOne();
            lock (m_obj_sync) {
                if (m_hs_stop_host.Contains(uIP)) {
                    m_nRuned++;
                    m_nJumped++;
                    m_se.Release();
                    return;
                }
                m_nRunning++;
            }
            m_scanner.Scan(uIP,
                nPort,
                ScannerConfiger.ProbesCount,
                ScannerConfiger.Timeout,
                ScannerConfiger.Retry,
                ScannerConfiger.TotalTimeout,
                ScannerConfiger.IsUserNullProbe);
        }

19 Source : DeadlockMonitor.cs
with MIT License
from dinazil

private void FindDeadlockStartingFrom(ClrThread thread, HashSet<uint> visitedThreadIds, Stack<string> chain)
        {
            if (thread == null)
                return;

            if (visitedThreadIds.Contains(thread.OSThreadId))
            {
                WriteTraceLine("Deadlock found between the following threads:");
                foreach (var entry in chain.Reverse())
                {
                    WriteTraceLine($"  {entry} -->");
                }
                WriteTraceLine($"  Thread {thread.OSThreadId}, DEADLOCK!");
                return;
            }

            visitedThreadIds.Add(thread.OSThreadId);
            string topStackTrace = String.Join("\n      ",
                thread.StackTrace.Where(f => f.Kind == ClrStackFrameType.ManagedMethod)
                                 .Select(f => f.DisplayString)
                                 .Take(5));
            chain.Push($"Thread {thread.OSThreadId} at {topStackTrace}");

            foreach (var blockingObject in thread.BlockingObjects)
            {
                chain.Push($"{blockingObject.Reason} at {blockingObject.Object:X}");
                foreach (var owner in blockingObject.Owners)
                {
                    FindDeadlockStartingFrom(owner, visitedThreadIds, chain);
                }
                chain.Pop();
            }

            chain.Pop();
            visitedThreadIds.Remove(thread.OSThreadId);
        }

19 Source : ClusteringTests.cs
with MIT License
from dotnet

[Fact]
        public void PredictClusters()
        {
            int n = 1000;
            int k = 4;
            var rand = new Random(1);
            var clusters = new ClusteringData[k];
            var data = new ClusteringData[n];
            for (int i = 0; i < k; i++)
            {
                //pick clusters as points on circle with angle to axis X equal to 360*i/k
                clusters[i] = new ClusteringData { Points = new float[2] { (float)Math.Cos(Math.PI * i * 2 / k), (float)Math.Sin(Math.PI * i * 2 / k) } };
            }
            // create data points by randomly picking cluster and shifting point slightly away from it.
            for (int i = 0; i < n; i++)
            {
                var index = rand.Next(0, k);
                var shift = (rand.NextDouble() - 0.5) / 10;
                data[i] = new ClusteringData
                {
                    Points = new float[2]
                    {
                        (float)(clusters[index].Points[0] + shift),
                        (float)(clusters[index].Points[1] + shift)
                    }
                };
            }

            var mlContext = new MLContext(seed: 1);

            // Turn the data into the ML.NET data view.
            // We can use CreateDataView or ReadFromEnumerable, depending on whether 'churnData' is an IList, 
            // or merely an IEnumerable.
            var trainData = mlContext.Data.LoadFromEnumerable(data);
            var testData = mlContext.Data.LoadFromEnumerable(clusters);

            // Create Estimator
            var pipe = mlContext.Clustering.Trainers.KMeans("Features", numberOfClusters: k);

            // Train the pipeline
            var trainedModel = pipe.Fit(trainData);

            // Validate that initial points we pick up as centers of cluster during data generation belong to different clusters.
            var labels = new HashSet<uint>();
            var predictFunction = mlContext.Model.CreatePredictionEngine<ClusteringData, ClusteringPrediction>(trainedModel);

            for (int i = 0; i < k; i++)
            {
                var scores = predictFunction.Predict(clusters[i]);
                replacedert.True(!labels.Contains(scores.SelectedClusterId));
                labels.Add(scores.SelectedClusterId);
            }

            // Evaluate the trained pipeline
            var predicted = trainedModel.Transform(testData);
            var metrics = mlContext.Clustering.Evaluate(predicted);

            //Label is not specified, so NMI would be equal to NaN
            replacedert.Equal(metrics.NormalizedMutualInformation, double.NaN);
            //Calculate dbi is false by default so Dbi would be 0
            replacedert.Equal(metrics.DaviesBouldinIndex, (double)0.0);
            replacedert.Equal(metrics.AverageDistance, (double)0.0, 5);
        }

19 Source : BlockHandler.Mesh.cs
with MIT License
from dotnetGame

private bool HasNonTransparentBlock(BlockState blockState)
        {
            return !_transparentBlockIds.Contains(blockState.Id);
        }

19 Source : BlockHandler.Mesh.cs
with MIT License
from dotnetGame

private bool HasNonTransparentBlock(ChunkSectionCompactStorage storage, Vector3Int position, NeighborSections neighbor)
        {
            var target = storage;
            for (int i = 0; i < 3; i++)
            {
                if (position[i] < 0)
                {
                    target = neighbor[i * 2];
                    position[i] += ChunkConstants.BlockEdgeWidthInSection;
                }
                else if (position[i] >= ChunkConstants.BlockEdgeWidthInSection)
                {
                    target = neighbor[i * 2 + 1];
                    position[i] -= ChunkConstants.BlockEdgeWidthInSection;
                }
            }

            if (target == null) return false;

            return !_transparentBlockIds.Contains(target.Data[position.x, position.y, position.z].Id);
        }

19 Source : CavesGenerator.cs
with MIT License
from dotnetGame

protected bool CanReplaceBlock(BlockState curBlock, BlockState upBlock)
        {
            return _canReplaceSet.Contains(curBlock.Id) ||
                    ((curBlock.Id == (uint)BlockId.Sand
                        || curBlock.Id == (uint)BlockId.Gravel)
                    && upBlock.Id != (uint)BlockId.Water);
        }

19 Source : GhostNetRaceManager.cs
with MIT License
from EverestAPI

public void Move(uint playerID, int index, GhostNetFrame frame = null) {
                Logger.Log(LogLevel.Verbose, "ghostnet-race", $"Moving player {playerID} to index {index}");
                GhostNetConnection con = Manager.Server.Connections[(int) playerID];
                ChunkMPlayer playerCached;
                if (con == null || !Manager.Server.PlayerMap.TryGetValue(playerID, out playerCached) || playerCached == null)
                    return;
                Indices[playerID] = index;
                if (index == -1 && WaitingForStart.Contains(playerID) && string.IsNullOrEmpty(playerCached.SID)) {
                    WaitingForStart.Remove(playerID);
                    return;
                }

                ChunkMPlayer player = new ChunkMPlayer {
                    Name = playerCached.Name,
                    SID = index == -1 ? "" : Areas[index].Item1,
                    Mode = index == -1 ? AreaMode.Normal : Areas[index].Item2,
                    Level = ""
                };

                if (frame == null) {
                    con.SendManagement(new GhostNetFrame {
                        HHead = new ChunkHHead {
                            PlayerID = playerID
                        },

                        MPlayer = player
                    }, true);

                } else {
                    frame.MPlayer = player;
                    frame.PropagateM = true;
                }
            }

See More Examples