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

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

5695 Examples 7

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

public void RebuildList() {
            if (MDraw.DefaultFont == null || Client == null || Channels == null)
                return;

            DataPlayerInfo[] all = Client.Data.GetRefs<DataPlayerInfo>();

            List<Blob> list = new() {
                new Blob {
                    Text = $"{all.Length} player{(all.Length == 1 ? "" : "s")}",
                    Color = ColorCountHeader
                }
            };

            StringBuilder builder = new();


            switch (Mode) {
                case ListMode.Clreplacedic:
                    foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
                        if (string.IsNullOrWhiteSpace(player.DisplayName))
                            continue;

                        builder.Append(player.DisplayName);

                        DataChannelList.Channel channel = Channels.List.FirstOrDefault(c => c.Players.Contains(player.ID));
                        if (channel != null && !string.IsNullOrEmpty(channel.Name)) {
                            builder
                                .Append(" #")
                                .Append(channel.Name);
                        }

                        if (Client.Data.TryGetBoundRef(player, out DataPlayerState state))
                            AppendState(builder, state);

                        builder.AppendLine();
                    }

                    list.Add(new() {
                        Text = builder.ToString().Trim(),
                        ScaleFactor = 1f
                    });
                    break;

                case ListMode.Channels:
                    HashSet<DataPlayerInfo> listed = new();

                    DataChannelList.Channel own = Channels.List.FirstOrDefault(c => c.Players.Contains(Client.PlayerInfo.ID));

                    if (own != null) {
                        list.Add(new() {
                            Text = own.Name,
                            Color = ColorChannelHeaderOwn
                        });

                        builder.Clear();
                        foreach (DataPlayerInfo player in own.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p))) 
                            listed.Add(ListPlayerUnderChannel(builder, player));
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 0.5f
                        });
                    }

                    foreach (DataChannelList.Channel channel in Channels.List) {
                        if (channel == own)
                            continue;

                        list.Add(new() {
                            Text = channel.Name,
                            Color = ColorChannelHeader
                        });

                        builder.Clear();
                        foreach (DataPlayerInfo player in channel.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p)))
                            listed.Add(ListPlayerUnderChannel(builder, player));
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 1f
                        });
                    }

                    bool wrotePrivate = false;

                    builder.Clear();
                    foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
                        if (listed.Contains(player) || string.IsNullOrWhiteSpace(player.DisplayName))
                            continue;

                        if (!wrotePrivate) {
                            wrotePrivate = true;
                            list.Add(new() {
                                Text = "!<private>",
                                Color = ColorChannelHeaderPrivate
                            });
                        }

                        builder.AppendLine(player.DisplayName);
                    }

                    if (wrotePrivate) {
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 1f
                        });
                    }
                    break;
            }

            List = list;
        }

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

public void Tick(bool inCombat) {
            if (!JobBars.Config.BuffBarEnabled) return;
            if (JobBars.Config.BuffHideOutOfCombat) {
                if (inCombat) JobBars.Builder.ShowBuffs();
                else JobBars.Builder.HideBuffs();
            }

            Dictionary<uint, BuffPartyMember> newObjectIdToMember = new();
            HashSet<BuffTracker> activeBuffs = new();

            if (JobBars.PartyMembers == null) PluginLog.LogError("PARTYMEMBERS IS NULL");

            for (int idx = 0; idx < JobBars.PartyMembers.Count; idx++) {
                var partyMember = JobBars.PartyMembers[idx];

                if (partyMember == null || partyMember?.Job == JobIds.OTHER || partyMember?.ObjectId == 0) continue;
                if (!JobBars.Config.BuffIncludeParty && partyMember.ObjectId != JobBars.ClientState.LocalPlayer.ObjectId) continue;

                var member = ObjectIdToMember.TryGetValue(partyMember.ObjectId, out var _member) ? _member : new BuffPartyMember(partyMember.ObjectId, partyMember.IsPlayer);
                var highlightMember = member.Tick(activeBuffs, partyMember);
                JobBars.Builder.SetBuffPartyListVisible(idx, JobBars.Config.BuffPartyListEnabled && highlightMember);
                newObjectIdToMember[partyMember.ObjectId] = member;
            }
            for (int idx = JobBars.PartyMembers.Count; idx < 8; idx++) {
                JobBars.Builder.SetBuffPartyListVisible(idx, false);
            }

            var buffIdx = 0;
            foreach (var buff in JobBars.Config.BuffOrderByActive ?
                activeBuffs.OrderBy(b => b.CurrentState) :
                activeBuffs.OrderBy(b => b.Id)
            ) {
                if (buffIdx >= (UIBuilder.MAX_BUFFS - 1)) break;
                buff.TickUI(JobBars.Builder.Buffs[buffIdx]);
                buffIdx++;
            }
            for (int i = buffIdx; i < UIBuilder.MAX_BUFFS; i++) {
                JobBars.Builder.Buffs[i].Hide(); // hide unused
            }

            ObjectIdToMember = newObjectIdToMember;
        }

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

public async Task<IReadOnlyList<TableModel>> SelectTables()
        {
            var columnsRaw = await this.Database.LoadColumns();
            var indexes = await this.Database.LoadIndexes();
            var fk = await this.Database.LoadForeignKeys();

            var acc = new Dictionary<TableRef, Dictionary<ColumnRef, ColumnModel>>();

            foreach (var rawColumn in columnsRaw)
            {
                var table = rawColumn.DbName.Table;
                if (!acc.TryGetValue(table, out var colList))
                {
                    colList = new Dictionary<ColumnRef, ColumnModel>();
                    acc.Add(table, colList);
                }

                var colModel = BuildColumnModel(
                    rawColumn,
                    indexes.Pks.TryGetValue(table, out var pkCols) ? pkCols.Columns : null,
                    fk.TryGetValue(rawColumn.DbName, out var fkList) ? fkList : null);

                colList.Add(colModel.DbName, colModel);
            }

            var sortedTables = SortTablesByForeignKeys(acc: acc);

            var result = sortedTables.Select(t =>
                    new TableModel(
                        name: ToTableCrlName(tableRef: t),
                        dbName: t,
                        columns: acc[key: t]
                            .Select(p => p.Value)
                            .OrderBy(c => c.Pk?.Index ?? 10000)
                            .ThenBy(c => c.OrdinalPosition)
                            .ToList(),
                        indexes: indexes.Indexes.TryGetValue(key: t, value: out var tIndexes)
                            ? tIndexes
                            : new List<IndexModel>(capacity: 0)))
                .ToList();

            EnsureTableNamesAreUnique(result, this.Database.DefaultSchemaName);

            return result;

        }

19 Source : GameConversationsController.cs
with MIT License
from 0xbustos

public void AddConversation()
        {
            PendingStatus unlockedStatus = this.model.ConversationsToAdd[0];
            this.model.ConversationsToAdd.RemoveAt( 0 );
            Dictionary<string, List<PendingStatus>> conversations = this.model.PendingConversations;
            if (!conversations.ContainsKey( unlockedStatus.ConversationName ))
            {
                conversations[unlockedStatus.ConversationName] = new List<PendingStatus>();
            }

            List<PendingStatus> pending = conversations[unlockedStatus.ConversationName];
            PendingStatus match = pending.Where( status => status.ConversationName == unlockedStatus.StatusName ).FirstOrDefault();
            if (match == null)
            {
                pending.Add( unlockedStatus );
                pending.OrderBy( status => status.Importance );
            }
        }

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

public static IReadOnlyList<SqModelMeta> Createreplacedysis(this IEnumerable<SqModelMetaRaw> rawModels)
        {
            var acc = new Dictionary<string, SqModelMeta>();

            foreach (var raw in rawModels)
            {
                var meta = GetFromAcc(raw);

                var property = meta.AddPropertyCheckExistence(new SqModelPropertyMeta(raw.FieldName, raw.FieldTypeName, raw.CastTypeName, raw.IsPrimaryKey, raw.IsIdenreplacedy));

                property.AddColumnCheckExistence(meta.Name, new SqModelPropertyTableColMeta(new SqModelTableRef(raw.TableName, raw.TableNamespace, raw.BaseTypeKindTag), raw.ColumnName));
            }

            var res =  acc.Values.OrderBy(v => v.Name).ToList();

            foreach (var model in res)
            {
                int? num = null;

                foreach (var p in model.Properties)
                {
                    if (num == null)
                    {
                        num = p.Column.Count;
                    }
                    else
                    {
                        if (num.Value != p.Column.Count)
                        {
                            throw new SqExpressCodeGenException($"{nameof(SqModelAttribute)} with name \"{model.Name}\" was declared in several table descriptors but numbers of properties do not match");
                        }
                    }
                }
            }


            return res;

            SqModelMeta GetFromAcc(SqModelMetaRaw raw)
            {
                if (acc.TryGetValue(raw.ModelName, out var result))
                {
                    return result;
                }

                var meta = new SqModelMeta(raw.ModelName);
                acc.Add(raw.ModelName, meta);
                return meta;
            }
            

        }

19 Source : ExifWriter.cs
with MIT License
from 0xC0000054

private void WriteDirectory(BinaryWriter writer, Dictionary<ushort, MetadataEntry> tags, List<IFDEntry> entries, long ifdOffset)
        {
            writer.BaseStream.Position = ifdOffset;

            long nextIFDPointerOffset = ifdOffset + sizeof(ushort) + ((long)entries.Count * IFDEntry.SizeOf);

            writer.Write((ushort)entries.Count);

            foreach (IFDEntry entry in entries.OrderBy(e => e.Tag))
            {
                entry.Write(writer);

                if (!TagDataTypeUtil.ValueFitsInOffsetField(entry.Type, entry.Count))
                {
                    long oldPosition = writer.BaseStream.Position;

                    writer.BaseStream.Position = entry.Offset;

                    writer.Write(tags[entry.Tag].GetDataReadOnly());

                    writer.BaseStream.Position = oldPosition;
                }
            }

            writer.BaseStream.Position = nextIFDPointerOffset;
            // There is only one IFD in this directory.
            writer.Write(0);
        }

19 Source : ExifWriter.cs
with MIT License
from 0xC0000054

private static IFDEntryInfo CreateIFDList(Dictionary<ushort, MetadataEntry> tags, long startOffset)
        {
            List<IFDEntry> ifdEntries = new List<IFDEntry>(tags.Count);

            // Leave room for the tag count, tags and next IFD offset.
            long ifdDataOffset = startOffset + sizeof(ushort) + ((long)tags.Count * IFDEntry.SizeOf) + sizeof(uint);

            foreach (KeyValuePair<ushort, MetadataEntry> item in tags.OrderBy(i => i.Key))
            {
                MetadataEntry entry = item.Value;

                uint count;
                switch (entry.Type)
                {
                    case TagDataType.Byte:
                    case TagDataType.Ascii:
                    case TagDataType.SByte:
                    case TagDataType.Undefined:
                        count = (uint)entry.LengthInBytes;
                        break;
                    case TagDataType.Short:
                    case TagDataType.SShort:
                        count = (uint)entry.LengthInBytes / 2;
                        break;
                    case TagDataType.Long:
                    case TagDataType.SLong:
                    case TagDataType.Float:
                        count = (uint)entry.LengthInBytes / 4;
                        break;
                    case TagDataType.Rational:
                    case TagDataType.SRational:
                    case TagDataType.Double:
                        count = (uint)entry.LengthInBytes / 8;
                        break;
                    default:
                        throw new InvalidOperationException("Unexpected tag type.");
                }

                if (TagDataTypeUtil.ValueFitsInOffsetField(entry.Type, count))
                {
                    uint packedOffset = 0;

                    // Some applications may write EXIF fields with a count of zero.
                    // See https://github.com/0xC0000054/pdn-webp/issues/6.
                    if (count > 0)
                    {
                        byte[] data = entry.GetDataReadOnly();

                        // The data is always in little-endian byte order.
                        switch (data.Length)
                        {
                            case 1:
                                packedOffset |= data[0];
                                break;
                            case 2:
                                packedOffset |= data[0];
                                packedOffset |= (uint)data[1] << 8;
                                break;
                            case 3:
                                packedOffset |= data[0];
                                packedOffset |= (uint)data[1] << 8;
                                packedOffset |= (uint)data[2] << 16;
                                break;
                            case 4:
                                packedOffset |= data[0];
                                packedOffset |= (uint)data[1] << 8;
                                packedOffset |= (uint)data[2] << 16;
                                packedOffset |= (uint)data[3] << 24;
                                break;
                            default:
                                throw new InvalidOperationException("data.Length must be in the range of [1-4].");
                        }
                    }

                    ifdEntries.Add(new IFDEntry(entry.TagId, entry.Type, count, packedOffset));
                }
                else
                {
                    ifdEntries.Add(new IFDEntry(entry.TagId, entry.Type, count, (uint)ifdDataOffset));
                    ifdDataOffset += entry.LengthInBytes;

                    // The IFD offsets must begin on a WORD boundary.
                    if ((ifdDataOffset & 1) == 1)
                    {
                        ifdDataOffset++;
                    }
                }
            }

            return new IFDEntryInfo(ifdEntries, startOffset, ifdDataOffset);
        }

19 Source : ExifWriter.cs
with MIT License
from 0xC0000054

private void WriteDirectory(BinaryWriter writer, Dictionary<ushort, MetadataEntry> tags,  List<IFDEntry> entries, long ifdOffset)
        {
            writer.BaseStream.Position = ifdOffset;

            long nextIFDPointerOffset = ifdOffset + sizeof(ushort) + ((long)entries.Count * IFDEntry.SizeOf);

            writer.Write((ushort)entries.Count);

            foreach (IFDEntry entry in entries.OrderBy(e => e.Tag))
            {
                entry.Write(writer);

                if (!TagDataTypeUtil.ValueFitsInOffsetField(entry.Type, entry.Count))
                {
                    long oldPosition = writer.BaseStream.Position;

                    writer.BaseStream.Position = entry.Offset;

                    writer.Write(tags[entry.Tag].GetDataReadOnly());

                    writer.BaseStream.Position = oldPosition;
                }
            }

            writer.BaseStream.Position = nextIFDPointerOffset;
            // There is only one IFD in this directory.
            writer.Write(0);
        }

19 Source : ConsistentHash.cs
with MIT License
from 1100100

public T GetNodeForKey(string key)
        {
            if (!Ring.Any())
                throw new InvalidOperationException("Can not find the available nodes, please call the AddNode method to add nodes.");

            var hash = HashAlgorithm.Hash(key);
            if (Ring.ContainsKey(hash))
                return Ring[hash];
            var node = Ring.Where(p => p.Key > hash).OrderBy(i => i.Key).Select(p => p.Value).FirstOrDefault();
            if (node != null)
                return node;
            return Ring.FirstOrDefault().Value;
        }

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 : MenuService.cs
with MIT License
from 17MKH

private void ResolveTree(IList<MenuEnreplacedy> all, TreeResultModel<MenuEnreplacedy> parent)
    {
        foreach (var menu in all.Where(m => m.ParentId == parent.Id).OrderBy(m => m.Sort))
        {
            var child = new TreeResultModel<MenuEnreplacedy>
            {
                Id = menu.Id,
                Label = menu.Name,
                Item = menu
            };

            child.Path.AddRange(parent.Path);
            child.Path.Add(child.Label);

            //只有节点菜单才有子级
            if (menu.Type == MenuType.Node)
            {
                ResolveTree(all, child);
            }

            parent.Children.Add(child);
        }
    }

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

public void Load()
    {
        var modulesRootPath = Path.Combine(AppContext.BaseDirectory, Constants.ROOT_DIR);
        if (!Directory.Exists(modulesRootPath))
            return;

        var moduleDirs = Directory.GetDirectories(modulesRootPath);
        if (!moduleDirs.Any())
            return;

        _replacedemblyHelper = new replacedemblyHelper();
        var optionsList = new List<ModuleOptions>();
        foreach (var dir in moduleDirs)
        {
            var code = Path.GetFileName(dir)!.Split("_")[1];
            var options = _configuration.Get<ModuleOptions>($"Mkh:Modules:{code}");
            if (options.Db != null)
            {
                options.Code = code;
                options.Dir = dir;
                optionsList.Add(options);
            }
        }

        foreach (var options in optionsList.OrderBy(m => m.Sort))
        {
            LoadModule(options);
        }

        //释放资源
        _replacedemblyHelper = null;
    }

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

private List<TreeResultModel<int, DicreplacedemTreeVo>> ResolveTree(IList<DicreplacedemEnreplacedy> all, int parentId = 0)
    {
        return all.Where(m => m.ParentId == parentId).OrderBy(m => m.Sort).Select(m =>
        {
            var node = new TreeResultModel<int, DicreplacedemTreeVo>
            {
                Id = m.Id,
                Label = m.Name,
                Value = m.Value,
                Item = _mapper.Map<DicreplacedemTreeVo>(m),
                Children = ResolveTree(all, m.Id)
            };

            return node;
        }).ToList();
    }

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

private List<OptionResultModel> ResolveCascader(IList<DicreplacedemEnreplacedy> all, int parentId = 0)
    {
        return all.Where(m => m.ParentId == parentId).OrderBy(m => m.Sort).Select(m =>
        {
            var node = new OptionResultModel
            {
                Label = m.Name,
                Value = m.Value,
                Data = new
                {
                    m.Id,
                    m.Name,
                    m.Value,
                    m.Extend,
                    m.Icon,
                    m.Level
                },
                Children = ResolveCascader(all, m.Id)
            };

            if (!node.Children.Any())
            {
                node.Children = null;
            }
            return node;
        }).ToList();
    }

19 Source : PubSub.cs
with MIT License
from 2881099

void OnData(string pattern, string key, object data)
            {
                var regkey = pattern == null ? key : $"{_psub_regkey_prefix}{pattern}";
                if (_registers.TryGetValue(regkey, out var tryval) == false) return;
                var multirecvs = tryval.Values.OrderBy(a => a.RegTime).ToArray(); //Execute in order
                foreach (var recv in multirecvs)
                    recv.Handler(pattern, key, data);
            }

19 Source : GodotOnReadySourceGenerator.cs
with MIT License
from 31

public void Execute(GeneratorExecutionContext context)
		{
			// If this isn't working, run 'dotnet build-server shutdown' first.
			if (Environment
				.GetEnvironmentVariable($"Debug{nameof(GodotOnReadySourceGenerator)}") == "true")
			{
				Debugger.Launch();
			}

			var receiver = context.SyntaxReceiver as OnReadyReceiver ?? throw new Exception();

			INamedTypeSymbol GetSymbolByName(string fullName) =>
				context.Compilation.GetTypeByMetadataName(fullName)
				?? throw new Exception($"Can't find {fullName}");

			var onReadyGetSymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyGetAttribute");
			var onReadySymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyAttribute");
			var generateDataSelectorEnumSymbol =
				GetSymbolByName("GodotOnReady.Attributes.GenerateDataSelectorEnumAttribute");

			var resourceSymbol = GetSymbolByName("Godot.Resource");
			var nodeSymbol = GetSymbolByName("Godot.Node");

			List<PartialClreplacedAddition> additions = new();

			var clreplacedSymbols = receiver.AllClreplacedes
				.Select(clreplacedDecl =>
				{
					INamedTypeSymbol? clreplacedSymbol = context.Compilation
						.GetSemanticModel(clreplacedDecl.SyntaxTree)
						.GetDeclaredSymbol(clreplacedDecl);

					if (clreplacedSymbol is null)
					{
						context.ReportDiagnostic(
							Diagnostic.Create(
								new DiagnosticDescriptor(
									"GORSG0001",
									"Inspection",
									$"Unable to find declared symbol for {clreplacedDecl}. Skipping.",
									"GORSG.Parsing",
									DiagnosticSeverity.Warning,
									true
								),
								clreplacedDecl.GetLocation()
							)
						);
					}

					return clreplacedSymbol;
				})
				.Distinct(SymbolEqualityComparer.Default)
				.OfType<INamedTypeSymbol>();

			foreach (var clreplacedSymbol in clreplacedSymbols)
			{
				foreach (var attribute in clreplacedSymbol.GetAttributes()
					.Where(a => Equal(a.AttributeClreplaced, generateDataSelectorEnumSymbol)))
				{
					var fields = clreplacedSymbol.GetMembers()
						.OfType<IFieldSymbol>()
						.Where(f => f.IsReadOnly && f.IsStatic)
						.ToArray();

					additions.Add(new DataSelectorEnumAddition(
						fields,
						new AttributeSite(clreplacedSymbol, attribute)));
				}

				var members = Enumerable
					.Concat(
						clreplacedSymbol.GetMembers().OfType<IPropertySymbol>().Select(MemberSymbol.Create),
						clreplacedSymbol.GetMembers().OfType<IFieldSymbol>().Select(MemberSymbol.Create))
					.ToArray();

				foreach (var member in members)
				{
					foreach (var attribute in member.Symbol
						.GetAttributes()
						.Where(a => Equal(a.AttributeClreplaced, onReadyGetSymbol)))
					{
						var site = new MemberAttributeSite(
							member,
							new AttributeSite(clreplacedSymbol, attribute));

						if (site.AttributeSite.Attribute.NamedArguments.Any(
							a => a.Key == "Property" && a.Value.Value is string { Length: > 0 }))
						{
							additions.Add(new OnReadyGetNodePropertyAddition(site));
						}
						else if (member.Type.IsOfBaseType(nodeSymbol))
						{
							additions.Add(new OnReadyGetNodeAddition(site));
						}
						else if (member.Type.IsOfBaseType(resourceSymbol))
						{
							additions.Add(new OnReadyGetResourceAddition(site));
						}
						else
						{
							string issue =
								$"The type '{member.Type}' of '{member.Symbol}' is not supported." +
								" Expected a Resource or Node subclreplaced.";

							context.ReportDiagnostic(
								Diagnostic.Create(
									new DiagnosticDescriptor(
										"GORSG0002",
										"Inspection",
										issue,
										"GORSG.Parsing",
										DiagnosticSeverity.Error,
										true
									),
									member.Symbol.Locations.FirstOrDefault()
								)
							);
						}
					}
				}

				foreach (var methodSymbol in clreplacedSymbol.GetMembers().OfType<IMethodSymbol>())
				{
					foreach (var attribute in methodSymbol
						.GetAttributes()
						.Where(a => Equal(a.AttributeClreplaced, onReadySymbol)))
					{
						additions.Add(new OnReadyAddition(methodSymbol, attribute, clreplacedSymbol));
					}
				}
			}

			foreach (var clreplacedAdditionGroup in additions.GroupBy(a => a.Clreplaced))
			{
				SourceStringBuilder source = CreateInitializedSourceBuilder();

				if (clreplacedAdditionGroup.Key is not { } clreplacedSymbol) continue;

				source.NamespaceBlockBraceIfExists(clreplacedSymbol.GetSymbolNamespaceName(), () =>
				{
					source.Line("public partial clreplaced ", clreplacedAdditionGroup.Key.Name);
					source.BlockBrace(() =>
					{
						foreach (var addition in clreplacedAdditionGroup)
						{
							addition.DeclarationWriter?.Invoke(source);
						}

						if (clreplacedAdditionGroup.Any(a => a.ConstructorStatementWriter is not null))
						{
							source.Line();
							source.Line("public ", clreplacedAdditionGroup.Key.Name, "()");
							source.BlockBrace(() =>
							{
								foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
								{
									addition.ConstructorStatementWriter?.Invoke(source);
								}

								source.Line("Constructor();");
							});

							source.Line("partial void Constructor();");
						}

						if (clreplacedAdditionGroup.Any(a => a.OnReadyStatementWriter is not null))
						{
							source.Line();
							source.Line("public override void _Ready()");
							source.BlockBrace(() =>
							{
								source.Line("base._Ready();");

								// OrderBy is a stable sort.
								// Sort by Order, then by discovery order (implicitly).
								foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
								{
									addition.OnReadyStatementWriter?.Invoke(source);
								}
							});
						}
					});

					foreach (var addition in clreplacedAdditionGroup)
					{
						addition.OutsideClreplacedStatementWriter?.Invoke(source);
					}
				});

				string escapedNamespace =
					clreplacedAdditionGroup.Key.GetSymbolNamespaceName()?.Replace(".", "_") ?? "";

				context.AddSource(
					$"Partial_{escapedNamespace}_{clreplacedAdditionGroup.Key.Name}",
					source.ToString());
			}
		}

19 Source : Seat.cs
with Apache License 2.0
from 42skillz

public bool IsAdjacentWith(List<Seat> seats)
        {
            var orderedSeats = seats.OrderBy(s => s.Number).ToList();

            var seat = orderedSeats.First();

            if (Number + 1 == seat.Number || Number - 1 == seat.Number)
            {
                return true;
            }

            seat = seats.Last();

            return Number + 1 == seat.Number || Number - 1 == seat.Number;
        }

19 Source : SeatCollectionExtensions.cs
with Apache License 2.0
from 42skillz

public static IEnumerable<AdjacentSeats> SelectAdjacentSeats(this IEnumerable<Seat> seats, PartyRequested partyRequested)
        {
            var adjacentSeatsGroups = new List<AdjacentSeats>();
            var adjacentSeats = new List<Seat>();

            if (partyRequested.PartySize == 1)
            {
                return seats.Select(s => new AdjacentSeats(new List<Seat> {s}));
            }

            foreach (var candidateSeat in seats.OrderBy(s => s.DistanceFromRowCentroid))
            {
                if (!adjacentSeats.Any())
                {
                    adjacentSeats.Add(candidateSeat);
                    continue;
                }

                adjacentSeats = adjacentSeats.OrderBy(s => s.Number).ToList();

                if (DoesNotExceedPartyRequestedAndCandidateSeatIsAdjacent(candidateSeat, adjacentSeats, partyRequested))
                {
                    adjacentSeats.Add(candidateSeat);
                }
                else
                {
                    if (adjacentSeats.Any())
                    {
                        adjacentSeatsGroups.Add(new AdjacentSeats(adjacentSeats));
                    }

                    adjacentSeats = new List<Seat> {candidateSeat};
                }
            }

            return adjacentSeatsGroups.Where(adjacent => adjacent.Count() == partyRequested.PartySize);
        }

19 Source : CommandTree.cs
with MIT License
from 5minlab

public string _complete(string[] partialCommand, int index, string result) {
            if (partialCommand.Length == index && m_command != null) {
                // this is a valid command... so we do nothing
                return result;
            } else if (partialCommand.Length == index) {
                // This is valid but incomplete.. print all of the subcommands
                Shell.LogCommand(result);
                foreach (string key in m_subcommands.Keys.OrderBy(m => m)) {
                    Shell.Log(result + " " + key);
                }
                return result + " ";
            } else if (partialCommand.Length == (index + 1)) {
                string partial = partialCommand[index];
                if (m_subcommands.ContainsKey(partial)) {
                    result += partial;
                    return m_subcommands[partial]._complete(partialCommand, index + 1, result);
                }

                // Find any subcommands that match our partial command
                List<string> matches = new List<string>();
                foreach (string key in m_subcommands.Keys.OrderBy(m => m)) {
                    if (key.StartsWith(partial)) {
                        matches.Add(key);
                    }
                }

                if (matches.Count == 1) {
                    // Only one command found, log nothing and return the complete command for the user input
                    return result + matches[0] + " ";
                } else if (matches.Count > 1) {
                    // list all the options for the user and return partial
                    Shell.LogCommand(result + partial);
                    foreach (string match in matches) {
                        Shell.Log(result + match);
                    }
                }
                return result + partial;
            }

            string token = partialCommand[index];
            if (!m_subcommands.ContainsKey(token)) {
                return result;
            }
            result += token + " ";
            return m_subcommands[token]._complete(partialCommand, index + 1, result);
        }

19 Source : CompilationProcessor.cs
with MIT License
from 71

public void RegisterAttributes(IreplacedemblySymbol replacedembly)
        {
            // Sort the attributes based on order and declaration
            // Note: Since we're getting symbols here, the order is based
            // on the order in which the files were read, and the order in code.
            var attributes = replacedembly.GetAttributes();

            // Find all used editors, and register 'em
            var allEditors = new Dictionary<int, IList<CompilationEditor>>(attributes.Length);
            int editorsCount = 0;

            for (int i = 0; i < attributes.Length; i++)
            {
                AttributeData attr = attributes[i];
                INamedTypeSymbol attrType = attr.AttributeClreplaced;

                // Make sure the attribute inherits CometaryAttribute
                for (;;)
                {
                    attrType = attrType.BaseType;

                    if (attrType == null)
                        goto NextAttribute;
                    if (attrType.Name == nameof(CometaryAttribute))
                        break;
                }

                // We got here: we have a cometary attribute
                IEnumerable<CompilationEditor> editors;
                int order;

                try
                {
                    editors = InitializeAttribute(attr, out order);
                }
                catch (TargetInvocationException e)
                {
                    initializationExceptions.Add((e.InnerException, attr));
                    continue;
                }
                catch (TypeInitializationException e)
                {
                    initializationExceptions.Add((e.InnerException, attr));
                    continue;
                }
                catch (Exception e)
                {
                    initializationExceptions.Add((e, attr));
                    continue;
                }

                if (!allEditors.TryGetValue(order, out var editorsOfSameOrder))
                {
                    editorsOfSameOrder = new LightList<CompilationEditor>();
                    allEditors[order] = editorsOfSameOrder;
                }

                foreach (CompilationEditor editor in editors)
                {
                    if (editor == null)
                        continue;

                    editorsOfSameOrder.Add(editor);
                    editorsCount++;
                }

                NextAttribute:;
            }

            Editors.Capacity = Editors.Count + editorsCount;
            Editors.AddRange(allEditors.OrderBy(x => x.Key).SelectMany(x => x.Value));
        }

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 : 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 : Monitor.cs
with Apache License 2.0
from A7ocin

void OnGUI()
    {
        if (!initialized)
        {
            Initialize();
            initialized = true;
        }

        var toIterate = displayTransformValues.Keys.ToList();
        foreach (Transform target in toIterate)
        {
            if (target == null)
            {
                displayTransformValues.Remove(target);
                continue;
            }
 
            float widthScaler = (Screen.width / 1000f);
            float keyPixelWidth = 100 * widthScaler;
            float keyPixelHeight = 20 * widthScaler;
            float paddingwidth = 10 * widthScaler;

            float scale = 1f;
            Vector2 origin = new Vector3(0, Screen.height);
            if (!(target == canvas.transform))
            {
                Vector3 cam2obj = target.position - Camera.main.transform.position;
                scale = Mathf.Min(1, 20f / (Vector3.Dot(cam2obj, Camera.main.transform.forward)));
                Vector3 worldPosition = Camera.main.WorldToScreenPoint(target.position + new Vector3(0, verticalOffset, 0));
                origin = new Vector3(worldPosition.x - keyPixelWidth * scale, Screen.height - worldPosition.y);
            }
            keyPixelWidth *= scale;
            keyPixelHeight *= scale;
            paddingwidth *= scale;
            keyStyle.fontSize = (int)(keyPixelHeight * 0.8f);
            if (keyStyle.fontSize < 2)
            {
                continue;
            }
                

            Dictionary<string, DisplayValue> displayValues = displayTransformValues[target];

            int index = 0;
            foreach (string key in displayValues.Keys.OrderBy(x => -displayValues[x].time))
            {
                keyStyle.alignment = TextAnchor.MiddleRight;
                GUI.Label(new Rect(origin.x, origin.y - (index + 1) * keyPixelHeight, keyPixelWidth, keyPixelHeight), key, keyStyle);
                if (displayValues[key].monitorDisplayType == MonitorType.text)
                {
                    valueStyle.alignment = TextAnchor.MiddleLeft;
                    GUI.Label(new Rect(
                            origin.x + paddingwidth + keyPixelWidth,
                            origin.y - (index + 1) * keyPixelHeight, 
                            keyPixelWidth, keyPixelHeight), 
                        JsonConvert.SerializeObject(displayValues[key].value, Formatting.None), valueStyle);

                }
                else if (displayValues[key].monitorDisplayType == MonitorType.slider)
                {
                    float sliderValue = 0f;
                    if (displayValues[key].value.GetType() == typeof(float))
                    {
                        sliderValue = (float)displayValues[key].value;
                    }
                    else
                    {
                        Debug.LogError(string.Format("The value for {0} could not be displayed as " +
                                "a slider because it is not a number.", key));
                    }

                    sliderValue = Mathf.Min(1f, sliderValue);
                    GUIStyle s = greenStyle;
                    if (sliderValue < 0)
                    {
                        sliderValue = Mathf.Min(1f, -sliderValue);
                        s = redStyle;
                    }
                    GUI.Box(new Rect(
                            origin.x + paddingwidth + keyPixelWidth,
                            origin.y - (index + 0.9f) * keyPixelHeight, 
                            keyPixelWidth * sliderValue, keyPixelHeight * 0.8f), 
                        GUIContent.none, s);

                }
                else if (displayValues[key].monitorDisplayType == MonitorType.hist)
                {
                    float histWidth = 0.15f;
                    float[] vals = ToFloatArray(displayValues[key].value);
                    for (int i = 0; i < vals.Length; i++)
                    {
                        float value = Mathf.Min(vals[i], 1);
                        GUIStyle s = greenStyle;
                        if (value < 0)
                        {
                            value = Mathf.Min(1f, -value);
                            s = redStyle;
                        }
                        GUI.Box(new Rect(
                                origin.x + paddingwidth + keyPixelWidth + (keyPixelWidth * histWidth + paddingwidth / 2) * i,
                                origin.y - (index + 0.1f) * keyPixelHeight, 
                                keyPixelWidth * histWidth, -keyPixelHeight * value), 
                            GUIContent.none, s);
                    }


                }
                else if (displayValues[key].monitorDisplayType == MonitorType.bar)
                {
                    float[] vals = ToFloatArray(displayValues[key].value);
                    float valsSum = 0f;
                    float valsreplaced = 0f; 
                    foreach (float f in vals)
                    {
                        valsSum += Mathf.Max(f, 0);
                    }
                    if (valsSum == 0)
                    {
                        Debug.LogError(string.Format("The Monitor value for key {0} must be "
                                + "a list or array of positive values and cannot be empty.", key));
                    }
                    else
                    {
                        for (int i = 0; i < vals.Length; i++)
                        {
                            float value = Mathf.Max(vals[i], 0) / valsSum;
                            GUI.Box(new Rect(
                                    origin.x + paddingwidth + keyPixelWidth + keyPixelWidth * valsreplaced,
                                    origin.y - (index + 0.9f) * keyPixelHeight, 
                                    keyPixelWidth * value, keyPixelHeight * 0.8f), 
                                GUIContent.none, colorStyle[i % colorStyle.Length]);
                            valsreplaced += value;

                        }

                    }

                }

                index++;
            }
        }
    }

19 Source : ListExtends.cs
with MIT License
from a3geek

public static List<T> Shuffle<T>(this List<T> list)
        {
            return list.OrderBy(e => Guid.NewGuid()).ToList();
        }

19 Source : HuobiAPI.cs
with MIT License
from aabiryukov

private string DoMethod2(string method, NameValueCollection jParams)
		{
            // add some more args for authentication
            var seconds = UnixTime.GetFromDateTime(DateTime.UtcNow);

            var args = new NameValueDictionary
		    {
                {"created", seconds.ToString(CultureInfo.InvariantCulture)},
                {"access_key", m_accessKey},
                {"method", method},
                {"secret_key", m_secretKey}
            };

		    if (jParams != null)
			{
				foreach (var key in jParams.AllKeys)
				{
					args.Add(key, jParams[key]);
				}
			}

            var argsSortedByKey = args.OrderBy(kvp => kvp.Key).ToList();

            var sign = GetSignature(argsSortedByKey);
            argsSortedByKey.Add( new KeyValuePair<string, string>("sign", sign));

			var httpContent = new FormUrlEncodedContent(argsSortedByKey);
			var response = WebApi.Client.PostAsync("apiv3/" + method, httpContent).Result;
			var resultString = response.Content.ReadreplacedtringAsync().Result;

            if (resultString.Contains("code"))
            {
                var error = JsonConvert.DeserializeObject<HuobiError>(resultString);
                throw new HuobiException(method, "Request failed with code: " + error.Code);
            }

            return resultString;
		}

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

public static byte[] CreateListFolder(string directory)
        {
            var dirs = Directory.GetDirectories(directory).OrderBy(x => x);
            var sb = new StringBuilder();
            foreach (var dir in dirs)
            {
                // только для дебага, а то папка Online city каждый раз обновляется

                var di = new DirectoryInfo(dir);
#if DEBUG
                if (di.Name.Equals("OnlineCity"))
                    continue;
#endif
                sb.AppendLine(di.Name);
            }

            var txt = sb.ToString();
            var diRoot = new DirectoryInfo(directory);
            File.WriteAllText(Path.Combine(Loger.PathLog, diRoot.Name + ".txt"), txt);
            return Encoding.ASCII.GetBytes(txt);
        }

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

public ModelInfo GetInfo(ModelInt packet, ServiceContext context)
        {
            lock (context.Player)
            {
                switch (packet.Value)
                {
                    case (long)ServerInfoType.Full:
                        {
                            var result = GetModelInfo(context.Player);
                            return result;
                        }

                    case (long)ServerInfoType.SendSave:
                        {
                            if (context.PossiblyIntruder)
                            {
                                context.Disconnect("Possibly intruder");
                                return null;
                            }
                            var result = new ModelInfo();
                            //передача файла игры, для загрузки WorldLoad();
                            // файл передать можно только в том случае если файлы прошли проверку

                            //!Для Pvp проверка нужна всегда, в PvE нет
                            if (ServerManager.ServerSettings.IsModsWhitelisted)
                            {
                                if ((int)context.Player.ApproveLoadWorldReason > 0)
                                {
                                    context.Player.ExitReason = DisconnectReason.FilesMods;
                                    Loger.Log($"Login : {context.Player.Public.Login} not all files checked,{context.Player.ApproveLoadWorldReason.ToString() } Disconnect");
                                    result.SaveFileData = null;
                                    return result;
                                }
                            }

                            result.SaveFileData = Repository.GetSaveData.LoadPlayerData(context.Player.Public.Login, 1);

                            if (result.SaveFileData != null)
                            {
                                if (context.Player.MailsConfirmationSave.Count > 0)
                                {
                                    for (int i = 0; i < context.Player.MailsConfirmationSave.Count; i++) 
                                        context.Player.MailsConfirmationSave[i].NeedSaveGame = false;

                                    Loger.Log($"MailsConfirmationSave add {context.Player.MailsConfirmationSave.Count} (mails={context.Player.Mails.Count})");
                                    //Ого! Игрок не сохранился после приема письма, с обязательным сохранением после получения
                                    //Отправляем письма ещё раз
                                    if (context.Player.Mails.Count == 0)
                                    {
                                        context.Player.Mails = context.Player.MailsConfirmationSave.ToList();
                                    }
                                    else
                                    {
                                        var ms = context.Player.MailsConfirmationSave
                                            .Where(mcs => context.Player.Mails.Any(m => m.GetHashBase() != mcs.GetHashBase()))
                                            .ToList();
                                        context.Player.Mails.AddRange(ms);
                                    }
                                    Loger.Log($"MailsConfirmationSave (mails={context.Player.Mails.Count})");
                                }
                            }
                            Loger.Log($"Load World for {context.Player.Public.Login}. (mails={context.Player.Mails.Count}, fMails={context.Player.FunctionMails.Count})");

                            return result;
                        }

                    case (long)ServerInfoType.FullWithDescription:
                        {
                            var result = GetModelInfo(context.Player);
                            //result.Description = "";
                            var displayAttributes = new List<Tuple<int, string>>();

                            foreach (var prop in typeof(ServerSettings).GetFields())
                            {
                                var attribute = prop.GetCustomAttributes(typeof(DisplayAttribute)).FirstOrDefault();
                                if (attribute is null || !prop.IsPublic)
                                {
                                    continue;
                                }

                                var dispAtr = (DisplayAttribute)attribute;
                                var strvalue = string.IsNullOrEmpty(dispAtr.GetDescription()) ? prop.Name : dispAtr.GetDescription();
                                strvalue = strvalue + "=" + prop.GetValue(ServerManager.ServerSettings).ToString();
                                var order = dispAtr.GetOrder().HasValue ? dispAtr.GetOrder().Value : 0;
                                displayAttributes.Add(Tuple.Create(order, strvalue));
                            }

                            var sb = new StringBuilder();
                            var sorte = new List<string>(displayAttributes.OrderBy(x => x.Item1).Select(y => y.Item2)).AsReadOnly();
                            foreach (var prop in sorte)
                            {
                                sb.AppendLine(prop);
                            }

                            //result.Description = sb.ToString();
                            return result;
                        }
                    case (long)ServerInfoType.Short:
                    default:
                        {
                            // краткая (зарезервированно, пока не используется) fullInfo = false
                            var result = new ModelInfo();
                            return result;
                        }
                }
            }
        }

19 Source : SimpleAnimationNodeEditor.cs
with MIT License
from aarthificial

[MenuItem("replacedets/Create/Reanimator/Simple Animation (From Textures)", false, 400)]
        private static void CreateFromTextures()
        {
            var trailingNumbersRegex = new Regex(@"(\d+$)");

            var sprites = new List<Sprite>();
            var textures = Selection.GetFiltered<Texture2D>(SelectionMode.replacedets);
            foreach (var texture in textures)
            {
                string path = replacedetDatabase.GetreplacedetPath(texture);
                sprites.AddRange(replacedetDatabase.LoadAllreplacedetsAtPath(path).OfType<Sprite>());
            }

            var cels = sprites
                .OrderBy(
                    sprite =>
                    {
                        var match = trailingNumbersRegex.Match(sprite.name);
                        return match.Success ? int.Parse(match.Groups[0].Captures[0].ToString()) : 0;
                    }
                )
                .Select(sprite => new SimpleCel(sprite))
                .ToArray();

            var replacedet = SimpleAnimationNode.Create<SimpleAnimationNode>(
                cels: cels
            );
            string baseName = trailingNumbersRegex.Replace(textures[0].name, "");
            replacedet.name = baseName + "_animation";

            string replacedetPath = Path.GetDirectoryName(replacedetDatabase.GetreplacedetPath(textures[0]));
            replacedetDatabase.Createreplacedet(replacedet, Path.Combine(replacedetPath ?? Application.dataPath, replacedet.name + ".replacedet"));
            replacedetDatabase.Savereplacedets();
        }

19 Source : HierarchicalResolver.cs
with MIT License
from Abc-Arbitrage

public void Build(IHierarchicalConfiguration config)
        {
            var oldRoot = _root;
            var newRoot = new Node();

            foreach (var loggerWithAppenders in CreateLoggersWithAppenders(config).OrderBy(x => x.logger.Name))
            {
                AddNode(newRoot, loggerWithAppenders.logger, loggerWithAppenders.appenders);
            }

            ApplyEncodingToAllAppenders(newRoot);

            _root = newRoot;

            Updated?.Invoke();

            oldRoot?.Dispose();
        }

19 Source : DataBaseManager.cs
with MIT License
from Abdesol

public async Task<ObservableCollection<CodeBoxModel>> OrderCode(string order)
        {
            int ind = AllOrderKind.IndexOf(order);
            ObservableCollection<CodeBoxModel> lst;

            var currentCodes = AllCodes;

            if (ind > 2)
            {
                lst = new ObservableCollection<CodeBoxModel>();
                foreach (var code in currentCodes)
                {
                    if (code.langType == order) lst.Add(code);
                }
            }
            else
            {
                if (ind == 0) lst = new ObservableCollection<CodeBoxModel>(currentCodes.OrderBy(x => x.replacedle).ToList());
                else if (ind == 1) lst = new ObservableCollection<CodeBoxModel>(currentCodes.OrderBy(x => x.timestamp).ToList());
                else lst = AllCodes;

                if (ind == 0 || ind == 1) ChangeSort(AllOrderKind[ind]);
            }

            return lst;
        }

19 Source : DataBaseManager.cs
with MIT License
from Abdesol

public async Task<ObservableCollection<CodeBoxModel>> OrderCode(string order)
        {
            int ind = AllOrderKind.IndexOf(order);
            ObservableCollection<CodeBoxModel> lst;

            var currentCodes = AllCodes;

            if (ind > 2)
            {
                lst = new ObservableCollection<CodeBoxModel>();
                foreach (var code in currentCodes)
                {
                    if (code.Language == order) lst.Add(code);
                }
            }
            else
            {
                if (ind == 0) lst = new ObservableCollection<CodeBoxModel>(currentCodes.OrderBy(x => x.replacedle).ToList());
                else if (ind == 1) lst = new ObservableCollection<CodeBoxModel>(currentCodes.OrderBy(x => x.Timestamp).ToList());
                else lst = AllCodes;

                if (ind == 0 || ind == 1) ChangeSort(AllOrderKind[ind]);
            }

            return lst;
        }

19 Source : Aggregate.cs
with MIT License
from abdullin

public void HandleCommands(IList<Command> commands) {
            // whenever multiple commands arrive at a point in time
            // aggregate will decide the order
            foreach (var cmd in commands.OrderBy(CommandPriority)) {
                HandleCommand(cmd);
            }
        }

19 Source : VectorExtensions.cs
with Apache License 2.0
from abist-co-ltd

public static Vector2 Median(this IEnumerable<Vector2> vectors)
        {
            var enumerable = vectors as Vector2[] ?? vectors.ToArray();
            int count = enumerable.Length;
            return count == 0 ? Vector2.zero : enumerable.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
        }

19 Source : VectorExtensions.cs
with Apache License 2.0
from abist-co-ltd

public static Vector3 Median(this IEnumerable<Vector3> vectors)
        {
            var enumerable = vectors as Vector3[] ?? vectors.ToArray();
            int count = enumerable.Length;
            return count == 0 ? Vector3.zero : enumerable.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
        }

19 Source : VectorExtensions.cs
with Apache License 2.0
from abist-co-ltd

public static Vector2 Median(this ICollection<Vector2> vectors)
        {
            int count = vectors.Count;
            return count == 0 ? Vector2.zero : vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
        }

19 Source : VectorExtensions.cs
with Apache License 2.0
from abist-co-ltd

public static Vector3 Median(this ICollection<Vector3> vectors)
        {
            int count = vectors.Count;
            return count == 0 ? Vector3.zero : vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2);
        }

19 Source : OVRDirectorySyncer.cs
with MIT License
from absurd-joy

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

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

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

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

		return syncResult;
	}

19 Source : GroupingByCategory.cs
with MIT License
from ABTSoftware

public ObservableCollection<TileViewModel> GroupingPredicate(IDictionary<Guid, Example> examples)
        {
            var groups = examples
                .OrderBy(example => example.Value.replacedle)
                .GroupBy(example => example.Value.Group)
                .OrderBy(group => group.Key);

            var result = new ObservableCollection<TileViewModel>();
            foreach (IGrouping<string, KeyValuePair<Guid, Example>> pairs in groups)
            {
                result.Add(new TileViewModel
                {
                    TileDataContext = new EverythingGroupViewModel { GroupingName = pairs.Key }
                });

                foreach (var example in pairs.Select(x => x.Value))
                {
                    result.Add(new TileViewModel{TileDataContext = example});
                }
            }

            return result;
        }

19 Source : GroupingByName.cs
with MIT License
from ABTSoftware

public ObservableCollection<TileViewModel> GroupingPredicate(IDictionary<Guid, Example> examples)
        {
            var groups = examples
                .Select(example => new {Letter = example.Value.replacedle.FirstOrDefault(), Example = example.Value})
                .OrderBy(arg => arg.Example.replacedle)
                .GroupBy(arg => arg.Letter);

            var result = new ObservableCollection<TileViewModel>();
            foreach (var pairs in groups)
            {
                result.Add(new TileViewModel
                {
                    TileDataContext = new EverythingGroupViewModel { GroupingName = pairs.Key.ToString() }
                }); 
                
                foreach (var example in pairs)
                {
                    result.Add(new TileViewModel { TileDataContext = example.Example });
                }
            }

            return result;
        }

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

public void CreateSQLINSERTStatement(IList<LandblockInstance> input, StreamWriter writer)
        {
            var instanceWcids = input.ToDictionary(i => i.Guid, i => i.WeenieClreplacedId);

            input = input.OrderBy(r => r.Guid).ToList();

            foreach (var value in input)
            {
                if (value != input[0])
                    writer.WriteLine();

                writer.WriteLine("INSERT INTO `landblock_instance` (`guid`, `weenie_Clreplaced_Id`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`, `is_Link_Child`, `last_Modified`)");

                string label = null;

                if (WeenieNames != null)
                    WeenieNames.TryGetValue(value.WeenieClreplacedId, out label);

                var output = "VALUES (" +
                             $"0x{value.Guid.ToString("X8")}, " +
                             $"{value.WeenieClreplacedId.ToString().PadLeft(5)}, " +
                             $"0x{value.ObjCellId:X8}, " +
                             $"{TrimNegativeZero(value.OriginX):0.######}, " +
                             $"{TrimNegativeZero(value.OriginY):0.######}, " +
                             $"{TrimNegativeZero(value.OriginZ):0.######}, " +
                             $"{TrimNegativeZero(value.AnglesW):0.######}, " +
                             $"{TrimNegativeZero(value.AnglesX):0.######}, " +
                             $"{TrimNegativeZero(value.AnglesY):0.######}, " +
                             $"{TrimNegativeZero(value.AnglesZ):0.######}, " +
                             $"{value.IsLinkChild.ToString().PadLeft(5)}, " +
                             $"'{value.LastModified:yyyy-MM-dd HH:mm:ss}'" +
                             $"); /* {label} */" +
                             Environment.NewLine + $"/* @teleloc 0x{value.ObjCellId:X8} [{TrimNegativeZero(value.OriginX):F6} {TrimNegativeZero(value.OriginY):F6} {TrimNegativeZero(value.OriginZ):F6}] {TrimNegativeZero(value.AnglesW):F6} {TrimNegativeZero(value.AnglesX):F6} {TrimNegativeZero(value.AnglesY):F6} {TrimNegativeZero(value.AnglesZ):F6} */";

                output = FixNullFields(output);

                writer.WriteLine(output);

                if (value.LandblockInstanceLink != null && value.LandblockInstanceLink.Count > 0)
                {
                    writer.WriteLine();
                    CreateSQLINSERTStatement(value.LandblockInstanceLink.OrderBy(r => r.ChildGuid).ToList(), instanceWcids, writer);
                }
            }
        }

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

private static float RollEnchantmentDifficulty(List<SpellId> spellIds)
        {
            var spells = new List<Server.Enreplacedy.Spell>();

            foreach (var spellId in spellIds)
            {
                var spell = new Server.Enreplacedy.Spell(spellId);
                spells.Add(spell);
            }

            spells = spells.OrderBy(i => i.Formula.Level).ToList();

            var itemDifficulty = 0.0f;

            // exclude highest spell
            for (var i = 0; i < spells.Count - 1; i++)
            {
                var spell = spells[i];

                var rng = (float)ThreadSafeRandom.Next(0.5f, 1.5f);

                itemDifficulty += spell.Formula.Level * 5.0f * rng;
            }

            return itemDifficulty;
        }

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

public List<WorldObjectInfo<int>> GetConsumeItems(List<WorldObject> items)
        {
            if (Remaining == 0) return new List<WorldObjectInfo<int>>();

            // filter to payment tab items that apply to this HousePayment wcid
            // consume from smallest stacks first, to clear out the clutter
            var wcidItems = items.Where(i => i.WeenieClreplacedId == WeenieID).OrderBy(i => i.StackSize ?? 1).ToList();

            // house monetary payments have pyreal wcid, and can be also be paid with trade notes
            if (WeenieID == 273)
            {
                // append trade notes
                // consume from smallest denomination stacks first, with multiple stacks of the same denomination sorted by stack size

                // note that this does not produce an optimal solution for minimizing the amount of trade notes consumed

                // a slightly better solution would be to iteratively consume the highest denomination trade note that is <= the remaining amount,
                // but there are still some sets where even that wouldn't be optimized..

                var tradeNotes = items.Where(i => i.ItemType == ItemType.PromissoryNote).OrderBy(i => i.StackSize ?? 1).OrderBy(i => i.StackUnitValue).ToList();

                var coinsAndTradeNotes = wcidItems.Concat(tradeNotes).ToList();

                return GetConsumeItems_Inner(coinsAndTradeNotes);
            }
            else
            {
                return GetConsumeItems_Inner(wcidItems);
            }
        }

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

public static void WriteOld(this BinaryWriter writer, List<CharacterPropertiesFillCompBook> fillComps)
        {
            const int numBuckets = 256; // constant from retail pcaps

            WriteHeader(writer, fillComps.Count, numBuckets);

            var sorted = fillComps.OrderBy(i => i.SpellComponentId % numBuckets);

            foreach (var fillComp in sorted)
            {
                writer.Write(fillComp.SpellComponentId);
                writer.Write(fillComp.QuanreplacedyToRebuy);
            }
        }

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

public void SortObjects()
        {
            ServerObjects = ServerObjects.OrderBy(i => i.Order).ToList();
        }

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

private void SortWorldObjectsIntoInventory(IList<WorldObject> worldObjects)
        {
            // This will pull out all of our main pack items and side slot items (foci & containers)
            for (int i = worldObjects.Count - 1; i >= 0; i--)
            {
                if ((worldObjects[i].ContainerId ?? 0) == Biota.Id)
                {
                    Inventory[worldObjects[i].Guid] = worldObjects[i];
                    worldObjects[i].Container = this;

                    if (worldObjects[i].WeenieType != WeenieType.Container) // We skip over containers because we'll add their burden/value in the next loop.
                    {
                        EnreplacedbranceVal += (worldObjects[i].EnreplacedbranceVal ?? 0);
                        Value += (worldObjects[i].Value ?? 0);
                    }

                    worldObjects.RemoveAt(i);
                }
            }

            // Make sure placement positions are correct. They could get out of sync from a client issue, server issue, or orphaned biota
            var mainPackItems = Inventory.Values.Where(wo => !wo.UseBackpackSlot).OrderBy(wo => wo.PlacementPosition).ToList();
            for (int i = 0; i < mainPackItems.Count; i++)
                mainPackItems[i].PlacementPosition = i;
            var sidPackItems = Inventory.Values.Where(wo => wo.UseBackpackSlot).OrderBy(wo => wo.PlacementPosition).ToList();
            for (int i = 0; i < sidPackItems.Count; i++)
                sidPackItems[i].PlacementPosition = i;

            InventoryLoaded = true;

            // All that should be left are side pack sub contents.

            var sideContainers = Inventory.Values.Where(i => i.WeenieType == WeenieType.Container).ToList();
            foreach (var container in sideContainers)
            {
                ((Container)container).SortWorldObjectsIntoInventory(worldObjects); // This will set the InventoryLoaded flag for this sideContainer
                EnreplacedbranceVal += container.EnreplacedbranceVal; // This value includes the containers burden itself + all child items
                Value += container.Value; // This value includes the containers value itself + all child items
            }

            OnInitialInventoryLoadCompleted();
        }

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

public List<WorldObject> GetInventoryItemsOfTypeWeenieType(WeenieType type)
        {
            var items = new List<WorldObject>();

            // first search me / add all items of type.
            var localInventory = Inventory.Values.Where(wo => wo.WeenieType == type).OrderBy(i => i.PlacementPosition).ToList();

            items.AddRange(localInventory);

            // next search all containers for type.. run function again for each container.
            var sideContainers = Inventory.Values.Where(i => i.WeenieType == WeenieType.Container).OrderBy(i => i.PlacementPosition).ToList();
            foreach (var container in sideContainers)
                items.AddRange(((Container)container).GetInventoryItemsOfTypeWeenieType(type));

            return items;
        }

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

public List<WorldObject> GetInventoryItemsOfWCID(uint weenieClreplacedId)
        {
            var items = new List<WorldObject>();

            // search main pack / creature
            var localInventory = Inventory.Values.Where(i => i.WeenieClreplacedId == weenieClreplacedId).OrderBy(i => i.PlacementPosition).ToList();

            items.AddRange(localInventory);

            // next search any side containers
            var sideContainers = Inventory.Values.Where(i => i.WeenieType == WeenieType.Container).Select(i => i as Container).OrderBy(i => i.PlacementPosition).ToList();
            foreach (var container in sideContainers)
                items.AddRange(container.GetInventoryItemsOfWCID(weenieClreplacedId));

            return items;
        }

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

public List<WorldObject> GetInventoryItemsOfWeenieClreplaced(string weenieClreplacedName)
        {
            var items = new List<WorldObject>();

            // search main pack / creature
            var localInventory = Inventory.Values.Where(i => i.WeenieClreplacedName.Equals(weenieClreplacedName, StringComparison.OrdinalIgnoreCase)).OrderBy(i => i.PlacementPosition).ToList();

            items.AddRange(localInventory);

            // next search any side containers
            var sideContainers = Inventory.Values.Where(i => i.WeenieType == WeenieType.Container).Select(i => i as Container).OrderBy(i => i.PlacementPosition).ToList();
            foreach (var container in sideContainers)
                items.AddRange(container.GetInventoryItemsOfWeenieClreplaced(weenieClreplacedName));

            return items;
        }

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

public List<WorldObject> GetTradeNotes()
        {
            // FIXME: search by clreplacedname performance
            var items = new List<WorldObject>();

            // search main pack / creature
            var localInventory = Inventory.Values.Where(i => i.WeenieClreplacedName.StartsWith("tradenote")).OrderBy(i => i.PlacementPosition).ToList();

            items.AddRange(localInventory);

            // next search any side containers
            var sideContainers = Inventory.Values.Where(i => i.WeenieType == WeenieType.Container).Select(i => i as Container).OrderBy(i => i.PlacementPosition).ToList();
            foreach (var container in sideContainers)
                items.AddRange(container.GetTradeNotes());

            return items;
        }

See More Examples