System.Collections.Generic.List.AddRange(System.Collections.Generic.IEnumerable)

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

19673 Examples 7

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

public BuffConfig[] GetBuffConfigs(JobIds job, bool isLocalPlayer) {
            var jobBuffs = JobToValue.TryGetValue(job, out var props) ? props : JobToValue[JobIds.OTHER];
            if (!isLocalPlayer) return jobBuffs;

            var combinedProps = new List<BuffConfig>();
            combinedProps.AddRange(LocalPlayerConfigs);
            combinedProps.AddRange(jobBuffs.Where(x => !x.IsPlayerOnly));
            return combinedProps.ToArray();
        }

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

public BuffConfig[] GetBuffConfigs(JobIds job, bool isLocalPlayer) {
            var jobBuffs = JobToValue.TryGetValue(job, out var props) ? props : JobToValue[JobIds.OTHER];
            if (!isLocalPlayer) return jobBuffs;

            var combinedProps = new List<BuffConfig>();
            combinedProps.AddRange(LocalPlayerConfigs);
            combinedProps.AddRange(jobBuffs.Where(x => !x.IsPlayerOnly));
            return combinedProps.ToArray();
        }

19 Source : ListSnapshot.cs
with MIT License
from 0x0ade

public void Set(IEnumerable<T> list) {
            List.Clear();
            List.AddRange(list);
        }

19 Source : MergeSimulation.cs
with MIT License
from 0x1000000

public static ExprList ConvertMerge(ExprMerge merge, string tempTableName)
        {
            var derivedTableValues = merge.Source as ExprDerivedTableValues;

            if (derivedTableValues == null)
            {
                throw new SqExpressException("Only derived table values can be used as a source in MERGE simulation");
            }

            var acc = new List<IExprExec>();

            var keys = ExtractKeys(merge, derivedTableValues.Alias.Alias);

            var exprInsertIntoTmp = TempTableData.FromDerivedTableValuesInsert(derivedTableValues, keys.SourceKeys, out var tempTable, name: tempTableName, alias: Alias.From(derivedTableValues.Alias.Alias));

            acc.AddRange(exprInsertIntoTmp.Expressions);

            //MATCHED
            var e = WhenMatched(merge, tempTable);
            if (e != null)
            {
                acc.Add(e);
            }

            //NOT MATCHED BY TARGET
            e = WhenNotMatchedByTarget(merge, tempTable, keys);
            if (e != null)
            {
                acc.Add(e);
            }

            //NOT MATCHED BY SOURCE
            e = WhenNotMatchedBySource(merge, tempTable);
            if (e != null)
            {
                acc.Add(e);
            }

            acc.Add(new ExprStatement(tempTable.Script.Drop()));
            return new ExprList(acc);
        }

19 Source : TableClassGenerator.cs
with MIT License
from 0x1000000

private static MemberDeclarationSyntax[] ConcatClreplacedMembers(ConstructorDeclarationSyntax empty, ConstructorDeclarationSyntax main, IReadOnlyList<PropertyDeclarationSyntax> properties)
        {
            var result = new List<MemberDeclarationSyntax>(2 + properties.Count)
            {
                empty, main
            };

            result.AddRange(properties);

            return result.ToArray();
        }

19 Source : UpdateBuilder.cs
with MIT License
from 0x1000000

internal UpdateBuilderSetter Set(IReadOnlyList<ExprColumnSetClause> sets)
        {
            this._sets.AddRange(sets);
            return new UpdateBuilderSetter(this._target, this._sets);
        }

19 Source : StatementList.cs
with MIT License
from 0x1000000

public static StatementList Combine(IStatement statement, params IStatement[] statements)
        {
            List<IStatement> result = new List<IStatement>((statements.Length + 1) * 2);
            if (statement is StatementList sli)
            {
                result.AddRange(sli.Statements);
            }
            else
            {
                result.Add(statement);
            }

            foreach (var statementI in statements)
            {
                if (statementI is StatementList sl)
                {
                    result.AddRange(sl.Statements);
                }
                else
                {
                    result.Add(statementI);
                }
            }
            return new StatementList(result);
        }

19 Source : StatementList.cs
with MIT License
from 0x1000000

public static StatementList Combine(IReadOnlyList<IStatement> statements)
        {
            List<IStatement> result = new List<IStatement>((statements.Count + 1) * 2);

            foreach (var statementI in statements)
            {
                if (statementI is StatementList sl)
                {
                    result.AddRange(sl.Statements);
                }
                else
                {
                    result.Add(statementI);
                }
            }
            return new StatementList(result);
        }

19 Source : TableBase.cs
with MIT License
from 0x1000000

protected internal void AddColumns(IReadOnlyList<TableColumn> columns)
        {
            this._columns.AddRange(columns);
        }

19 Source : IScenario.cs
with MIT License
from 0x1000000

public void Add(IScenario scenario)
            {
                if (scenario is ScenarioList sl)
                {
                    this._scenarios.AddRange(sl._scenarios);
                }
                else
                {
                    this._scenarios.Add(scenario);
                }
            }

19 Source : Program.cs
with MIT License
from 0x1000000

public static IReadOnlyList<NodeModel> BuildModelRoslyn(string projectFolder)
        {
            List<NodeModel> result = new List<NodeModel>();
				
            var files = Directory.EnumerateFiles(Path.Combine(projectFolder, "Syntax"), "*.cs", SearchOption.AllDirectories);

            files = files.Concat(Directory.EnumerateFiles(projectFolder, "IExpr*.cs"));

            var trees = files.Select(f => CSharpSyntaxTree.ParseText(File.ReadAllText(f))).ToList();
            var cSharpCompilation = CSharpCompilation.Create("Syntax", trees);

            foreach (var tree in trees)
            {
                var semantic = cSharpCompilation.GetSemanticModel(tree);

                foreach (var clreplacedDeclarationSyntax in tree.GetRoot().DescendantNodesAndSelf().OfType<ClreplacedDeclarationSyntax>())
                {
                    var clreplacedSymbol = semantic.GetDeclaredSymbol(clreplacedDeclarationSyntax);
                    
                    var isSuitable = clreplacedSymbol != null 
                                 && !clreplacedSymbol.IsAbstract 
                                 && clreplacedSymbol.DeclaredAccessibility == Accessibility.Public
                                 && IsExpr(clreplacedSymbol) 
                                 && clreplacedSymbol.Name.StartsWith("Expr");
                        
                    if (!isSuitable)
                    {
                        continue;
                    }

                    var properties = GetProperties(clreplacedSymbol);

                    var subNodes = new List<SubNodeModel>();
                    var modelProps = new List<SubNodeModel>();

                    foreach (var constructor in clreplacedSymbol.Constructors)
                    {
                        foreach (var parameter in constructor.Parameters)
                        {
                            INamedTypeSymbol pType = (INamedTypeSymbol)parameter.Type;

                            var correspondingProperty = properties.FirstOrDefault(prop =>
                                string.Equals(prop.Name,
                                    parameter.Name,
                                    StringComparison.CurrentCultureIgnoreCase));

                            if (correspondingProperty == null)
                            {
                                throw new Exception(
                                    $"Could not find a property for the constructor arg: '{parameter.Name}'");
                            }

                            var ta = replacedyzeSymbol(ref pType);

                            var subNodeModel = new SubNodeModel(correspondingProperty.Name,
                                parameter.Name,
                                pType.Name,
                                ta.ListName,
                                ta.IsNullable,
                                ta.HostTypeName);
                            if (ta.Expr)
                            {
                                subNodes.Add(subNodeModel);
                            }
                            else
                            {
                                modelProps.Add(subNodeModel);
                            }

                        }
                    }

                    result.Add(new NodeModel(clreplacedSymbol.Name,
                        modelProps.Count == 0 && subNodes.Count == 0,
                        subNodes,
                        modelProps));
                }
            }

            result.Sort((a, b) => string.CompareOrdinal(a.TypeName, b.TypeName));

            return result;

            bool IsExpr(INamedTypeSymbol symbol)
            {
                if (symbol.Name == "IExpr")
                {
                    return true;
                }
                while (symbol != null)
                {
                    if (symbol.Interfaces.Any(HasA))
                    {
                        return true;
                    }
                    symbol = symbol.BaseType;
                }

                return false;


                bool HasA(INamedTypeSymbol iSym)
                {
                    if (iSym.Name == "IExpr")
                    {
                        return true;
                    }

                    return IsExpr(iSym);
                }
            }

            List<ISymbol> GetProperties(INamedTypeSymbol symbol)
            {
                List<ISymbol> result = new List<ISymbol>();
                while (symbol != null)
                {
                    result.AddRange(symbol.GetMembers().Where(m => m.Kind == SymbolKind.Property));
                    symbol = symbol.BaseType;
                }

                return result;
            }

            Symbolreplacedysis replacedyzeSymbol(ref INamedTypeSymbol typeSymbol)
            {
                string listName = null;
                string hostType = null;
                if (typeSymbol.ContainingType != null)
                {
                    var host = typeSymbol.ContainingType;
                    hostType = host.Name;
                }

                var nullable = typeSymbol.NullableAnnotation == NullableAnnotation.Annotated;

                if (nullable && typeSymbol.Name == "Nullable")
                {
                    typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
                }

                if (typeSymbol.IsGenericType)
                {
                    if (typeSymbol.Name.Contains("List"))
                    {
                        listName = typeSymbol.Name;
                    }

                    if (typeSymbol.Name == "Nullable")
                    {
                        nullable = true;
                    }

                    typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
                }

                return new Symbolreplacedysis(nullable, listName, IsExpr(typeSymbol), hostType);
            }
        }

19 Source : Chromium.cs
with GNU General Public License v3.0
from 0xfd3

public static List<Account> Grab()
        {
            Dictionary<string, string> ChromiumPaths = new Dictionary<string, string>()
            {
                {
                    "Chrome",
                    LocalApplicationData + @"\Google\Chrome\User Data"
                },
                {
                    "Opera",
                    Path.Combine(ApplicationData, @"Opera Software\Opera Stable")
                },
                {
                    "Yandex",
                    Path.Combine(LocalApplicationData, @"Yandex\YandexBrowser\User Data")
                },
                {
                    "360 Browser",
                    LocalApplicationData + @"\360Chrome\Chrome\User Data"
                },
                {
                    "Comodo Dragon",
                    Path.Combine(LocalApplicationData, @"Comodo\Dragon\User Data")
                },
                {
                    "CoolNovo",
                    Path.Combine(LocalApplicationData, @"MapleStudio\ChromePlus\User Data")
                },
                {
                    "SRWare Iron",
                    Path.Combine(LocalApplicationData, @"Chromium\User Data")
                },
                {
                    "Torch Browser",
                    Path.Combine(LocalApplicationData, @"Torch\User Data")
                },
                {
                    "Brave Browser",
                    Path.Combine(LocalApplicationData, @"BraveSoftware\Brave-Browser\User Data")
                },
                {
                    "Iridium Browser",
                    LocalApplicationData + @"\Iridium\User Data"
                },
                {
                    "7Star",
                    Path.Combine(LocalApplicationData, @"7Star\7Star\User Data")
                },
                {
                    "Amigo",
                    Path.Combine(LocalApplicationData, @"Amigo\User Data")
                },
                {
                    "CentBrowser",
                    Path.Combine(LocalApplicationData, @"CentBrowser\User Data")
                },
                {
                    "Chedot",
                    Path.Combine(LocalApplicationData, @"Chedot\User Data")
                },
                {
                    "CocCoc",
                    Path.Combine(LocalApplicationData, @"CocCoc\Browser\User Data")
                },
                {
                    "Elements Browser",
                    Path.Combine(LocalApplicationData, @"Elements Browser\User Data")
                },
                {
                    "Epic Privacy Browser",
                    Path.Combine(LocalApplicationData, @"Epic Privacy Browser\User Data")
                },
                {
                    "Kometa",
                    Path.Combine(LocalApplicationData, @"Kometa\User Data")
                },
                {
                    "Orbitum",
                    Path.Combine(LocalApplicationData, @"Orbitum\User Data")
                },
                {
                    "Sputnik",
                    Path.Combine(LocalApplicationData, @"Sputnik\Sputnik\User Data")
                },
                {
                    "uCozMedia",
                    Path.Combine(LocalApplicationData, @"uCozMedia\Uran\User Data")
                },
                {
                    "Vivaldi",
                    Path.Combine(LocalApplicationData, @"Vivaldi\User Data")
                },
                {
                    "Sleipnir 6",
                    Path.Combine(ApplicationData, @"Fenrir Inc\Sleipnir5\setting\modules\ChromiumViewer")
                },
                {
                    "Citrio",
                    Path.Combine(LocalApplicationData, @"CatalinaGroup\Citrio\User Data")
                },
                {
                    "Coowon",
                    Path.Combine(LocalApplicationData, @"Coowon\Coowon\User Data")
                },
                {
                    "Liebao Browser",
                    Path.Combine(LocalApplicationData, @"liebao\User Data")
                },
                {
                    "QIP Surf",
                    Path.Combine(LocalApplicationData, @"QIP Surf\User Data")
                },
                {
                    "Edge Chromium",
                    Path.Combine(LocalApplicationData, @"Microsoft\Edge\User Data")
                }
            };

            var list = new List<Account>();

            foreach (var item in ChromiumPaths)
                list.AddRange(Accounts(item.Value, item.Key));

            return list;
        }

19 Source : GmicPipeServer.cs
with GNU General Public License v3.0
from 0xC0000054

public void AddLayers(IEnumerable<GmicLayer> collection)
        {
            VerifyNotDisposed();

            layers.AddRange(collection);
        }

19 Source : ConsulServiceDiscovery.cs
with MIT License
from 1100100

public async Task NodeMonitor(CancellationToken cancellationToken)
        {
            Logger.LogTrace("Start refresh service status,waiting for locking...");
            using (await AsyncLock.LockAsync(cancellationToken))
            {
                if (cancellationToken.IsCancellationRequested)
                    return;

                foreach (var service in ServiceNodes)
                {
                    Logger.LogTrace($"Service {service.Key} refreshing...");
                    try
                    {
                        var healthNodes = await QueryServiceAsync(service.Key, cancellationToken);
                        if (cancellationToken.IsCancellationRequested)
                            break;

                        var leavedNodes = service.Value.Where(p => healthNodes.All(a => a.ServiceId != p.ServiceId))
                            .Select(p => p.ServiceId).ToArray();
                        if (leavedNodes.Any())
                        {
                            //RemoveNode(service.Key, leavedNodes);
                            if (!ServiceNodes.TryGetValue(service.Key, out var services)) return;
                            services.RemoveAll(p => leavedNodes.Any(n => n == p.ServiceId));
                            OnNodeLeave?.Invoke(service.Key, leavedNodes);
                            Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
                        }

                        var addedNodes = healthNodes.Where(p =>
                                service.Value.All(e => e.ServiceId != p.ServiceId)).Select(p =>
                                new ServiceNodeInfo(p.ServiceId, p.Address, p.Port, p.Weight, p.EnableTls, p.Meta))
                            .ToList();

                        if (addedNodes.Any())
                        {
                            //AddNode(service.Key, addedNodes);
                            if (ServiceNodes.TryGetValue(service.Key, out var services))
                                services.AddRange(addedNodes);
                            else
                                ServiceNodes.TryAdd(service.Key, addedNodes);

                            OnNodeJoin?.Invoke(service.Key, addedNodes);

                            Logger.LogTrace(
                                $"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }
                Logger.LogTrace("Complete refresh.");
            }
        }

19 Source : ServiceBuilder.cs
with MIT License
from 1100100

public async Task StartAsync(CancellationToken cancellationToken)
        {
            UraganoSettings.ClientGlobalInterceptors.Reverse();
            UraganoSettings.ServerGlobalInterceptors.Reverse();

            var enableClient = ServiceProvider.GetService<ILoadBalancing>() != null;
            var enableServer = UraganoSettings.ServerSettings != null;

            var types = ReflectHelper.GetDependencyTypes();
            var services = types.Where(t => t.IsInterface && typeof(IService).IsreplacedignableFrom(t)).Select(@interface => new
            {
                Interface = @interface,
                Implementation = types.FirstOrDefault(p => p.IsClreplaced && p.IsPublic && !p.IsAbstract && !p.Name.EndsWith("_____UraganoClientProxy") && @interface.IsreplacedignableFrom(p))
            }).ToList();

            foreach (var service in services)
            {
                var imp = service.Implementation;

                var routeAttr = service.Interface.GetCustomAttribute<ServiceRouteAttribute>();
                var routePrefix = routeAttr == null ? $"{service.Interface.Namespace}/{service.Interface.Name}" : routeAttr.Route;


                var interfaceMethods = service.Interface.GetMethods();

                List<MethodInfo> implementationMethods = null;
                if (enableServer && imp != null)
                    implementationMethods = imp.GetMethods().ToList();

                var disableClientIntercept = service.Interface.GetCustomAttribute<NonInterceptAttribute>(true) != null;
                var clientClreplacedInterceptors = new List<Type>();
                if (!disableClientIntercept)
                    clientClreplacedInterceptors = service.Interface.GetCustomAttributes(true).Where(p => p is IInterceptor)
                    .Select(p => p.GetType()).ToList();

                var serverClreplacedInterceptors = new List<Type>();
                var disableServerIntercept = false;
                if (enableServer && imp != null)
                {
                    disableServerIntercept = imp.GetCustomAttribute<NonInterceptAttribute>(true) != null;
                    if (!disableServerIntercept)
                        serverClreplacedInterceptors = imp.GetCustomAttributes(true).Where(p => p is IInterceptor)
                            .Select(p => p.GetType()).ToList();
                }

                foreach (var interfaceMethod in interfaceMethods)
                {
                    MethodInfo serverMethod = null;
                    var idAttr = interfaceMethod.GetCustomAttribute<ServiceRouteAttribute>();
                    var route = idAttr == null ? $"{routePrefix}/{interfaceMethod.Name}" : $"{routePrefix}/{idAttr.Route}";

                    var clientInterceptors = new List<Type>();
                    if (enableClient && !disableClientIntercept && interfaceMethod.GetCustomAttribute<NonInterceptAttribute>(true) == null)
                    {
                        clientInterceptors.AddRange(UraganoSettings.ClientGlobalInterceptors);
                        clientInterceptors.AddRange(clientClreplacedInterceptors);
                        clientInterceptors.AddRange(interfaceMethod.GetCustomAttributes(true)
                            .Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
                        clientInterceptors.Reverse();
                    }


                    var serverInterceptors = new List<Type>();
                    if (enableServer && imp != null)
                    {
                        serverMethod = implementationMethods.First(p => IsImplementationMethod(interfaceMethod, p));
                        if (!disableServerIntercept && serverMethod?.GetCustomAttribute<NonInterceptAttribute>(true) == null)
                        {
                            serverInterceptors.AddRange(UraganoSettings.ServerGlobalInterceptors);
                            serverInterceptors.AddRange(serverClreplacedInterceptors.ToList());
                            if (serverMethod != null)
                                serverInterceptors.AddRange(serverMethod.GetCustomAttributes(true)
                                    .Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
                            serverInterceptors.Reverse();
                        }
                    }

                    ServiceFactory.Create(route, serverMethod, interfaceMethod, serverInterceptors, clientInterceptors);
                }
            }

            await Task.CompletedTask;
        }

19 Source : ServiceBuilder.cs
with MIT License
from 1100100

public async Task StartAsync(CancellationToken cancellationToken)
        {
            UraganoSettings.ClientGlobalInterceptors.Reverse();
            UraganoSettings.ServerGlobalInterceptors.Reverse();

            var enableClient = ServiceProvider.GetService<ILoadBalancing>() != null;
            var enableServer = UraganoSettings.ServerSettings != null;

            var types = ReflectHelper.GetDependencyTypes();
            var services = types.Where(t => t.IsInterface && typeof(IService).IsreplacedignableFrom(t)).Select(@interface => new
            {
                Interface = @interface,
                Implementation = types.FirstOrDefault(p => p.IsClreplaced && p.IsPublic && !p.IsAbstract && !p.Name.EndsWith("_____UraganoClientProxy") && @interface.IsreplacedignableFrom(p))
            }).ToList();

            foreach (var service in services)
            {
                var imp = service.Implementation;

                var routeAttr = service.Interface.GetCustomAttribute<ServiceRouteAttribute>();
                var routePrefix = routeAttr == null ? $"{service.Interface.Namespace}/{service.Interface.Name}" : routeAttr.Route;


                var interfaceMethods = service.Interface.GetMethods();

                List<MethodInfo> implementationMethods = null;
                if (enableServer && imp != null)
                    implementationMethods = imp.GetMethods().ToList();

                var disableClientIntercept = service.Interface.GetCustomAttribute<NonInterceptAttribute>(true) != null;
                var clientClreplacedInterceptors = new List<Type>();
                if (!disableClientIntercept)
                    clientClreplacedInterceptors = service.Interface.GetCustomAttributes(true).Where(p => p is IInterceptor)
                    .Select(p => p.GetType()).ToList();

                var serverClreplacedInterceptors = new List<Type>();
                var disableServerIntercept = false;
                if (enableServer && imp != null)
                {
                    disableServerIntercept = imp.GetCustomAttribute<NonInterceptAttribute>(true) != null;
                    if (!disableServerIntercept)
                        serverClreplacedInterceptors = imp.GetCustomAttributes(true).Where(p => p is IInterceptor)
                            .Select(p => p.GetType()).ToList();
                }

                foreach (var interfaceMethod in interfaceMethods)
                {
                    MethodInfo serverMethod = null;
                    var idAttr = interfaceMethod.GetCustomAttribute<ServiceRouteAttribute>();
                    var route = idAttr == null ? $"{routePrefix}/{interfaceMethod.Name}" : $"{routePrefix}/{idAttr.Route}";

                    var clientInterceptors = new List<Type>();
                    if (enableClient && !disableClientIntercept && interfaceMethod.GetCustomAttribute<NonInterceptAttribute>(true) == null)
                    {
                        clientInterceptors.AddRange(UraganoSettings.ClientGlobalInterceptors);
                        clientInterceptors.AddRange(clientClreplacedInterceptors);
                        clientInterceptors.AddRange(interfaceMethod.GetCustomAttributes(true)
                            .Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
                        clientInterceptors.Reverse();
                    }


                    var serverInterceptors = new List<Type>();
                    if (enableServer && imp != null)
                    {
                        serverMethod = implementationMethods.First(p => IsImplementationMethod(interfaceMethod, p));
                        if (!disableServerIntercept && serverMethod?.GetCustomAttribute<NonInterceptAttribute>(true) == null)
                        {
                            serverInterceptors.AddRange(UraganoSettings.ServerGlobalInterceptors);
                            serverInterceptors.AddRange(serverClreplacedInterceptors.ToList());
                            if (serverMethod != null)
                                serverInterceptors.AddRange(serverMethod.GetCustomAttributes(true)
                                    .Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
                            serverInterceptors.Reverse();
                        }
                    }

                    ServiceFactory.Create(route, serverMethod, interfaceMethod, serverInterceptors, clientInterceptors);
                }
            }

            await Task.CompletedTask;
        }

19 Source : ZooKeeperServiceDiscovery.cs
with MIT License
from 1100100

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

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

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

19 Source : IsoHeaderParser.cs
with MIT License
from 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 Source : Program.cs
with MIT License
from 13xforever

internal static async Task Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
                    var isFirstChar = true;
                    var completedPath = false;
                    var path = new StringBuilder();
                    do
                    {
                        var keyInfo = Console.ReadKey(true);
                        if (isFirstChar)
                        {
                            isFirstChar = false;
                            if (keyInfo.KeyChar != '"')
                                return;
                        }
                        else
                        {
                            if (keyInfo.KeyChar == '"')
                            {
                                completedPath = true;
                                args = new[] {path.ToString()};
                            }
                            else
                                path.Append(keyInfo.KeyChar);
                        }
                    } while (!completedPath);
                    Console.Clear();
                }

                Console.OutputEncoding = new UTF8Encoding(false);
                Console.replacedle = replacedle;
                Console.CursorVisible = false;
                Console.WriteLine("Scanning for PKGs...");
                var pkgList = new List<FileInfo>();
                Console.ForegroundColor = ConsoleColor.Yellow;
                foreach (var item in args)
                {
                    var path = item.Trim('"');
                    if (File.Exists(path))
                        pkgList.Add(new FileInfo(path));
                    else if (Directory.Exists(path))
                        pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
                    else
                        Console.WriteLine("Unknown path: " + path);
                }
                Console.ResetColor();
                if (pkgList.Count == 0)
                {
                    Console.WriteLine("No packages were found. Check paths, and try again.");
                    return;
                }

                var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
                var sigWidth = Math.Max(HeaderSignature.Length, 8);
                var csumWidth = Math.Max(HeaderChecksum.Length, 5);
                var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
                var idealWidth = longestFilename + csumsWidth;
                try
                {
                    if (idealWidth > Console.LargestWindowWidth)
                    {
                        longestFilename = Console.LargestWindowWidth - csumsWidth;
                        idealWidth = Console.LargestWindowWidth;
                    }
                    if (idealWidth > Console.WindowWidth)
                    {
                        Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
                        Console.WindowWidth = idealWidth;
                    }
                    Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
                }
                catch (PlatformNotSupportedException) { }
                Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
                using var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
                var t = new Thread(() =>
                                   {
                                       try
                                       {
                                           var indicatorIdx = 0;
                                           while (!cts.Token.IsCancellationRequested)
                                           {
                                               Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                                               if (cts.Token.IsCancellationRequested)
                                                   return;

                                               PkgChecker.Sync.Wait(cts.Token);
                                               try
                                               {
                                                   var frame = Animation[(indicatorIdx++) % Animation.Length];
                                                   var currentProgress = PkgChecker.CurrentFileProcessedBytes;
                                                   Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
                                                   if (PkgChecker.CurrentPadding > 0)
                                                   {
                                                       Console.CursorVisible = false;
                                                       var (top, left) = (Console.CursorTop, Console.CursorLeft);
                                                       Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
                                                       Console.CursorTop = top;
                                                       Console.CursorLeft = left;
                                                       Console.CursorVisible = false;
                                                   }
                                               }
                                               finally
                                               {
                                                   PkgChecker.Sync.Release();
                                               }
                                           }
                                       }
                                       catch (TaskCanceledException)
                                       {
                                       }
                                   });
                t.Start();
                await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
                cts.Cancel(false);
                t.Join();
            }
            finally
            {
                Console.replacedle = replacedle;
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                Console.WriteLine();
                Console.CursorVisible = true;
            }
        }

19 Source : DbContext.cs
with Apache License 2.0
from 1448376744

private void Initialize(IDbCommand cmd, string sql, object parameter, int? commandTimeout = null, CommandType? commandType = null)
        {
            var dbParameters = new List<IDbDataParameter>();
            cmd.Transaction = _transaction;
            cmd.CommandText = sql;
            if (commandTimeout.HasValue)
            {
                cmd.CommandTimeout = commandTimeout.Value;
            }
            if (commandType.HasValue)
            {
                cmd.CommandType = commandType.Value;
            }
            if (parameter is IDbDataParameter)
            {
                dbParameters.Add(parameter as IDbDataParameter);
            }
            else if (parameter is IEnumerable<IDbDataParameter> parameters)
            {
                dbParameters.AddRange(parameters);
            }
            else if (parameter is Dictionary<string, object> keyValues)
            {
                foreach (var item in keyValues)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            else if (parameter != null)
            {
                var handler = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(parameter.GetType());
                var values = handler(parameter);
                foreach (var item in values)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            if (dbParameters.Count > 0)
            {
                foreach (IDataParameter item in dbParameters)
                {
                    if (item.Value == null)
                    {
                        item.Value = DBNull.Value;
                    }
                    var pattern = $@"in\s+([\@,\:,\?]?{item.ParameterName})";
                    var options = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline;
                    if (cmd.CommandText.IndexOf("in", StringComparison.OrdinalIgnoreCase) != -1 && Regex.IsMatch(cmd.CommandText, pattern, options))
                    {
                        var name = Regex.Match(cmd.CommandText, pattern, options).Groups[1].Value;
                        var list = new List<object>();
                        if (item.Value is IEnumerable<object> || item.Value is Array)
                        {
                            list = (item.Value as IEnumerable).Cast<object>().Where(a => a != null && a != DBNull.Value).ToList();
                        }
                        else
                        {
                            list.Add(item.Value);
                        }
                        if (list.Count() > 0)
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"({string.Join(",", list.Select(s => $"{name}{list.IndexOf(s)}"))})");
                            foreach (var iitem in list)
                            {
                                var key = $"{item.ParameterName}{list.IndexOf(iitem)}";
                                var param = CreateParameter(cmd, key, iitem);
                                cmd.Parameters.Add(param);
                            }
                        }
                        else
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"(SELECT 1 WHERE 1 = 0)");
                        }
                    }
                    else
                    {
                        cmd.Parameters.Add(item);
                    }
                }
            }
            if (Logging != null)
            {
                var parameters = new Dictionary<string, object>();
                foreach (IDbDataParameter item in cmd.Parameters)
                {
                    parameters.Add(item.ParameterName, item.Value);
                }
                Logging.Invoke(cmd.CommandText, parameters, commandTimeout, commandType);
            }
        }

19 Source : Inline_Hook.cs
with Apache License 2.0
from 1694439208

public static IntPtr InlineHook(int HookAddress, int Hooklen,
            byte[] HookBytes0,int Callback,int CallbackOffset,
            bool IsFront,int CallAddress,string name, Action<Methods.Register> func)
        {
            WeChetHook.DllcallBack dllcallBack = new WeChetHook.DllcallBack((de1, de2, ECX1, EAX1, EDX1, EBX1, ESP1, EBP1, ESI1, EDI1) => {
                func(new Register
                {
                    EAX = EAX1,
                    EBP = EBP1,
                    EBX = EBX1,
                    ECX = ECX1,
                    EDI = EDI1,
                    EDX = EDX1,
                    ESI = ESI1,
                    ESP = ESP1
                });
            });
            int CallHandle = ComputeHash(name);
            Methods.callBacks.Add(CallHandle, dllcallBack);

            List<byte> byteSource1 = new List<byte>();
            byteSource1.AddRange(new byte[] { 199, 134, 240, 2, 0, 0 });
            byteSource1.AddRange(BitConverter.GetBytes(CallHandle));
            byteSource1.AddRange(HookBytes0);

            byte[] hookbytes = byteSource1.ToArray();


            List<byte> byteSource = new List<byte>();
            IntPtr ptr = NativeAPI.VirtualAlloc(0, 128, 4096, 64);
            if (IsFront)
            {
                NativeAPI.WriteProcessMemory(-1, ptr, Add(new byte[] { 232 }, Inline_GetBuf(ptr, CallAddress)), 5, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + 5, hookbytes, hookbytes.Length, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + 5 + CallbackOffset, Inline_GetBuf(ptr + 5 + CallbackOffset - 1, Callback), 4, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + 5 + hookbytes.Length, Add(new byte[] { 233 }, Inline_GetBuf(ptr + 5 + HookBytes0.Length, HookAddress + Hooklen)), 5, 0);
            }
            else {
                NativeAPI.WriteProcessMemory(-1, ptr, hookbytes, hookbytes.Length, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + CallbackOffset, Inline_GetBuf(ptr + CallbackOffset - 1, Callback), 4, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + hookbytes.Length,Add(new byte[] { 232 },Inline_GetBuf(ptr + hookbytes.Length, CallAddress)), Hooklen, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + Hooklen + hookbytes.Length, Add(new byte[] { 233 }, Inline_GetBuf(ptr + Hooklen + HookBytes0.Length, HookAddress + Hooklen)), 5, 0);
            }
            NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress), Add(new byte[] { 233 }, Inline_GetBuf(HookAddress, ptr.ToInt32())), 5, 0);
            for (int i = 0; i < Hooklen - 5; i++)
            {
                byteSource.Add(144);
            }
            byte[] ByteFill = byteSource.ToArray();
            NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress + 5), ByteFill, ByteFill.Length, 0);
            return ptr;
        }

19 Source : Inline_Hook.cs
with Apache License 2.0
from 1694439208

public static IntPtr InlineHook(int HookAddress, int Hooklen,
            byte[] HookBytes0, int Callback, int CallbackOffset,string name, Action<Methods.Register> func)
        {

            WeChetHook.DllcallBack dllcallBack = new WeChetHook.DllcallBack((de1, de2, ECX1, EAX1, EDX1, EBX1, ESP1, EBP1, ESI1, EDI1) => {
                //int ECX, int EAX, int EDX, int EBX, int ESP, int EBP, int ESI, int EDI
                func(new Register
                {
                    EAX = EAX1,
                    EBP = EBP1,
                    EBX = EBX1,
                    ECX = ECX1,
                    EDI = EDI1,
                    EDX = EDX1,
                    ESI = ESI1,
                    ESP = ESP1
                });
            });
            int CallHandle = ComputeHash(name);
            System.Windows.Forms.MessageBox.Show("CallHandle:" + CallHandle.ToString());
            Methods.callBacks.Add(CallHandle, dllcallBack);

            List<byte> byteSource1 = new List<byte>();
            byteSource1.AddRange(new byte[] { 199, 134, 240, 2, 0, 0 });
            byteSource1.AddRange(BitConverter.GetBytes(CallHandle));//把标识指针绑定到寄存器我觉得不靠谱但是目前没啥问题
            byteSource1.AddRange(HookBytes0);

            byte[] hookbytes = byteSource1.ToArray();


            List<byte> byteSource = new List<byte>();
            IntPtr ptr = NativeAPI.VirtualAlloc(0, 128, 4096, 64);
            NativeAPI.WriteProcessMemory(-1, ptr, hookbytes, hookbytes.Length, 0);
            NativeAPI.WriteProcessMemory(-1, ptr + CallbackOffset, Inline_GetBuf(ptr + CallbackOffset - 1, Callback), 4, 0);
            NativeAPI.WriteProcessMemory(-1, ptr + hookbytes.Length, Add(new byte[] { 233 }, Inline_GetBuf(ptr + hookbytes.Length, HookAddress+ Hooklen)), 5, 0);

            NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress), Add(new byte[] { 233 }, Inline_GetBuf(HookAddress, ptr.ToInt32())), 5, 0);
            for (int i = 0; i < Hooklen - 5; i++)
            {
                byteSource.Add(144);
            }
            byte[] ByteFill = byteSource.ToArray();
            NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress + 5), ByteFill, ByteFill.Length, 0);
            return ptr;
        }

19 Source : QueryBody.cs
with MIT License
from 17MKH

public QueryBody Copy()
    {
        var copy = new QueryBody(Repository)
        {
            Repository = Repository,
            FilterDeleted = FilterDeleted,
            FilterTenant = FilterTenant,
            GroupBy = GroupBy,
            Skip = Skip,
            Take = Take
        };

        copy.Joins.AddRange(Joins);

        if (Wheres != null)
        {
            copy.Wheres = new List<QueryWhere>();
            copy.Wheres.AddRange(Wheres);
        }

        if (Sorts != null)
        {
            copy.Sorts = new List<QuerySort>();
            copy.Sorts.AddRange(Sorts);
        }

        if (Update != null)
        {
            copy.Update = new QueryUpdate { Lambda = Update.Lambda, Sql = Update.Sql, Mode = Update.Mode };
        }

        if (Select != null)
        {
            copy.Select = new QuerySelect
            {
                Sql = Select.Sql,
                FunctionName = Select.FunctionName,
                Exclude = Select.Exclude,
                FunctionExpression = Select.FunctionExpression,
                Include = Select.Include,
                Mode = Select.Mode
            };
        }

        if (Havings != null)
        {
            copy.Havings = new List<QueryHaving>();
            copy.Havings.AddRange(Havings);
        }

        return copy;
    }

19 Source : TypeUtils.cs
with MIT License
from 1996v

public static List<MemberInfo> GetAllInterfaceMembers(this Type type)
        {
            Stack<Type> pending = new Stack<Type>();
            pending.Push(type);
            List<MemberInfo> ret = new List<MemberInfo>();
            while (pending.Count > 0)
            {
                Type current = pending.Pop();

                ret.AddRange(current.GetMembers());

                if (current.BaseType != null)
                {
                    pending.Push(current.BaseType);
                }

                foreach (Type x in current.GetInterfaces())
                {
                    pending.Push(x);
                }
            }
            return ret;
        }

19 Source : Form1.cs
with Apache License 2.0
from 1694439208

private void button5_Click(object sender, EventArgs e)
        {
            byte[] jmp_inst =
            {
                233,0,0,0,0,//JMP Address
            };
            int Method = NativeAPI.GetMethodPTR(typeof(WeChetHook), "Callback");
            textBox3.Text = (3212659 + int.Parse(label1.Text)).ToString();

            List<byte> byteSource = new List<byte>();
            byteSource.AddRange(new byte[] { 199, 134, 236, 2, 0, 0 });//mov dword [esi+0x000002EC],
            byteSource.AddRange(BitConverter.GetBytes(int.Parse(textBox3.Text) + 5));//0x00000000  把hook的后五个字节地址压进寄存器
            byteSource.AddRange(jmp_inst);//让他跳到跳板函数
            //这部分根据实际情况填写
            byteSource.Add(185);//补充替换的汇编指令
            byteSource.AddRange(BitConverter.GetBytes(int.Parse(label1.Text) + 19255272));//补充替换的汇编指令地址
            //开始hook
            Inline_Hook.InlineHook(int.Parse(textBox3.Text),5, byteSource.ToArray(), getInt(Method),11+10,"接收消息",(obj) =>{
                StringBuilder sb = new StringBuilder();
                sb.Append("接收消息:");
                int a = 0x68;
                //System.Windows.Forms.MessageBox.Show("esp:"+a.ToString());
                try
                {
                    if (obj.ESP == 0)
                        return;
                    int MsgPtr = NativeAPI.ReadMemoryValue(obj.ESP);
                    if (MsgPtr == 0)
                        return;
                    MsgPtr = NativeAPI.ReadMemoryValue(MsgPtr);
                    if (MsgPtr == 0)
                        return;
                    MsgPtr = NativeAPI.ReadMemoryValue(MsgPtr + 0x68);
                    if (MsgPtr == 0)
                        return;
                    int len = NativeAPI.lstrlenW(MsgPtr);
                    if (len == 0)
                        return;
                    sb.Append(NativeAPI.ReadMemoryStrValue(MsgPtr, len*2+2));
                    sb.Append("\r\n");
                    listBox1.Items.Add(sb.ToString());
                }
                catch (Exception es)
                {
                    File.AppendAllText("error.txt", es.Message);
                }
            });
        }

19 Source : NetworkUtils.cs
with MIT License
from 1ZouLTReX1

public static void SerializeInt(List<byte> byteList, int data)
    {
        byteList.AddRange(BitConverter.GetBytes(data));
    }

19 Source : NetworkUtils.cs
with MIT License
from 1ZouLTReX1

public static void SerializeLong(List<byte> byteList, long data)
    {
        byteList.AddRange(BitConverter.GetBytes(data));
    }

19 Source : NetworkUtils.cs
with MIT License
from 1ZouLTReX1

public static void SerializeFloat(List<byte> byteList, float data)
    {
        byteList.AddRange(BitConverter.GetBytes(data));
    }

19 Source : NetworkUtils.cs
with MIT License
from 1ZouLTReX1

public static void SerializeVector2(List<byte> byteList, Vector2 data)
    {
        byteList.AddRange(BitConverter.GetBytes(data.x));
        byteList.AddRange(BitConverter.GetBytes(data.y));
    }

19 Source : NetworkUtils.cs
with MIT License
from 1ZouLTReX1

public static void SerializeVector3(List<byte> byteList, Vector3 data)
    {
        byteList.AddRange(BitConverter.GetBytes(data.x));
        byteList.AddRange(BitConverter.GetBytes(data.y));
        byteList.AddRange(BitConverter.GetBytes(data.z));
    }

19 Source : Player.cs
with MIT License
from 1ZouLTReX1

public void CacheClientInput(ClientInput ci)
    {
        lock (userCommandBufferList)
        {
            userCommandBufferList.AddRange(ServerUserCommand.CreaetUserCommands(this, ci));
        }
    }

19 Source : Player.cs
with MIT License
from 1ZouLTReX1

public void MergeWithBuffer()
    {
        lock (userCommandBufferList)
        {
            // TODO work out why some User Commands are null 
            // it works for now tho
            for (int i = userCommandBufferList.Count - 1; i >= 0; i--)
            {
                if (userCommandBufferList[i] == null)
                {
                    userCommandBufferList.RemoveAt(i);
                }
                else
                {
                    jitter.Update(userCommandBufferList[i].serverRecTime - lastRecTime);
                    lastRecTime = userCommandBufferList[i].serverRecTime;
                }
            }

            userCommandList.AddRange(userCommandBufferList);
            userCommandBufferList.Clear();
        }
            
        userCommandList.Sort((a, b) => a.serverRecTime.CompareTo(b.serverRecTime));

        // DEBUG Jitter
        //Debug.Log(jitter.stdDeviation + ", " + jitter.average);
    }

19 Source : NetworkUtils.cs
with MIT License
from 1ZouLTReX1

public static void SerializeUshort(List<byte> byteList, ushort data)
    {
        byteList.AddRange(BitConverter.GetBytes(data));
    }

19 Source : UnityThread.cs
with MIT License
from 1ZouLTReX1

public void Update()
    {
        if (noActionQueueToExecuteUpdateFunc)
        {
            return;
        }

        //Clear the old actions from the actionCopiedQueueUpdateFunc queue
        actionCopiedQueueUpdateFunc.Clear();
        lock (actionQueuesUpdateFunc)
        {
            //Copy actionQueuesUpdateFunc to the actionCopiedQueueUpdateFunc variable
            actionCopiedQueueUpdateFunc.AddRange(actionQueuesUpdateFunc);
            //Now clear the actionQueuesUpdateFunc since we've done copying it
            actionQueuesUpdateFunc.Clear();
            noActionQueueToExecuteUpdateFunc = true;
        }

        // Loop and execute the functions from the actionCopiedQueueUpdateFunc
        for (int i = 0; i < actionCopiedQueueUpdateFunc.Count; i++)
        {
            actionCopiedQueueUpdateFunc[i].Invoke();
        }
    }

19 Source : UnityThread.cs
with MIT License
from 1ZouLTReX1

public void LateUpdate()
    {
        if (noActionQueueToExecuteLateUpdateFunc)
        {
            return;
        }

        //Clear the old actions from the actionCopiedQueueLateUpdateFunc queue
        actionCopiedQueueLateUpdateFunc.Clear();
        lock (actionQueuesLateUpdateFunc)
        {
            //Copy actionQueuesLateUpdateFunc to the actionCopiedQueueLateUpdateFunc variable
            actionCopiedQueueLateUpdateFunc.AddRange(actionQueuesLateUpdateFunc);
            //Now clear the actionQueuesLateUpdateFunc since we've done copying it
            actionQueuesLateUpdateFunc.Clear();
            noActionQueueToExecuteLateUpdateFunc = true;
        }

        // Loop and execute the functions from the actionCopiedQueueLateUpdateFunc
        for (int i = 0; i < actionCopiedQueueLateUpdateFunc.Count; i++)
        {
            actionCopiedQueueLateUpdateFunc[i].Invoke();
        }
    }

19 Source : UnityThread.cs
with MIT License
from 1ZouLTReX1

public void FixedUpdate()
    {
        if (noActionQueueToExecuteFixedUpdateFunc)
        {
            return;
        }

        //Clear the old actions from the actionCopiedQueueFixedUpdateFunc queue
        actionCopiedQueueFixedUpdateFunc.Clear();
        lock (actionQueuesFixedUpdateFunc)
        {
            //Copy actionQueuesFixedUpdateFunc to the actionCopiedQueueFixedUpdateFunc variable
            actionCopiedQueueFixedUpdateFunc.AddRange(actionQueuesFixedUpdateFunc);
            //Now clear the actionQueuesFixedUpdateFunc since we've done copying it
            actionQueuesFixedUpdateFunc.Clear();
            noActionQueueToExecuteFixedUpdateFunc = true;
        }

        // Loop and execute the functions from the actionCopiedQueueFixedUpdateFunc
        for (int i = 0; i < actionCopiedQueueFixedUpdateFunc.Count; i++)
        {
            actionCopiedQueueFixedUpdateFunc[i].Invoke();
        }
    }

19 Source : NetworkUtils.cs
with MIT License
from 1ZouLTReX1

public static void SerializeBool(List<byte> byteList, bool data)
    {
        byteList.AddRange(BitConverter.GetBytes(data));
    }

19 Source : RedisArgs.cs
with MIT License
from 2881099

public static object[] GetTupleArgs<replacedem1, replacedem2>(Tuple<replacedem1, replacedem2>[] tuples)
        {
            List<object> args = new List<object>();
            foreach (var kvp in tuples)
                args.AddRange(new object[] { kvp.Item1, kvp.Item2 });

            return args.ToArray();
        }

19 Source : LandLord.cs
with Apache License 2.0
from 2881099

public static List<int> GetTipList(List<int> _shoupai, List<int> _lastPaiArr)
        {
            //剩余牌的数量小于  只能用炸了  //等于上手出牌的数量     //剩余牌的数量大于上手出牌的数量
            List<int> _tiplist = new List<int>();
            LordPokerSplitHelper _splitHelper = new LordPokerSplitHelper();
            _splitHelper.Split(_shoupai);
            if (_lastPaiArr.Count == 0)
            {//没有上家牌,直接按AI规则出牌
                //最大牌型,考虑春天 再最多牌数
                if (_splitHelper._straight.Count != 0)
                {
                    _tiplist = _splitHelper._straight[0];
                }
                else if (_splitHelper._linkerPair.Count != 0)
                {
                    _tiplist = _splitHelper._linkerPair[0];
                    if (_tiplist.Count != 0) _tiplist.AddRange(_tiplist);
                }
                else if (_splitHelper._planeWith.Count != 0)
                {
                    List<int> _planeList = _splitHelper._planeWith[0];
                    List<int> _existoneList = new List<int>();
                    foreach (int _plane in _planeList)
                    {
                        _tiplist.Add(_plane);
                        _tiplist.Add(_plane);
                        _tiplist.Add(_plane);
                        int _tempwithone = _splitHelper.GetSingleToPlaneWith(_planeList, _existoneList);
                        if (_tempwithone != -1)
                        {
                            _tiplist.Add(_tempwithone);
                            _existoneList.Add(_tempwithone);
                        }
                    }
                    if (_tiplist.Count != _planeList.Count * 4) _tiplist = new List<int>();//重置========可能会出现全三带没的带的情况而可以把3张拆成
                }
                else if (_splitHelper._double.Count != 0)
                {
                    int _double = _splitHelper._double[_splitHelper._double.Count - 1];
                    _tiplist.Add(_double);
                    _tiplist.Add(_double);
                }
                ////else if (_splitHelper._bomb22.Count != 0)
                ////{
                ////    _tiplist.Add(_splitHelper._bomb22[0]);
                ////    _tiplist.Add(_splitHelper._bomb22[0]);
                ////}
                ////else if (_splitHelper._bomb33.Count != 0)
                ////{
                ////    _tiplist.Add(_splitHelper._bomb33[0]);
                ////    _tiplist.Add(_splitHelper._bomb33[0]);
                ////}
                else if (_splitHelper._bomb4List.Count != 0)
                {
                    int _bomb = _splitHelper._bomb4List[_splitHelper._bomb4List.Count - 1];
                    _tiplist.Add(_bomb);
                    _tiplist.Add(_bomb);
                    _tiplist.Add(_bomb);
                    _tiplist.Add(_bomb);
                }
                else if (_splitHelper._doubleKing.Count != 0)
                {
                    _tiplist.AddRange(_splitHelper._doubleKing);
                }
                else
                {
                    _tiplist.Add(_splitHelper._single[_splitHelper._single.Count - 1]);
                }
                _tiplist = GetPaiColor(_shoupai, _tiplist);
                return _tiplist;
            }
            List<int> _templastPoker = OrderPaiLord(_lastPaiArr);
            LordPokerTypeEnum _lordtype = GetLordType(_templastPoker);
            switch (_lordtype)
            {
                case LordPokerTypeEnum.DoubleKing_2: return new List<int>();//如果上手出了王炸,直接要不起 
                case LordPokerTypeEnum.Bomb_4:
                    _tiplist = UseBomb(_splitHelper, _templastPoker[0]);
                    if (_tiplist.Count != 0) _tiplist = GetPaiColor(_shoupai, _tiplist);
                    return _tiplist;

                case LordPokerTypeEnum.Single_1:// 单张           
                    _tiplist = GetSingleBig(_templastPoker, _splitHelper);
                    break;
                case LordPokerTypeEnum.Double_2:
                    _tiplist = GetDoubleBig(_templastPoker, _splitHelper);
                    break;
                case LordPokerTypeEnum.Three_3:
                    _tiplist = GetThreeBig(_templastPoker, _splitHelper);
                    break;
                case LordPokerTypeEnum.PlaneWing1_4:
                case LordPokerTypeEnum.PlaneWing2_8:
                case LordPokerTypeEnum.PlaneWing3_12:
                case LordPokerTypeEnum.PlaneWing4_16:
                case LordPokerTypeEnum.PlaneWing5_20:
                    _tiplist = GetPlaneBig(_templastPoker, _splitHelper);
                    break;
                case LordPokerTypeEnum.Straight5_5:
                case LordPokerTypeEnum.Straight6_6:
                case LordPokerTypeEnum.Straight7_7:
                case LordPokerTypeEnum.Straight8_8:
                case LordPokerTypeEnum.Straight9_9:
                case LordPokerTypeEnum.Straight10_10:
                case LordPokerTypeEnum.Straight11_11:
                case LordPokerTypeEnum.Straight12_12:
                    _tiplist = GetStraightBig(_templastPoker, _splitHelper);
                    break;
                case LordPokerTypeEnum.LinkPair3_6:
                case LordPokerTypeEnum.LinkPair4_8:
                case LordPokerTypeEnum.LinkPair5_10:
                case LordPokerTypeEnum.LinkPair6_12:
                case LordPokerTypeEnum.LinkPair7_14:
                case LordPokerTypeEnum.LinkPair8_16:
                case LordPokerTypeEnum.LinkPair9_18:
                case LordPokerTypeEnum.LinkPair10_20:
                    _tiplist = GetLinkerPairBig(_templastPoker, _splitHelper);
                    break;
                case LordPokerTypeEnum.FourWithTwo_6:
                    _tiplist = GetFourWithTwoBig(_templastPoker, _splitHelper);
                    break;
                default:
                    TraceLogEx.Error(_lordtype + ":...............................lllllllllllllllllllllll");
                    break;
            }

            if (_tiplist.Count == 0)
            {
                _tiplist = UseBomb(_splitHelper, 0);
            }
            if (_tiplist.Count != 0) _tiplist = GetPaiColor(_shoupai, _tiplist);
            return _tiplist;
        }

19 Source : CentralServerConfigForm.cs
with Apache License 2.0
from 214175590

private List<string> getTreeNodeContent(TreeListViewItemCollection items)
        {
            List<string> list = new List<string>();
            string line = "";
            int level = 0;
            foreach (TreeListViewItem treeNode in items)
            {
                line = treeNode.Text;
                if (!line.TrimStart().StartsWith("#"))
                {
                    line += ": ";
                    level = Convert.ToInt32(treeNode.SubItems[2].Text);
                    line = YmlFormatUtil.GetSpace(level * 4) + line;
                    line += treeNode.SubItems[1].Text;
                    line += treeNode.SubItems[3].Text;                    
                }
                if (!string.IsNullOrWhiteSpace(line))
                {
                    list.Add(line);
                }
                list.AddRange(getTreeNodeContent(treeNode.Items));
            }
            return list;
        }

19 Source : YmlNodeForm.cs
with Apache License 2.0
from 214175590

private List<string> getParentText(TreeListViewItem node)
        {
            List<string> list = new List<string>();
            if(node != null){
                list.Add(node.Text);
                List<string> plist = getParentText(node.Parent);
                if (plist.Count > 0)
                {
                    list.AddRange(plist);
                }
            }
            return list;
        }

19 Source : LandLord.cs
with Apache License 2.0
from 2881099

private void Shuffle()
        {
            ALLPoker = new Queue<int>();
            List<int> arrPoker = new List<int>();
            arrPoker.AddRange(arrHeart);
            arrPoker.AddRange(arrSpade);
            arrPoker.AddRange(arrClub);
            arrPoker.AddRange(arrDiamond);
            arrPoker.AddRange(arrKing);
            ////TDisruptedHelper<int> _thelper = new TDisruptedHelper<int>(arrPoker.ToArray());
            ////arrPoker = _thelper.GetDisruptedItems().ToList();
            ////for (int i = 0; i < arrPoker.Count; i++)
            ////{
            ////    ALLPoker.Enqueue(arrPoker[i]);
            ////}
            //随机生成排序这x张牌
            ALLPoker = new Queue<int>(ToolsEx.DisrupteList(arrPoker));
            if (ALLPoker.Count != mNumALLPoker)
            {
                TraceLogEx.Error("201610212116ll ALLPoker.Count != mNumALLPoker 即扑克初始不正确");
            }
        }

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

public List<HandPokerComplieResult> replacedysisPlan1() {
			//组合牌型,当机器人是地主,主动出牌时,怎么出牌能收回,或者怎么扔小牌最小合理
			//组合牌型,当机器人是地主,被动出牌时,怎么压死牌最合理

			//组合牌型,当机器人上家是地主,主动出牌时,下家能顶什么牌,地主不要什么牌
			//组合牌型,当机器人上家是地主,被动出牌时

			//组合牌型,当机器人下家是地主,主动出牌时,如果牌不好,则防止出牌让地主拖牌,否则自己逃走
			//组合牌型,当机器人下家是地主,被动出牌时,怎么出牌不让地主拖牌

			var gb = Utils.GroupByPoker(this.pokers.ToArray()).OrderBy(a => a.key).ToList();

			var pks = new List<int>(this.pokers);
			var hands = new List<HandPokerComplieResult>();
			HandPokerComplieResult hand = null;
			var cards = this.GetOutsideCard(); //外面所有的牌
			var gbOutsize = Utils.GroupByPoker(cards.ToArray()).OrderBy(a => a.key).ToList();

			var gbjks = gb.Where(a => a.count == 1 && a.key == 16 || a.key == 17).ToArray(); //王炸作为一手牌
			if (gbjks.Length == 2) {
				hand = Utils.ComplierHandPoker(gbjks);
				hands.Add(hand);
				foreach (var v in hand.value) pks.Remove(v);
			}

			//var gb1 = gb.Where(a => a.count == 1 && a.key < 15).ToList(); //所有单张
			//var gb2 = gb.Where(a => a.count == 2 && a.key < 15).ToList(); //所有两张
			//var gb3 = gb.Where(a => a.count == 3 && a.key < 15).ToList(); //所有三张

			//var gbLow2 = new List<Utils.GroupByPokerResult>();
			//var gbTop2 = new List<Utils.GroupByPokerResult>();
			//var gbLow2Index = gb2.Count - 1;
			//for (var a = gb2.Count - 1; a >= 0; a--) {
			//	if (gbOutsize.Where(z => z.count >= 2).Any()) {
			//		gbLow2Index = a;
			//		break;
			//	}
			//	gbTop2.Add(gb2[a]);
			//}
			//gbTop2.Sort((x, y) => y.key.CompareTo(x.key));
			//for (var a = 0; a < gbLow2Index; a++) {
			//	gbLow2.Add(gb2[a]);
			//}


			//var gbLow1 = gb.Where(a => a.count == 1 && a.key < 10).ToArray(); //单张小牌,10以下
			//var gbLow2 = gb.Where(a => a.count == 2 && a.key < 8).ToArray(); //对子小牌,8以下
			//var gbMid1 = gb.Where(a => a.count == 1 && a.key >= 10 && a.key < 15).ToArray(); //单张中牌,10-A,可以穿牌
			//var gbMid2 = gb.Where(a => a.count == 2 && a.key >= 8 && a.key < 14).ToArray(); //对子小牌,8-K,可以穿牌

			//var gbHard1 = gb.Where(a => (a.count == 1 && a.key >= 10 && a.key < 15) || a.count < 4 && a.key >= 15).OrderBy(a => a.key).ToArray(); //单张硬牌,10以上
			//var gbHard2 = gb.Where(a => a.count == 2 && a.key >= 10).OrderBy(a => a.key).ToArray();
			//var gb1 = gb.Where(a => a.count == 1 && a.key < 15).OrderBy(a => a.key).ToArray(); //所有单张
			//var gb2 = gb.Where(a => a.count == 2 && a.key < 15).OrderBy(a => a.key).ToArray(); //所有两张
			//var gb3 = gb.Where(a => a.count == 3 && a.key < 15).OrderBy(a => a.key).ToArray(); //所有三张
			//var gb4 = gb.Where(a => a.count == 4).OrderBy(a => a.key).ToArray();
			//if (gb1.Length > 0) { //尝试组合三带一个
				
			//}

			//var gbseries = gb.Where(a => a.key < 15).OrderBy(a => a.key).ToArray();
			//var gbseriesStartIndex = 0;
			//for (var a = 0; a < gbseries.Length; a++) {
			//	var pkseries = new List<int>();
			//	pkseries.AddRange(gbseries[a].poker);
			//	for (var b = a + 1; b < gbseries.Length; b++) {
			//		//if (gbseries[b].count < gbseries[a].count)
			//		if (gbseries[b].key - a - 1 == gbseries[a].key) {

			//		}
			//	}
			//}
			//while (true) {
			//	bool isbreak = false;
			//	for (var a = gbseriesStartIndex + 1; a < gbseries.Length; a++) {
			//		if (gbseries[a].key - 1 == gbseries[a - 1].key && gbseries[a].count == gbseries[a - 1].count) {
			//			if (a == gbseries.Length - 1) {
			//				isbreak = true;
			//				break;
			//			}
			//			continue;
			//		}
			//		if (gbseries[a].count == 2 && a - gbseriesStartIndex >= 2) { //连对

			//		}
			//		if (gbseries[a].count == 1 && a - gbseriesStartIndex >= 4) { //顺子

			//		}
			//		gbseriesStartIndex = a;
			//	}
			//	if (isbreak) {

			//	}
			//}
			//for (var a = 1; a < gbseries.Length; a++) {
			//	if (gbseries[a].key - 1 == gbseries[a - 1].key) {

			//	}
			//}

			var gbseries = gb.Where(a => a.key < 15).OrderBy(a => a.key).ToArray();
			var gbseriesStartIndex = 0;
			for (var a = 1; a < gbseries.Length; a++) {
				if (gbseries[a].key - 1 == gbseries[a - 1].key) continue;
				if (a - gbseriesStartIndex >= 4) {
					var gbs = gb.Where((x, y) => y >= gbseriesStartIndex && y < a).ToArray();
					if (gbs.Where(x => x.count == 1).Count() > gbs.Length / 2) { //顺子

					}
				}
				gbseriesStartIndex = a;
			}
			
			var gb4 = gb.Where(a => a.count == 4).ToArray();
			foreach(var g4 in gb4) {
				hand = Utils.ComplierHandPoker(new[] { g4 }); //炸弹作为一手牌
				hands.Add(hand);
				foreach (var v in hand.value) pks.Remove(v);
			}
			var hand33 = new Stack<HandPokerComplieResult>(); //飞机
			var hand3 = new Stack<HandPokerComplieResult>(); //三条
			var gb3 = gb.Where(a => a.count == 3 && a.key < 15).OrderBy(a => a.key).ToList();
			var gb3seriesStartIndex = 0;
			for (var a = 1; a < gb3.Count; a++) {
				if (Utils.IsSeries(gb3.Where((x, y) => y <= a).Select(x => x.key)) == false || a == gb3.Count - 1) {
					hand = Utils.ComplierHandPoker(gb3.Where((x, y) => y >= gb3seriesStartIndex && y < a));
					if (hand.type == HandPokerType.飞机) hand33.Push(hand);
					if (hand.type == HandPokerType.三条) hand3.Push(hand);
					foreach (var v in hand.value) pks.Remove(v);
					gb3seriesStartIndex = a;
				}
			}
			hand = Utils.ComplierHandPoker(gb.Where(a => a.count == 3 && a.key == 15)); //三条2
			if (hand != null) {
				hand3.Push(hand);
				foreach (var v in hand.value) pks.Remove(v);
			}
			if (hand33.Any()) hands.AddRange(hand33.ToArray());
			if (hand3.Any()) hands.AddRange(hand3.ToArray());

			var hand22 = new Stack<HandPokerComplieResult>(); //连对
			var hand2 = new Stack<HandPokerComplieResult>(); //对
			var gb2 = gb.Where(a => a.count == 2 && a.key < 15).OrderBy(a => a.key).ToList();
			var gb2seriesStartIndex = 0;
			for (var a = 2; a < gb2.Count; a++) {
				if (Utils.IsSeries(gb2.Where((x, y) => y <= a).Select(x => x.key)) == false || a == gb2.Count - 1) {
					if (a - gb2seriesStartIndex >= 3) {
						hand = Utils.ComplierHandPoker(gb2.Where((x, y) => y >= gb2seriesStartIndex && y < a));
						hand22.Push(hand);
						foreach (var v in hand.value) pks.Remove(v);
					} else {
						for (var b = gb2seriesStartIndex; b < a; b++) {
							hand = Utils.ComplierHandPoker(new[] { gb2[b] });
							hand2.Push(hand);
							foreach (var v in hand.value) pks.Remove(v);
						}
					}
					gb2seriesStartIndex = a;
				}
			}
			hand = Utils.ComplierHandPoker(gb.Where(a => a.count == 2 && a.key == 15)); //对2
			if (hand != null) {
				hand2.Push(hand);
				foreach (var v in hand.value) pks.Remove(v);
			}
			if (hand22.Any()) hands.AddRange(hand22.ToArray());
			if (hand2.Any()) hands.AddRange(hand2.ToArray());

			var hand11 = new Stack<HandPokerComplieResult>(); //顺子
			var hand1 = new Stack<HandPokerComplieResult>(); //个
			var gb1 = gb.Where(a => a.count == 1 && a.key < 15).OrderBy(a => a.key).ToList();
			var gb1seriesStartIndex = 0;
			for (var a = 4; a < gb1.Count; a++) {
				if (Utils.IsSeries(gb1.Where((x, y) => y <= a).Select(x => x.key)) == false || a == gb1.Count - 1) {
					if (a - gb1seriesStartIndex >= 3) {
						hand = Utils.ComplierHandPoker(gb1.Where((x, y) => y >= gb1seriesStartIndex && y < a));
						hand11.Push(hand);
						foreach (var v in hand.value) pks.Remove(v);
					} else {
						for (var b = gb1seriesStartIndex; b < a; b++) {
							hand = Utils.ComplierHandPoker(new[] { gb1[b] });
							hand1.Push(hand);
							foreach (var v in hand.value) pks.Remove(v);
						}
					}
					gb1seriesStartIndex = a;
				}
			}
			hand = Utils.ComplierHandPoker(gb.Where(a => a.count == 1 && a.key == 15)); //个2
			if (hand != null) {
				hand1.Push(hand);
				foreach (var v in hand.value) pks.Remove(v);
			}
			if (hand11.Any()) hands.AddRange(hand11.ToArray());
			if (hand1.Any()) hands.AddRange(hand1.ToArray());

			return hands;
		}

19 Source : CommandPacket.cs
with MIT License
from 2881099

public CommandPacket InputIf(bool condition, params object[] args)
        {
            if (condition && args != null)
            {
                foreach (var item in args)
                {
                    if (item is object[] objs) _input.AddRange(objs);
                    else if (item is string[] strs) _input.AddRange(strs.Select(a => (object)a));
                    else if (item is int[] ints) _input.AddRange(ints.Select(a => (object)a));
                    else if (item is long[] longs) _input.AddRange(longs.Select(a => (object)a));
                    else if (item is KeyValuePair<string, long>[] kvps1) _input.AddRange(kvps1.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
                    else if (item is KeyValuePair<string, string>[] kvps2) _input.AddRange(kvps2.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
                    else if (item is Dictionary<string, long> dict1) _input.AddRange(dict1.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
                    else if (item is Dictionary<string, string> dict2) _input.AddRange(dict2.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
                    else _input.Add(item);
                }
            }
            return this;
        }

19 Source : RedisArgs.cs
with MIT License
from 2881099

public static object[] FromDict(Dictionary<string, object> dict)
        {
            var array = new List<object>();
            foreach (var keyValue in dict)
            {
                if (keyValue.Key != null && keyValue.Value != null)
                    array.AddRange(new[] { keyValue.Key, keyValue.Value });
            }
            return array.ToArray();
        }

19 Source : LandLord.cs
with Apache License 2.0
from 2881099

private static List<int> GetFourWithTwoBig(List<int> _lastPoker, LordPokerSplitHelper _splitHelper)
        {
            List<int> _lastThreeList = GetSameMoreThan3(_lastPoker);
            List<int> _ret = new List<int>();
            if (_lastPoker.Count != 6) return _ret;
            if (_splitHelper._shouPai.Count < _lastPoker.Count) return _ret;
            if (_splitHelper._four.Count < 1) return _ret;

            for (int i = _splitHelper._four.Count - 1; i >= 0; i--)
            {
                if (_splitHelper._four[i] > _lastThreeList[0])
                {
                    _ret.Add(_splitHelper._four[i]);
                    _ret.Add(_splitHelper._four[i]);
                    _ret.Add(_splitHelper._four[i]);
                    _ret.Add(_splitHelper._four[i]);
                    List<int> _tempwithone = _splitHelper.GetSingleToFourWith(new List<int>() { _splitHelper._four[i] });
                    _ret.AddRange(_tempwithone);
                    break;
                }
            }
            if (_ret.Count == 6) return _ret;
            return new List<int>();

        }

19 Source : LandLord.cs
with Apache License 2.0
from 2881099

private static List<int> GetLinkerPairBig(List<int> _lastPoker, LordPokerSplitHelper _splitHelper)
        {
            List<int> _ret = new List<int>();
            if (_lastPoker.Count < 6) return _ret;
            if (_splitHelper._shouPai.Count < _lastPoker.Count) return _ret;
            if (_splitHelper._linkerPair.Count < 0) return _ret;
            List<int> _lastLinkPair = new List<int>();//处理成单个,利于比较
            for (int i = 0; i < _lastPoker.Count; i += 2)
            {
                _lastLinkPair.Add(_lastPoker[i]);
            }

            foreach (var _tlinkerpair in _splitHelper._linkerPair)
            {
                if (_tlinkerpair.Count < _lastLinkPair.Count) continue;
                int _tempfirstindex = -1;
                for (int i = 0; i <= _tlinkerpair.Count - _lastLinkPair.Count; i++) //不安全代码前面必须处理
                {
                    if (_tlinkerpair[i] <= _lastLinkPair[0]) break;//连子的最大值 都大不过,不找了
                    _tempfirstindex = i;
                }
                if (_tempfirstindex != -1)
                {
                    for (int i = 0; i < _lastLinkPair.Count; i++)
                    {
                        _ret.Add(_tlinkerpair[_tempfirstindex + i]);
                    }
                }
                if (_ret.Count > 0) break;
            }
            List<int> _retLinkerPair = new List<int>();
            if (_ret.Count == _lastLinkPair.Count)
            {
                _retLinkerPair.AddRange(_ret);
                _retLinkerPair.AddRange(_ret);
            }
            return _retLinkerPair;
        }

19 Source : CommandFlagsTests.cs
with MIT License
from 2881099

[Fact]
        public void Command()
        {
			string UFString(string text)
			{
				if (text.Length <= 1) return text.ToUpper();
				else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
			}

			var rt = cli.Command();
			//var rt = cli.CommandInfo("mset", "mget", "set", "get", "rename");
			var flags = new List<string>();
			var flags7 = new List<string>();
			var diccmd = new Dictionary<string, (string[], string[])>();

			var sb = string.Join("\r\n\r\n", (rt).OrderBy(a1 => (a1 as object[])[0].ToString()).Select(a1 =>
			{
				var a = a1 as object[];
				var cmd = a[0].ToString();
				var plen = int.Parse(a[1].ToString());
				var firstKey = int.Parse(a[3].ToString());
				var lastKey = int.Parse(a[4].ToString());
				var stepCount = int.Parse(a[5].ToString());

				var aflags = (a[2] as object[]).Select(a => a.ToString()).ToArray();
				var fopts = (a[6] as object[]).Select(a => a.ToString()).ToArray();
				flags.AddRange(aflags);
				flags7.AddRange(fopts);

				diccmd.Add(cmd.ToUpper(), (aflags, fopts));

				var parms = "";
				if (plen > 1)
				{
					for (var x = 1; x < plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += $"string arg{x}, ";
					}
					parms = parms.Remove(parms.Length - 2);
				}
				if (plen < 0)
				{
					for (var x = 1; x < -plen; x++)
					{
						if (x == firstKey)
						{
							if (firstKey != lastKey) parms += "string[] keys, ";
							else parms += "string key, ";
						}
						else
						{
							if (firstKey != lastKey) parms += $"string[] arg{x}, ";
							else parms += $"string arg{x}, ";
						}
					}
					if (parms.Length > 0)
						parms = parms.Remove(parms.Length - 2);
				}

				return $@"
//{string.Join(", ", a[2] as object[])}
//{string.Join(", ", a[6] as object[])}
public void {UFString(cmd)}({parms}) {{ }}";
			}));
			flags = flags.Distinct().ToList();
			flags7 = flags7.Distinct().ToList();


			var sboptions = new StringBuilder();
            foreach (var cmd in CommandSets._allCommands)
            {
                if (diccmd.TryGetValue(cmd, out var tryv))
                {
                    sboptions.Append($@"
[""{cmd}""] = new CommandSets(");

                    for (var x = 0; x < tryv.Item1.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerFlag.{tryv.Item1[x].Replace("readonly", "@readonly")}");
                    }

                    sboptions.Append(", ");
                    for (var x = 0; x < tryv.Item2.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerTag.{tryv.Item2[x].TrimStart('@').Replace("string", "@string")}");
                    }

                    sboptions.Append(", LocalStatus.none),");
                }
                else
                {
                    sboptions.Append($@"
[""{cmd}""] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none), ");
                }
            }

            var optioncode = sboptions.ToString();
		}

19 Source : DynamicProxy.cs
with MIT License
from 2881099

public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
        {
            if (type == null) return null;
            var typeCSharpName = type.DisplayCsharp();

            if (type.IsNotPublic)
            {
                if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
                return null;
            }

            var matchedMemberInfos = new List<MemberInfo>();
            var matchedAttributes = new List<DynamicProxyAttribute>();
            var matchedAttributesFromServices = new List<FieldInfo[]>();
            var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
            var methodOverrideSb = new StringBuilder();
            var sb = methodOverrideSb;

            #region Common Code

            Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
            {
                var sbt = new StringBuilder();
                for (var a = attrsIndex; a < matchedAttributes.Count; a++)
                {
                    sbt.Append($@"{(proxyMethodName == "Before" ? $@"
        var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
        __DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
        var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
        {(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
        {(proxyMethodName == "Before" ? 
        $@"if (__DP_ARG___is_return == false)
        {{
            __DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? $@"
            if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
        }}" : 
        $"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
                }
                return sbt.ToString();
            };
            Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
            {
                var sbt = new StringBuilder();
                var taskType = returnType.ReturnTypeWithoutTask();
                sbt.Append($@"
        {(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
                (taskType.IsValueType || taskType.IsGenericParameter ?
                    $"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
                    $"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
                ) :
                (returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
                return sbt.ToString();
            };
            Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
            {
                return $@"
            if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? $@"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : $@"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
            };
            #endregion

            #region Methods
            var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
            var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
            foreach (var method in methods)
            {
                if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
                    if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
                var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                if (attrs.Any() == false) continue;
                var attrsIndex = matchedAttributes.Count;
                matchedMemberInfos.AddRange(attrs.Select(a => method));
                matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
                matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
                    .Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
                matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
                if (method.IsVirtual == false || method.IsFinal)
                {
                    if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
                    continue;
                }

#if net40
                var returnType = method.ReturnType;
                var methodIsAsync = false;
#else
                var returnType = method.ReturnType.ReturnTypeWithoutTask();
                var methodIsAsync = method.ReturnType.IsTask();

                //if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
                //    attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
                //{

                //}
#endif

                var baseInvoke = type.IsInterface == false ? $@"

        try
        {{
            if (__DP_ARG___is_return == false)
            {{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
                {(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
            }}
        }}
        catch (Exception __DP_ARG___ex)
        {{
            __DP_ARG___exception = __DP_ARG___ex;
        }}" : "";

                sb.Append($@"

    {(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
    {{
        Exception __DP_ARG___exception = null;
        var __DP_ARG___is_return = false;
        object __DP_ARG___return_value = null;
        var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n        ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
        {getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
        {getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
        {getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
    }}");
            }
            #endregion

            var propertyOverrideSb = new StringBuilder();
            sb = propertyOverrideSb;
            #region Property
            var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
            foreach (var prop2 in props)
            {
                var getMethod = prop2.GetGetMethod(false);
                var setMethod = prop2.GetSetMethod(false);
                if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
                {
                    if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
                        setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
                    {
                        if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
                        continue;
                    }
                }

                var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                var prop2AttributeAny = attrs.Any();
                var getMethodAttributeAny = prop2AttributeAny;
                var setMethodAttributeAny = prop2AttributeAny;
                if (attrs.Any() == false && getMethod?.IsVirtual == true)
                {
                    attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                    getMethodAttributeAny = attrs.Any();
                }
                if (attrs.Any() == false && setMethod?.IsVirtual == true)
                {
                    attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                    setMethodAttributeAny = attrs.Any();
                }
                if (attrs.Any() == false) continue;

                var attrsIndex = matchedAttributes.Count;
                matchedMemberInfos.AddRange(attrs.Select(a => prop2));
                matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
                matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
                    .Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
                matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif

                var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();

                var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
                var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
                var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
                if (propSetModification == propModification) propSetModification = "";
                if (propGetModification == propModification) propGetModification = "";

                //if (getMethod.IsAbstract) sb.Append("abstract ");
                sb.Append($@"

    {propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
    {{");

                if (getMethod != null)
                {
                    if (getMethodAttributeAny == false) sb.Append($@"
        {propGetModification} get
        {{
            return base.{prop2.Name}
        }}");
                    else sb.Append($@"
        {propGetModification} get
        {{
            Exception __DP_ARG___exception = null;
            var __DP_ARG___is_return = false;
            object __DP_ARG___return_value = null;
            var __DP_ARG___parameters = new Dictionary<string, object>();
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}

            try
            {{
                if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
            }}
            catch (Exception __DP_ARG___ex)
            {{
                __DP_ARG___exception = __DP_ARG___ex;
            }}
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
            {getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
        }}");
                }

                if (setMethod != null)
                {
                    if (setMethodAttributeAny == false) sb.Append($@"
        {propSetModification} set
        {{
            base.{prop2.Name} = value;
        }}");
                    else sb.Append($@"
        {propSetModification} set
        {{
            Exception __DP_ARG___exception = null;
            var __DP_ARG___is_return = false;
            object __DP_ARG___return_value = null;
            var __DP_ARG___parameters = new Dictionary<string, object>();
            __DP_ARG___parameters.Add(""value"", value);
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}

            try
            {{
                if (__DP_ARG___is_return == false)
                {{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
                    base.{prop2.Name} = value;
                }}
            }}
            catch (Exception __DP_ARG___ex)
            {{
                __DP_ARG___exception = __DP_ARG___ex;
            }}
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
        }}");
                }


                sb.Append($@"
    }}");
            }
            #endregion

            string proxyCscode = "";
            replacedembly proxyreplacedembly = null;
            Type proxyType = null;

            if (matchedMemberInfos.Any())
            {
                #region Constructors
                sb = new StringBuilder();
                var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
                sb.Append(string.Join("", fromServicesTypes.Select(serviceType => $@"
    private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
                foreach (var ctor in ctors)
                {
                    var ctorParams = ctor.GetParameters();
                    sb.Append($@"

    {(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
                        (ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
                        string.Join(", ", fromServicesTypes.Select(serviceType => $@"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
        : base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
    {{{string.Join("", fromServicesTypes.Select(serviceType => $@"
        {serviceType.Value} = parameter{serviceType.Value};"))}
    }}");
                }
                for (var a = 0; a < matchedAttributesFromServices.Count; a++)
                {
                    sb.Append($@"

    private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
    {{{string.Join("", matchedAttributesFromServices[a].Select(fs => $@"
        __DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
    }}");
                }
                #endregion

                proxyCscode = $@"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

public clreplaced {clreplacedName} : {typeCSharpName}
{{
    private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));

    //这里要注释掉,如果重写的基类没有无参构造函数,会报错
    //public {clreplacedName}({_metaName} meta)
    //{{
    //    __DP_Meta = meta;
    //}}
    {sb.ToString()}
    {methodOverrideSb.ToString()}

    {propertyOverrideSb.ToString()}
}}";
                proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
                proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
            }
            methodOverrideSb.Clear();
            propertyOverrideSb.Clear();
            sb.Clear();
            return new DynamicProxyMeta(
                type, ctors,
                matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
                isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
        }

19 Source : KeysTests.cs
with MIT License
from 2881099

[Fact]
        public void Scan()
        {
            for (var a = 0; a < 11; a++)
                cli.Set(Guid.NewGuid().ToString(), a);

            var keys = new List<string>();
            foreach (var rt in cli.Scan("*", 2, null))
            {
                keys.AddRange(rt);
            }
        }

See More Examples