System.Collections.Generic.IEnumerable.Skip(int)

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

4393 Examples 7

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

public IEnumerable<Enreplacedy> Select(int offset, int limit)
		{
			if (offset % limit != 0)
			{
				throw new ArgumentException("limit value must be a factor of offset");
			}

			var items = new List<Enreplacedy>();

			Select(0, (offset + limit) * _initialLimitMultiple, offset + limit, items);

			return items.Skip(offset).Take(limit).ToArray();
		}

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

private IEnumerable<IForumThread> SelectThreadsWithSecurity(int startRowIndex, int maximumRows)
		{
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("startRowIndex={0}, maximumRows={1}: Start", startRowIndex, maximumRows));

			var serviceContext = Dependencies.GetServiceContext();
			var website = Dependencies.GetWebsite();

			var query = SelectThreadEnreplacedies(serviceContext);

			var securityProvider = Dependencies.GetSecurityProvider();
			var forumPermissionCache = new Dictionary<Guid, bool>();

			if (maximumRows < 0)
			{
				var readableEnreplacedies = query
					.ToArray()
					.Where(e => TryreplacedertReadPermission(serviceContext, securityProvider, e, forumPermissionCache))
					.Skip(startRowIndex);

				return CreateForumThreads(serviceContext, securityProvider, website, readableEnreplacedies);
			}

			var paginator = new PostFilterPaginator<Enreplacedy>(
				(offset, limit) => query.Skip(offset).Take(limit).ToArray(),
				e => TryreplacedertReadPermission(serviceContext, securityProvider, e, forumPermissionCache),
				2);

			var threads = CreateForumThreads(serviceContext, securityProvider, website, paginator.Select(startRowIndex, maximumRows));

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");

			return threads;
		}

19 View Source File : GuidGenerator.cs
License : MIT License
Project Creator : abock

protected sealed override Guid GenerateGuid(IEnumerable<string> args)
            {
                var name = args.FirstOrDefault();
                if (string.IsNullOrEmpty(name))
                    throw new Exception("Must specify NAME as the first positional argument.");

                if (name == "-")
                    name = Console.In.ReadToEnd();

                var @namespace = args.Skip(1).FirstOrDefault();
                Guid namespaceGuid = default;

                if (!string.IsNullOrEmpty(@namespace))
                {
                    switch (@namespace.ToLowerInvariant())
                    {
                        case "url":
                            namespaceGuid = GuidNamespace.URL;
                            break;
                        case "dns":
                            namespaceGuid = GuidNamespace.DNS;
                            break;
                        case "oid":
                            namespaceGuid = GuidNamespace.OID;
                            break;
                        default:
                            if (!Guid.TryParse(@namespace, out namespaceGuid))
                                throw new Exception("Invalid namespace GUID");
                            break;
                    }
                }

                if (namespaceGuid == default)
                    namespaceGuid = GuidNamespace.URL;

                return generator(namespaceGuid, name);
            }

19 View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX

public static Guid GetGuid(byte[] data, int index) 
            => new Guid(data.Skip(index).Take(16).ToArray());

19 View Source File : ExpressionUtility.cs
License : MIT License
Project Creator : actions

internal static Double ParseNumber(String str)
        {
            // Trim
            str = str?.Trim() ?? String.Empty;

            // Empty
            if (String.IsNullOrEmpty(str))
            {
                return 0d;
            }
            // Try parse
            else if (Double.TryParse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var value))
            {
                return value;
            }
            // Check for 0x[0-9a-fA-F]+
            else if (str[0] == '0' &&
                str.Length > 2 &&
                str[1] == 'x' &&
                str.Skip(2).All(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F')))
            {
                // Try parse
                if (Int32.TryParse(str.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var integer))
                {
                    return (Double)integer;
                }

                // Otherwise exceeds range
            }
            // Check for 0o[0-9]+
            else if (str[0] == '0' &&
                str.Length > 2 &&
                str[1] == 'o' &&
                str.Skip(2).All(x => x >= '0' && x <= '7'))
            {
                // Try parse
                var integer = default(Int32?);
                try
                {
                    integer = Convert.ToInt32(str.Substring(2), 8);
                }
                // Otherwise exceeds range
                catch (Exception)
                {
                }

                // Success
                if (integer != null)
                {
                    return (Double)integer.Value;
                }
            }
            // Infinity
            else if (String.Equals(str, ExpressionConstants.Infinity, StringComparison.Ordinal))
            {
                return Double.PositiveInfinity;
            }
            // -Infinity
            else if (String.Equals(str, ExpressionConstants.NegativeInfinity, StringComparison.Ordinal))
            {
                return Double.NegativeInfinity;
            }

            // Otherwise NaN
            return Double.NaN;
        }

19 View Source File : ListExtensions.cs
License : MIT License
Project Creator : Abdulrhman5

public static async  Task<List<T>> SkipTakeAsync<T>(this IQueryable<T> query, PagingArguments arguments)
        {
            return await query.Skip(arguments.StartObject).Take(arguments.Size).ToListAsync();
        }

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

private static string ToAlternateServiceUrl(string serviceUrl)
		{
			if (string.IsNullOrWhiteSpace(serviceUrl))
			{
				return null;
			}

			var url = new Uri(serviceUrl);
			var parts = url.Host.Split('.');
			var organizationName = parts.First();
			var tail = parts.Skip(1);
			var host = organizationName + "--S." + string.Join(".", tail);
			var alternateUrl = new UriBuilder(serviceUrl) { Host = host };

			return alternateUrl.Uri.OriginalString;
		}

19 View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<string> BuildBase64PayloadMacros(byte[] shellcode)
        {
            List<string> base64Strings = new List<string>(); 
            //Base64 expansion is 4/3, and we have 252 bytes to spend, so we can have 189 bytes / cell
            //As an added bonus, 189 is always divisible by 3, so we won't have == padding.
            int maxBytesPerCell = 189;
            for (int offset = 0; offset < shellcode.Length; offset += maxBytesPerCell)
            {
                byte[] guidShellcode;
                if (shellcode.Length - offset < maxBytesPerCell)
                {
                    guidShellcode = shellcode.Skip(offset).ToArray();
                }
                else
                {
                    guidShellcode = shellcode.Skip(offset).Take(maxBytesPerCell).ToArray();
                }
                base64Strings.Add(Convert.ToBase64String(guidShellcode));
            }
            base64Strings.Add("END");
            return base64Strings;
        }

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

public ISharePointCollection GetFoldersAndFiles(EnreplacedyReference regarding, string sortExpression = DefaultSortExpression, int page = 1, int pageSize = DefaultPageSize, string pagingInfo = null, string folderPath = null)
		{
			var context = _dependencies.GetServiceContextForWrite();
			var website = _dependencies.GetWebsite();
			var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
			var result = new SharePointResult(regarding, enreplacedyPermissionProvider, context);

			// replacedert permission to create the sharepointdoreplacedentlocation enreplacedy
			if (!result.PermissionsExist || !result.CanCreate || !result.CanAppend || !result.CanAppendTo)
			{
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Enreplacedy Permissions to Create or Append doreplacedent locations or AppendTo the regarding enreplacedy.");
				return SharePointCollection.Empty(true);
			}

			var enreplacedyMetadata = context.GetEnreplacedyMetadata(regarding.LogicalName);
			var enreplacedy = context.CreateQuery(regarding.LogicalName).First(e => e.GetAttributeValue<Guid>(enreplacedyMetadata.PrimaryIdAttribute) == regarding.Id);

			var spConnection = new SharePointConnection(SharePointConnectionStringName);
			var spSite = context.GetSharePointSiteFromUrl(spConnection.Url);

			var location = GetDoreplacedentLocation(context, enreplacedy, enreplacedyMetadata, spSite);

			if (!enreplacedyPermissionProvider.Tryreplacedert(context, CrmEnreplacedyPermissionRight.Read, location))
			{
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Enreplacedy Permissions to Read doreplacedent locations.");
				return SharePointCollection.Empty(true);
			}

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Read SharePoint Doreplacedent Location Permission Granted.");

			var factory = new ClientFactory();

			using (var client = factory.CreateClientContext(spConnection))
			{
				// retrieve the SharePoint list and folder names for the doreplacedent location
				string listUrl, folderUrl;

				context.GetDoreplacedentLocationListAndFolder(location, out listUrl, out folderUrl);

				var sharePointFolder = client.AddOrGetExistingFolder(listUrl, folderUrl + folderPath);

				var list = client.GetListByUrl(listUrl);

				if (!sharePointFolder.IsPropertyAvailable("ServerRelativeUrl"))
				{
					client.Load(sharePointFolder, folder => folder.ServerRelativeUrl);
				}

				if (!sharePointFolder.IsPropertyAvailable("ItemCount"))
				{
					client.Load(sharePointFolder, folder => folder.ItemCount);
				}

				var camlQuery = new CamlQuery
				{
					FolderServerRelativeUrl = sharePointFolder.ServerRelativeUrl,
					ViewXml = @"
					<View>
						<Query>
							<OrderBy>
								<FieldRef {0}></FieldRef>
							</OrderBy>
							<Where></Where>
						</Query>
						<RowLimit>{1}</RowLimit>
					</View>".FormatWith(
							ConvertSortExpressionToCaml(sortExpression),
							pageSize)
				};
				if (page > 1)
				{
					camlQuery.LisreplacedemCollectionPosition = new LisreplacedemCollectionPosition { PagingInfo = pagingInfo };
				}
				var folderItems = list.Gereplacedems(camlQuery);
				client.Load(folderItems,
					items => items.LisreplacedemCollectionPosition,
					items => items.Include(
						item => item.ContentType,
						item => item["ID"],
						item => item["FileLeafRef"],
						item => item["Created"],
						item => item["Modified"],
						item => item["FileSizeDisplay"]));
				client.ExecuteQuery();

				var sharePoinreplacedems = new List<SharePoinreplacedem>();

				if (!string.IsNullOrEmpty(folderPath) && folderPath.Contains("/"))
				{
					var relativePaths = folderPath.Split('/');
					var parentFolderName = relativePaths.Length > 2 ? relativePaths.Skip(relativePaths.Length - 2).First() : "/";

					sharePoinreplacedems.Add(new SharePoinreplacedem()
					{
						Name = @"""{0}""".FormatWith(parentFolderName),
						IsFolder = true,
						FolderPath = folderPath.Substring(0, folderPath.LastIndexOf('/')),
						IsParent = true
					});
				}

				if (folderItems.Count < 1)
				{
					return new SharePointCollection(sharePoinreplacedems, null, sharePoinreplacedems.Count());
				}

				foreach (var item in folderItems)
				{
					var id = item["ID"] as int?;
					var name = item["FileLeafRef"] as string;
					var created = item["Created"] as DateTime?;
					var modified = item["Modified"] as DateTime?;

					long longFileSize;
					var fileSize = long.TryParse(item["FileSizeDisplay"] as string, out longFileSize) ? longFileSize : null as long?;

					if (string.Equals(item.ContentType.Name, "Folder", StringComparison.InvariantCultureIgnoreCase))
					{
						sharePoinreplacedems.Add(new SharePoinreplacedem
						{
							Id = id,
							Name = name,
							IsFolder = true,
							CreatedOn = created,
							ModifiedOn = modified,
							FolderPath = "{0}/{1}".FormatWith(folderPath, name)
						});
					}
					else
					{
						sharePoinreplacedems.Add(new SharePoinreplacedem
						{
							Id = id,
							Name = name,
							CreatedOn = created,
							ModifiedOn = modified,
							FileSize = fileSize,
							Url = GetAbsolutePath(website, location, name, folderPath)
						});
					}
				}

				var pageInfo = folderItems.LisreplacedemCollectionPosition != null
					? folderItems.LisreplacedemCollectionPosition.PagingInfo
					: null;

				return new SharePointCollection(sharePoinreplacedems, pageInfo, sharePointFolder.ItemCount);
			}
		}

19 View Source File : WorkbookEditor.cs
License : Apache License 2.0
Project Creator : aaaddress1

private WorkbookStream GetMacroStream()
        {
            List<BoundSheet8> sheets = WbStream.GetAllRecordsByType<BoundSheet8>();
            int macroSheetIndex = sheets.TakeWhile(sheet => sheet.dt != BoundSheet8.SheetType.Macrosheet).Count();
            string macroSheetName = sheets.Skip(macroSheetIndex).First().stName.Value;
            BOF macroBof = WbStream.GetAllRecordsByType<BOF>().Skip(macroSheetIndex + 1).First();
            List<BiffRecord> macroRecords = WbStream.GetRecordsForBOFRecord(macroBof);

            WorkbookStream macroStream = new WorkbookStream(macroRecords);
            return macroStream;
        }

19 View Source File : POGeneratorTest.cs
License : MIT License
Project Creator : adams85

private void Generate_LineBreak_Core(string id, params string[] lines)
        {
            var generator = new POGenerator(new POGeneratorSettings
            {
                IgnoreEncoding = true,
                SkipInfoHeaders = true,
            });

            var catalog = new POCatalog { Encoding = "UTF-8" };
            var entry = new POSingularEntry(new POKey(id));
            catalog.Add(entry);

            var sb = new StringBuilder();
            generator.Generate(sb, catalog);

            var expected = new List<string>();
            expected.Add(@"msgid """"");
            expected.AddRange(lines);
            expected.Add(@"msgstr """"");

            IEnumerable<string> actual = sb.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None).Skip(5).Take(lines.Length + 2);
            replacedert.Equal(expected, actual);
        }

19 View Source File : PatchOperation.cs
License : MIT License
Project Creator : actions

private static Type GetType(Type type, IEnumerable<string> path)
        {
            var current = path.First();
            Type currentType = null;

            // The start of the path should always be an empty string after splitting.
            if (string.IsNullOrEmpty(current))
            {
                currentType = type;
            }
            else if (type.IsList())
            {
                currentType = type.GenericTypeArguments[0];
            }
            else if (type.IsDictionary())
            {
                currentType = type.GenericTypeArguments[1];
            }
            else
            {
                currentType = type.GetMemberType(current);
            }

            // Couldn't map the type, return null and let consumer handle.
            if (currentType == null)
            {
                return null;
            }
            // The end of the list, this must be the type we're looking for.
            else if (path.Count() == 1)
            {
                return currentType;
            }
            else
            {
                return GetType(currentType, path.Skip(1));
            }
        }

19 View Source File : ListExtensions.cs
License : MIT License
Project Creator : Abdulrhman5

public static List<T> SkipTake<T>(this IQueryable<T> query, PagingArguments arguments)
        {
            return query.Skip(arguments.StartObject).Take(arguments.Size).ToList();
        }

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

public virtual IEnumerable<IBlog> SelectBlogs(int startRowIndex, int maximumRows = -1)
		{
			if (startRowIndex < 0)
			{
				throw new ArgumentException("Value must be a positive integer.", "startRowIndex");
			}

			if (maximumRows == 0)
			{
				return new IBlog[] { };
			}

			var serviceContext = Dependencies.GetServiceContext();
			var security = Dependencies.GetSecurityProvider();
			var urlProvider = Dependencies.GetUrlProvider();

			var query = SelectBlogEnreplacedies(serviceContext).ToList().OrderBy(blog => blog.GetAttributeValue<string>("adx_name"));

			if (maximumRows < 0)
			{
				return query.ToArray()
					.Where(e => security.Tryreplacedert(serviceContext, e, CrmEnreplacedyRight.Read))
					.Skip(startRowIndex)
					.Select(e => new Blog(e, urlProvider.GetApplicationPath(serviceContext, e), Dependencies.GetBlogFeedPath(e.Id)))
					.ToArray();
			}

			var pagedQuery = query;

			var paginator = new PostFilterPaginator<Enreplacedy>(
				(offset, limit) => pagedQuery.Skip(offset).Take(limit).ToArray(),
				e => security.Tryreplacedert(serviceContext, e, CrmEnreplacedyRight.Read),
				2);

			return paginator.Select(startRowIndex, maximumRows)
				.Select(e => new Blog(e, urlProvider.GetApplicationPath(serviceContext, e), Dependencies.GetBlogFeedPath(e.Id))).ToArray();
		}

19 View Source File : BiffRecordExtensions.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static string ToHexDumpString(this BiffRecord record, int maxLength = 0x10, bool showAttrInfo = false, bool includeHeader = false)
        {
            string biffString = record.ToString();
            byte[] bytes = record.GetBytes();

            //Skip the 4 byte header if we aren't including the header
            if (includeHeader == false)
            {
                bytes = bytes.Skip(4).ToArray();
            }

            string hexDumpString = HexDump(bytes);

            if (record is Formula)
            {
                Formula f = (Formula) record;
                if (f.cce == 0 && f.RawBytesValue.Length != bytes.Length + 4)
                {
                    biffString = "!Error Parsing Formula!";
                }
                else
                {
                    biffString = f.ToFormulaString(showAttrInfo);
                } 
            }
            else if (record.Id == RecordType.Dimensions)
            {
                biffString = record.AsRecordType<Dimensions>().ToString();
            }
            else if (record.Id == RecordType.Lbl)
            {
                try
                {
                    biffString = record.AsRecordType<Lbl>().ToString();
                }
                catch (Exception e)
                {
                    biffString = record.ToString();
                }
            }


            if ((bytes.Length <= maxLength && bytes.Length > 0) ||
                record.Id == RecordType.Obj)
            {
                biffString += "\n" + hexDumpString;
            }

            return biffString;
        }

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

public Page GetPage(int pageNumber)
		{
			var items = new List<T>();

			var totalUnfilteredItems = Gereplacedems(
				((_pageSize * pageNumber) * _initialSearchLimitMultiple),
				0,
				(_pageSize * pageNumber),
				items);

			var itemOffset = (pageNumber - 1) * _pageSize;

			var pageItems = items.Skip(itemOffset).Take(_pageSize).ToList();

			return new Page(pageItems, totalUnfilteredItems, pageNumber, _pageSize);
		}

19 View Source File : ListExtensions.cs
License : MIT License
Project Creator : Abdulrhman5

public static async Task<List<T>> SkipTakeAsync<T>(this IQueryable<T> query, IQueryableHelper queryHelper, PagingArguments arguments) 
        {
            return await queryHelper.ToListAsync(query.Skip(arguments.StartObject).Take(arguments.Size));
        }

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

private static Expression In<TValue>(Expression selectorBody, IEnumerable<TValue> values, Expression expression)
		{
			return values.Any()
				? In(
					selectorBody,
					values.Skip(1),
					Expression.OrElse(expression, Expression.Equal(selectorBody, Expression.Constant(values.First()))))
				: expression;
		}

19 View Source File : PlyHandler.cs
License : MIT License
Project Creator : 3DBear

private static PlyResult ParseBinaryLittleEndian(string path, PlyHeader header)
        {
            var headerAsText = header.RawHeader.Aggregate((a, b) => $"{a}\n{b}") + "\n";
            var headerAsBytes = Encoding.ASCII.GetBytes(headerAsText);
            var withoutHeader = File.ReadAllBytes(path).Skip(headerAsBytes.Length).ToArray();
            var colors = new List<Color>();
            var vertices = GetVertices(withoutHeader, header, out colors);
            var triangles = GetTriangles(withoutHeader, header);
            return new PlyResult(vertices, triangles, colors);
        }

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

protected virtual ICrmEnreplacedySearchResultPage GenerateResultPage(ICollection<ICrmEnreplacedySearchResult> results, int approximateTotalHits, int pageNumber, int pageSize, RawSearchResultSet rawSearchResultSet)
        {
            var resultOffset = (pageNumber - 1) * pageSize;

            var pageResults = results.Skip(resultOffset).Take(pageSize).ToList();

            return new CrmEnreplacedySearchResultPage(pageResults, approximateTotalHits, pageNumber, pageSize);
        }

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

public void AddCell(List<LandVertex> vertices, int polyIdx)
        {
            Vertices.AddRange(vertices.Skip(polyIdx * 3).Take(6));
        }

19 View Source File : CmdLineActions.cs
License : MIT License
Project Creator : action-bi-toolkit

[ArgActionMethod, ArgShortcut("cache"), ArgDescription("Manages the internal replacedembly cache.")]
        [ArgExample("pbi-tools.exe cache list", "Lists all cache folders present in the current user profile.")]
        public void Cache(
            [ArgRequired, ArgDescription("The cache action to perform.")] CacheAction action
        )
        {
            var folders = Directory.GetDirectories(ApplicationFolders.AppDataFolder);
            
            switch (action)
            {
                case CacheAction.List:
                    Array.ForEach(folders, f =>
                        Console.WriteLine($"- {Path.GetFileName(f)}")
                    );
                    break;
                case CacheAction.ClearAll:
                    Array.ForEach(folders, f => 
                    {
                        Directory.Delete(f, recursive: true);
                        Console.WriteLine($"Deleted: {Path.GetFileName(f)}");
                    });
                    break;
                case CacheAction.ClearOutdated:
                    Array.ForEach(folders.OrderByDescending(x => x).Skip(1).ToArray(), f => 
                    {
                        Directory.Delete(f, recursive: true);
                        Console.WriteLine($"Deleted: {Path.GetFileName(f)}");
                    });
                    break;
            }
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

private void ButtonRestoreViewport_Click(object sender, RoutedEventArgs e)
		{
			string[] scoords = Properties.Settings.Default.ViewPortPos.Split(';');

			try
			{
				IEnumerable<double> coords = scoords.Select(s => double.Parse(s));

				viewport.Camera.Position = new Vector3(coords.Take(3).ToArray()).ToPoint3D();
				viewport.Camera.LookDirection = new Vector3(coords.Skip(3).ToArray()).ToVector3D();
				viewport.Camera.UpDirection = new System.Windows.Media.Media3D.Vector3D(0, 0, 1);
			}
			catch
			{
				ButtonResetViewport_Click(null, null);
			}
		}

19 View Source File : PatchOperation.cs
License : MIT License
Project Creator : actions

private void Apply(object target, IEnumerable<string> path, Action<Type, object, string> actionToApply)
        {
            var current = path.First();
            var type = target.GetType();

            // We're at the end, time to apply the action.  
            if (path.Count() == 1)
            {
                if (PatchOperationApplying != null)
                {
                    PatchOperationApplying(this, new PatchOperationApplyingEventArgs(this.EvaluatedPath, this.Operation));
                }

                actionToApply(type, target, current);

                if (PatchOperationApplied != null)
                {
                    PatchOperationApplied(this, new PatchOperationAppliedEventArgs(this.EvaluatedPath, this.Operation));
                }
            }
            else
            {
                object newTarget = null;

                // The start of the path should always be an empty string after splitting.
                // We just replacedign target to new target and move down the path.
                if (string.IsNullOrEmpty(current))
                {
                    newTarget = target;
                }
                // If the next level is a dictionary, we want to get object at the key.
                else if (type.IsDictionary())
                {
                    var dictionary = ((IDictionary)target);
                    if (dictionary.Contains(current))
                    {
                        newTarget = dictionary[current];
                    }
                }
                else if (type.IsList())
                {
                    var list = (IList)target;
                    int index;
                    if (int.TryParse(current, out index) &&
                        list.Count > index)
                    {
                        newTarget = ((IList)target)[index];
                    }
                }
                else
                {
                    newTarget = type.GetMemberValue(current, target);
                }

                if (newTarget == null)
                {
                    // An extra layer of protection, since this should never happen because the earlier call to GetType would have failed.
                    throw new PatchOperationFailedException(PatchResources.TargetCannotBeNull());
                }

                this.Apply(newTarget, path.Skip(1), actionToApply);
            }
        }

19 View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<BiffRecord> ConvertMaxLengthStringToFormulas(string curString, int rwStart, int colStart, int dstRw, int dstCol, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc)
        {
            string actualString =
                new string(curString.Skip(FormulaHelper.TOOLONGMARKER.Length).ToArray());

            string earlyString = new string(actualString.Take(16).ToArray());
            string remainingString = new string(actualString.Skip(16).ToArray());
            List<BiffRecord> formulas = new List<BiffRecord>();

            int curRow = rwStart;
            int curCol = colStart;


            Random r = new Random();
            int rndCol = r.Next(0x90, 0x9F);
            int rndRw = r.Next(0xF000, 0xF800);
            formulas.AddRange(ConvertStringToFormulas(remainingString, curRow, curCol, rndRw, rndCol, ixfe, packingMethod));

            curRow += formulas.Count;

            Cell remainderCell = new Cell(rndRw, rndCol);
            List<Cell> createdCells = new List<Cell>();

            //Create a formula string like 
            //"=CHAR(123)&CHAR(234)&CHAR(345)&R[RandomRw]C[RandomCol]";
            //To split the 255 bytes into multiple cells - the first few bytes are CHAR() encoded, the remaining can be wrapped in ""s
            string macroString = "=";

            foreach (char c in earlyString)
            {
                macroString += string.Format("CHAR({0})&", Convert.ToUInt16(c));
            }
            macroString += string.Format("R{0}C{1}",rndRw + 1, rndCol + 1);
            createdCells.Add(remainderCell);

            List<BiffRecord> mainFormula = ConvertStringToFormulas(macroString, curRow, curCol, dstRw, dstCol, ixfe, packingMethod);
            formulas.AddRange(mainFormula);

            return formulas;
        }

19 View Source File : DmnDecisionTable.cs
License : MIT License
Project Creator : adamecr

private static bool MatchRuleOutputs(IEnumerable<DmnDecisionTableRule> positiveRules, DmnDecisionTableRuleExecutionResults results)
        {
            var array = positiveRules.ToArray();
            if (array.Length < 2) return true;

            var firsreplacedem = results.GetResultsHashCode(array[0]);
            var allEqual = array.Skip(1).All(i => Equals(firsreplacedem, results.GetResultsHashCode(i)));
            return allEqual;
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : ad313

public static List<List<T>> SplitList<T>(List<T> list, int length)
        {
            if (list == null || list.Count <= 0 || length <= 0)
            {
                return new List<List<T>>();
            }

            var result = new List<List<T>>();
            var count = list.Count / length;
            count += list.Count % length > 0 ? 1 : 0;
            for (var i = 0; i < count; i++)
            {
                result.Add(list.Skip(i * length).Take(length).ToList());
            }
            return result;
        }

19 View Source File : CompletionList.cs
License : MIT License
Project Creator : Abdesol

static bool CamelCaseMatch(string text, string query)
		{
			// We take the first letter of the text regardless of whether or not it's upper case so we match
			// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
			var theFirstLetterOfEachWord = text.Take(1).Concat(text.Skip(1).Where(char.IsUpper));

			int i = 0;
			foreach (var letter in theFirstLetterOfEachWord) {
				if (i > query.Length - 1)
					return true;    // return true here for CamelCase partial match ("CQ" matches "CodeQualityreplacedysis")
				if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
					return false;
				i++;
			}
			if (i >= query.Length)
				return true;
			return false;
		}

19 View Source File : Output.Results.cs
License : Apache License 2.0
Project Creator : adamralph

private static string GetResultLines(IEnumerable<KeyValuePair<Target, TargetResult>> results, TimeSpan? totalDuration, string prefix, Palette p)
        {
            // whitespace (e.g. can change to '·' for debugging)
            var ws = ' ';

            var rows = new List<SummaryRow> { new SummaryRow($"{p.Default}Target{p.Reset}", $"{p.Default}Outcome{p.Reset}", $"{p.Default}Duration{p.Reset}", "") };

            foreach (var item in results.OrderBy(i => i.Value.Ordinal))
            {
                var target = $"{p.Target}{item.Key}{p.Reset}";

                var outcome = item.Value.Outcome == TargetOutcome.Failed
                    ? $"{p.Failed}{FailedMessage}{p.Reset}"
                    : item.Value.Outcome == TargetOutcome.NoInputs
                        ? $"{p.Warning}{NoInputsMessage}{p.Reset}"
                        : $"{p.Succeeded}{SucceededMessage}{p.Reset}";

                var duration = item.Value.Duration.HasValue
                    ? $"{p.Timing}{item.Value.Duration.Humanize()}{p.Reset}"
                    : "";

                var percentage = item.Value.Duration.HasValue && totalDuration.HasValue && totalDuration.Value > TimeSpan.Zero
                    ? $"{p.Timing}{100 * item.Value.Duration.Value.TotalMilliseconds / totalDuration.Value.TotalMilliseconds:N1}%{p.Reset}"
                    : "";

                rows.Add(new SummaryRow(target, outcome, duration, percentage));

                var index = 0;

                foreach (var result in item.Value.InputResults.Values.OrderBy(result => result.Ordinal))
                {
                    var input = $"{ws}{ws}{p.Input}{result.Input}{p.Reset}";

                    var inputOutcome = result.Outcome == TargetInputOutcome.Failed ? $"{p.Failed}{FailedMessage}{p.Reset}" : $"{p.Succeeded}{SucceededMessage}{p.Reset}";

                    var inputDuration = result.Duration.HasValue
                        ? $"{(index < item.Value.InputResults.Count - 1 ? p.TreeFork : p.TreeCorner)}{p.Timing}{result.Duration.Humanize()}{p.Reset}"
                        : "";

                    var inputPercentage = result.Duration.HasValue && totalDuration.HasValue && totalDuration.Value > TimeSpan.Zero
                        ? $"{(index < item.Value.InputResults.Count - 1 ? p.TreeFork : p.TreeCorner)}{p.Timing}{100 * result.Duration.Value.TotalMilliseconds / totalDuration.Value.TotalMilliseconds:N1}%{p.Reset}"
                        : "";

                    rows.Add(new SummaryRow(input, inputOutcome, inputDuration, inputPercentage));

                    ++index;
                }
            }

            // target or input column width
            var tarW = rows.Max(row => Palette.StripColours(row.TargetOrInput).Length);

            // outcome column width
            var outW = rows.Max(row => Palette.StripColours(row.Outcome).Length);

            // duration column width
            var durW = rows.Count > 1 ? rows.Skip(1).Max(row => Palette.StripColours(row.Duration).Length) : 0;

            // percentage column width
            var perW = rows.Max(row => Palette.StripColours(row.Percentage).Length);

            // timing column width (duration and percentage)
            var timW = Max(Palette.StripColours(rows[0].Duration).Length, durW + 2 + perW);

            // expand percentage column width to ensure time and percentage are as wide as duration
            perW = Max(timW - durW - 2, perW);

            var builder = new StringBuilder();

            // summary start separator
            _ = builder.AppendLine($"{p.Prefix}{prefix}:{p.Reset} {p.Default}{Prp("", tarW + 2 + outW + 2 + timW, p.Horizontal)}{p.Reset}");

            // header
            _ = builder.AppendLine($"{p.Prefix}{prefix}:{p.Reset} {Prp(rows[0].TargetOrInput, tarW, ws)}{ws}{ws}{Prp(rows[0].Outcome, outW, ws)}{ws}{ws}{Prp(rows[0].Duration, timW, ws)}");

            // header separator
            _ = builder.AppendLine($"{p.Prefix}{prefix}:{p.Reset} {p.Default}{Prp("", tarW, p.Horizontal)}{p.Reset}{ws}{ws}{p.Default}{Prp("", outW, p.Horizontal)}{p.Reset}{ws}{ws}{p.Default}{Prp("", timW, p.Horizontal)}{p.Reset}");

            // targets
            foreach (var row in rows.Skip(1))
            {
                _ = builder.AppendLine($"{p.Prefix}{prefix}:{p.Reset} {Prp(row.TargetOrInput, tarW, ws)}{p.Reset}{ws}{ws}{Prp(row.Outcome, outW, ws)}{p.Reset}{ws}{ws}{Prp(row.Duration, durW, ws)}{p.Reset}{ws}{ws}{Prp(row.Percentage, perW, ws)}{p.Reset}");
            }

            // summary end separator
            _ = builder.AppendLine($"{p.Prefix}{prefix}:{p.Reset} {p.Default}{Prp("", tarW + 2 + outW + 2 + timW, p.Horizontal)}{p.Reset}");

            return builder.ToString();

            // pad right printed
            static string Prp(string text, int totalWidth, char paddingChar) =>
                text.PadRight(totalWidth + (text.Length - Palette.StripColours(text).Length), paddingChar);
        }

19 View Source File : WorkbookStream.cs
License : Apache License 2.0
Project Creator : aaaddress1

public WorkbookStream FixBoundSheetOffsets()
        {
            List<BoundSheet8> oldSheetBoundRecords = GetAllRecordsByType<BoundSheet8>();

            //We ignore the first BOF record for the global/workbook stream
            List<BOF> bofRecords = GetAllRecordsByType<BOF>().Skip(1).ToList();

            WorkbookStream newStream = new WorkbookStream(Records);

            int sheetOffset = 0;

            //replacedign each offset in order of definition (as per specification)
            foreach (var boundSheet in oldSheetBoundRecords)
            {
                long offset = newStream.GetRecordByteOffset(bofRecords[sheetOffset]);
                BoundSheet8 newBoundSheet8 = ((BiffRecord) boundSheet.Clone()).AsRecordType<BoundSheet8>();
                newBoundSheet8.lbPlyPos = (uint)offset;
                newStream = newStream.ReplaceRecord(boundSheet, newBoundSheet8);
                sheetOffset += 1;
            }

            return newStream;
        }

19 View Source File : MethodHelpers.cs
License : MIT License
Project Creator : ADeltaX

public static KeyValuePair<byte[], byte[]> SplitDataRaw(byte[] dataRaw)
        {
            byte[] data = dataRaw.SkipLast(8).ToArray();
            byte[] timestamp = dataRaw.Skip(data.Length).ToArray();

            return new KeyValuePair<byte[], byte[]>(timestamp, data);
        }

19 View Source File : ListExtensions.cs
License : MIT License
Project Creator : Abdulrhman5

public static async Task<List<T>> SkipTakeAsync<T,TKey,TEnreplacedy>(this IQueryable<T> query, IRepository<TKey,TEnreplacedy> repo, PagingArguments arguments) 
            where TEnreplacedy : clreplaced, IEnreplacedy<TKey>
        {
            return await repo.ToListAsync(query.Skip(arguments.StartObject).Take(arguments.Size));
        }

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

public virtual IEnumerable<IBlogPost> SelectPosts(int startRowIndex, int maximumRows = -1)
		{
			if (startRowIndex < 0)
			{
				throw new ArgumentException("Value must be a positive integer.", "startRowIndex");
			}

			if (maximumRows == 0)
			{
				return new IBlogPost[] { };
			}

			var serviceContext = Dependencies.GetServiceContext();
			var security = Dependencies.GetSecurityProvider();
			var urlProvider = Dependencies.GetUrlProvider();

			var query = SelectBlogPostEnreplacedies(serviceContext);

			var blogPostFactory = new BlogPostFactory(serviceContext, urlProvider, Website, new WebsiteBlogAggregationArchiveApplicationPathGenerator(Dependencies));
			var blogReadPermissionCache = new Dictionary<Guid, bool>();

			if (maximumRows < 0)
			{
				return blogPostFactory.Create(query.ToArray()
					.Where(e => TryreplacedertBlogPostRight(serviceContext, security, e, CrmEnreplacedyRight.Read, blogReadPermissionCache))
					.Skip(startRowIndex));
			}

			var pagedQuery = query;

			var paginator = new PostFilterPaginator<Enreplacedy>(
				(offset, limit) => pagedQuery.Skip(offset).Take(limit).ToArray(),
				e => TryreplacedertBlogPostRight(serviceContext, security, e, CrmEnreplacedyRight.Read, blogReadPermissionCache),
				2);

			return blogPostFactory.Create(paginator.Select(startRowIndex, maximumRows));
		}

19 View Source File : X86Assembly.cs
License : MIT License
Project Creator : 20chan

public static string FromInline(params object[] code)
        {
            switch(code[0])
            {
                case ASM asm:
                    return FromInline(asm, code.Skip(1));
                case Label label:
                    return $"{label.Name}:";
                case RawreplacedemblyCode raw:
                    return raw.Code;
                default:
                    throw new Exception("Unexpected Type");
            }
        }

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

public IEnumerable<T> Select(int offset, int limit)
		{
			var items = new List<T>();

			Select(0, (offset + limit) * _initialLimitMultiple, offset + limit, items);

			return items.Skip(offset).Take(limit).ToArray();
		}

19 View Source File : SimCluster.cs
License : MIT License
Project Creator : abdullin

static string GetNetwork(string machine) {
            if (machine.IndexOf('.') < 0) {
                return machine;
            }

            return string.Join('.', machine.Split('.').Skip(1));
        }

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

private int Gereplacedems(int topLimit, int unfilteredItemOffset, int itemLimit, ICollection<T> items)
		{
			var top = _getTop(topLimit);

			if (unfilteredItemOffset >= top.TotalUnfilteredItems)
			{
				return top.TotalUnfilteredItems;
			}

			foreach (var item in top.Skip(unfilteredItemOffset))
			{
				unfilteredItemOffset++;

				if (!_selector(item))
				{
					continue;
				}

				items.Add(item);

				if (items.Count >= itemLimit)
				{
					return top.TotalUnfilteredItems;
				}
			}

			if (topLimit >= top.TotalUnfilteredItems)
			{
				return items.Count;
			}

			return Gereplacedems(topLimit * _extendedSearchLimitMultiple, unfilteredItemOffset, itemLimit, items);
		}

19 View Source File : StringExtensions.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<String> SplitStringIntoChunks(this string str, int maxChunkSize)
        {
            List<string> chunks = new List<string>();

            for (int offset = 0; offset < str.Length; offset += maxChunkSize)
            {
                int bytesRemaining = str.Length - offset;
                int chunkSize = maxChunkSize;
                if (chunkSize > bytesRemaining)
                {
                    chunkSize = bytesRemaining;
                }

                chunks.Add(new string(str.Skip(offset).Take(chunkSize).ToArray()));
            }

            return chunks;
        }

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

private static Expression In<TValue>(Expression selectorBody, IEnumerable<TValue> values)
		{
			return In(
				selectorBody,
				values.Skip(1),
				Expression.Equal(selectorBody, Expression.Constant(values.First())));
		}

19 View Source File : CommitLogServer.cs
License : MIT License
Project Creator : abdullin

async Task HandleAsync(IConn conn) {
            try {
                using (conn) {
                    var req = await conn.Read(5.Sec());

                    switch (req) {
                        case DownloadRequest dr:
                            await conn.Write(_stored.Skip((int)dr.From).Take(dr.Count).ToList());
                            return;
                        case CommitRequest cr:
                            await _env.SimulateWork(5.Ms());

                            foreach (var e in cr.Events) {
                                _buffer.Enqueue(e);    
                            }

                            
                            ScheduleStore();
                            await conn.Write("OK");
                            return;
                        default:
                            conn.Write($"Unknown request {req}");
                            return;
                    }
                }
            } catch (Exception ex) {
                _env.Debug($"Error: {ex.Message}");
            }
        }

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

private IEnumerable<IForumThread> SelectThreadsWithSecurity(int startRowIndex, int maximumRows)
		{
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("startRowIndex={0}, maximumRows={1}: Start", startRowIndex, maximumRows));

			var serviceContext = Dependencies.GetServiceContext();
			var website = Dependencies.GetWebsite();

			var query = SelectThreadEnreplacedies(serviceContext);

			var securityProvider = Dependencies.GetSecurityProvider();
			var forumPermissionCache = new Dictionary<Guid, bool>();

			if (maximumRows < 0)
			{
				var readableEnreplacedies = query
					.ToArray()
					.Where(e => TryreplacedertReadPermission(serviceContext, securityProvider, e, forumPermissionCache))
					.Skip(startRowIndex);

				return CreateForumThreads(serviceContext, securityProvider, website, readableEnreplacedies);
			}

			var paginator = new PostFilterPaginator<Enreplacedy>(
				(offset, limit) => query.Skip(offset).Take(limit).ToArray(),
				e => TryreplacedertReadPermission(serviceContext, securityProvider, e, forumPermissionCache),
				2);

			var threads = CreateForumThreads(serviceContext, securityProvider, website, paginator.Select(startRowIndex, maximumRows));

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");

			return threads;
		}

19 View Source File : RedisDatabase.cs
License : MIT License
Project Creator : 17MKH

private IList<RedisKey> GetKeys(string prefix = null, int pageSize = 10, int pageOffset = 0)
    {
        var pat = prefix.IsNull() ? null : $"{GetKey(prefix)}*";
        var endPoints = _redis.GetEndPoints();
        if (endPoints.Length > 1)
        {
            var skipNum = pageOffset * pageSize;
            var leftNum = skipNum + pageSize;
            var keys = new List<RedisKey>();
            foreach (var endPoint in endPoints)
            {
                if (leftNum > 0)
                {
                    foreach (var key in _redis.GetServer(endPoint).Keys(_dbIndex, pat, pageSize: leftNum))
                    {
                        if (keys.Any(m => m == key))
                        {
                            continue;
                        }
                        keys.Add(key);
                        leftNum--;
                    }
                }
            }
            return keys.Skip(pageSize * pageOffset).Take(pageSize).ToList();
        }
        else
        {
            return _redis.GetServer(_redis.GetEndPoints().FirstOrDefault()).Keys(_dbIndex, pat, pageSize: pageSize, pageOffset: pageOffset).ToList();
        }
    }

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

public void WriteBytes(byte[] source, int offset, int length)
		{
			var range = source.Skip(offset).Take(length).ToArray();

			foreach (byte @byte in range)
			{
				this.WriteByte(@byte);
			}
		}

19 View Source File : MovingAverage.cs
License : MIT License
Project Creator : ABTSoftware

public static IEnumerable<double> Rsi(this IEnumerable<PriceBar> inputStream, int period)
        {
            var averageGain = new MovingAverage(period);
            var averageLoss = new MovingAverage(period);

            var previous = inputStream.First();
            foreach (var item in inputStream.Skip(1))
            {
                double gain = item.Close > previous.Close ? item.Close - previous.Close : 0.0;
                double loss = previous.Close > item.Close ? previous.Close - item.Close : 0.0;

                averageGain.Push(gain);
                averageLoss.Push(loss);

                double relativeStrength = double.IsNaN(averageGain.Current) || double.IsNaN(averageLoss.Current) ? double.NaN : averageGain.Current / averageLoss.Current;

                previous = item;
                yield return double.IsNaN(relativeStrength) ? double.NaN : 100.0 - (100.0 / (1.0 + relativeStrength));
            }
        }

19 View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1

private static string ImportCellFormula(string cellFormula)
        {
            if (cellFormula.Length == 0) return cellFormula;

            string newCellFormula = cellFormula;

            //Unescape the "s if we are looking at a CellFormula that has been escaped
            if (newCellFormula.StartsWith('"'))
            {
                //Strip the outer quotes
                newCellFormula = new string(newCellFormula.Skip(1).Take(newCellFormula.Length - 2).ToArray());

                //Escape the inside content
                newCellFormula = ExcelHelperClreplaced.UnescapeFormulaString(newCellFormula);
            }

            //Replace any uses of SELECT and ACTIVE.CELL with variable usage to better enable the sheet being hidden
            //Mainly for use with importing EXCELntDonut macros
            newCellFormula = ReplaceSelectActiveCellFormula(newCellFormula);

            //FORMULA requires R1C1 strings
            newCellFormula = ConvertA1StringToR1C1String(newCellFormula);

            int charReplacements = 0;
            //Remap CHAR() to actual bytes
            for (int i = 1; i <= 255; i += 1)
            {
                int oldLength = newCellFormula.Length;
                newCellFormula = newCellFormula.Replace(string.Format("CHAR({0})&", i), "" + (char) i);
                newCellFormula = newCellFormula.Replace(string.Format("CHAR({0})", i), "" + (char)i);

                //Update our poor heuristic for when we're getting a cell that is just CHAR()&CHAR()&CHAR()&CHAR()...
                if (oldLength != newCellFormula.Length)
                {
                    double lengthDelta = oldLength - newCellFormula.Length;
                    charReplacements += (int)Math.Floor(lengthDelta / 6.0);
                }
            }
            
            //Arbitrary metric to determine if we should convert this to a string cell vs. formula cell
            if (charReplacements > 3 && newCellFormula[0] == '=')
            {
                newCellFormula = new string(newCellFormula.Skip(1).ToArray());

                //Excel cells will also check to see if we are a variable replacedignment cell:
                //if we have valid variable letters before an =, it will process the replacedignment value
                bool looksLikeVariablereplacedignment = LooksLikeVariablereplacedignment(newCellFormula);

                //If we have a raw string content that starts with = or @, we can wrap this with ="" and it will work
                //If the string content is already 255 bytes though, this won't work (FORMULA will fail trying to write the 258 byte string)
                //If we're close to the limit then populate the cell with =CHAR(w/e)&Ref to cell with remainder of the content
                if (newCellFormula.StartsWith('=') || newCellFormula.StartsWith('@') || looksLikeVariablereplacedignment)
                {
                    //Need to make sure there's room for inserting 3 more characters =""
                    if (newCellFormula.Length >= 255 - 3)
                    {
                        //If this is a max length cell (common with 255 byte increments of shellcode)
                        //then mark the macro with a marker and we'll break it into two cells when we're building the sheet
                        return FormulaHelper.TOOLONGMARKER + newCellFormula;
                    }
                    else
                    {
                        newCellFormula = string.Format("=\"{0}\"", newCellFormula);
                    }
                    
                }
            }
            else
            {
                //TODO Use a proper logging package and log this as DEBUG info
                // Console.WriteLine(newCellFormula);
            }

            if (newCellFormula.Length > 255)
            {
                throw new ArgumentException(string.Format("Imported Cell Formula is too long - length must be 255 or less:\n{0}", newCellFormula));
            }


            return newCellFormula;
        }

19 View Source File : RCEPControl.cs
License : MIT License
Project Creator : 0x0ade

[RCEndpoint(true, "/userinfos", "?from={first}&count={count}", "?from=0&count=100", "User Infos", "Get some basic information about ALL users.")]
        public static void UserInfos(Frontend f, HttpRequestEventArgs c) {
            using UserDataBatchContext ctx = f.Server.UserData.OpenBatch();

            string[] uids = f.Server.UserData.GetAll();

            NameValueCollection args = f.ParseQueryString(c.Request.RawUrl);
            if (!int.TryParse(args["from"], out int from) || from <= 0)
                from = 0;
            if (!int.TryParse(args["count"], out int count) || count <= 0)
                count = 100;
            if (from + count > uids.Length)
                count = uids.Length - from;

            f.RespondJSON(c, uids.Skip(from).Take(count).Select(uid => {
                BasicUserInfo info = f.Server.UserData.Load<BasicUserInfo>(uid);
                BanInfo ban = f.Server.UserData.Load<BanInfo>(uid);
                KickHistory kicks = f.Server.UserData.Load<KickHistory>(uid);
                return new {
                    UID = uid,
                    info.Name,
                    info.Discrim,
                    info.Tags,
                    Key = f.Server.UserData.GetKey(uid),
                    Ban = ban.Reason.IsNullOrEmpty() ? null : new {
                        ban.Name,
                        ban.Reason,
                        From = ban.From?.ToUnixTime() ?? 0,
                        To = ban.To?.ToUnixTime() ?? 0
                    },
                    Kicks = kicks.Log.Select(e => new {
                        e.Reason,
                        From = e.From?.ToUnixTime() ?? 0
                    }).ToArray()
                };
            }).ToArray());
        }

19 View Source File : X86Assembly.cs
License : MIT License
Project Creator : 20chan

public static string GetCode(params object[] code)
        {
            string asmcode = "";

            for (int i = 0; i < code.Length; i++)
            {
                if (!(code[i] is ASM))
                    if (!(code[i] is int))
                        if (!(code[i] is REG))
                            if (!(code[i] is MEM))
                                if (!(code[i] is string))
                                    if (!(code[i] is Label))
                                        if (!(code[i] is RawreplacedemblyCode))
                                            throw new ArrayTypeMismatchException("Not supported type");

                var cnt = InstructionPattern.CheckPattern(code, i);
                if (cnt < 0)
                    throw new FormatException("Format error");
                asmcode += $"{FromInline(code.Skip(i).Take(cnt + 1).ToArray())}\n";
                i += cnt;
            }

            return asmcode;
        }

19 View Source File : CommandTree.cs
License : MIT License
Project Creator : 5minlab

private void _run(string[] commands, int index) {
            if (commands.Length == index) {
                RunCommand(emptyArgs);
                return;
            }

            string token = commands[index].ToLower();
            if (!m_subcommands.ContainsKey(token)) {
                RunCommand(commands.Skip(index).ToArray());
                return;
            }
            m_subcommands[token]._run(commands, index + 1);
        }

19 View Source File : SimpleLatencyBenchmark.cs
License : MIT License
Project Creator : Abc-Arbitrage

private static HistogramBase Concatenate(List<HistogramBase> seq)
        {
            var result = seq.First().Copy();
            foreach (var h in seq.Skip(1))
                result.Add(h);
            return result;
        }

19 View Source File : LoadedNodeManager.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public void PlaceNode(IEnumerable<string> catagoryPath, INodeContainer node)
            {
                if (!catagoryPath.Any() || catagoryPath.First() == null || catagoryPath.First() == "")
                {
                    Nodes.Add(node);
                }
                else
                {
                    if (!SubCatagories.ContainsKey(catagoryPath.First()))
                    {
                        SubCatagories.Add(catagoryPath.First(), new NodeCatagories(SubCatagories.Count));
                    }

                    SubCatagories[catagoryPath.First()].PlaceNode(catagoryPath.Skip(1), node);
                }
            }

See More Examples