System.Collections.Generic.IEnumerable.Except(System.Collections.Generic.IEnumerable)

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

903 Examples 7

19 View Source File : IsoHeaderParser.cs
License : MIT License
Project Creator : 13xforever

public static (List<FileRecord> files, List<string> dirs) GetFilesystemStructure(this CDReader reader)
        {
            var fsObjects = reader.GetFileSystemEntries(reader.Root.FullName).ToList();
            var nextLevel = new List<string>();
            var filePaths = new List<string>();
            var dirPaths = new List<string>();
            while (fsObjects.Any())
            {
                foreach (var path in fsObjects)
                {
                    if (reader.FileExists(path))
                        filePaths.Add(path);
                    else if (reader.DirectoryExists(path))
                    {
                        dirPaths.Add(path);
                        nextLevel.AddRange(reader.GetFileSystemEntries(path));
                    }
                    else
                        Log.Warn($"Unknown filesystem object: {path}");
                }
                (fsObjects, nextLevel) = (nextLevel, fsObjects);
                nextLevel.Clear();
            }
            
            var filenames = filePaths.Distinct().Select(n => n.TrimStart('\\')).ToList();
            var dirnames = dirPaths.Distinct().Select(n => n.TrimStart('\\')).OrderByDescending(n => n.Length).ToList();
            var deepestDirnames = new List<string>();
            foreach (var dirname in dirnames)
            {
                var tmp = dirname + "\\";
                if (deepestDirnames.Any(n => n.StartsWith(tmp)))
                    continue;
                
                deepestDirnames.Add(dirname);
            }
            dirnames = deepestDirnames.OrderBy(n => n).ToList();
            var dirnamesWithFiles = filenames.Select(Path.GetDirectoryName).Distinct().ToList();
            var emptydirs = dirnames.Except(dirnamesWithFiles).ToList();

            var fileList = new List<FileRecord>();
            foreach (var filename in filenames)
            {
                var clusterRange = reader.PathToClusters(filename);
                if (clusterRange.Length != 1)
                    Log.Warn($"{filename} is split in {clusterRange.Length} ranges");
                if (filename.EndsWith("."))
                    Log.Warn($"Fixing potential mastering error in {filename}");
                fileList.Add(new FileRecord(filename.TrimEnd('.'), clusterRange.Min(r => r.Offset), reader.GetFileLength(filename)));
            }
            fileList = fileList.OrderBy(r => r.StartSector).ToList();
            return (files: fileList, dirs: emptydirs);
        }

19 View Source File : InterfaceImplementation.cs
License : MIT License
Project Creator : 1996v

public static Type CreateType(Type interfaceType)
        {
            try
            {
                TypeBuilder typeBuilder = Impreplacedembly.DefineInterfaceImpType(interfaceType);

                List<MemberInfo> allMembers = interfaceType.GetAllInterfaceMembers();

                List<MethodInfo> propertyInfos = new List<MethodInfo>();

                foreach (PropertyInfo prop in allMembers.OfType<PropertyInfo>())
                {
                    Type propType = prop.PropertyType;

                    PropertyBuilder propBuilder = typeBuilder.DefineProperty(prop.Name, prop.Attributes, propType, Type.EmptyTypes);

                    MethodInfo iGetter = prop.GetMethod;
                    MethodInfo iSetter = prop.SetMethod;
                    if (iGetter != null)
                    {
                        propertyInfos.Add(iGetter);
                    }

                    if (iSetter != null)
                    {
                        propertyInfos.Add(iSetter);
                    }

                    if (prop.Name == "Item")
                    {
                        if (iGetter != null)
                        {
                            MethodAttributes accessor = iGetter.Attributes;
                            accessor &= ~MethodAttributes.Abstract;
                            MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, iGetter.ReturnType, iGetter.GetParameters().Select(e => e.ParameterType).ToArray());
                            ILGenerator il = methBuilder.GetILGenerator();
                            il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                            il.Emit(OpCodes.Throw);
                            propBuilder.SetGetMethod(methBuilder);
                        }
                        if (iSetter != null)
                        {
                            MethodAttributes accessor = iSetter.Attributes;
                            accessor &= ~MethodAttributes.Abstract;
                            MethodBuilder methBuilder = typeBuilder.DefineMethod(iSetter.Name, accessor, iSetter.ReturnType, iSetter.GetParameters().Select(e => e.ParameterType).ToArray());
                            ILGenerator il = methBuilder.GetILGenerator();
                            il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                            il.Emit(OpCodes.Throw);
                            propBuilder.SetSetMethod(methBuilder);
                        }
                        continue;
                    }


                    Func<FieldInfo> getBackingField;
                    {
                        FieldInfo backingField = null;
                        getBackingField =
                            () =>
                            {
                                if (backingField == null)
                                {
                                    backingField = typeBuilder.DefineField("_" + prop.Name + "_" + Guid.NewGuid(), propType, FieldAttributes.Private);
                                }

                                return backingField;
                            };
                    }

                    if (iGetter != null)
                    {
                        MethodAttributes accessor = iGetter.Attributes;
                        accessor &= ~MethodAttributes.Abstract;

                        MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, propType, Type.EmptyTypes);
                        ILGenerator il = methBuilder.GetILGenerator();
                        il.Emit(OpCodes.Ldarg_0);
                        il.Emit(OpCodes.Ldfld, getBackingField());
                        il.Emit(OpCodes.Ret);
                        propBuilder.SetGetMethod(methBuilder);
                    }

                    if (iGetter != null || iSetter != null)
                    {
                        MethodAttributes accessor = iSetter != null ? iSetter.Attributes : MethodAttributes.Private;
                        string name = iSetter != null ? iSetter.Name : "set_" + prop.Name;

                        accessor &= ~MethodAttributes.Abstract;

                        MethodBuilder methBuilder = typeBuilder.DefineMethod(name, accessor, typeof(void), new[] { propType });
                        ILGenerator il = methBuilder.GetILGenerator();

                        if (iGetter != null)
                        {
                            il.Emit(OpCodes.Ldarg_0);
                            il.Emit(OpCodes.Ldarg_1);
                            il.Emit(OpCodes.Stfld, getBackingField());
                            il.Emit(OpCodes.Ret);
                        }
                        else
                        {
                            il.Emit(OpCodes.Ret);
                        }

                        propBuilder.SetSetMethod(methBuilder);
                    }
                }

                foreach (MethodInfo method in allMembers.OfType<MethodInfo>().Except(propertyInfos))
                {
                    MethodBuilder methBuilder = typeBuilder.DefineMethod(method.Name, MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, method.ReturnType, method.GetParameters().Select(e => e.ParameterType).ToArray());
                    if (method.IsGenericMethod)
                    {
                        methBuilder.DefineGenericParameters(method.GetGenericArguments().Select(e => e.Name).ToArray());
                    }
                    ILGenerator il = methBuilder.GetILGenerator();
                    il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                    il.Emit(OpCodes.Throw);

                    typeBuilder.DefineMethodOverride(methBuilder, method);
                }

                return typeBuilder.CreateTypeInfo();
            }
            catch
            {
                throw BssomSerializationTypeFormatterException.UnsupportedType(interfaceType);
            }
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<int> LastChanceToFindNotAlreadyProvidedInteger(SortedSet<object> alreadyProvidedValues, int? minValue, int? maxValue, IFuzz fuzzer)
        {
            minValue = minValue ?? int.MinValue;
            maxValue = maxValue ?? int.MaxValue;

            var allPossibleValues = Enumerable.Range(minValue.Value, maxValue.Value).ToArray();

            var remainingCandidates = allPossibleValues.Except<int>(alreadyProvidedValues.Cast<int>()).ToArray();

            if (remainingCandidates.Any())
            {
                var pickOneFrom = fuzzer.PickOneFrom<int>(remainingCandidates);
                return new Maybe<int>(pickOneFrom);
            }

            return new Maybe<int>();
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<long> LastChanceToFindNotAlreadyProvidedLong(ref long? minValue, ref long? maxValue, SortedSet<object> alreadyProvidedValues, IFuzz fuzzer)
        {
            minValue = minValue ?? long.MinValue;
            maxValue = maxValue ?? long.MaxValue;

            var allPossibleValues = GenerateAllPossibleOptions(minValue.Value, maxValue.Value);
            
            var remainingCandidates = allPossibleValues.Except<long>(alreadyProvidedValues.Cast<long>()).ToArray();
            
            if (remainingCandidates.Any())
            {
                var index = fuzzer.GenerateInteger(0, remainingCandidates.Length - 1);
                var randomRemainingNumber = remainingCandidates[index];

                return new Maybe<long>(randomRemainingNumber);
            }

            return new Maybe<long>();
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<int> LastChanceToFindAge(SortedSet<object> alreadyProvidedValues, int minAge, int maxAge, IFuzz fuzzer)
        {
            var allPossibleValues = Enumerable.Range(minAge, maxAge - minAge).ToArray();

            var remainingCandidates = allPossibleValues.Except(alreadyProvidedValues.Cast<int>()).ToArray();

            if (remainingCandidates.Any())
            {
                var pickOneFrom = fuzzer.PickOneFrom<int>(remainingCandidates);
                return new Maybe<int>(pickOneFrom);
            }

            return new Maybe<int>();
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<T> LastChanceToFindNotAlreadyPickedValue<T>(SortedSet<object> alreadyProvidedValues, IList<T> candidates, IFuzz fuzzer)
        {
            var allPossibleValues = candidates.ToArray();

            var remainingCandidates = allPossibleValues.Except<T>(alreadyProvidedValues.Cast<T>()).ToArray();

            if (remainingCandidates.Any())
            {
                var index = fuzzer.GenerateInteger(0, remainingCandidates.Length - 1);
                var pickOneFrom = remainingCandidates[index];

                return new Maybe<T>(pickOneFrom);
            }

            return new Maybe<T>();
        }

19 View Source File : LeapMotionConfigurationChecker.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static string GetPathDifference()
        {
            // The file LeapXRServiceProvider.cs is used as a location anchor instead of the LeapMotion directory
            // to avoid a potential incorrect location return if there is a folder named LeapMotion prior to the leap 
            // core replacedets import 
            FileInfo[] leapPathLocationAnchor = FileUtilities.FindFilesInreplacedets(trackedLeapFileName);
            string leapFilePath = leapPathLocationAnchor[0].FullName;

            List<string> leapPath = leapFilePath.Split(Path.DirectorySeparatorChar).ToList();

            // Remove the last 3 elements of leap path (/Core/Scripts/LeapXRService.cs) from the list to get the root of the leap core replacedets
            leapPath.RemoveRange(leapPath.Count - 3, 3);

            List<string> unityDataPath = Application.dataPath.Split('/').ToList();
            unityDataPath.Add("LeapMotion");

            // Get the difference between the root of replacedets and the root of leap core replacedets
            IEnumerable<string> difference = leapPath.Except(unityDataPath);

            return string.Join("/", difference);
        }

19 View Source File : ScriptUtilities.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static void RemoveScriptingDefinitions(
            BuildTargetGroup targetGroup,
            string[] symbols)
        {
            if (symbols == null || symbols.Length == 0) { return; }

            List<string> toRemove = new List<string>(symbols);
            List<string> defines = new List<string>(PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup).Split(';'));

            PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defines.Except(toRemove).ToArray()));
        }

19 View Source File : OVRDirectorySyncer.cs
License : MIT License
Project Creator : absurd-joy

[SuppressMessage("ReSharper", "ParameterTypeCanBeEnumerable.Local")]
	private void DeleteOutdatedEmptyDirectoriesFromTarget(HashSet<string> sourceDirs, HashSet<string> targetDirs,
		CancellationToken cancellationToken)
	{
		var deleted = targetDirs.Except(sourceDirs).OrderByDescending(s => s);

		// By sorting in descending order above, we delete leaf-first,
		// this is simpler than collapsing the list above (which would also allow us to run these ops in parallel).
		// replacedumption is that there are few empty folders to delete
		foreach (var dir in deleted)
		{
			Directory.Delete(Path.Combine(Target, dir));
			cancellationToken.ThrowIfCancellationRequested();
		}
	}

19 View Source File : OVRDirectorySyncer.cs
License : MIT License
Project Creator : absurd-joy

[SuppressMessage("ReSharper", "ParameterTypeCanBeEnumerable.Local")]
	private void CreateRelevantDirectoriesAtTarget(HashSet<string> sourceDirs, HashSet<string> targetDirs,
		CancellationToken cancellationToken)
	{
		var created = sourceDirs.Except(targetDirs);
		foreach (var dir in created)
		{
			Directory.CreateDirectory(Path.Combine(Target, dir));
			cancellationToken.ThrowIfCancellationRequested();
		}
	}

19 View Source File : OVRDirectorySyncer.cs
License : MIT License
Project Creator : absurd-joy

public SyncResult Synchronize(CancellationToken cancellationToken)
	{
		var sourceDirs = RelevantRelativeDirectoriesBeneathDirectory(Source, cancellationToken);
		var targetDirs = RelevantRelativeDirectoriesBeneathDirectory(Target, cancellationToken);
		var sourceFiles = RelevantRelativeFilesBeneathDirectory(Source, cancellationToken);
		var targetFiles = RelevantRelativeFilesBeneathDirectory(Target, cancellationToken);

		var created = sourceFiles.Except(targetFiles).OrderBy(s => s).ToList();
		var updated = sourceFiles.Intersect(targetFiles).OrderBy(s => s).ToList();
		var deleted = targetFiles.Except(sourceFiles).OrderBy(s => s).ToList();
		var syncResult = new SyncResult(created, updated, deleted);

		if (WillPerformOperations != null)
		{
			WillPerformOperations.Invoke(syncResult);
		}

		DeleteOutdatedFilesFromTarget(syncResult, cancellationToken);
		DeleteOutdatedEmptyDirectoriesFromTarget(sourceDirs, targetDirs, cancellationToken);
		CreateRelevantDirectoriesAtTarget(sourceDirs, targetDirs, cancellationToken);
		MoveRelevantFilesToTarget(syncResult, cancellationToken);

		return syncResult;
	}

19 View Source File : BuilderEntityMetadata.cs
License : MIT License
Project Creator : abvogel

public void RemoveRelationshipsWhereIdentical(String relationshipName, Dictionary<Guid, List<Guid>> relatedEnreplacedies)
        {
            if (!RelatedEnreplacedies.ContainsKey(relationshipName))
                return;

            foreach (var id in relatedEnreplacedies.Keys)
            {
                if (!RelatedEnreplacedies[relationshipName].ContainsKey(id))
                    return;

                var newRelatedIds = this.RelatedEnreplacedies[relationshipName][id].Except(relatedEnreplacedies[id]);
                if (newRelatedIds.Count() == 0)
                {
                    this.RelatedEnreplacedies[relationshipName].Remove(id);
                    if (this.RelatedEnreplacedies[relationshipName].Count == 0)
                        this.RelatedEnreplacedies.Remove(relationshipName);
                } else
                {
                    this.RelatedEnreplacedies[relationshipName][id] = newRelatedIds.ToList();
                }
            }
        }

19 View Source File : Player_Spells.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void EquipDequipItemFromSet(WorldObject item, List<Spell> spells, List<Spell> prevSpells, WorldObject surrogateItem = null)
        {
            // compare these 2 spell sets -
            // see which spells are being added, and which are being removed
            var addSpells = spells.Except(prevSpells);
            var removeSpells = prevSpells.Except(spells);

            // set spells are not affected by mana
            // if it's equipped, it's active.

            foreach (var spell in removeSpells)
                EnchantmentManager.Dispel(EnchantmentManager.GetEnchantment(spell.Id, item.EquipmentSetId.Value));

            var addItem = surrogateItem ?? item;

            foreach (var spell in addSpells)
                CreateItemSpell(addItem, spell.Id);
        }

19 View Source File : EnumerableExtensions.cs
License : MIT License
Project Creator : adamant

[DebuggerStepThrough]
        public static IEnumerable<T> Except<T>(this IEnumerable<T> source, T value)
        {
            return source.Except(value.Yield());
        }

19 View Source File : PolyRelationsSieveProgress.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public void PurgePrimeRoughRelations()
		{
			List<Relation> roughRelations = Relations.RoughRelations.ToList();

			IEnumerable<Relation> toRemoveAlg = roughRelations
				.Where(r => r.AlgebraicQuotient != 1 && FactorizationFactory.IsProbablePrime(r.AlgebraicQuotient));

			roughRelations = roughRelations.Except(toRemoveAlg).ToList();

			Relations.RoughRelations = roughRelations;

			IEnumerable<Relation> toRemoveRational = roughRelations
				.Where(r => r.RationalQuotient != 1 && FactorizationFactory.IsProbablePrime(r.RationalQuotient));

			roughRelations = roughRelations.Except(toRemoveRational).ToList();

			Relations.RoughRelations = roughRelations;
		}

19 View Source File : SqlSyncTable.cs
License : MIT License
Project Creator : adospace

internal void SetupCommand(SqlCommand cmd, ChangeType itemChangeType, Dictionary<string, SyncItemValue> syncItemValues)
        {
            var allColumnsExceptSkipColumns = Columns.Keys.Except(SkipColumns).ToArray();

            //take values only for existing columns (server table schema could be not in sync with local table schema)
            var allSyncItems = syncItemValues
                .Where(value => allColumnsExceptSkipColumns.Any(_ => StringComparer.OrdinalIgnoreCase.Compare(_, value.Key) == 0))
                .ToList();

            var allSyncItemsExceptPrimaryKey = allSyncItems.Where(_ => !PrimaryKeyColumns.Any(kc => kc == _.Key)).ToArray();

            switch (itemChangeType)
            {
                case ChangeType.Insert:
                    {
                        cmd.CommandText = [email protected]"{(HasTableIdenreplacedyColumn ? $"SET IDENreplacedY_INSERT {NameWithSchema} ON" : string.Empty)}
BEGIN TRY 
INSERT INTO {NameWithSchema} ({string.Join(", ", allSyncItems.Select(_ => "[" + _.Key + "]"))}) 
VALUES ({string.Join(", ", allSyncItems.Select((_, index) => $"@p{index}"))});
END TRY  
BEGIN CATCH  
PRINT ERROR_MESSAGE()
END CATCH
{(HasTableIdenreplacedyColumn ? $"SET IDENreplacedY_INSERT {NameWithSchema} OFF" : string.Empty)}";


                        int pIndex = 0;
                        foreach (var valueItem in allSyncItems)
                        {
                            cmd.Parameters.Add(new SqlParameter($"@p{pIndex}", Columns[valueItem.Key].DbType)
                            {
                                Value = Utils.ConvertToSqlType(valueItem.Value, Columns[valueItem.Key].DbType)
                            });
                            //cmd.Parameters.AddWithValue("@" + valueItem.Key.Replace(" ", "_"), valueItem.Value.Value ?? DBNull.Value);
                            pIndex++;
                        }
                    }
                    break;

                case ChangeType.Update:
                    {
                        cmd.CommandText = [email protected]"BEGIN TRY 
UPDATE {NameWithSchema}
SET {string.Join(", ", allSyncItemsExceptPrimaryKey.Select((_, index) => $"[{_.Key}] = @p{index}"))}
WHERE {NameWithSchema}.[{PrimaryColumnName}] = @PrimaryColumnParameter
AND (@sync_force_write = 1 OR (SELECT MAX(ID) FROM __CORE_SYNC_CT WHERE PK_{PrimaryColumnType} = @PrimaryColumnParameter AND TBL = '{NameWithSchema}') <= @last_sync_version)
END TRY  
BEGIN CATCH  
PRINT ERROR_MESSAGE()
END CATCH";
                        cmd.Parameters.Add(new SqlParameter("@PrimaryColumnParameter", Columns[PrimaryColumnName].DbType)
                        {
                            Value = Utils.ConvertToSqlType(syncItemValues[PrimaryColumnName], Columns[PrimaryColumnName].DbType)
                        });

                        int pIndex = 0;
                        foreach (var valueItem in allSyncItemsExceptPrimaryKey)
                        {
                            cmd.Parameters.Add(new SqlParameter($"@p{pIndex}", Columns[valueItem.Key].DbType)
                            {
                                Value = Utils.ConvertToSqlType(valueItem.Value, Columns[valueItem.Key].DbType)
                            });
                            //cmd.Parameters.AddWithValue("@" + valueItem.Key.Replace(" ", "_"), valueItem.Value.Value ?? DBNull.Value);
                            pIndex++;
                        }

                    }
                    break;

                case ChangeType.Delete:
                    {
                        cmd.CommandText = [email protected]"BEGIN TRY 
DELETE FROM {NameWithSchema}
WHERE {NameWithSchema}.[{PrimaryColumnName}] = @PrimaryColumnParameter
AND (@sync_force_write = 1 OR (SELECT MAX(ID) FROM __CORE_SYNC_CT WHERE PK_{PrimaryColumnType} = @PrimaryColumnParameter AND TBL = '{NameWithSchema}') <= @last_sync_version)
END TRY  
BEGIN CATCH  
PRINT ERROR_MESSAGE()
END CATCH";

                        cmd.Parameters.Add(new SqlParameter("@PrimaryColumnParameter", Columns[PrimaryColumnName].DbType)
                        {
                            Value = Utils.ConvertToSqlType(syncItemValues[PrimaryColumnName], Columns[PrimaryColumnName].DbType)
                        });

                    }
                    break;
            }


        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio

public static IEnumerable<Enreplacedy> ToRemovedEnreplacedies(this Enreplacedy enreplacedy, Enreplacedy snapshot)
		{
			var removed = ToRemovedEnreplacedy(enreplacedy, snapshot);
			return GetRelatedEnreplacediesRecursive(removed).Except(new[] { removed }).ToList();
		}

19 View Source File : CrmContactRoleProvider.cs
License : MIT License
Project Creator : Adoxio

private void ForEachUserAndRole(OrganizationServiceContext context, string[] usernames, string[] roleNames, Action<Enreplacedy, Enreplacedy> action)
		{
			// If there are no usernames or no roles, there's nothing to be done, so exit.
			if (!(usernames.Any() && roleNames.Any()))
			{
				return;
			}

			var users = context.CreateQuery(_userEnreplacedyName)
				.Where(ContainsPropertyValueEqual<Enreplacedy>(_attributeMapUsername, usernames))
				.Where(GetDeactivatedPredicate())
				.ToList();

			var usersNotFound = usernames.Except(users.Select(contact => contact.GetAttributeValue<string>(_attributeMapUsername)));

			if (usersNotFound.Any())
			{
				throw new ProviderException("The users {0} weren't found.".FormatWith(string.Join(", ", usersNotFound.ToArray())));
			}

			var roles = context.CreateQuery(_roleEnreplacedyName)
				.Where(ContainsPropertyValueEqual<Enreplacedy>(_attributeMapRoleName, roleNames))
				.Where(role => role.GetAttributeValue<int>(_attributeMapStateCode) == 0
					&& role.GetAttributeValue<EnreplacedyReference>(_attributeMapRoleWebsiteId) == WebsiteID)
				.ToList();

			var rolesNotFound = roleNames.Except(roles.Select(role => role.GetAttributeValue<string>(_attributeMapRoleName)));

			if (rolesNotFound.Any())
			{
				throw new ProviderException("The role(s) {0} was/were not found.".FormatWith(string.Join(", ", rolesNotFound.ToArray())));
			}

			foreach (var user in users)
			{
				foreach (var role in roles)
				{
					action(user, role);
				}
			}
		}

19 View Source File : CrmRoleProvider.cs
License : MIT License
Project Creator : Adoxio

private void ForEachUserAndRole(OrganizationServiceContext context, string[] usernames, string[] roleNames, Action<Enreplacedy, Enreplacedy> action)
		{
			// If there are no usernames or no roles, there's nothing to be done, so exit.
			if (!(usernames.Any() && roleNames.Any()))
			{
				return;
			}

			var users = context.CreateQuery(_userEnreplacedyName)
				.Where(ContainsPropertyValueEqual<Enreplacedy>(_attributeMapUsername, usernames))
				.ToList();

			var usersNotFound = usernames.Except(users.Select(contact => contact.GetAttributeValue<string>(_attributeMapUsername)));

			if (usersNotFound.Any())
			{
				throw new ProviderException("The user(s) {0} was/were not found.".FormatWith(string.Join(", ", usersNotFound.ToArray())));
			}

			var roles = context.CreateQuery(_roleEnreplacedyName)
				.Where(ContainsPropertyValueEqual<Enreplacedy>(_attributeMapRoleName, roleNames))
				.Where(role => role.GetAttributeValue<EnreplacedyReference>(_attributeMapRoleWebsiteId) == WebsiteID)
				.ToList();

			var rolesNotFound = roleNames.Except(roles.Select(role => role.GetAttributeValue<string>(_attributeMapRoleName)));

			if (rolesNotFound.Any())
			{
				throw new ProviderException("The role(s) {0} was/were not found.".FormatWith(string.Join(", ", rolesNotFound.ToArray())));
			}

			foreach (var user in users)
			{
				foreach (var role in roles)
				{
					action(user, role);
				}
			}
		}

19 View Source File : ExecutionPluginForResourceFeeTest.cs
License : MIT License
Project Creator : AElfProject

private async Task AdvanceResourceToken(List<string> except = null, long amount = 10_000_00000000)
        {
            var resourceTokenList = new List<string> {"READ", "WRITE", "STORAGE", "TRAFFIC"};
            if (except != null && except.Any())
            {
                resourceTokenList = resourceTokenList.Except(except).ToList();
            }

            foreach (var symbol in resourceTokenList)
            {
                await TokenConverterContractStub.Buy.SendAsync(new BuyInput
                {
                    Symbol = symbol,
                    Amount = amount
                });
                await TokenContractStub.Transfer.SendAsync(new TransferInput
                {
                    To = TestContractAddress,
                    Amount = amount,
                    Symbol = symbol
                });
            }

            foreach (var symbol in resourceTokenList)
            {
                var balance = (await TokenContractStub.GetBalance.CallAsync(new GetBalanceInput
                {
                    Owner = TestContractAddress,
                    Symbol = symbol
                })).Balance;
                balance.ShouldBe(amount);
            }
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static void Main(string[] args)
        {
            var seed = args.Any(x => x == "/seed");
            if (seed)
            {
                args = args.Except(new[] { "/seed" }).ToArray();
            }

            var host = CreateWebHostBuilder(args).Build();

            if (seed)
            {
                var config = host.Services.GetRequiredService<IConfiguration>();
                SeedData.EnsureSeedData(config);
                return;
            }

            host.Run();
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static async Task Main(string[] args)
        {
            var seed = args.Any(x => x == "/seed");
            if (seed)
            {
                args = args.Except(new[] { "/seed" }).ToArray();
            }

            var host = CreateWebHostBuilder(args).Build();

            if (seed)
            {
                var config = host.Services.GetRequiredService<IConfiguration>();
                SeedData.EnsureSeedData(config);
                return;
            }

            await host.RunAsync().ConfigureAwait(false);
        }

19 View Source File : CommandBuilder.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public CommandBuilder WithExecutionChecks(params CheckBaseAttribute[] checks)
        {
            this.ExecutionCheckList.AddRange(checks.Except(this.ExecutionCheckList));
            return this;
        }

19 View Source File : MissionGeneratorCountries.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal Country[][] GenerateCountries(DCSMission mission, MissionTemplate template)
        {
            int i;

            List<Country>[] countries = new List<Country>[] { new List<Country>(), new List<Country>() };

            // Add default country for each coalition
            for (i = 0; i < 2; i++)
                countries[i].Add(DEFAULT_COUNTRIES[i]);

            // Add countries for player FGs to player coalition
            foreach (MissionTemplateFlightGroup flightGroup in template.PlayerFlightGroups)
                countries[(int)template.ContextPlayerCoalition].Add(flightGroup.Country);

            // Removes countries added multiple times
            countries[(int)template.ContextPlayerCoalition] = countries[(int)template.ContextPlayerCoalition].Distinct().ToList();

            // Make sure each country doesn't contain the other's coalition default country
            for (i = 0; i < 2; i++)
                if (countries[i].Contains(DEFAULT_COUNTRIES[1 - i]))
                    countries[i].Remove(DEFAULT_COUNTRIES[1 - i]);

            // Add all non-aligned countries to the list of neutral countries
            List<Country> neutralCountries = new List<Country>(Toolbox.GetEnumValues<Country>());
            for (i = 0; i < 2; i++) neutralCountries = neutralCountries.Except(countries[i]).ToList();

            mission.SetValue("CoalitionNeutral", GetCountriesLuaTable(neutralCountries));
            mission.SetValue("CoalitionBlue", GetCountriesLuaTable(countries[(int)Coalition.Blue]));
            mission.SetValue("CoalitionRed", GetCountriesLuaTable(countries[(int)Coalition.Red]));

            return new Country[][] { countries[0].ToArray(), countries[1].ToArray(), };
        }

19 View Source File : ClstWatcher.cs
License : MIT License
Project Creator : akpaevj

private void ReadInfoBasesAndRaiseEvents()
        {
            var newInfoBases = ReadInfoBases();

            var added = newInfoBases.Except(_infoBases);
            foreach (var (key, (item1, item2)) in added)
                InfoBasesAdded?.Invoke(this, new ClstEventArgs(key, item1, item2));

            var deleted = _infoBases.Except(newInfoBases);
            foreach (var (key, (item1, item2)) in deleted)
                InfoBasesDeleted?.Invoke(this, new ClstEventArgs(key, item1, item2));

            _infoBases = newInfoBases;
        }

19 View Source File : KFixedTableRouter.cs
License : MIT License
Project Creator : alethic

ValueTask<IEnumerable<KNodeEndpointInfo<TNodeId>>> SelectAsyncIter(in TNodeId key, int k, CancellationToken cancellationToken = default)
        {
            if (k == 0)
                return GetBucket(key).SelectAsync(key, cancellationToken);

            // take first bucket; then append others; pretty inefficient
            var c = new KNodeIdDistanceComparer<TNodeId>(key);
            var f = key.Equals(host.SelfId) ? null : buckets[GetBucketIndex(host.SelfId, key)];
            var s = f == null ? Enumerable.Empty<KBucket<TNodeId>>() : new[] { f };
            var l = s.Concat(buckets.Except(s)).SelectMany(i => i).OrderBy(i => i.NodeId, c).Take(k).Select(i => new KNodeEndpointInfo<TNodeId>(i.NodeId, i.Endpoints));
            return new ValueTask<IEnumerable<KNodeEndpointInfo<TNodeId>>>(l);
        }

19 View Source File : ScalingService.cs
License : MIT License
Project Creator : AlexanderFroemmgen

private bool capabilitiesMatch(IEnumerable<string> image, IEnumerable<string> experiment)
        {
            return !experiment.Except(image).Any();
        }

19 View Source File : ApiConsistencyTestBase.cs
License : MIT License
Project Creator : alexandre-spieser

[Fact]
        public void Async_methods_should_end_with_async_suffix()
        {
            var asyncMethods
                = (from type in GetAllTypes(Targetreplacedembly.DefinedTypes)
                    where type.IsVisible
                    from method in type.DeclaredMethods.Where(m => m.IsPublic)
                    where GetBasestTypeInreplacedembly(method.DeclaringType) == type
                    where typeof(Task).IsreplacedignableFrom(method.ReturnType)
                    select method).ToList();

            var missingSuffixMethods
                = asyncMethods
                    .Where(method => !method.Name.EndsWith("Async"))
                    .Select(method => method.DeclaringType.Name + "." + method.Name)
                    .Except(GetAsyncSuffixExceptions())
                    .ToList();

            replacedert.False(
                missingSuffixMethods.Any(),
                "\r\n-- Missing async suffix --\r\n" + string.Join("\r\n", missingSuffixMethods));
        }

19 View Source File : Zone.cs
License : Apache License 2.0
Project Creator : alexreinert

private Zone SignWithNSec(DateTime inception, DateTime expiration, List<DnsKeyRecord> zoneSigningKeys, List<DnsKeyRecord> keySigningKeys)
		{
			var soaRecord = _records.OfType<SoaRecord>().First();
			var subZones = _records.Where(x => (x.RecordType == RecordType.Ns) && (x.Name != Name)).Select(x => x.Name).Distinct().ToList();
			var glueRecords = _records.Where(x => subZones.Any(y => x.Name.IsSubDomainOf(y))).ToList();
			var recordsByName = _records.Except(glueRecords).Union(zoneSigningKeys).Union(keySigningKeys).GroupBy(x => x.Name).Select(x => new Tuple<DomainName, List<DnsRecordBase>>(x.Key, x.OrderBy(y => y.RecordType == RecordType.Soa ? -1 : (int) y.RecordType).ToList())).OrderBy(x => x.Item1).ToList();

			Zone res = new Zone(Name, Count * 3);

			for (int i = 0; i < recordsByName.Count; i++)
			{
				List<RecordType> recordTypes = new List<RecordType>();

				DomainName currentName = recordsByName[i].Item1;

				foreach (var recordsByType in recordsByName[i].Item2.GroupBy(x => x.RecordType))
				{
					List<DnsRecordBase> records = recordsByType.ToList();

					recordTypes.Add(recordsByType.Key);
					res.AddRange(records);

					// do not sign nameserver delegations for sub zones
					if ((records[0].RecordType == RecordType.Ns) && (currentName != Name))
						continue;

					recordTypes.Add(RecordType.RrSig);

					foreach (var key in zoneSigningKeys)
					{
						res.Add(new RrSigRecord(records, key, inception, expiration));
					}
					if (records[0].RecordType == RecordType.DnsKey)
					{
						foreach (var key in keySigningKeys)
						{
							res.Add(new RrSigRecord(records, key, inception, expiration));
						}
					}
				}

				recordTypes.Add(RecordType.NSec);

				NSecRecord nsecRecord = new NSecRecord(recordsByName[i].Item1, soaRecord.RecordClreplaced, soaRecord.NegativeCachingTTL, recordsByName[(i + 1) % recordsByName.Count].Item1, recordTypes);
				res.Add(nsecRecord);

				foreach (var key in zoneSigningKeys)
				{
					res.Add(new RrSigRecord(new List<DnsRecordBase>() { nsecRecord }, key, inception, expiration));
				}
			}

			res.AddRange(glueRecords);

			return res;
		}

19 View Source File : Zone.cs
License : Apache License 2.0
Project Creator : alexreinert

private Zone SignWithNSec3(DateTime inception, DateTime expiration, List<DnsKeyRecord> zoneSigningKeys, List<DnsKeyRecord> keySigningKeys, NSec3HashAlgorithm nsec3Algorithm, int nsec3Iterations, byte[] nsec3Salt, bool nsec3OptOut)
		{
			var soaRecord = _records.OfType<SoaRecord>().First();
			var subZoneNameserver = _records.Where(x => (x.RecordType == RecordType.Ns) && (x.Name != Name)).ToList();
			var subZones = subZoneNameserver.Select(x => x.Name).Distinct().ToList();
			var unsignedRecords = _records.Where(x => subZones.Any(y => x.Name.IsSubDomainOf(y))).ToList(); // glue records
			if (nsec3OptOut)
				unsignedRecords = unsignedRecords.Union(subZoneNameserver.Where(x => !_records.Any(y => (y.RecordType == RecordType.Ds) && (y.Name == x.Name)))).ToList(); // delegations without DS record
			var recordsByName = _records.Except(unsignedRecords).Union(zoneSigningKeys).Union(keySigningKeys).GroupBy(x => x.Name).Select(x => new Tuple<DomainName, List<DnsRecordBase>>(x.Key, x.OrderBy(y => y.RecordType == RecordType.Soa ? -1 : (int) y.RecordType).ToList())).OrderBy(x => x.Item1).ToList();

			byte nsec3RecordFlags = (byte) (nsec3OptOut ? 1 : 0);

			Zone res = new Zone(Name, Count * 3);
			List<NSec3Record> nSec3Records = new List<NSec3Record>(Count);

			if (nsec3Salt == null)
				nsec3Salt = _secureRandom.GenerateSeed(8);

			recordsByName[0].Item2.Add(new NSec3ParamRecord(soaRecord.Name, soaRecord.RecordClreplaced, 0, nsec3Algorithm, 0, (ushort) nsec3Iterations, nsec3Salt));

			HashSet<DomainName> allNames = new HashSet<DomainName>();

			for (int i = 0; i < recordsByName.Count; i++)
			{
				List<RecordType> recordTypes = new List<RecordType>();

				DomainName currentName = recordsByName[i].Item1;

				foreach (var recordsByType in recordsByName[i].Item2.GroupBy(x => x.RecordType))
				{
					List<DnsRecordBase> records = recordsByType.ToList();

					recordTypes.Add(recordsByType.Key);
					res.AddRange(records);

					// do not sign nameserver delegations for sub zones
					if ((records[0].RecordType == RecordType.Ns) && (currentName != Name))
						continue;

					recordTypes.Add(RecordType.RrSig);

					foreach (var key in zoneSigningKeys)
					{
						res.Add(new RrSigRecord(records, key, inception, expiration));
					}
					if (records[0].RecordType == RecordType.DnsKey)
					{
						foreach (var key in keySigningKeys)
						{
							res.Add(new RrSigRecord(records, key, inception, expiration));
						}
					}
				}

				byte[] hash = recordsByName[i].Item1.GetNSec3Hash(nsec3Algorithm, nsec3Iterations, nsec3Salt);
				nSec3Records.Add(new NSec3Record(DomainName.ParseFromMasterfile(hash.ToBase32HexString()) + Name, soaRecord.RecordClreplaced, soaRecord.NegativeCachingTTL, nsec3Algorithm, nsec3RecordFlags, (ushort) nsec3Iterations, nsec3Salt, hash, recordTypes));

				allNames.Add(currentName);
				for (int j = currentName.LabelCount - Name.LabelCount; j > 0; j--)
				{
					DomainName possibleNonTerminal = currentName.GetParentName(j);

					if (!allNames.Contains(possibleNonTerminal))
					{
						hash = possibleNonTerminal.GetNSec3Hash(nsec3Algorithm, nsec3Iterations, nsec3Salt);
						nSec3Records.Add(new NSec3Record(DomainName.ParseFromMasterfile(hash.ToBase32HexString()) + Name, soaRecord.RecordClreplaced, soaRecord.NegativeCachingTTL, nsec3Algorithm, nsec3RecordFlags, (ushort) nsec3Iterations, nsec3Salt, hash, new List<RecordType>()));

						allNames.Add(possibleNonTerminal);
					}
				}
			}

			nSec3Records = nSec3Records.OrderBy(x => x.Name).ToList();

			byte[] firstNextHashedOwnerName = nSec3Records[0].NextHashedOwnerName;

			for (int i = 1; i < nSec3Records.Count; i++)
			{
				nSec3Records[i - 1].NextHashedOwnerName = nSec3Records[i].NextHashedOwnerName;
			}

			nSec3Records[nSec3Records.Count - 1].NextHashedOwnerName = firstNextHashedOwnerName;

			foreach (var nSec3Record in nSec3Records)
			{
				res.Add(nSec3Record);

				foreach (var key in zoneSigningKeys)
				{
					res.Add(new RrSigRecord(new List<DnsRecordBase>() { nSec3Record }, key, inception, expiration));
				}
			}

			res.AddRange(unsignedRecords);

			return res;
		}

19 View Source File : TriggerConfigMeta.cs
License : MIT License
Project Creator : aliyun

public override bool Equals(object obj)
        {
            //Check for null and compare run-time types.
            if ((obj == null) || !this.GetType().Equals(obj.GetType()))
            {
                return false;
            }
            else
            {
                LogTriggerConfig p = (LogTriggerConfig)obj;
                return SourceConfig.Equals(p.SourceConfig) && JobConfig.Equals(p.JobConfig)
                        && (FunctionParameter.Count == p.FunctionParameter.Count && !FunctionParameter.Except(p.FunctionParameter).Any()) 
                        && LogConfig.Equals(p.LogConfig) && Enable == p.Enable;
            }
        }

19 View Source File : ConsoleDriver.cs
License : MIT License
Project Creator : allisterb

public static void RunAndExit(string[] args)
        {
            if (args.Contains("--wait-for-attach"))
            {
                Console.WriteLine("Attach debugger and press any key to continue execution...");
                Console.ReadKey(true);
                if (!Debugger.IsAttached)
                {
                    Console.WriteLine("No debugger detected! Exiting.");
                    return;
                }
                else
                {
                    Debugger.Break();
                }
            }
            if (args.Contains("--with-debug"))
            {
                WithDebugOutput = true;
            }
            if (args.Contains("--with-log-file"))
            {
                WithLogFile = true;
            }
            if (args.Contains("--without-console"))
            {
                WithoutConsole = true;
            }
            
            LoggerConfiguration = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .Enrich.WithThreadId();
            if (WithDebugOutput)
            {
                LoggerConfiguration = LoggerConfiguration.MinimumLevel.Debug();
            }
            if (!WithoutConsole)
            {
                LoggerConfiguration = LoggerConfiguration.WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss} [{ThreadId:d2}][{Level:u3}] {Message}{NewLine}{Exception}");
            }
            if (WithLogFile)
            {
                LogFileName = Path.Combine("logs", "ClreplacedifyBot") + "-{Date}.log";
                LoggerConfiguration = LoggerConfiguration.WriteTo.RollingFile(LogFileName, outputTemplate: "{Timestamp:HH:mm:ss}[{ThreadId:d2}] [{Level:u3}] {Message}{NewLine}{Exception}");
            }

            Log.Logger = LoggerConfiguration.CreateLogger();
            L = Log.ForContext<Driver>();

            ExitToEnvironment = true;

            if (WithLogFile)
            {
                L.Information("Log file is at {0}.", LogFileName);
            }

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == "-x" || args[i] == "--explicit")
                {
                    if ((i + 1) <= args.Length - 1)
                    {
                        ExplicitreplacedemblyName = args[i + 1].StartsWith("ClreplacedifyBot.") ? args[i + 1] : "ClreplacedifyBot." + args[i + 1];
                        args = args.Except(new string[] { "-x", "--explicit", args[i + 1] }).ToArray();
                    }
                    else
                    {
                        L.Error("You must enter an replacedembly name to explicitly load. Valid replacedembly names are : {0}."
                            .F(string.Join(", ", AllLoadedreplacedemblies.Select(a => a.GetName().Name).ToArray())));
                        Exit(StageResult.INVALID_OPTIONS);
                    }
                    break;
                }
            }

            StageResult result = MarshalOptionsForStage(args, ExplicitreplacedemblyName, out Stage stage, out string optionsHelp);
            if (result == StageResult.INVALID_OPTIONS && stage == null && !optionsHelp.IsEmpty())
            {
                L.Information(optionsHelp);
            }
            else if (result == StageResult.CREATED && stage != null && optionsHelp.IsEmpty())
            {
                Exit(stage.Run());
            }
            else
            {
                throw new Exception("Unknown stage state {0} {1}.".F( result, stage));
            }
        }

19 View Source File : VoiceServer.Clients.cs
License : MIT License
Project Creator : AlternateLife

private VoiceHandle CreateFreeVoiceHandle()
        {
            var freeHandle = Enumerable
                .Range(ushort.MinValue + 1, ushort.MaxValue)
                .Select(v => (ushort) v)
                .Except(_clients.Keys.ToArray())
                .First();
            
            return new VoiceHandle(freeHandle);
        }

19 View Source File : ModsMenu.cs
License : MIT License
Project Creator : amazingalek

private IModPopupMenu CreateModsMenu(IModTabbedMenu options)
		{
			_menuOptions.Clear();
			var modsTab = CreateTab(options, Modsreplacedle, true);

			var owmlButton = CreateButton(options, Constants.Owmlreplacedle);
			modsTab.AddButton((IModButtonBase)owmlButton, 0);
			var owmlTab = CreateTab(options, Constants.Owmlreplacedle, false);
			InitConfigMenu(OwmlMenu, options, owmlTab);
			owmlButton.OnClick += () => owmlTab.Open();

			var enabledMods = _modConfigMenus.Where(modConfigMenu => modConfigMenu.ModData.Config.Enabled).ToList();
			var index = CreateBlockOfButtons(options, modsTab, enabledMods, 1, "ENABLED MODS");
			var disabledMods = _modConfigMenus.Except(enabledMods).ToList();
			CreateBlockOfButtons(options, modsTab, disabledMods, index, "DISABLED MODS");

			modsTab.Menu.SetValue("_menuOptions", _menuOptions.ToArray());
			return modsTab;
		}

19 View Source File : SearchInput.cs
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites

public static SearchInput Parse(string searchText)
        {
            var searchInput = new SearchInput
            {
                SourceText = searchText
            };
            if (string.IsNullOrWhiteSpace(searchText))
            {
                return searchInput;
            }

            var keywords = searchText
                .Split(" ")
                .Select(x => x.Trim())
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .ToArray();

            var tags = keywords.Where(x => x.StartsWith("t:")).ToArray();
            var tagSearchValues = tags.Select(x => x[2..]).ToArray();
            keywords = keywords.Except(tags).ToArray();
            searchInput.Keywords = keywords;
            searchInput.Tags = tagSearchValues;
            return searchInput;
        }

19 View Source File : BuildInfo.cs
License : MIT License
Project Creator : anderm

public void AppendSymbols(IEnumerable<string> symbols)
        {
            string[] toAdd = symbols.Except(BuildSymbols.Split(';'))
                .Where(sym => !string.IsNullOrEmpty(sym)).ToArray();

            if (!toAdd.Any())
            {
                return;
            }

            if (!string.IsNullOrEmpty(BuildSymbols))
            {
                BuildSymbols += ";";
            }

            BuildSymbols += string.Join(";", toAdd);
        }

19 View Source File : ObjectInitializerAnalyzer.cs
License : MIT License
Project Creator : angularsen

internal void replacedyzeObjectInitializers(SyntaxNodereplacedysisContext ctx)
        {
            var objectInitializer = (InitializerExpressionSyntax) ctx.Node;

            // For now, only perform replacedysis when explicitly enabled by comment.
            // TODO Support other means to enable, such as static configuration (replacedyze all/none by default), attributes on types and members
            if (!_regionsToreplacedyze.TextSpans.Any(enabledTextSpan => enabledTextSpan.Contains(objectInitializer.SpanStart))) return;

            // Only handle initializers immediately following object creation,
            // not sure what the scenario would be since we are only registered for
            // object initializers, not things like list/collection initializers.
            if (!(objectInitializer.Parent is ObjectCreationExpressionSyntax objectCreation))
                return;

            var objectCreationNamedType =
                (INamedTypeSymbol) ctx.SemanticModel.GetSymbolInfo(objectCreation.Type).Symbol;
            if (objectCreationNamedType == null)
                return;

            ImmutableArray<ISymbol> members = objectCreationNamedType.GetMembers();

            List<string> replacedignedMemberNames = objectInitializer.ChildNodes()
                .OfType<replacedignmentExpressionSyntax>()
                .Select(replacedignmentSyntax => ((IdentifierNameSyntax) replacedignmentSyntax.Left).Identifier.ValueText)
                .ToList();


            // TODO Check if member is replacedignable using Roslyn data flow replacedysis instead of these constraints,
            // as that is the only way to properly determine if it is replacedignable or not in a context
            IEnumerable<ISymbol> replacedignableProperties = members
                .OfType<IPropertySymbol>()
                .Where(m =>
                    // Exclude indexer properties
                    !m.IsIndexer &&
                    // Exclude read-only getter properties
                    !m.IsReadOnly &&
                    // Simplification, only care about public members
                    m.DeclaredAccessibility == Accessibility.Public);

            IEnumerable<ISymbol> replacedignableFields = members.OfType<IFieldSymbol>()
                .Where(m =>
                    // Exclude readonly fields
                    !m.IsReadOnly &&
                    // Exclude const fields
                    !m.HasConstantValue &&
                    // Exclude generated backing fields for properties
                    !m.IsImplicitlyDeclared &&
                    // Simplification, only care about public members
                    m.DeclaredAccessibility == Accessibility.Public);

            IEnumerable<string> replacedignableMemberNames = replacedignableProperties
                .Concat(replacedignableFields)
                .Select(x => x.Name);

            ImmutableArray<string> ignoredPropertyNames = GetIgnoredPropertyNames(objectCreation);

            List<string> unreplacedignedMemberNames =
                replacedignableMemberNames
                    .Except(replacedignedMemberNames)
                    .Except(ignoredPropertyNames)
                    .ToList();

            if (unreplacedignedMemberNames.Any())
            {
                var unreplacedignedMembersString = string.Join(", ", unreplacedignedMemberNames);

                ImmutableDictionary<string, string> properties =
                    new Dictionary<string, string>
                        {
                            {
                                replacedignAllreplacedyzer.Properties_UnreplacedignedMemberNames,
                                unreplacedignedMembersString
                            }
                        }
                        .ToImmutableDictionary();

                var diagnostic = Diagnostic.Create(replacedignAllreplacedyzer.Rule,
                    objectCreation.GetLocation(),
                    properties, objectCreationNamedType.Name, unreplacedignedMembersString);

                ctx.ReportDiagnostic(diagnostic);
            }
        }

19 View Source File : SharlayanHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private void GetPartyInfo()
        {
            var newPartyList = new List<ActorItem>(8);

            if (!this.IsExistsActors ||
                string.IsNullOrEmpty(this.CurrentZoneName))
            {
                if (this.CurrentPlayer != null)
                {
                    newPartyList.Add(this.CurrentPlayer);
                }

                this.PartyMemberList.Clear();
                this.PartyMemberList.AddRange(newPartyList);
                this.PartyMemberCount = newPartyList.Count();
                this.PartyComposition = PartyCompositions.Unknown;

                return;
            }

            var now = DateTime.Now;
            if ((now - this.partyListTimestamp).TotalSeconds <= 0.5)
            {
                return;
            }

            this.partyListTimestamp = now;

            var result = this._memoryHandler.Reader.GetPartyMembers().PartyMembers.Keys;

            foreach (var id in result)
            {
                var actor = this.GetActor(id);
                if (actor != null)
                {
                    newPartyList.Add(actor);
                }
            }

            if (!newPartyList.Any() &&
                this.CurrentPlayer != null)
            {
                newPartyList.Add(this.CurrentPlayer);
            }

            if (this.PartyMemberList.Count != newPartyList.Count ||
                newPartyList.Except(this.PartyMemberList).Any() ||
                this.PartyMemberList.Except(newPartyList).Any())
            {
                this.PartyListChangedTimestamp = DateTime.Now;
            }

            this.PartyMemberList.Clear();
            this.PartyMemberList.AddRange(newPartyList);
            this.PartyMemberCount = newPartyList.Count();

            var composition = PartyCompositions.Unknown;

            var partyPCCount = newPartyList.Count(x => x.Type == Actor.Type.PC);
            if (partyPCCount == 4)
            {
                composition = PartyCompositions.LightParty;
            }
            else
            {
                if (partyPCCount >= 8)
                {
                    var tanks = this.PartyMemberList.Count(x => x.GetJobInfo().Role == Roles.Tank);
                    switch (tanks)
                    {
                        case 1:
                        case 3:
                            composition = PartyCompositions.FullPartyT1;
                            break;

                        case 2:
                        case 6:
                            composition = PartyCompositions.FullPartyT2;
                            break;
                    }
                }
            }

            if (this.PartyComposition != composition)
            {
                this.PartyComposition = composition;
                AppLogger.Info($"party composition changed. current={composition} party_count={partyPCCount}");
            }
        }

19 View Source File : DatabaseConnectionFactory.cs
License : MIT License
Project Creator : ansel86castro

private string BuildUpsertQuery(string[] keys, string table, bool insertKeys, object args, Dictionary<string, string> onUpdateArgs = null, Dictionary<string, string> onInsertArgs = null)
            {
                if (_connection is not SqlConnection)
                    throw new InvalidOperationException("Merge is not supported for the current connection");

                var type = args.GetType();
                return _upsertCache.GetOrAdd($"{table}:{type.FullName}", _ =>
                {
                    var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(x => x.Name).ToList();

                    var argValues = string.Join(", ", props.Select(x => "@" + x));
                    var condition = keys.Select(k => $"Target.[{k}] = Source.[{k}]").Aggregate((x, y) => $"{x} AND {y}");

                    var columns = (insertKeys ? props : props.Except(keys)).Select(x => $"[{x}]").ToList();

                    var update = string.Join(", ", columns.Select(c => $"{c} = Source.{c}"));
                    var sourceColumns = string.Join(", ", columns.Select(c => $"Source.{c}"));

                    var onUpdate = onUpdateArgs?.Any() ?? false ? "," + string.Join(", ", onUpdateArgs.Select(x => $"[{x.Key}] = {x.Value}")) : "";
                    var onInsertColumns = onInsertArgs?.Any() ?? false ? "," + string.Join(", ", onInsertArgs.Select(x => $"[{x.Key}]")) : "";
                    var onInsertValues = onInsertArgs?.Any() ?? false ? "," + string.Join(", ", onInsertArgs.Select(x => $"{x.Value}")) : "";

                    var columnString = string.Join(",", columns);

                    var sql = [email protected]"
                MERGE {table} AS Target USING ( VALUES ({argValues})) 
                AS Source ({string.Join(",", props.Select(x => $"[{x}]"))})
                ON {condition}
                WHEN MATCHED THEN 
                UPDATE SET {update}{onUpdate}
                WHEN NOT MATCHED BY TARGET THEN 
                INSERT ({columnString}{onInsertColumns}) VALUES ( {sourceColumns}{onInsertValues})
                OUTPUT INSERTED.*;";

                    return sql;
                });
            }

19 View Source File : Utils.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd

public static bool Equal<T>(T a, T b)
        {
            if (a is IEquatable<T> aieq) return aieq.Equals(b);
            else if (a is Array aa2 && b is Array ba2 && aa2.Rank == 2)
            {
                int I = aa2.GetLength(0), J = aa2.GetLength(1);
                if (I != ba2.GetLength(0) || J != ba2.GetLength(1)) return false;
                for (int i = 0; i < I; i++)
                    for (int j = 0; j < J; j++)
                        if (!aa2.GetValue(i, j).Equals(ba2.GetValue(i, j)))
                            return false;
                return true;
            }
            else if (a is IList ail && b is IList bil)
            {
                if (ail.Count != bil.Count) return false;
                for (int i = 0; i < ail.Count; i++)
                    if (!ail[i].Equals(bil[i]))
                        return false;
                return true;
            }
            else if (a.GetType().GetInterface(typeof(IReadOnlyList<>).Name) != null)
            {
                var e1 = ((IEnumerable)a).GetEnumerator();
                var e2 = ((IEnumerable)b).GetEnumerator();
                while (true)
                {
                    var e1MoveNext = e1.MoveNext();
                    if (e1MoveNext != e2.MoveNext()) return false;
                    if (!e1MoveNext) return true;
                    if (!Equal(e1.Current, e2.Current)) return false;
                }
            }
            else if (a is ICollection aic && b is ICollection bic)
            {
                return aic.Count == bic.Count && !aic.Cast<object>().Except(bic.Cast<object>()).Any();
            }
            else if (a is IEnumerable aie && b is IEnumerable bie)
            {
                var aieo = aie.Cast<object>().ToList();
                var bieo = bie.Cast<object>().ToList();
                return aieo.Count == bieo.Count && !aieo.Except(bieo).Any();
            }
            return a.Equals(b);
        }

19 View Source File : Utils.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd

public static bool ModelEqual<T, M>(T actual, M model)
        {
            if (actual is IList ail && model is IList bil)
            {
                if (ail.Count != bil.Count) return false;
                for (int i = 0; i < ail.Count; i++)
                    if (!ail[i].Equals(bil[i]))
                        return false;
                return true;
            }
            else if (actual.GetType().GetInterface(typeof(IReadOnlyList<>).Name) != null
                  && model.GetType().GetInterface(typeof(IReadOnlyList<>).Name) != null)
            {
                var e1 = ((IEnumerable)actual).GetEnumerator();
                var e2 = ((IEnumerable)model).GetEnumerator();
                while (true)
                {
                    var e1MoveNext = e1.MoveNext();
                    if (e1MoveNext != e2.MoveNext()) return false;
                    if (!e1MoveNext) return true;
                    if (!Equal(e1.Current, e2.Current)) return false;
                }
            }
            else if (actual is ICollection aic && model is ICollection bic)
            {
                return aic.Count == bic.Count && !aic.Cast<object>().Except(bic.Cast<object>()).Any();
            }
            else if (actual is IEnumerable aie && model is IEnumerable bie)
            {
                var aieo = aie.Cast<object>().ToList();
                var bieo = bie.Cast<object>().ToList();
                return aieo.Count == bieo.Count && !aieo.Except(bieo).Any();
            }
            return actual.Equals(model);
        }

19 View Source File : IdentifyDirectDependencyCounts.cs
License : MIT License
Project Creator : aolszowka

internal static (Dictionary<string, string> ColoringDictionary, Dictionary<string, SortedSet<string>> UniqueProjectsForDependency) Walk(string targetProject, IDictionary<string, SortedSet<string>> dependencyGraph)
        {
            // We are going to need to perform this for every direct dependency of the target project
            if (!dependencyGraph.ContainsKey(targetProject))
            {
                string exception = $"Could not find project `{targetProject}` in given dictionary.";
                throw new NotSupportedException(exception);
            }

            // If we do not have enough colors to represent all N-Order Dependencies we need to throw
            if (dependencyGraph[targetProject].Count > ColorScheme.Length)
            {
                string exception = $"There are not enough colors to properly render the graph. Need {dependencyGraph[targetProject].Count}; only have {ColorScheme.Length}";
                throw new NotSupportedException(exception);
            }

            Dictionary<string, string> coloringDictionary = new Dictionary<string, string>();
            Dictionary<string, SortedSet<string>> uniqueDependenciesForProject = new Dictionary<string, SortedSet<string>>();

            // Load the Initial Dependencies into the Color Dictionary
            string[] directDependencyProjects = dependencyGraph[targetProject].ToArray();
            for (int i = 0; i < directDependencyProjects.Length; i++)
            {
                coloringDictionary.Add(directDependencyProjects[i], ColorScheme[i]);
            }

            SortedSet<string> directDependenciesOfTargetProject = dependencyGraph[targetProject];

            foreach (string dependencyOfTargetProject in directDependenciesOfTargetProject)
            {
                // We need to remove the direct dependency from the existing
                // graph to determine what the remaining N-Order Dependencies
                // of the target project are. To do this we need a DEEP COPY
                // CLONE of the Original Dependency Graph. DO NOT USE THE
                // OVERLOAD WHICH IS ONLY A SHALLOW COPY!
                IDictionary<string, SortedSet<string>> modifiedDependencyGraph = CloneDependencyGraph(dependencyGraph);
                modifiedDependencyGraph[targetProject].Remove(dependencyOfTargetProject);
                HashSet<string> modifiedDependencies = IdentifyRequiredProjects.GenerateNOrderDependencies(targetProject, modifiedDependencyGraph);

                // Now using the original dependency graph get the N-Order
                // Dependencies of the current dependency
                HashSet<string> directDependencyDependencies = IdentifyRequiredProjects.GenerateNOrderDependencies(dependencyOfTargetProject, dependencyGraph);

                // Now if there are any dependencies that are ONLY dependencies
                // of the current dependency then those would "fall away" if we
                // trimmed out the reference.
                string[] distinctDependenciesOfCurrentDependency = directDependencyDependencies.Except(modifiedDependencies).ToArray();

                // Save this information
                uniqueDependenciesForProject.Add(dependencyOfTargetProject, new SortedSet<string>(distinctDependenciesOfCurrentDependency));

                // Update the coloring information as well
                foreach (string dependency in distinctDependenciesOfCurrentDependency)
                {
                    coloringDictionary.Add(dependency, coloringDictionary[dependencyOfTargetProject]);
                }
            }

            return (coloringDictionary, uniqueDependenciesForProject);
        }

19 View Source File : Set_up_age_distributions.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

private static bool Compare(List<string> list1, List<string> list2)
        {
            if (list1.Count != list2.Count)
            {
                return false;
            }

            return !list1.Except(list2).Any();
        }

19 View Source File : LineBrush.cs
License : MIT License
Project Creator : Aroueterra

public static IEnumerable<Vector2Int> GetPointsOnLine(Vector2Int startPos, Vector2Int endPos, bool fillGaps)
        {
            var points = GetPointsOnLine(startPos, endPos);
            if (fillGaps)
            {
                var rise = endPos.y - startPos.y;
                var run = endPos.x - startPos.x;

                if (rise != 0 || run != 0)
                {
                    var extraStart = startPos;
                    var extraEnd = endPos;


                    if (Mathf.Abs(rise) >= Mathf.Abs(run))
                    {
                        // up
                        if (rise > 0)
                        {
                            extraStart.y += 1;
                            extraEnd.y += 1;
                        }
                        // down
                        else // rise < 0
                        {

                            extraStart.y -= 1;
                            extraEnd.y -= 1;
                        }
                    }
                    else // Mathf.Abs(rise) < Mathf.Abs(run)
                    {

                        // right
                        if (run > 0)
                        {
                            extraStart.x += 1;
                            extraEnd.x += 1;
                        }
                        // left
                        else // run < 0
                        {
                            extraStart.x -= 1;
                            extraEnd.x -= 1;
                        }
                    }

                    var extraPoints = GetPointsOnLine(extraStart, extraEnd);
                    extraPoints = extraPoints.Except(new[] { extraEnd });
                    points = points.Union(extraPoints);
                }

            }

            return points;
        }

19 View Source File : CollectionView.cs
License : GNU General Public License v3.0
Project Creator : Artentus

public void Refresh()
        {
            var old = _evaluated.ToArray();
            _evaluated = Evaluate(_baseCollection);

            var removed = old.Except(_evaluated).ToArray();
            if (removed.Length > 0) OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed, 0));

            var added = _evaluated.Except(old).ToArray();
            if (added.Length > 0) OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, added, 0));

            if (old.Length != _evaluated.Count)
                OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
        }

19 View Source File : UnusedResourceUsageRule.cs
License : Apache License 2.0
Project Creator : aspnet

public override ProblemCollection Check(ModuleNode node)
        {
            var replacedemblyNode = node as replacedemblyNode;
            if (replacedemblyNode != null)
            {
                var replacedemblyAvailableResources = new HashSet<PropertyNode>();
                var replacedemblyUsedResources = new HashSet<PropertyNode>();

                _availableResources[replacedemblyNode] = replacedemblyAvailableResources;
                _usedResources[replacedemblyNode] = replacedemblyUsedResources;

                Visitreplacedembly(replacedemblyNode);

                IEnumerable<PropertyNode> unusedResources = from res in replacedemblyAvailableResources.Except(replacedemblyUsedResources)
                                                            where !IsCommonResource(res)
                                                            select res;

                foreach (PropertyNode item in unusedResources)
                {
                    Problems.Add(new Problem(this.GetResolution(item.Name.Name, item.DeclaringType.FullName), item.UniqueKey.ToString()));
                }
            }

            return Problems;
        }

19 View Source File : ImmutableMemberSet.cs
License : Apache License 2.0
Project Creator : asynkron

public ImmutableMemberSet Except(ImmutableMemberSet other)
        {
            var both = Members.Except(other.Members);
            return new ImmutableMemberSet(both);
        }

19 View Source File : AudibleAppSimsBySeries.cs
License : GNU General Public License v3.0
Project Creator : audiamus

private AA.AsinJsonFile findSeriesFileBySkuSubDir (
      Book.Part part, string subDirPath, bool fileOnly, string filePattern, GetProductsDelegate getProducts
    ) {
      var filepaths = Directory.GetFiles (subDirPath, filePattern);
      var filenames = filepaths.Select (p => Path.GetFileName (p));
      filenames = filenames.Except (_discardedFiles);

      foreach (var filename in filenames) {
        string asinfile = Path.Combine (subDirPath, filename).AsUncIfLong();
        string json = File.ReadAllText (asinfile);

        var products = getProducts (json);

        string asin = findBySku (products, part, fileOnly);
        if (asin != null)
          return new AA.AsinJsonFile (asinfile, asin);

        _discardedFiles.Add (filename);
      }

      return null;
    }

19 View Source File : TreeDecomposition.cs
License : GNU General Public License v3.0
Project Creator : audiamus

private void dump (
      ref IEnumerable<PropertyInfo> propInfos, object o, IEnumerable<Type> path,
      Stack<Type> stack, TextWriter tw, Indent ind, EDumpFlags flags, bool inEnum
    ) {

      Type ifcType = path.Last ();
      if (!ifcType.IsInterface)
        return;
      IEnumerable<PropertyInfo> ifcPropInfos = ifcType.GetProperties ();
      if (ifcPropInfos.Count () == 0)
        return;

      var propNames = ifcPropInfos.Select (pi => pi.Name);
      var filteredPropInfos = propInfos.Where (pi => propNames.Contains (pi.Name));
      if (filteredPropInfos.Count () == 0)
        return;

      propInfos = propInfos.Except (filteredPropInfos);

      string sPath = path.ToHierarchyString ();
      tw.WriteLine ($"{ind}:{sPath}");
      using (new ResourceGuard (ind))
        dump (o, filteredPropInfos, stack, tw, ind, flags, inEnum);

    }

19 View Source File : PMProject.cs
License : MIT License
Project Creator : Autodesk

private void RefreshEnreplacedies(List<PMEnreplacedy> enreplacediesToRefresh, List<string> enreplacediesToRefreshFrom, string type)
        {
            var currentEnreplacedies = new List<PMEnreplacedy>();
            foreach (string name in enreplacediesToRefreshFrom)
            {
                var originalEnreplacedy =
                    enreplacediesToRefresh.SingleOrDefault(x => x.Name.ToUpperInvariant() == name.ToUpperInvariant());
                if (originalEnreplacedy != null)
                {
                    //Enreplacedy is already in the project collections
                    currentEnreplacedies.Add(originalEnreplacedy);
                }
                else
                {
                    PMEnreplacedy enreplacedy = null;
                    enreplacedy = PMEnreplacedyFactory.CreateEnreplacedy(_powerMILL, type, name);
                    AddEnreplacedyToCollection(enreplacedy);
                    currentEnreplacedies.Add(enreplacedy);
                }
            }

            //Remove old enreplacedies from the project
            var enreplacediesToDelete = enreplacediesToRefresh.Except(currentEnreplacedies).ToList();
            foreach (PMEnreplacedy enreplacedy in enreplacediesToDelete)
            {
                RemoveEnreplacedyFromCollection(enreplacedy);
            }
        }

See More Examples