System.Collections.Generic.IEnumerable.Where(System.Func)

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

31569 Examples 7

19 Source : HelpersTests.cs
with MIT License
from 71

[Fact]
        public void TestUninitializedMethods()
        {
            bool IsValidMethod(MethodInfo method)
            {
                if (method.IsAbstract)
                    return false;

                if (!method.IsStatic && method.DeclaringType.GetTypeInfo().IsAbstract)
                    return false;

                return !method.ContainsGenericParameters;
            }

            // We're testing LINQ expressions here, cuz there are (instance / static) and (public / non-public) methods,
            // properties, and most methods are independant. Last time I checked, running this step checks
            // 193 different methods.
            foreach (var method in typeof(Expression).GetMethods(BindingFlags.Instance |
                                                                 BindingFlags.Static   |
                                                                 BindingFlags.Public   |
                                                                 BindingFlags.NonPublic)
                                                     .Where(IsValidMethod)
                                                     .GroupBy(x => x.Name)
                                                     .Select(Enumerable.First))
            {
                // Find non-jitted start
                IntPtr start = method.GetRuntimeMethodHandle().GetMethodStart();

                // Compile method (should work on this platform)
                Helpers.TryPrepareMethod(method, method.GetRuntimeMethodHandle()).ShouldBeTrue();

                // Find freshly jitted start
                IntPtr newStart = method.GetRuntimeMethodHandle().GetMethodStart();

                // start != newStart => it wasn't jitted before: Fixup should be good
                start.HasBeenCompiled().ShouldBe(start == newStart);

                // In any case, the new method shouldn't be a fixup
                newStart.HasBeenCompiled().ShouldBeTrue();
            }
        }

19 Source : AINavMeshGenerator.cs
with MIT License
from 7ark

private Node[] GetAStar(Vector2 currentPosition, Vector2 destination, GameObject obj = null)
    {
        Node start = generator.FindClosestNode(currentPosition, false, obj);
        Node end = generator.FindClosestNode(destination, true, obj);
        if (start == null || end == null)
        {
            return null;
        }

        openSet.Clear();
        closedSet.Clear();
        openSet.Add(start);
        while (openSet.Count > 0)
        {
            Node current = openSet[0];

            //Evaluate costs
            for (int i = 1; i < openSet.Count; i++)
            {
                if (openSet[i].fCost < current.fCost || openSet[i].fCost == current.fCost)
                {
                    if (openSet[i].hCost < current.hCost)
                    {
                        current = openSet[i];
                    }
                }
            }

            openSet.Remove(current);
            closedSet.Add(current);

            if (current.Equals(end))
            {
                break;
            }

            //Go through neighbors
            foreach (Node neighbor in current.connections.Where(x => x != null))
            {
                //The replacedociated object check is so the enemy ignores pathing through it's own bad sector
                if ((!neighbor.valid && neighbor.replacedociatedObject != obj) || closedSet.Contains(neighbor))
                {
                    continue;
                }

                float newCost = current.gCost + Heuristic(current, neighbor);
                if (newCost < neighbor.gCost || !openSet.Contains(neighbor))
                {
                    neighbor.gCost = newCost;
                    neighbor.hCost = Heuristic(neighbor, end);
                    neighbor.parent = current;

                    if (!openSet.Contains(neighbor))
                    {
                        openSet.Add(neighbor);
                    }
                }
            }
        }

        if(end.parent == null)
        {
            return null;
        }

        //Calculate path
        path.Clear();
        Node currentCheck = end;
        while (!path.Contains(currentCheck) && currentCheck != null)
        {
            path.Add(currentCheck);
            currentCheck = currentCheck.parent;
        }
        path.Reverse();
        if(path[0] != start)
        {
            return null;
        }
        return path.ToArray();
    }

19 Source : ServiceCollectionExtension.cs
with GNU Lesser General Public License v3.0
from 8720826

public static void AutoRegister(this IServiceCollection services)
        {
            #region 自动注入

            var allreplacedemblies = replacedembly.GetEntryreplacedembly().GetReferencedreplacedemblies().Select(replacedembly.Load);
            foreach (var serviceAsm in allreplacedemblies)
            {
                var serviceList = serviceAsm.GetTypes().Where(t => t.IsClreplaced && !t.IsAbstract && !t.IsInterface);

                foreach (Type serviceType in serviceList.Where(t => typeof(IScoped).IsreplacedignableFrom(t)))
                {
                    var interfaceTypes = serviceType.GetInterfaces();

                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddScoped(interfaceType, serviceType);
                    }
                }

                foreach (Type serviceType in serviceList.Where(t => typeof(ISingleton).IsreplacedignableFrom(t)))
                {
                    var interfaceTypes = serviceType.GetInterfaces();

                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddSingleton(interfaceType, serviceType);
                    }
                }

                foreach (Type serviceType in serviceList.Where(t => typeof(ITransient).IsreplacedignableFrom(t)))
                {
                    var interfaceTypes = serviceType.GetInterfaces();

                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddTransient(interfaceType, serviceType);
                    }
                }

                foreach (Type serviceType in serviceList.Where(t => t.IsSubclreplacedOf(typeof(BackgroundService))))
                {
                    services.AddTransient(typeof(IHostedService), serviceType);
                }
            }
            #endregion

        }

19 Source : AutoMapperExtension.cs
with GNU Lesser General Public License v3.0
from 8720826

public static void AddAutoMapper(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            //添加服务
            //可以添加筛选
            services.AddAutoMapper(AppDomain.CurrentDomain.Getreplacedemblies().Where(t => t.GetName().ToString().StartsWith("Emprise.")));
            //启动配置

            AutoMapperConfig.RegisterMappings();
        }

19 Source : ServiceCollectionExtension.cs
with GNU Lesser General Public License v3.0
from 8720826

public static void AutoRegister(this IServiceCollection services)
        {
            #region 自动注入

            var allreplacedemblies = replacedembly.GetEntryreplacedembly().GetReferencedreplacedemblies().Select(replacedembly.Load);
            foreach (var serviceAsm in allreplacedemblies)
            {
                var serviceList = serviceAsm.GetTypes().Where(t => t.IsClreplaced && !t.IsAbstract && !t.IsInterface);

                foreach (Type serviceType in serviceList.Where(t => typeof(IScoped).IsreplacedignableFrom(t)))
                {
                    var interfaceTypes = serviceType.GetInterfaces();

                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddScoped(interfaceType, serviceType);
                    }
                }

                foreach (Type serviceType in serviceList.Where(t => typeof(ISingleton).IsreplacedignableFrom(t)))
                {
                    var interfaceTypes = serviceType.GetInterfaces();

                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddSingleton(interfaceType, serviceType);
                    }
                }

                foreach (Type serviceType in serviceList.Where(t => typeof(ITransient).IsreplacedignableFrom(t)))
                {
                    var interfaceTypes = serviceType.GetInterfaces();

                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddTransient(interfaceType, serviceType);
                    }
                }

                foreach (Type serviceType in serviceList.Where(t => t.IsSubclreplacedOf(typeof(BackgroundService))))
                {
                    services.AddTransient(typeof(IHostedService), serviceType);
                }
            }
            #endregion

        }

19 Source : BaseController.cs
with Apache License 2.0
from 91270

public static List<UserMenusVM> ResolveUserMenuTree(List<Sys_Menu> menus, string parentId = null)
        {
            List<UserMenusVM> userMenus = new List<UserMenusVM>();

            foreach (var menu in menus.Where(m => m.ParentUID == parentId).OrderBy(m => m.SortIndex))
            {
                var childrenMenu = ResolveUserMenuTree(menus, menu.ID);

                UserMenusVM menusVM = new UserMenusVM
                {
                    alwaysShow = menu.Type == 0 ? true : null,
                    name = menu.Name,
                    path = menu.Type == 0 && menu.ParentUID == null ? "/" + menu.Path : menu.Path,
                    hidden = menu.Hidden,
                    component = menu.Type == 0 ? menu.ParentUID == null ? "Layout" : "LayoutSub" : menu.Component,
                    redirect = menu.Type == 0 ? "noredirect" : null,
                    meta = new MenuMetaVM() { replacedle = menu.Name, icon = menu.Icon, path = menu.Path, keepAlive = menu.KeepAlive },
                    children = childrenMenu.Count == 0 ? null : childrenMenu
                };

                if (childrenMenu.Count == 0 && menu.Type == 0)
                {
                    continue;
                }

                userMenus.Add(menusVM);

            }

            return userMenus;
        }

19 Source : BaseController.cs
with Apache License 2.0
from 91270

public static List<MenuListVM> ResolveMenuTree(List<Sys_Menu> menus, string parentId = null)
        {
            List<MenuListVM> resultMenus = new List<MenuListVM>();

            foreach (var menu in menus.Where(m => m.ParentUID == parentId).OrderBy(m => m.SortIndex))
            {
                var childrenMenu = ResolveMenuTree(menus, menu.ID);

                MenuListVM menusVM = new MenuListVM
                {
                    ID = menu.ID,
                    Name = menu.Name,
                    Type = menu.Type,
                    Icon = menu.Icon,
                    Path = menu.Path,
                    Component = menu.Component,
                    SortIndex = menu.SortIndex,
                    ViewPower = menu.ViewPower,
                    ParentUID = menu.ParentUID,
                    Remark = menu.Remark,
                    Hidden = menu.Hidden,
                    System = menu.System,
                    isFrame = menu.isFrame,
                    KeepAlive = menu.KeepAlive,
                    Children = childrenMenu.Count == 0 ? null : childrenMenu,
                    CreateTime = menu.CreateTime,
                    UpdateTime = menu.UpdateTime,
                    CreateID = menu.CreateID,
                    CreateName = menu.CreateName,
                    UpdateID = menu.UpdateID,
                    UpdateName = menu.UpdateName

                };
                resultMenus.Add(menusVM);
            }

            return resultMenus;
        }

19 Source : EmpriseDbContext.cs
with GNU Lesser General Public License v3.0
from 8720826

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            base.OnModelCreating(modelBuilder);

            var typesToRegister = replacedembly.Load("Emprise.Domain").GetTypes().Where(type => !string.IsNullOrEmpty(type.Namespace) && type.BaseType == typeof(BaseEnreplacedy));
            foreach (var enreplacedyType in typesToRegister)
            {
                if (modelBuilder.Model.FindEnreplacedyType(enreplacedyType) != null)
                {
                    continue;
                }
                modelBuilder.Model.AddEnreplacedyType(enreplacedyType);
            }

        }

19 Source : NpcMovingJobService.cs
with GNU Lesser General Public License v3.0
from 8720826

private async Task DoWork()
        {
            using (var scope = _services.CreateScope())
            {
                var _npcDomainService = scope.ServiceProvider.GetRequiredService<INpcDomainService>();
                var _redisDb = scope.ServiceProvider.GetRequiredService<IRedisDb>();
                var _mudProvider = scope.ServiceProvider.GetRequiredService<IMudProvider>();
                var _roomDomainService = scope.ServiceProvider.GetRequiredService<IRoomDomainService>();
                var _bus = scope.ServiceProvider.GetRequiredService<IMediatorHandler>();


                var npcs = await _npcDomainService.GetAllFromCache();
                var npc = npcs.Where(x => x.CanMove && !x.IsDead && x.IsEnable).OrderBy(x => Guid.NewGuid()).FirstOrDefault();
                if (npc == null)
                {
                    return;
                }

                var npcFightingPlayerId = await _redisDb.StringGet<int>(string.Format(RedisKey.NpcFighting, npc.Id));
                if (npcFightingPlayerId > 0)
                {
                    return;
                }

                var roomOut = await _roomDomainService.Get(npc.RoomId);
                if (roomOut == null)
                {
                    return;
                }

                var roomOutId = npc.RoomId;

                var roomIds = new List<int> { roomOut.East, roomOut.West, roomOut.South, roomOut.North }.Where(x => x > 0).ToList();
                if (roomIds.Count == 0)
                {
                    return;
                }

                var roomInId = roomIds.OrderBy(x => Guid.NewGuid()).First();
                var roomIn = await _roomDomainService.Get(roomInId);
                if (roomIn == null)
                {
                    return;
                }

                npc.RoomId = roomInId;
                await _npcDomainService.Update(npc);

                await _bus.RaiseEvent(new NpcMovedEvent(npc, roomIn, roomOut));
            }
        }

19 Source : MockDataStore.cs
with GNU General Public License v3.0
from 9vult

public async Task<bool> UpdateItemAsync(Item item)
        {
            var oldItem = items.Where((Item arg) => arg.Id == item.Id).FirstOrDefault();
            items.Remove(oldItem);
            items.Add(item);

            return await Task.FromResult(true);
        }

19 Source : MockDataStore.cs
with GNU General Public License v3.0
from 9vult

public async Task<bool> DeleteItemAsync(string id)
        {
            var oldItem = items.Where((Item arg) => arg.Id == id).FirstOrDefault();
            items.Remove(oldItem);

            return await Task.FromResult(true);
        }

19 Source : CommandMessage.cs
with MIT License
from a1q123456

public void DeserializeAmf0(SerializationContext context)
        {
            var buffer = context.ReadBuffer.Span;
            if (!context.Amf0Reader.TryGetNumber(buffer, out var txid, out var consumed))
            {
                throw new InvalidOperationException();
            }

            TranscationID = txid;
            buffer = buffer.Slice(consumed);
            context.Amf0Reader.TryGetObject(buffer, out var commandObj, out consumed);
            CommandObject = commandObj;
            buffer = buffer.Slice(consumed);
            var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
            var i = 0;
            while (buffer.Length > 0)
            {
                if (!context.Amf0Reader.TryGetValue(buffer, out _, out var optArg, out consumed))
                {
                    break;
                }
                buffer = buffer.Slice(consumed);
                optionArguments[i].SetValue(this, optArg);
                i++;
                if (i >= optionArguments.Count)
                {
                    break;
                }
            }
        }

19 Source : CommandMessage.cs
with MIT License
from a1q123456

public void DeserializeAmf3(SerializationContext context)
        {
            var buffer = context.ReadBuffer.Span;
            if (!context.Amf3Reader.TryGetDouble(buffer, out var txid, out var consumed))
            {
                throw new InvalidOperationException();
            }
            TranscationID = txid;
            buffer = buffer.Slice(consumed);
            context.Amf3Reader.TryGetObject(buffer, out var commandObj, out consumed);
            CommandObject = commandObj as AmfObject;
            buffer = buffer.Slice(consumed);
            var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
            var i = 0;
            while (buffer.Length > 0)
            {
                context.Amf0Reader.TryGetValue(buffer, out _, out var optArg, out _);
                optionArguments[i].SetValue(this, optArg);
            }
        }

19 Source : CommandMessage.cs
with MIT License
from a1q123456

public void SerializeAmf3(SerializationContext context)
        {
            using (var writeContext = new Amf.Serialization.Amf3.SerializationContext(context.WriteBuffer))
            {
                if (ProcedureName == null)
                {
                    ProcedureName = GetType().GetCustomAttribute<RtmpCommandAttribute>().Name;
                }
                Debug.replacedert(!string.IsNullOrEmpty(ProcedureName));
                context.Amf3Writer.WriteBytes(ProcedureName, writeContext);
                context.Amf3Writer.WriteBytes(TranscationID, writeContext);
                context.Amf3Writer.WriteValueBytes(CommandObject, writeContext);
                var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
                foreach (var optionArgument in optionArguments)
                {
                    context.Amf3Writer.WriteValueBytes(optionArgument.GetValue(this), writeContext);
                }
            }
        }

19 Source : RpcService.cs
with MIT License
from a1q123456

internal void CleanupRegistration()
        {
            foreach (var controller in Controllers)
            {
                var gps = controller.Value.GroupBy(m => m.MethodName).Where(gp => gp.Count() > 1);

                var hiddenMethods = new List<RpcMethod>();

                foreach (var gp in gps)
                {
                    hiddenMethods.AddRange(gp.Where(m => m.Method.DeclaringType != controller.Key));
                }
                foreach (var m in hiddenMethods)
                {
                    controller.Value.Remove(m);
                }
            }
        }

19 Source : Amf3Reader.cs
with MIT License
from a1q123456

public void RegisterTypedObject<T>() where T: new()
        {
            var type = typeof(T);
            var props = type.GetProperties();
            var fields = props.Where(p => p.CanWrite && Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute)) != null).ToList();
            var members = fields.ToDictionary(p => ((ClreplacedFieldAttribute)Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute))).Name ?? p.Name, p => new Action<object, object>(p.SetValue));
            if (members.Keys.Where(s => string.IsNullOrEmpty(s)).Any())
            {
                throw new InvalidOperationException("Field name cannot be empty or null");
            }
            string mapedName = null;
            var attr = type.GetCustomAttribute<TypedObjectAttribute>();
            if (attr != null)
            {
                mapedName = attr.Name;
            }

            var typeName = mapedName == null ? type.Name : mapedName;
            var state = new TypeRegisterState()
            {
                Members = members,
                Type = type
            };
            _registeredTypes.Add(type);
            _registeredTypedObejectStates.Add(typeName, state);
        }

19 Source : Form1.cs
with MIT License
from a1xd

static void MakeStartupShortcut(bool gui)
        {
            var startupFolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

            if (string.IsNullOrEmpty(startupFolder))
            {
                throw new Exception("Startup folder does not exist");
            }

            //Windows Script Host Shell Object
            Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8"));
            dynamic shell = Activator.CreateInstance(t);

            try
            {
                // Delete any other RA related startup shortcuts
                var candidates = new[] { "rawaccel", "raw accel", "writer" };

                foreach (string path in Directory.EnumerateFiles(startupFolder, "*.lnk")
                    .Where(f => candidates.Any(f.Substring(startupFolder.Length).ToLower().Contains)))
                {
                    var link = shell.CreateShortcut(path);
                    try
                    {
                        string targetPath = link.TargetPath;

                        if (!(targetPath is null) && 
                            (targetPath.EndsWith("rawaccel.exe") ||
                                targetPath.EndsWith("writer.exe") &&
                                    new FileInfo(targetPath).Directory.GetFiles("rawaccel.exe").Any()))
                        {
                            File.Delete(path);
                        }
                    }
                    finally
                    {
                        Marshal.FinalReleaseComObject(link);
                    }
                }

                var name = gui ? "rawaccel" : "writer";

                var lnk = shell.CreateShortcut($@"{startupFolder}\{name}.lnk");

                try
                {
                    if (!gui) lnk.Arguments = Constants.DefaultSettingsFileName;
                    lnk.TargetPath = $@"{Application.StartupPath}\{name}.exe";
                    lnk.Save();
                }
                finally
                {
                    Marshal.FinalReleaseComObject(lnk);
                }

            }
            finally
            {
                Marshal.FinalReleaseComObject(shell);
            }
        }

19 Source : Inspector.cs
with GNU General Public License v3.0
from a2659802

private static void _reflectProps(Type t, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance)
        {
            if (cache_prop.ContainsKey(t))
                return;
            var propInfos =t.GetProperties(flags)
                .Where(x =>
                {
                    var handlers = x.GetCustomAttributes(typeof(HandleAttribute), true).OfType<HandleAttribute>();
                    bool handflag = handlers.Any();
                    bool ignoreflag = x.GetCustomAttributes(typeof(InspectIgnoreAttribute), true).OfType<InspectIgnoreAttribute>().Any();
                    if(handflag && (!ignoreflag))
                    {
                        if(!handler.ContainsKey(x))
                            handler.Add(x, handlers.FirstOrDefault().handleType);
                    }

                    return handflag && (!ignoreflag);
                });
            foreach(var p in propInfos)
            {
                if(cache_prop.TryGetValue(t,out var npair))
                {
                    npair.Add(p.Name, p);
                }
                else
                {
                    var d = new Dictionary<string, PropertyInfo>();
                    d.Add(p.Name, p);
                    cache_prop.Add(t, d);
                }

                //Logger.LogDebug($"Cache PropInfo:T:{t},name:{p.Name}");
            }
            //Logger.LogDebug($"_reflectProp_resutl:{propInfos.ToArray().Length}");
        }

19 Source : ObjectManager.cs
with GNU General Public License v3.0
from a2659802

public static void RegisterBehaviour<T>()
        {
            var behaviours = typeof(T).GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(CustomDecoration)));
            var items = typeof(ItemDef).GetNestedTypes(BindingFlags.Public | BindingFlags.Instance).Where(x => x.IsSubclreplacedOf(typeof(Item)));

            foreach (Type b in behaviours)
            {
                DecorationAttribute attr = b.GetCustomAttributes(typeof(DecorationAttribute), false).OfType<DecorationAttribute>().FirstOrDefault();
                if (attr == null)
                    continue;

                string poolname = attr.Name;

                Type DataStruct = null;
                foreach (Type i in items) // Search Item Defination in ItemDef
                {
                    DecorationAttribute[] i_attr = i.GetCustomAttributes(typeof(DecorationAttribute), false).OfType<DecorationAttribute>().ToArray();
                    if (i_attr == null || i_attr.Length == 0)
                        continue;
                        
                    if(i_attr.Contains(attr))
                    {
                        DataStruct = i;
                        break;
                    }
                }
                if(DataStruct == null) // Search Item Defination in Behaviour
                {
                    DataStruct = b.GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(Item))).FirstOrDefault();
                }
                if (DataStruct == null) // Search Item Defination in T
                {
                    DataStruct = typeof(T).GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(Item))).FirstOrDefault();
                }
                if (DataStruct == null) // Fill with defatult Item
                {
                    Logger.LogWarn($"Could Not Found an Item that match {b.FullName},Attr:{attr.Name},will use default item instance");
                    DataStruct = typeof(ItemDef.Defaulreplacedem);
                }

                Register(poolname, b, DataStruct);
            }
        }

19 Source : ServiceCollectionExtension.cs
with MIT License
from a34546

private static void AddRepository(this IServiceCollection services, IEnumerable<replacedembly> replacedemblies, Type baseType)
        {
            foreach (var replacedembly in replacedemblies)
            {
                var types = replacedembly.GetTypes()
                                    .Where(x => x.IsClreplaced
                                            && !x.IsAbstract
                                            && x.BaseType != null
                                            && x.HasImplementedRawGeneric(baseType));
                foreach (var type in types)
                {
                    var interfaces = type.GetInterfaces();
                    var interfaceType = interfaces.FirstOrDefault(x => x.Name == $"I{type.Name}");
                    if (interfaceType == null) interfaceType = type;
                    var serviceDescriptor = new ServiceDescriptor(interfaceType, type, ServiceLifetime.Transient);
                    if (!services.Contains(serviceDescriptor)) services.Add(serviceDescriptor);
                }
            }
        }

19 Source : RepositoryBase.cs
with MIT License
from a34546

public virtual Task<List<TEnreplacedy>> GetAllAsync(Expression<Func<TEnreplacedy, bool>> predicate)
        {
            return Query().Where(x => x.IsDelete == false).Where(predicate).ToListAsync();
        }

19 Source : Mana.cs
with GNU General Public License v3.0
from a2659802

private void _remove_mana_go(ManaType t,int amount = 1)
        {
            List<Mana.ManaActive> toRemove = null;
            if(t != ManaType.C)
            {
                toRemove = manas.Where(x => (x != null && x.MType == t)).ToList();
            }
            else
            {
                toRemove = manas.Where(x => (x != null && x.MType != t)).ToList();
            }
            for(int i=0;i<amount;i++)
            {
                //GameObject target = toRemove[0].gameObject;
                manas.Remove(toRemove[i]);
                toRemove[i].CostSelf();
                //toRemove.Remove(toRemove[0]);
            }
        }

19 Source : Mana.cs
with GNU General Public License v3.0
from a2659802

public bool TryCost(Dictionary<ManaType,int> allCost)
        {
            var colorful = allCost.Where(x => x.Key != ManaType.C);
            //var colorless = allCost.Where(x => x.Key == ManaType.C);
            int colorfulAmount = 0;
            bool flag = true;
            foreach(var kv in colorful)
            {
                flag &= (mana_pool.ContainsKey(kv.Key) && mana_pool[kv.Key] >= kv.Value);
                if (!flag)
                    break;
                colorfulAmount += kv.Value;
            }
            if (!flag)
                return false;
            if (allCost.ContainsKey(ManaType.C))
            {
                int colorlessAmount = allCost[ManaType.C];
                if (colorlessAmount <= (mana_sum - colorfulAmount))
                    return true;
            }
            else
                return true;
            return false;
        }

19 Source : ReflectionCache.cs
with GNU General Public License v3.0
from a2659802

public static List<MethodInfo> GetMethods(Type t, Operation op)
        {

            if (BehaviourMethodCache.TryGetValue(t, out var props))
            {
                if (props.TryGetValue(op, out var res))
                    return res;
                else
                    return null;
            }
            var handle_methods = t.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(HandleAttribute), true).Any());
            Dictionary<Operation, List<MethodInfo>> opbind = new Dictionary<Operation, List<MethodInfo>>();
            foreach (var m in handle_methods)
            {
                var ops = m.GetCustomAttributes(typeof(HandleAttribute), true).OfType<HandleAttribute>().Select(x=>x.handleType);//.FirstOrDefault().handleType;
                foreach(var p_op in ops)
                {
                    if (opbind.TryGetValue(p_op, out var list))
                    {
                        list.Add(m);
                    }
                    else
                    {
                        opbind.Add(p_op, new List<MethodInfo> { m });
                    }
                    
                }

            }
            BehaviourMethodCache.Add(t, opbind);

            if (BehaviourMethodCache.TryGetValue(t, out var props2))
            {
                if (props2.TryGetValue(op, out var res2))
                    return res2;
                else
                    return null;
            }
            else
                return null;
        }

19 Source : ObjectManager.cs
with GNU General Public License v3.0
from a2659802

public static void RegisterSharedBehaviour<T>() where T : CustomDecoration
        {
            var shareAttr = typeof(T).GetCustomAttributes(typeof(DecorationAttribute), false).OfType<DecorationAttribute>();
            foreach(var attr in shareAttr)
            {
                if (attr == null)
                    continue;
                string poolname = attr.Name;

                var ti = typeof(T).GetNestedTypes(BindingFlags.Public).Where(x => x.IsSubclreplacedOf(typeof(Item))).FirstOrDefault();

                Register<T>(poolname, ti);
            }
        }

19 Source : GridAgent.cs
with Apache License 2.0
from A7ocin

public override void AgentStep(float[] act)
    {
        reward = -0.01f;
        int action = Mathf.FloorToInt(act[0]);

        // 0 - Forward, 1 - Backward, 2 - Left, 3 - Right
        if (action == 3)
        {
            Collider[] blockTest = Physics.OverlapBox(new Vector3(trueAgent.transform.position.x + 1, 0, trueAgent.transform.position.z), new Vector3(0.3f, 0.3f, 0.3f));
            if (blockTest.Where(col => col.gameObject.tag == "wall").ToArray().Length == 0)
            {
                trueAgent.transform.position = new Vector3(trueAgent.transform.position.x + 1, 0, trueAgent.transform.position.z);
            }
        }

        if (action == 2)
        {
            Collider[] blockTest = Physics.OverlapBox(new Vector3(trueAgent.transform.position.x - 1, 0, trueAgent.transform.position.z), new Vector3(0.3f, 0.3f, 0.3f));
            if (blockTest.Where(col => col.gameObject.tag == "wall").ToArray().Length == 0)
            {
                trueAgent.transform.position = new Vector3(trueAgent.transform.position.x - 1, 0, trueAgent.transform.position.z);
            }
        }

        if (action == 0)
        {
            Collider[] blockTest = Physics.OverlapBox(new Vector3(trueAgent.transform.position.x, 0, trueAgent.transform.position.z + 1), new Vector3(0.3f, 0.3f, 0.3f));
            if (blockTest.Where(col => col.gameObject.tag == "wall").ToArray().Length == 0)
            {
                trueAgent.transform.position = new Vector3(trueAgent.transform.position.x, 0, trueAgent.transform.position.z + 1);
            }
        }

        if (action == 1)
        {
            Collider[] blockTest = Physics.OverlapBox(new Vector3(trueAgent.transform.position.x, 0, trueAgent.transform.position.z - 1), new Vector3(0.3f, 0.3f, 0.3f));
            if (blockTest.Where(col => col.gameObject.tag == "wall").ToArray().Length == 0)
            {
                trueAgent.transform.position = new Vector3(trueAgent.transform.position.x, 0, trueAgent.transform.position.z - 1);
            }
        }

        Collider[] hitObjects = Physics.OverlapBox(trueAgent.transform.position, new Vector3(0.3f, 0.3f, 0.3f));
        if (hitObjects.Where(col => col.gameObject.tag == "goal").ToArray().Length == 1)
        {
            reward = 1f;
            done = true;
        }
        if (hitObjects.Where(col => col.gameObject.tag == "pit").ToArray().Length == 1)
        {
            reward = -1f;
            done = true;
        }

        //if (trainMode == "train") {
        if (true)
        {
            academy.visualAgent.transform.position = trueAgent.transform.position;
            academy.visualAgent.transform.rotation = trueAgent.transform.rotation;
        }
    }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from a4004

private async void Init()
        {
            if (Program.Portable)
                goto InitTaskEnd;
InitPyChk:
            WaitFm.Caption("Checking if Python is installed");
            await Task.Delay(1000);

            if (!ShellManager.CheckCommand("py", "--version"))
            {
                WaitFm.Debug("Python could not be detected on your system. You can choose to install Python or use N2D22 in portable mode.", Event.Warning);

                CreateRequest("Python isn't installed on this PC", "You can choose to install Python",
                    "Install Python 3.9.7 (Recommended)", "Portable mode (Legacy, not recommended)", out int result);

                if (result == 1 /*install python*/)
                {
                    WaitFm.Caption("Downloading Python x64 3.9.7");

                    try
                    {
                        WebClient client = new WebClient();

                        client.DownloadProgressChanged += (s, e) =>
                        {
                            WaitFm.Caption($"Downloading Python x64 3.9.7 from python.org ({e.ProgressPercentage}%)");
                        };
                        client.DownloadFileCompleted += delegate
                        {
                            WaitFm.Debug("Successfully downloaded python-3.9.7-amd64.exe from python.org", Event.Success);
                            WaitFm.Caption("Installing Python x64 3.9.7");
                        };

                        WaitFm.Debug("Downloading python-3.9.7-amd64.exe from python.org");
                        await client.DownloadFileTaskAsync("https://www.python.org/ftp/python/3.9.7/python-3.9.7-amd64.exe", "python-3.9.7-amd64.exe");

                        WaitFm.Caption("Installing Python");
                        WaitFm.Debug("Installing Python x64 3.9.7");

                        if (ShellManager.RunCommand(out string output, "python-3.9.7-amd64.exe", "/quiet InstallAllUsers=1 PrependPath=1"))
                        {
                            WaitFm.Caption("Verifying Python is installed");
                            WaitFm.Debug("Verifying Python x64 3.9.7", Event.Success);
                            WaitFm.replacedle("Preparing");
                            await Task.Delay(1000);

                            goto InitPyChk;
                        }
                        else
                            throw new Exception(output == default ? "Process not started." : output);
                    }
                    catch (Exception ex)
                    {
                        WaitFm.Debug($"Python could not be installed due to an error. {ex.Message}", Event.Critical);
                        await CreateMessage("We couldn't install Python", "Something went wrong during the install process. You can try again.");

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();
                        return;
                    }
                }
                else if (result == 2 /*run in portable mode*/)
                {
                    Process.Start(Application.ExecutablePath, string.Join(" ", Environment.GetCommandLineArgs()) + " --portable");
                    Program.Terminate();
                    return;
                }
                else
                    throw new Exception($"The selection could not be determined due to an invalid value. {result}");
            }
            else
            {
                if (ShellManager.RunCommand(out string filePath, "py", "-c \"import sys; print(sys.executable)\""))
                    WaitFm.Debug($"Python is installed on this PC at \"{filePath}\".", Event.Success);
                else
                    WaitFm.Debug("Could not get the executable path of the Python binary.", Event.Warning);

                Program.Settings.PythonExe = filePath;

                WaitFm.replacedle("Getting ready");
                WaitFm.Caption("Checking for esptool.py");
                await Task.Delay(1000);

                if (!ShellManager.CheckCommand("py", "-m esptool --help"))
                {
                    WaitFm.Debug("esptool.py isn't installed in the default Python environment. " +
                        "You can choose to install esptool or use N2D22 in portable mode.");

                    CreateRequest("esptool.py is missing", "You can choose to install it right now",
                        "Install esptool.py (Recommended)", "Portable mode (Legacy, not recommended)", out int result);

                    if (result == 1 /*install esptool*/)
                    {
                        WaitFm.Debug("Installing esptool.py");
                        WaitFm.Caption("Installing esptool.py");

                        if (ShellManager.RunCommand(out string output, "py", "-m pip install esptool"))
                        {
                            WaitFm.Debug("esptool.py was installed successfully.");
                            WaitFm.replacedle("Preparing");
                            await Task.Delay(3000);

                            goto InitPyChk;
                        }
                    }
                    else if (result == 2 /*run in portable mode*/)
                    {
                        Process.Start(Application.ExecutablePath, string.Join(" ", Environment.GetCommandLineArgs()) + " --portable");
                        Program.Terminate();
                        return;
                    }
                    else
                        throw new Exception($"The selection could not be determined due to an invalid value. {result}");
                }
                else
                {
                    WaitFm.Caption("Making sure you're ready to flash");
                    WaitFm.Debug("esptool.py is installed in the default Python environment.");
                    Program.Settings.EsptoolPy = true;

                    await Task.Delay(1000);
                    WaitFm.Debug("Searching for device drivers.");
                    await Task.Delay(1000);

                    string silabserPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("silabser")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"silabser\"");
                    string ch34serPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("ch341ser")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ch34ser\"");
                    string ftdiPortPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("ftdiport")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ftdiport\"");
                    string ftdiBusPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("ftdibus")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ftdibus\"");

                    if (silabserPath == default && ch34serPath == default && ftdiPortPath == default && ftdiBusPath == default)
                    {
                        WaitFm.Debug("Driver files not found in FileRepository.", Event.Warning);

                        await CreateMessage("Device drivers not found", "We could not detect any Espressif compatible device drivers " +
                            "on this PC. You can still try flashing your device as Windows may automatically install the correct drivers " +
                            "for you.", 10);
                    }
                    else if (silabserPath != default && ch34serPath != default && ftdiPortPath != default && ftdiBusPath != default)
                    {
                        WaitFm.Debug("Detected drivers: SILABSER, CH34SER, FTDIPORT-FTDIBUS", Event.Success);

                        await CreateMessage("Found multiple device drivers", "We found device drivers for Silicon Labs, CH34 and FTDI compatible " +
                            "devices on this PC. The correct driver will automatically take control of your device when flashing.", 10);
                    }
                    else
                    {
                        if (silabserPath != default)
                        {
                            WaitFm.Debug("Detected driver: SILABSER", Event.Success);

                            await CreateMessage("Found device driver (Silicon Labs)", "We found a device driver for Silicon Labs devices on this PC. " +
                                "Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
                        }
                        if (ch34serPath != default)
                        {
                            WaitFm.Debug("Detected driver: CH34SER", Event.Success);

                            await CreateMessage("Found device driver (CH34)", "We found a device driver for CH34 devices on this PC. " +
                                "Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
                        }
                        if (ftdiBusPath != default && ftdiPortPath != default)
                        {
                            WaitFm.Debug("Detected driver: FTDIPORT-FTDIBUS", Event.Success);

                            await CreateMessage("Found device driver (FTDI)", "We found a device driver for FTDI devices on this PC. " +
                                "Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
                        }
                        else if (ftdiBusPath != default || ftdiPortPath != default)
                        {
                            WaitFm.Debug($"Detected partial driver: {(ftdiPortPath != default ? "FTDIPORT" : ftdiBusPath != default ? "FTDIBUS" : "?")}", Event.Warning);

                            await CreateMessage("Found device driver files (FTDI)", "We found parts of a device driver package for FTDU " +
                                "devices on this PC. The driver might not be installed correctly. Ensure the driver is correct and/or " +
                                "installed correctly.", 7);
                        }
                    }
                }
            }

InitTaskEnd:
            WaitFm.Caption(""); 
            await Task.Delay(1000);
            WaitFm.Host.CloseTask();

            WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
            TaskManager.ReleaseFLock();

            if (Program.Settings.PortFix)
            {
                Invoke(new Action(() =>
                {
                    mitigationNotice.Show();
                    CreateForegroundTask("devicescan-patch", new Task(delegate() { }), "", "Please connect your device to this PC. When you've confirmed it's connected, click Continue.");
                }));
            }
            else
            {
                Invoke(new Action(() =>
                {
                    CreateForegroundTask("devicescan", new Task(Search), "Searching for your device", "You should connect your device now");
                }));
            }
        }

19 Source : Amf0Reader.cs
with MIT License
from a1q123456

public void RegisterType<T>() where T : new()
        {
            var type = typeof(T);
            var props = type.GetProperties();
            var fields = props.Where(p => p.CanWrite && Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute)) != null).ToList();
            var members = fields.ToDictionary(p => ((ClreplacedFieldAttribute)Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute))).Name ?? p.Name, p => new Action<object, object>(p.SetValue));
            if (members.Keys.Where(s => string.IsNullOrEmpty(s)).Any())
            {
                throw new InvalidOperationException("Field name cannot be empty or null");
            }
            string mapedName = null;
            var attr = type.GetCustomAttribute<TypedObjectAttribute>();
            if (attr != null)
            {
                mapedName = attr.Name;
            }
            var typeName = mapedName == null ? type.Name : mapedName;
            var state = new TypeRegisterState()
            {
                Members = members,
                Type = type
            };
            _registeredTypes.Add(type);
            _registeredTypeStates.Add(typeName, state);
            _amf3Reader.RegisterTypedObject(typeName, state);
        }

19 Source : CommandMessage.cs
with MIT License
from a1q123456

public void SerializeAmf0(SerializationContext context)
        {
            using (var writeContext = new Amf.Serialization.Amf0.SerializationContext(context.WriteBuffer))
            {
                if (ProcedureName == null)
                {
                    ProcedureName = GetType().GetCustomAttribute<RtmpCommandAttribute>().Name;
                }
                Debug.replacedert(!string.IsNullOrEmpty(ProcedureName));
                context.Amf0Writer.WriteBytes(ProcedureName, writeContext);
                context.Amf0Writer.WriteBytes(TranscationID, writeContext);
                context.Amf0Writer.WriteValueBytes(CommandObject, writeContext);
                var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
                foreach (var optionArgument in optionArguments)
                {
                    context.Amf0Writer.WriteValueBytes(optionArgument.GetValue(this), writeContext);
                }
            }
        }

19 Source : FsmUtil.cs
with GNU General Public License v3.0
from a2659802

public static void RemoveAction(PlayMakerFSM fsm, string stateName, int index)
        {
            foreach (FsmState t in fsm.FsmStates)
            {
                if (t.Name != stateName) continue;
                FsmStateAction[] actions = t.Actions;

                FsmStateAction action = fsm.GetAction(stateName, index);
                actions = actions.Where(x => x != action).ToArray();
                Log(action.GetType().ToString());

                t.Actions = actions;
            }
        }

19 Source : ReflectionCache.cs
with GNU General Public License v3.0
from a2659802

public static List<PropertyInfo> GereplacedemProps(Type t,Operation op)
        {
            
            if(ItemPropCache.TryGetValue(t,out var props))
            {
                if (props.TryGetValue(op, out var res))
                    return res;
                else
                    return null; 
            }
            var handle_prop = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(HandleAttribute), true).Any());
            Dictionary<Operation, List<PropertyInfo>> opbind = new Dictionary<Operation, List<PropertyInfo>>();
            foreach(var p in handle_prop)
            {
                Operation p_op = p.GetCustomAttributes(typeof(HandleAttribute), true).OfType<HandleAttribute>().FirstOrDefault().handleType;
                if (opbind.TryGetValue(p_op, out var list))
                {
                    list.Add(p);
                }
                else
                {
                    opbind.Add(p_op, new List<PropertyInfo> { p });
                }
                //Logger.LogDebug($"Cache: {p_op}:{p.Name},{t}");
            }
            ItemPropCache.Add(t, opbind);

            if (ItemPropCache.TryGetValue(t, out var props2))
            {
                if (props2.TryGetValue(op, out var res2))
                    return res2;
                else
                    return null;
            }
            else
                return null;
        }

19 Source : RepositoryBase.cs
with MIT License
from a34546

public virtual List<TEnreplacedy> GetAll(Expression<Func<TEnreplacedy, bool>> predicate)
        {
            return Query().Where(x => x.IsDelete == false).Where(predicate).ToList();
        }

19 Source : SerialBusManager.cs
with GNU General Public License v3.0
from a4004

private static string GetDeviceName(string comPort)
        {
            try
            {
                string result = new ManagementObjectSearcher("Select * from Win32_SerialPort")
                    .Get().OfType<ManagementObject>()
                    .Where(o => comPort.Equals(o["DeviceID"]))
                    .First().Properties.OfType<PropertyData>()
                    .Where(t => t.Name.Equals("Description"))
                    .First().Value as string;

                return result;
            }
            catch
            {
                return $"Unknown device ({comPort})";
            }
        }

19 Source : WindowManager.cs
with GNU General Public License v3.0
from a4004

public static void UnmountWindow(Control.ControlCollection parent, Form window)
        {
            if (window.InvokeRequired)
            {
                Program.Debug("windowmgr", $"Request to unmount {window.Name} into {parent.Owner.Name} requires control invokation.");
                Program.Debug("windowmgr", "Invoking the request on the UI thread.");

                window.Invoke(new Action(() => UnmountWindow(parent, window)));
                return;
            }

            foreach (Form w in parent.OfType<Form>().Where(a => a.Handle == window.Handle))
            {
                Program.Debug("windowmgr", $"Removing window {window.Name} from {parent.Owner.Name}");

                parent.Remove(w);
                w.Close();
                w.Dispose();
            }
        }

19 Source : WorkbookStream.cs
with Apache License 2.0
from aaaddress1

public List<BiffRecord> GetAllRecordsByType(RecordType type)
        {
            return _biffRecords.Where(r => r.Id == type).Select(r => (BiffRecord)r.Clone()).ToList();
        }

19 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream NeuterAutoOpenCells()
        {
            List<Lbl> autoOpenLbls = WbStream.GetAutoOpenLabels();

            List<BOF> macroSheetBofs = WbStream.GetMacroSheetBOFs();

            List<BiffRecord> macroSheetRecords =
                macroSheetBofs.SelectMany(bof => WbStream.GetRecordsForBOFRecord(bof)).ToList();

            List<BiffRecord> macroFormulaRecords = macroSheetRecords.Where(record => record.Id == RecordType.Formula).ToList();
            List<Formula> macroFormulas = macroFormulaRecords.Select(r => r.AsRecordType<Formula>()).ToList();

            foreach (Lbl autoOpenLbl in autoOpenLbls)
            {
                int autoOpenRw, autoOpenCol;
                switch (autoOpenLbl.rgce.First())
                {
                    case PtgRef3d ptgRef3d:
                        autoOpenCol = ptgRef3d.col;
                        autoOpenRw = ptgRef3d.rw;
                        break;
                    case PtgRef ptgRef:
                        autoOpenRw = ptgRef.rw;
                        autoOpenCol = ptgRef.col;
                        break;
                    default:
                        throw new NotImplementedException("Auto_Open Ptg Expressions that aren't PtgRef or PtgRef3d Not Implemented");
                }

                //TODO Add proper sheet referencing here so we don't just grab them all
                List<Formula> matchingFormulas =
                    macroFormulas.Where(f => f.col == autoOpenCol && f.rw == autoOpenRw).ToList();

                foreach (var matchingFormula in matchingFormulas)
                {
                    //TODO [Bug] This will currently break the entire sheet from loading. Not COMPLETED
                    Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>();
                    ptgStack.Push(new PtgConcat());
                    AbstractPtg[] ptgArray = matchingFormula.ptgStack.Reverse().ToArray();
                    foreach (var elem in ptgArray)
                    {
                        ptgStack.Push(elem);
                    }
                    ptgStack.Push(new PtgFunc(FtabValues.HALT, AbstractPtg.PtgDataType.VALUE));
                    Formula clonedFormula = ((BiffRecord) matchingFormula.Clone()).AsRecordType<Formula>();
                    clonedFormula.SetCellParsedFormula(new CellParsedFormula(ptgStack));

                    WbStream = WbStream.ReplaceRecord(matchingFormula, clonedFormula);
                }
            }

            return WbStream;
        }

19 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream NeuterAutoOpenCells()
        {
            List<Lbl> autoOpenLbls = WbStream.GetAutoOpenLabels();

            List<BOF> macroSheetBofs = WbStream.GetMacroSheetBOFs();

            List<BiffRecord> macroSheetRecords =
                macroSheetBofs.SelectMany(bof => WbStream.GetRecordsForBOFRecord(bof)).ToList();

            List<BiffRecord> macroFormulaRecords = macroSheetRecords.Where(record => record.Id == RecordType.Formula).ToList();
            List<Formula> macroFormulas = macroFormulaRecords.Select(r => r.AsRecordType<Formula>()).ToList();

            foreach (Lbl autoOpenLbl in autoOpenLbls)
            {
                int autoOpenRw, autoOpenCol;
                switch (autoOpenLbl.rgce.First())
                {
                    case PtgRef3d ptgRef3d:
                        autoOpenCol = ptgRef3d.col;
                        autoOpenRw = ptgRef3d.rw;
                        break;
                    case PtgRef ptgRef:
                        autoOpenRw = ptgRef.rw;
                        autoOpenCol = ptgRef.col;
                        break;
                    default:
                        throw new NotImplementedException("Auto_Open Ptg Expressions that aren't PtgRef or PtgRef3d Not Implemented");
                }

                //TODO Add proper sheet referencing here so we don't just grab them all
                List<Formula> matchingFormulas =
                    macroFormulas.Where(f => f.col == autoOpenCol && f.rw == autoOpenRw).ToList();

                foreach (var matchingFormula in matchingFormulas)
                {
                    //TODO [Bug] This will currently break the entire sheet from loading. Not COMPLETED
                    Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>();
                    ptgStack.Push(new PtgConcat());
                    AbstractPtg[] ptgArray = matchingFormula.ptgStack.Reverse().ToArray();
                    foreach (var elem in ptgArray)
                    {
                        ptgStack.Push(elem);
                    }
                    ptgStack.Push(new PtgFunc(FtabValues.HALT, AbstractPtg.PtgDataType.VALUE));
                    Formula clonedFormula = ((BiffRecord) matchingFormula.Clone()).AsRecordType<Formula>();
                    clonedFormula.SetCellParsedFormula(new CellParsedFormula(ptgStack));

                    WbStream = WbStream.ReplaceRecord(matchingFormula, clonedFormula);
                }
            }

            return WbStream;
        }

19 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream InsertBoundSheetRecord(BoundSheet8 boundSheet8)
        {
            List<BiffRecord> records = WbStream.Records;

            List<BoundSheet8> sheets = records.Where(r => r.Id == RecordType.BoundSheet8).Select(sheet => BuildBoundSheetFromBytes(sheet.GetBytes())).ToList();
            
            boundSheet8.lbPlyPos = sheets.First().lbPlyPos;
            sheets.Add(boundSheet8);

            foreach (var sheet in sheets)
            {
                sheet.lbPlyPos += boundSheet8.Length;
            }


            var preSheetRecords = records.TakeWhile(r => r.Id != RecordType.BoundSheet8);
            var postSheetRecords = records.SkipWhile(r => r.Id != RecordType.BoundSheet8)
                .SkipWhile(r => r.Id == RecordType.BoundSheet8);

            List<BiffRecord> newRecordList = preSheetRecords.Concat(sheets).Concat(postSheetRecords).ToList();

            WorkbookStream newStream = new WorkbookStream(newRecordList);

            WbStream = newStream;

            return WbStream;
        }

19 Source : WorkbookStream.cs
with Apache License 2.0
from aaaddress1

public int GetFirstEmptyRowInColumn(int col)
        {
            List<Formula> colFormulas = GetAllRecordsByType<Formula>().Where(f => f.col == col).ToList();
            int maxRwVal = 0;
            foreach (var colFormula in colFormulas)
            {
                if (colFormula.rw > maxRwVal) maxRwVal = colFormula.rw;
            }

            return maxRwVal;
        }

19 Source : Attributes.cs
with Apache License 2.0
from aadreja

internal bool IsKeyIdEmpty(object enreplacedy)
        {
            if (Columns.Where(p=>p.Value.IsPrimaryKey).Count()==0)
                return true;

            bool result = false;
            foreach (ColumnAttribute c in Columns.Where(p => p.Value.IsPrimaryKey).Select(a=>a.Value))
            {
                result = IsKeyFieldEmpty(c.GetAction(enreplacedy), c.replacedle);

                if (result)
                    break;
            }
            return result;
        }

19 Source : Attributes.cs
with Apache License 2.0
from aadreja

internal bool IsIdenreplacedyKeyIdEmpty(object enreplacedy)
        {
            if (Columns.Where(p => p.Value.IsPrimaryKey && p.Value.PrimaryKeyInfo.IsIdenreplacedy).Count() == 0)
                return true;

            ColumnAttribute pkIdenreplacedyCol = Columns.Where(p => p.Value.IsPrimaryKey && p.Value.PrimaryKeyInfo.IsIdenreplacedy).Select(p=>p.Value).FirstOrDefault();
            return IsKeyFieldEmpty(pkIdenreplacedyCol.GetAction(enreplacedy), pkIdenreplacedyCol.replacedle);
        }

19 Source : Attributes.cs
with Apache License 2.0
from aadreja

internal bool IsKeyIdenreplacedy()
        {
            //TODO: Test Pending
            return Columns.Where(p => p.Value.IsPrimaryKey).LongCount(p => p.Value.PrimaryKeyInfo.IsIdenreplacedy) > 0;
        }

19 Source : WorkbookStream.cs
with Apache License 2.0
from aaaddress1

public bool ContainsRecord(BiffRecord record)
        {
            var matchingRecordTypes = _biffRecords.Where(r => r.Id == record.Id).ToList();
            return matchingRecordTypes.Any(r => r.Equals(record));
        }

19 Source : VxHelpers.cs
with MIT License
from Aaltuj

internal static IEnumerable<PropertyInfo> GetModelProperties(Type modelType)
        {
            return modelType.GetProperties()
                     .Where(w => w.GetCustomAttribute<VxIgnoreAttribute>() == null);
        }

19 Source : VxHelpers.cs
with MIT License
from Aaltuj

internal static bool TypeImplementsInterface(Type type, Type typeToImplement)
        {
            Type foundInterface = type
                .GetInterfaces()
                .Where(i =>
                {
                    return i.Name == typeToImplement.Name;
                })
                .Select(i => i)
                .FirstOrDefault();

            return foundInterface != null;
        }

19 Source : UserModule.cs
with Apache License 2.0
from AantCoder

[Command("help")]
        [Description("List of all commands")]
        //RU: Выводит список команд
        public async Task Helpsync()
        {
            var sb = new StringBuilder();
            foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
            {
                if (!(type.IsClreplaced && type.IsSubclreplacedOf(typeof(ModuleBase<SocketCommandContext>))))
                {
                    continue;
                }

                foreach (var method in type.GetMethods().Where(x => x.IsPublic && x.GetCustomAttribute<CommandAttribute>() != null && x.GetCustomAttribute<CommandAttribute>() != null))
                {
                    DescriptionAttribute desc = method.GetCustomAttribute<DescriptionAttribute>();
                    CommandAttribute cmd = method.GetCustomAttribute<CommandAttribute>();

                    if (!string.IsNullOrEmpty(desc.Description))
                    {
                        // !OC help: 
                        sb.Append(Program.PX + ' ');
                        sb.Append(cmd.Text);
                        sb.Append(": ");
                        sb.Append(desc.Description);
                        sb.AppendLine();
                    }
                }
            }

            await ReplyAsync(sb.ToString());
        }

19 Source : GamePatch.cs
with Apache License 2.0
from AantCoder

[HarmonyPrefix]
        public static bool Prefix()
        {
            if (!GameXMLUtils.FromXmlIsActive) return true;
            if (Current.Game == null) return true;

            if (Scribe.loader?.crossRefs?.crossReferencingExposables == null) return true;

            Scribe.loader.crossRefs.crossReferencingExposables.AddRange(crossReferencingExposables
                .Where(e => !Scribe.loader.crossRefs.crossReferencingExposables.Any(ee => ee == e))
                .ToList());

            crossReferencingExposables = new List<IExposable>();

            return true;
        }

19 Source : UpdateWorldController.cs
with Apache License 2.0
from AantCoder

public static void SendToServer(ModelPlayToServer toServ, bool firstRun, ModelGameServerInfo modelGameServerInfo)
        {
            //Loger.Log("Empire=" + Find.FactionManager.FirstFactionOfDef(FactionDefOf.Empire)?.GetUniqueLoadID());

            toServ.LastTick = (long)Find.TickManager.TicksGame;
            var gameProgress = new PlayerGameProgress();

            var allWorldObjectsArr = new WorldObject[Find.WorldObjects.AllWorldObjects.Count];
            Find.WorldObjects.AllWorldObjects.CopyTo(allWorldObjectsArr);

            var allWorldObjects = allWorldObjectsArr.Where(wo => wo != null).ToList();
            List<Faction> factionList = Find.FactionManager.AllFactionsListForReading;

            if (SessionClientController.Data.GeneralSettings.EquableWorldObjects)
            {
                #region Send to Server: firstRun EquableWorldObjects
                try
                {
                    // Game on init
                    if (firstRun && modelGameServerInfo != null)
                    {
                        if (modelGameServerInfo.WObjectOnlineList.Count > 0)
                        {
                            toServ.WObjectOnlineList = allWorldObjectsArr.Where(wo => wo is Settlement)
                                                                 .Where(wo => wo.HasName && !wo.Faction.IsPlayer).Select(obj => GetWorldObjects(obj)).ToList();
                        }

                        if(modelGameServerInfo.FactionOnlineList.Count > 0)
                        {
                            List <Faction> factions = Find.FactionManager.AllFactionsListForReading;
                            toServ.FactionOnlineList = factions.Select(obj => GetFactions(obj)).ToList();
                        }
                        return;
                    }
                }
                catch (Exception e)
                {
                    Loger.Log("Exception >> " + e);
                    Log.Error("SendToServer FirstRun error");
                    return;
                }
                #endregion
            }

            if (!firstRun)
            {
                //Loger.Log("Client TestBagSD 035");
                Dictionary<Map, List<Pawn>> cacheColonists = new Dictionary<Map, List<Pawn>>();
                //отправка всех новых и измененных объектов игрока
                toServ.WObjects = allWorldObjects
                    .Where(o => o.Faction?.IsPlayer == true //o.Faction != null && o.Faction.IsPlayer
                        && (o is Settlement || o is Caravan)) //Чтобы отсеч разные карты событий
                    .Select(o => GetWorldObjectEntry(o, gameProgress, cacheColonists))
                    .ToList();
                LastSendMyWorldObjects = toServ.WObjects;

                //Loger.Log("Client TestBagSD 036");
                //свои объекты которые удалил пользователь с последнего обновления
                if (ToDelete != null)
                {
                    var toDeleteNewNow = WorldObjectEntrys
                        .Where(p => !allWorldObjects.Any(wo => wo.ID == p.Key))
                        .Select(p => p.Value)
                        .ToList();
                    ToDelete.AddRange(toDeleteNewNow);
                }

                toServ.WObjectsToDelete = ToDelete;
            }
            toServ.GameProgress = gameProgress;

            if (SessionClientController.Data.GeneralSettings.EquableWorldObjects)
            {
                #region Send to Server: Non-Player World Objects
                //  Non-Player World Objects
                try
                {
                    var OnlineWObjArr = allWorldObjectsArr.Where(wo => wo is Settlement)
                                          .Where(wo => wo.HasName && !wo.Faction.IsPlayer);
                    if (!firstRun)
                    {
                        if (LastWorldObjectOnline != null && LastWorldObjectOnline.Count > 0)
                        {
                            toServ.WObjectOnlineToDelete = LastWorldObjectOnline.Where(WOnline => !OnlineWObjArr.Any(wo => ValidateOnlineWorldObject(WOnline, wo))).ToList();

                            toServ.WObjectOnlineToAdd = OnlineWObjArr.Where(wo => !LastWorldObjectOnline.Any(WOnline => ValidateOnlineWorldObject(WOnline, wo)))
                                                                        .Select(obj => GetWorldObjects(obj)).ToList();
                        }
                    }

                    toServ.WObjectOnlineList = OnlineWObjArr.Select(obj => GetWorldObjects(obj)).ToList();
                    LastWorldObjectOnline = toServ.WObjectOnlineList;
                }
                catch (Exception e)
                {
                    Loger.Log("Exception >> " + e);
                    Log.Error("ERROR SendToServer WorldObject Online");
                }
                #endregion

                #region Send to Server: Non-Player Factions
                // Non-Player Factions
                try
                {
                    if (!firstRun)
                    {
                        if (LastFactionOnline != null && LastFactionOnline.Count > 0)
                        {
                            toServ.FactionOnlineToDelete = LastFactionOnline.Where(FOnline => !factionList.Any(f => ValidateFaction(FOnline, f))).ToList();

                            toServ.FactionOnlineToAdd = factionList.Where(f => !LastFactionOnline.Any(FOnline => ValidateFaction(FOnline, f)))
                                                                        .Select(obj => GetFactions(obj)).ToList();
                        }
                    }

                    toServ.FactionOnlineList = factionList.Select(obj => GetFactions(obj)).ToList();
                    LastFactionOnline = toServ.FactionOnlineList;
                }
                catch (Exception e)
                {
                    Loger.Log("Exception >> " + e);
                    Log.Error("ERROR SendToServer Faction Online");
                }
                #endregion
            }
        }

19 Source : ServiceContext.cs
with Apache License 2.0
from AantCoder

public void Logined()
        {
            if (IntruderKeys != null)
            {
                if (Player.IntruderKeys == null) Player.IntruderKeys = "";

                var lks = Player.IntruderKeys.Split("@@@")
                    .Where(k => k.Length > 3)
                    .ToList();

                var add = IntruderKeys.Split("@@@")
                    .Where(k => k.Length > 3)
                    .Where(k => !lks.Contains(k))
                    .ToList();

                if (add.Count > 0) Player.IntruderKeys = lks.Union(add).Aggregate((r, k) => r + "@@@" + k);
            }

        }

19 Source : Repository.cs
with Apache License 2.0
from AantCoder

public static bool CheckIsIntruder(string key)
        {
            if ((DateTime.UtcNow - BlockkeyUpdate).TotalSeconds > 30)
            {
                var fileName = Loger.PathLog + "blockkey.txt";

                BlockkeyUpdate = DateTime.UtcNow;
                if (!File.Exists(fileName)) Blockkey = new HashSet<string>();
                else
                    try
                    {
                        var listBlock = File.ReadAllLines(fileName, Encoding.UTF8)
                            .Select(b => b.Replace("@@@", "").Trim())
                            .Select(b => b.Contains(" ") ? b.Substring(0, b.IndexOf(" ")) : b)
                            .Where(b => b != String.Empty)
                            .ToArray();
                        Blockkey = new HashSet<string>(listBlock);
                    }
                    catch (Exception exp)
                    {
                        Loger.Log("CheckIsIntruder error " + exp.Message);
                        Blockkey = new HashSet<string>();
                        return false;
                    }
            }
            var k = key.Replace("@@@", "").Trim();
            return Blockkey.Contains(k);
        }

See More Examples