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 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

private static Uri GetDoreplacedentLocationUrl(IEnumerable<Enreplacedy> path)
		{
			var head = path.First();
			var tail = path.Skip(1).Select(segment => segment.GetAttributeValue<string>("relativeurl"));

			// the head should be a SharePoint site enreplacedy or an absolute doreplacedent location

			var baseUrl = head.GetAttributeValue<string>("absoluteurl");

			if (!tail.Any()) return new Uri(baseUrl);

			// the tail should be a sequence of doreplacedent location enreplacedies

			var relativeUrl = string.Join("/", tail.ToArray());
			var url = Combine(baseUrl, relativeUrl);

			return new Uri(url);
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static void GetDoreplacedentLocationListAndFolder(this OrganizationServiceContext context, Enreplacedy enreplacedy, out string listUrl, out string folderUrl)
		{
			var absoluteUrl = enreplacedy.GetAttributeValue<string>("absoluteurl");

			if (!string.IsNullOrWhiteSpace(absoluteUrl))
			{
				throw new NotImplementedException("Add support for 'absoluteurl' based doreplacedent locations.");
			}

			var path = context.GetDoreplacedentLocationPath(enreplacedy);

			var tail = path.Skip(1).ToList(); // path.First() is SP site.

			var listEnreplacedy = tail.First();
			var folderEnreplacedies = tail.Skip(1);

			listUrl = listEnreplacedy.GetAttributeValue<string>("relativeurl");

			var segments = folderEnreplacedies.Select(e => e.GetAttributeValue<string>("relativeurl"));

			folderUrl = string.Join("/", segments);
		}

19 Source : PortalFacetedIndexSearcher.cs
with MIT License
from Adoxio

protected override 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, rawSearchResultSet.FacetViews, rawSearchResultSet.SortingOptions);
		}

19 Source : SiteMapExtensions.cs
with MIT License
from Adoxio

private static IEnumerable<Tuple<SiteMapNode, SiteMapNodeType>> SiteMapPath(HtmlHelper html, Func<SiteMapProvider, SiteMapNode> getCurrentNode, int? takeLast)
		{
			var portalViewContext = PortalExtensions.GetPortalViewContext(html);
			var siteMapProvider = portalViewContext.SiteMapProvider;

			if (siteMapProvider == null)
			{
				return Enumerable.Empty<Tuple<SiteMapNode, SiteMapNodeType>>();
			}

			var current = getCurrentNode(siteMapProvider);

			if (current == null)
			{
				return Enumerable.Empty<Tuple<SiteMapNode, SiteMapNodeType>>();
			}

			var path = new Stack<Tuple<SiteMapNode, SiteMapNodeType>>();

			path.Push(new Tuple<SiteMapNode, SiteMapNodeType>(current, SiteMapNodeType.Current));

			current = current.ParentNode;

			while (current != null)
			{
				var parent = current.ParentNode;

				path.Push(new Tuple<SiteMapNode, SiteMapNodeType>(
					current,
					parent == null ? SiteMapNodeType.Root : SiteMapNodeType.Parent));

				current = parent;
			}

			var nodes = takeLast != null ? path.Skip(Math.Max(0, path.Count() - takeLast.Value)) : path;

			return nodes.ToList();
		}

19 Source : EnumerableFilters.cs
with MIT License
from Adoxio

public static object Paginate(object input, int index, int count)
		{
			var blogPostsDrop = input as BlogPostsDrop;

			if (blogPostsDrop != null)
			{
				return BlogFunctions.Paginate(blogPostsDrop, index, count);
			}

			var forumThreadsDrop = input as ForumThreadsDrop;

			if (forumThreadsDrop != null)
			{
				return ForumFunctions.Paginate(forumThreadsDrop, index, count);
			}

			var forumPostsDrop = input as ForumPostsDrop;

			if (forumPostsDrop != null)
			{
				return ForumFunctions.Paginate(forumPostsDrop, index, count);
			}

			var enumerable = input as IEnumerable;

			if (enumerable != null)
			{
				return enumerable.Cast<object>().Skip(index).Take(count);
			}

			return input;
		}

19 Source : EnumerableFilters.cs
with MIT License
from Adoxio

public static object Skip(object input, int count)
		{
			var blogPostsDrop = input as BlogPostsDrop;

			if (blogPostsDrop != null)
			{
				return BlogFunctions.FromIndex(blogPostsDrop, count);
			}

			var forumThreadsDrop = input as ForumThreadsDrop;

			if (forumThreadsDrop != null)
			{
				return ForumFunctions.FromIndex(forumThreadsDrop, count);
			}

			var forumPostsDrop = input as ForumPostsDrop;

			if (forumPostsDrop != null)
			{
				return ForumFunctions.FromIndex(forumPostsDrop, count);
			}

			var enumerable = input as IEnumerable;

			if (enumerable != null)
			{
				return enumerable.Cast<object>().Skip(count);
			}

			return input;
		}

19 Source : StyleExtensions.cs
with MIT License
from Adoxio

private void Add(Tuple<string, string, int> fileName, string[] fileNameParts, ICollection<Node> nodes)
			{
				if (!fileNameParts.Any())
				{
					nodes.Add(new Node(TerminalNodeKey, fileName));

					return;
				}

				var currentPart = fileNameParts.First();
				var matchingNode = nodes.SingleOrDefault(node => string.Equals(node.Key, currentPart, StringComparison.OrdinalIgnoreCase));

				if (matchingNode == null)
				{
					var newNode = new Node(currentPart);

					nodes.Add(newNode);

					Add(fileName, fileNameParts.Skip(1).ToArray(), newNode.Children);
				}
				else
				{
					Add(fileName, fileNameParts.Skip(1).ToArray(), matchingNode.Children);
				}
			}

19 Source : CrmContactRoleProvider.cs
with MIT License
from Adoxio

private static Expression ContainsPropertyValueEqual(string crmPropertyName, IEnumerable<object> values, ParameterExpression parameter, Expression expression)
		{
			if (!values.Any())
			{
				return expression;
			}

			var orElse = Expression.OrElse(expression, PropertyValueEqual(parameter, crmPropertyName, values.First()));

			return ContainsPropertyValueEqual(crmPropertyName, values.Skip(1), parameter, orElse);
		}

19 Source : CrmContactRoleProvider.cs
with MIT License
from Adoxio

private static Expression ContainsPropertyValueEqual(string crmPropertyName, IEnumerable<object> values, ParameterExpression parameter)
		{
			var left = PropertyValueEqual(parameter, crmPropertyName, values.First());

			return ContainsPropertyValueEqual(crmPropertyName, values.Skip(1), parameter, left);
		}

19 Source : XrmQueryExtensions.cs
with MIT License
from Adoxio

private static Expression ContainsPropertyValueEqual(string propertyName1, string propertyName2,
			IEnumerable<Tuple<string, string>> values, ParameterExpression parameter)
		{
			var enumerable = values as IList<Tuple<string, string>> ?? values.ToList();
			var left = PropertyValueEqual(parameter, propertyName1, enumerable.Select(v => v.Item1).First());
			var right = PropertyValueEqual(parameter, propertyName2, enumerable.Select(v => v.Item2).First());
			var leftAnd = Expression.And(left, right);

			return ContainsPropertyValueEqual(propertyName1, propertyName2, enumerable.Skip(1), parameter, leftAnd);
		}

19 Source : XrmQueryExtensions.cs
with MIT License
from Adoxio

private static Expression ContainsPropertyValueEqual(string propertyName1, string propertyName2,
			IEnumerable<Tuple<string, string>> values, ParameterExpression parameter, Expression expression)
		{
			var enumerable = values as IList<Tuple<string, string>> ?? values.ToList();

			if (!enumerable.Any())
			{
				return expression;
			}

			var orElse = Expression.OrElse(expression,
				ContainsPropertyValueEqual(propertyName1, propertyName2, enumerable, parameter));

			return ContainsPropertyValueEqual(propertyName1, propertyName2, enumerable.Skip(1), parameter, orElse);
		}

19 Source : LiquidServerControl.cs
with MIT License
from Adoxio

private void AddTemplate(string html)
		{
			var regex = new Regex(@"\<!--\[% (\w+) id:([A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12})? %\]--\>",
				RegexOptions.IgnoreCase);

			Control container = this;

			if (regex.IsMatch(html))
			{
				container = ServerForm(container);
			}

			while (regex.IsMatch(html))
			{
				var match = regex.Match(html);

				var control = match.Groups[1].Value;
				var id = match.Groups[2].Value;
				Guid guid;
				if (Guid.TryParse(id, out guid))
				{
					var splits = html.Split(new[] { match.Value }, StringSplitOptions.RemoveEmptyEntries);
					var preSplit = new LiteralControl(splits[0]);
					container.Controls.Add(preSplit);

					switch (control)
					{
					case "enreplacedyform":
						var enreplacedyForm = InitEnreplacedyForm(guid);
						container.Controls.Add(enreplacedyForm);
						break;
					case "webform":
						var webForm = InitWebForm(guid);
						container.Controls.Add(webForm);
						break;
					}

					html = string.Join(match.Value, splits.Skip(1));
				}
			}

			var close = new LiteralControl(html);
			container.Controls.Add(close);
		}

19 Source : EmbeddedResourceAssemblyAttribute.cs
with MIT License
from Adoxio

private static void AddResource(EmbeddedResourceNode node, IDictionary<string, EmbeddedResourceNode> lookup, IEnumerable<string> path, string resourceName)
		{
			if (path.Any())
			{
				var name = path.First();

				var child = node.Children.SingleOrDefault(n => n.Name == name);
				
				if (child == null)
				{
					var isFile = path.Count() == 1;
					var resource = isFile ? resourceName : GetResourceName(node, name);

					child = new EmbeddedResourceNode(name, !isFile, isFile, GetVirtualPath(node, name), resource);

					node.Children.Add(child);
					lookup.Add(resource, child);
				}

				AddResource(child, lookup, path.Skip(1), resourceName);
			}
		}

19 Source : MapController.cs
with MIT License
from Adoxio

private static Expression ContainsPropertyValueEqual(string crmPropertyName, IEnumerable<Guid> values, ParameterExpression parameter)
		{
			var left = PropertyValueEqual(parameter, crmPropertyName, values.First());

			return ContainsPropertyValueEqual(crmPropertyName, values.Skip(1), parameter, left);
		}

19 Source : MapController.cs
with MIT License
from Adoxio

private static Expression ContainsPropertyValueEqual(string crmPropertyName, IEnumerable<Guid> values, ParameterExpression parameter, Expression expression)
		{
			if (!values.Any())
			{
				return expression;
			}

			var orElse = Expression.OrElse(expression, PropertyValueEqual(parameter, crmPropertyName, values.First()));

			return ContainsPropertyValueEqual(crmPropertyName, values.Skip(1), parameter, orElse);
		}

19 Source : DataGridDemoViewModel.cs
with GNU General Public License v3.0
from aduskin

private void PageUpdated(FunctionEventArgs<int> info)
      {
         ContactList = new ObservableCollection<ChatUserModel>(TotalContactList.Skip((info.Info - 1) * 10).Take(10).ToList());
      }

19 Source : Maps.cs
with GNU General Public License v3.0
from aedenthorn

public static void BuildSpouseRooms(FarmHouse farmHouse)
        {
            if (config.DisableCustomSpousesRooms)
                return;

            try
            {
                if(farmHouse is Cabin)
                {
                    Monitor.Log("BuildSpouseRooms for Cabin");
                }

                Farmer f = farmHouse.owner;
                if (f == null)
                    return;
                Misc.ResetSpouses(f);
                Monitor.Log("Building all spouse rooms");
                if (Misc.GetSpouses(f, 1).Count == 0 || farmHouse.upgradeLevel > 3)
                {
                    ModEntry.PMonitor.Log("No spouses");
                    farmHouse.showSpouseRoom();
                    return;
                }

                List<string> spousesWithRooms = new List<string>();

                foreach (string spouse in Misc.GetSpouses(f, 1).Keys)
                {
                    Monitor.Log($"checking {spouse} for spouse room");
                    if (roomIndexes.ContainsKey(spouse) || tmxSpouseRooms.ContainsKey(spouse))
                    {
                        Monitor.Log($"Adding {spouse} to list for spouse rooms");
                        spousesWithRooms.Add(spouse);
                    }
                }

                if (spousesWithRooms.Count == 0)
                {
                    ModEntry.PMonitor.Log("No spouses with rooms");
                    return;
                }

                spousesWithRooms = new List<string>(Misc.ReorderSpousesForRooms(spousesWithRooms));

                if (!spousesWithRooms.Any())
                    return;

                if (!ModEntry.config.BuildAllSpousesRooms)
                {
                    if (f.spouse != null && !f.friendshipData[f.spouse].IsEngaged() && (roomIndexes.ContainsKey(f.spouse) || tmxSpouseRooms.ContainsKey(f.spouse)))
                    {
                        Monitor.Log($"Building spouse room for official spouse {f.spouse}");
                        BuildOneSpouseRoom(farmHouse, f.spouse, -1);
                    }
                    else
                    {
                        Monitor.Log($"No spouse room for official spouse {f.spouse}, placing for {spousesWithRooms[0]} instead.");
                        BuildOneSpouseRoom(farmHouse, spousesWithRooms[0], -1);
                        spousesWithRooms = new List<string>(spousesWithRooms.Skip(1));
                    }
                    return;
                }

                Monitor.Log($"Building {spousesWithRooms.Count} additional spouse rooms");

                List<string> sheets = new List<string>();
                for (int i = 0; i < farmHouse.map.TileSheets.Count; i++)
                {
                    sheets.Add(farmHouse.map.TileSheets[i].Id);
                }
                int unreplacedled = sheets.IndexOf("unreplacedled tile sheet");
                int floorsheet = sheets.IndexOf("walls_and_floors");
                int indoor = sheets.IndexOf("indoor");

                Monitor.Log($"Map has sheets: {string.Join(", ", sheets)}");

                int startx = 29;

                int ox = ModEntry.config.ExistingSpouseRoomOffsetX;
                int oy = ModEntry.config.ExistingSpouseRoomOffsetY;
                if (farmHouse.upgradeLevel > 1)
                {
                    ox += 6;
                    oy += 9;
                }

                Monitor.Log($"Preliminary adjustments");

                for (int i = 0; i < 7; i++)
                {
                    farmHouse.setMapTileIndex(ox + startx + i, oy + 11, 0, "Buildings", indoor);
                    farmHouse.removeTile(ox + startx + i, oy + 9, "Front");
                    farmHouse.removeTile(ox + startx + i, oy + 10, "Buildings");
                    farmHouse.setMapTileIndex(ox + startx - 1 + i, oy + 10, 165, "Front", indoor);
                    farmHouse.removeTile(ox + startx + i, oy + 10, "Back");
                }
                for (int i = 0; i < 8; i++)
                {
                    farmHouse.setMapTileIndex(ox + startx - 1 + i, oy + 10, 165, "Front", indoor);
                }
                for (int i = 0; i < 10; i++)
                {
                    farmHouse.removeTile(ox + startx + 6, oy + 0 + i, "Buildings");
                    farmHouse.removeTile(ox + startx + 6, oy + 0 + i, "Front");
                }
                for (int i = 0; i < 7; i++)
                {
                    // horiz hall
                    farmHouse.setMapTileIndex(ox + startx + i, oy + 10, (i % 2 == 0 ? 352: 336), "Back", floorsheet);
                }


                for (int i = 0; i < 7; i++)
                {
                    //farmHouse.removeTile(ox + startx - 1, oy + 4 + i, "Back");
                    //farmHouse.setMapTileIndex(ox + 28, oy + 4 + i, (i % 2 == 0 ? 352 : ModEntry.config.HallTileEven), "Back", 0);
                }


                farmHouse.removeTile(ox + startx - 1, oy + 9, "Front");
                farmHouse.removeTile(ox + startx - 1, oy + 10, "Buildings");
                
                if(farmHouse.upgradeLevel > 1) 
                    farmHouse.setMapTileIndex(ox + startx - 1, oy + 10, 163, "Front", indoor);
                farmHouse.removeTile(ox + startx + 6, oy + 0, "Front");
                farmHouse.removeTile(ox + startx + 6, oy + 0, "Buildings");



                int count = -1;

                ExtendMap(farmHouse, ox + startx + 8 + (7* spousesWithRooms.Count));

                // remove and rebuild spouse rooms
                for (int j = 0; j < spousesWithRooms.Count; j++)
                {
                    farmHouse.removeTile(ox + startx + 6 + (7 * count), oy + 0, "Buildings");
                    for (int i = 0; i < 10; i++)
                    {
                        farmHouse.removeTile(ox + startx + 6 + (7 * count), oy + 1 + i, "Buildings");
                    }
                    BuildOneSpouseRoom(farmHouse, spousesWithRooms[j], count++);
                }

                Monitor.Log($"Building far wall");

                // far wall
                farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 0, 11, "Buildings", indoor);
                for (int i = 0; i < 10; i++)
                {
                    farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 1 + i, 68, "Buildings", indoor);
                }
                farmHouse.setMapTileIndex(ox + startx + 6 + (7 * count), oy + 10, 130, "Front", indoor);
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(BuildSpouseRooms)}:\n{ex}", LogLevel.Error);
            }
            farmHouse.getWalls();
            farmHouse.getFloors();
        }

19 Source : SocialPost.cs
with GNU General Public License v3.0
from aedenthorn

private void GetPostDetails()
        {
            if(posreplacedems.Length > 0)
            {
                foreach(string item in posreplacedems)
                {
                    string key = item.Split(':')[0];
                    string val = string.Join("",item.Split(':').Skip(1));
                    if (key == null || val == null)
                        continue;
                    switch (key.ToLower())
                    {
                        case "text":
                            text = val;
                            lines = new List<string>(Utils.GetTextLines(text));
                            break;
                        case "picture":
                            picture = Utils.GetPicture(val);
                            break;
                        case "reactions":
                            reactions = val.Split(',');
                            GetReactions();
                            break;
                        case "comments":
                            comments = val.Split(',');
                            GetComments();
                            break;
                    }
                }

            }
        }

19 Source : SwimPatches.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> Wand_DoFunction_Transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            try
            {
                int start = 0;
                for (int i = 0; i < codes.Count; i++)
                {
                    if (codes[i].opcode == OpCodes.Ret)
                    {
                        start = i + 1;
                        return codes.Skip(start).AsEnumerable();
                    }
                }
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(Wand_DoFunction_Transpiler)}:\n{ex}", LogLevel.Error);
            }

            return codes.AsEnumerable();
        }

19 Source : Altars.cs
with GNU General Public License v3.0
from aedenthorn

internal static void OfferObject(MineShaft shaft, string action, Location tileLocation, Farmer who)
        {
            string[] parts = action.Split('_').Skip(1).ToArray();

            int type = int.Parse(parts[0]);
            int cx = int.Parse(parts[1]);
            int cy = int.Parse(parts[2]);

            if (who.ActiveObject == null)
            {
                Game1.activeClickableMenu = new DialogueBox(helper.Translation.Get($"altar-explain-{type}"));
                return;
            }

            int value = who.ActiveObject.salePrice();
            who.reduceActiveItemByOne();
            if (value < 10)
            {
                if (type == 0)
                {
                    CollapsingFloors.collapseFloor(shaft, who.getTileLocation());
                    return;
                }
                else if (type == 1)
                {
                    Traps.TriggerRandomTrap(shaft, who.getTileLocation(), false);
                    return;
                }
            }

            string sound = "yoba";
            if(type == 0)
            {
                sound = "grunt";
            }
            else if(type == 1)
            {
                sound = "debuffSpell";
            }
            shaft.playSound(sound, SoundContext.Default);

            BuffsDisplay buffsDisplay = Game1.buffsDisplay;
            Buff buff2 = GetBuff(value, who, shaft, type);
            buffsDisplay.addOtherBuff(buff2);
        }

19 Source : TilePuzzles.cs
with GNU General Public License v3.0
from aedenthorn

internal static void pressTile(MineShaft shaft, Vector2 playerStandingPosition, string action)
        {
            string[] parts = action.Split('_').Skip(1).ToArray();
            monitor.Log($"Pressed floor number {parts[0]} (row: {parts[1]} center: {parts[2]},{parts[3]}) at {playerStandingPosition} {shaft.Name}");

            int idx = int.Parse(parts[0]);
            int row = int.Parse(parts[1]);
            int cx = int.Parse(parts[2]);
            int cy = int.Parse(parts[3]);

            Vector2[] spots = Utils.getCenteredSpots(new Vector2(cx, cy), true);

            bool correct = CheckTileOrder(shaft, spots, idx,cx,cy);

            Layer layer = shaft.map.GetLayer("Back");
            TileSheet tilesheet = shaft.map.GetTileSheet(ModEntry.tileSheetId);
            if (correct)
            {
                monitor.Log($"correct order, deactivating tile {idx}");
                shaft.playSound("Ship", SoundContext.Default);
                layer.Tiles[(int)playerStandingPosition.X, (int)playerStandingPosition.Y] = new StaticTile(layer, tilesheet, BlendMode.Alpha, tileIndex: 16*row + idx + 8);
                shaft.removeTileProperty(cx, cy, "Back", "TouchAction");
            }
            else
            {
                shaft.playSound("Duggy", SoundContext.Default);
                monitor.Log($"wrong order, deactivating puzzle");
                foreach (Vector2 spot in spots)
                {
                    if (layer.Tiles[(int)spot.X, (int)spot.Y].TileIndex % 16 >= 8)
                        continue;
                    
                    layer.Tiles[(int)spot.X, (int)spot.Y] = new StaticTile(layer, tilesheet, BlendMode.Alpha, tileIndex: layer.Tiles[(int)spot.X, (int)spot.Y].TileIndex + 8);
                    shaft.removeTileProperty((int)spot.X, (int)spot.Y, "Back", "TouchAction");
                }
                Traps.TriggerRandomTrap(shaft, playerStandingPosition, false);
            }
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private List<string> GetHighestRankedStrings(string npcString, List<string> data, int checks)
        {
            List<string> outStrings = new List<string>();
            int rank = 0;
            foreach (string str in data)
            {
                int aRank = RankStringForNPC(npcString, str, checks);
                if (aRank > rank)
                {
                    outStrings = new List<string>(); // reset on higher rank
                    rank = aRank;
                }
                if (aRank == rank)
                {
                    outStrings.Add(string.Join("/", str.Split('/').Skip(checks)));
                }

            }
            return outStrings;
        }

19 Source : LightPuzzles.cs
with GNU General Public License v3.0
from aedenthorn

internal static void pressTile(MineShaft shaft, Vector2 pos, string action)
        {
            string[] parts = action.Split('_').Skip(1).ToArray();
            monitor.Log($"Pressed floor number {parts[0]} (center: {parts[1]},{parts[2]}) at {pos} {shaft.Name}");
            shaft.playSound("Ship", SoundContext.Default);

            int idx = int.Parse(parts[0]);
            int cx = int.Parse(parts[1]);
            int cy = int.Parse(parts[2]);
            Vector2 spot = new Vector2(cx, cy);

            Vector2[] corners = new Vector2[]
            {
                new Vector2(-1,-1),
                new Vector2(1,-1),
                new Vector2(1,1),
                new Vector2(-1,1)
            };

            int corner = 0;

            if(cx < pos.X && cy > pos.Y) // tr
            {
                corner = 1;
            }
            else if(cx < pos.X && cy < pos.Y) // br
            {
                corner = 2;
            }
            else if (cx > pos.X && cy < pos.Y) // bl
            {
                corner = 3;
            }
            monitor.Log($"corner {corner}, idx {idx}, center {cx},{cy}, pos {pos}");

            TileSheet tilesheet = shaft.map.GetTileSheet(ModEntry.tileSheetId);
            int lit = 0;
            for (int i = 0; i < 4; i++)
            {
                bool isLit = shaft.map.GetLayer("Buildings").Tiles[(int)(spot.X + 2 * corners[corner].X), (int)(spot.Y + 2 * corners[corner].Y)].TileIndex == 16 * (cornerY + 2) + 1;
                int light = isLit ? 0 : 1;

                if(i < idx)
                {
                    shaft.map.GetLayer("Front").Tiles[(int)(spot.X + 2 * corners[corner].X), (int)(spot.Y + 2 * corners[corner].Y) - 2] = new StaticTile(shaft.map.GetLayer("Front"), tilesheet, BlendMode.Alpha, tileIndex: 16 * cornerY + light);
                    shaft.map.GetLayer("Front").Tiles[(int)(spot.X + 2 * corners[corner].X), (int)(spot.Y + 2 * corners[corner].Y - 1)] = new StaticTile(shaft.map.GetLayer("Front"), tilesheet, BlendMode.Alpha, tileIndex: 16 * (cornerY + 1) + light);
                    shaft.map.GetLayer("Buildings").Tiles[(int)(spot.X + 2 * corners[corner].X), (int)(spot.Y + 2 * corners[corner].Y)] = new StaticTile(shaft.map.GetLayer("Buildings"), tilesheet, BlendMode.Alpha, tileIndex: 16 * (cornerY + 2) + light);
                    lit += light;
                    monitor.Log($"switched {i}, corner {corner}, idx {idx}, lit {lit}, isLit {isLit}, light {light}");
                }
                else
                {
                    lit += (isLit ? 1 : 0);
                    monitor.Log($"didn't switch {i}, corner {corner}, idx {idx}, lit {lit}, isLit {isLit}, light {light}");
                }
                corner++;
                corner %= 4;
            }
            if (lit == 4)
            {
                shaft.playSound("Duggy", SoundContext.Default);

                for (int i = 0; i < 4; i++)
                    shaft.removeTileProperty((int)(spot.X + corners[i].X), (int)(spot.Y + corners[i].Y), "Back", "TouchAction");
                Utils.DropChest(shaft, spot);
            }
        }

19 Source : OfferingPuzzles.cs
with GNU General Public License v3.0
from aedenthorn

internal static void StealAttempt(MineShaft shaft, string action, Location tileLocation, Farmer who)
        {
            monitor.Log($"Attempting to steal from altar");

            string[] parts = action.Split('_').Skip(1).ToArray();

            Vector2 spot = new Vector2(int.Parse(parts[0]), int.Parse(parts[1]));
            shaft.setMapTileIndex((int)spot.X - 1, (int)spot.Y + 1, OfferingPuzzles.offerIdx, "Buildings");
            shaft.setMapTileIndex((int)spot.X + 1, (int)spot.Y + 1, OfferingPuzzles.offerIdx, "Buildings");
            shaft.setMapTileIndex((int)spot.X - 1, (int)spot.Y - 1, 244, "Front");
            shaft.setMapTileIndex((int)spot.X + 1, (int)spot.Y - 1, 244, "Front");
            shaft.removeTileProperty((int)spot.X - 1, (int)spot.Y + 1, "Buildings", "Action");
            shaft.removeTileProperty((int)spot.X + 1, (int)spot.Y + 1, "Buildings", "Action");
            Traps.TriggerRandomTrap(shaft, new Vector2(who.getTileLocation().X, who.getTileLocation().Y), false);
        }

19 Source : OfferingPuzzles.cs
with GNU General Public License v3.0
from aedenthorn

internal static void OfferObject(MineShaft shaft, string action, Location tileLocation, Farmer who)
        {
            monitor.Log($"Attempting to offer to altar");

            string[] parts = action.Split('_').Skip(1).ToArray();
            Vector2 spot = new Vector2(int.Parse(parts[1]), int.Parse(parts[2]));
            if (ores[int.Parse(parts[0])] == who.ActiveObject.ParentSheetIndex)
            {
                monitor.Log($"Made acceptable offering to altar");
                who.reduceActiveItemByOne();
                shaft.setMapTileIndex(tileLocation.X, tileLocation.Y, OfferingPuzzles.offerIdx + 1 + int.Parse(parts[0]), "Buildings");
                shaft.setMapTileIndex(tileLocation.X, tileLocation.Y - 2, 245, "Front");
                shaft.setTileProperty((int)spot.X - 1, (int)spot.Y + 1, "Buildings", "Action", $"offerPuzzleSteal_{parts[1]}_{parts[2]}");
                shaft.setTileProperty((int)spot.X + 1, (int)spot.Y + 1, "Buildings", "Action", $"offerPuzzleSteal_{parts[1]}_{parts[2]}");
                Utils.DropChest(shaft, spot);
            }
            else
            {
                monitor.Log($"Made unacceptable offering to altar");
                who.reduceActiveItemByOne();
                shaft.setMapTileIndex((int)spot.X - 1, (int)spot.Y + 1, OfferingPuzzles.offerIdx, "Buildings");
                shaft.setMapTileIndex((int)spot.X + 1, (int)spot.Y + 1, OfferingPuzzles.offerIdx, "Buildings");
                shaft.removeTileProperty((int)spot.X - 1, (int)spot.Y + 1, "Buildings", "Action");
                shaft.removeTileProperty((int)spot.X + 1, (int)spot.Y + 1, "Buildings", "Action");
                Traps.TriggerRandomTrap(shaft, new Vector2(who.getTileLocation().X, who.getTileLocation().Y), false);
            }
        }

19 Source : IInValueCache.cs
with MIT License
from AElfProject

public Hash GetInValue(long roundId)
        {
            // Remove old in values. (Keep 10 in values.)
            const int keepInValuesCount = 10;
            if (_inValues.Keys.Count > keepInValuesCount)
            {
                foreach (var id in _inValues.Keys.OrderByDescending(id => id).Skip(keepInValuesCount))
                {
                    _inValues.Remove(id);
                }
            }

            _inValues.TryGetValue(roundId, out var inValue);
            return inValue ?? Hash.Empty;
        }

19 Source : BlockExecutingService.cs
with MIT License
from AElfProject

public async Task<BlockExecutedSet> ExecuteBlockAsync(BlockHeader blockHeader,
            List<Transaction> nonCancellableTransactions)
        {
            _systemTransactionExtraDataProvider.TryGetSystemTransactionCount(blockHeader,
                out var systemTransactionCount);
            return await ExecuteBlockAsync(blockHeader, nonCancellableTransactions.Take(systemTransactionCount),
                nonCancellableTransactions.Skip(systemTransactionCount),
                CancellationToken.None);
        }

19 Source : MultiTokenContractReferenceFeeTest.cs
with MIT License
from AElfProject

[Theory]
        [InlineData(false, new []{1}, new [] {100, 4, 3, 2})]
        [InlineData(false, new []{2,3}, new []{5000001, 1, 4, 10000},new []{5000002, 1, 4, 2, 2, 250, 50})]
        [InlineData(true, new []{2}, new []{int.MaxValue, 4, 3, 2})]
        [InlineData(true, new []{1}, new [] {100, 4, 3})]
        [InlineData(true, new []{2,3}, new []{5000001, 1, 4, 10000},new []{5000001, 1, 4, 2, 2, 250, 50})]
        [InlineData(true, new []{3,2}, new []{5000001, 1, 4, 10000},new []{5000002, 1, 4, 2, 2, 250, 50})]
        [InlineData(true, new []{2,3}, new []{5000002, 4, 3, 2})]
        public async Task Update_Coefficient_For_Sender_Test(bool isFail, int[] pieceNumber, 
            params int[][] newPieceFunctions)
        {
            var feeType = (int) FeeTypeEnum.Tx;
            var primaryTokenSymbol = await GetThePrimaryTokenAsync();
            await IssuePrimaryTokenToMainChainTesterAsync();
            var originalCoefficients = await GetCalculateFeeCoefficientsByFeeTypeAsync(feeType);
            var newPieceCoefficientList = newPieceFunctions.Select(x => new CalculateFeePieceCoefficients
            {
                Value = {x}
            }).ToList();
            var updateInput = new UpdateCoefficientsInput
            {
                PieceNumbers = {pieceNumber},
                Coefficients = new CalculateFeeCoefficients
                {
                    FeeTokenType = feeType,
                }
            };
            updateInput.Coefficients.PieceCoefficientsList.AddRange(newPieceCoefficientList);

            var proposalId = await CreateToRootForUserFeeByTwoLayerAsync(updateInput,
                nameof(TokenContractImplContainer.TokenContractImplStub.UpdateCoefficientsForSender));
            await ApproveToRootForUserFeeByTwoLayerAsync(proposalId);
            await VoteToReferendumAsync(proposalId, primaryTokenSymbol);
            await ReleaseToRootForUserFeeByTwoLayerAsync(proposalId);
            
            var updatedCoefficients = await GetCalculateFeeCoefficientsByFeeTypeAsync(feeType);
            if (!isFail)
            {
                foreach (var newPieceFunction in newPieceFunctions)
                {
                    var hasModified =
                        GetCalculateFeePieceCoefficients(updatedCoefficients.PieceCoefficientsList, newPieceFunction[0]);
                    var newCoefficient = newPieceFunction.Skip(1).ToArray();
                    hasModified.Value.Skip(1).ShouldBe(newCoefficient);
                }
            }
            else
            {
                var pieceCount = originalCoefficients.PieceCoefficientsList.Count;
                updatedCoefficients.PieceCoefficientsList.Count.ShouldBe(pieceCount);
                for (var i = 0; i < pieceCount; i++)
                {
                    originalCoefficients.PieceCoefficientsList[i]
                        .ShouldBe(updatedCoefficients.PieceCoefficientsList[i]);
                }
            }
        }

19 Source : MultiTokenContractReferenceFeeTest.cs
with MIT License
from AElfProject

[Theory]
        [InlineData(false, 3, new []{1}, new [] {1000000, 4, 3, 2})]
        [InlineData(false, 0, new []{2}, new []{999999, 1, 4, 2, 5, 250, 40})]
        [InlineData(false, 0, new []{3}, new []{int.MaxValue, 2, 8, 2, 6, 300, 50})]
        [InlineData(false, 2, new []{2,3}, new []{100, 1, 4, 10000},new []{1000000, 1, 4, 2, 2, 250, 50})]
        [InlineData(true, 0, new []{2}, new []{int.MaxValue, 4, 3, 2})]
        [InlineData(true, 0, new []{3}, new []{int.MaxValue, 2, 8, 2, 6, 300})]
        [InlineData(true, 0, new []{3,2}, new []{1000, 4, 3, 2}, new []{int.MaxValue, 4, 3, 2})]
        [InlineData(true, 0, new []{2,3}, new []{100, 4, 3, 2})]
        [InlineData(true, 3, new []{1}, new [] {1000000, -1, 3, 2})]
        [InlineData(true, 3, new []{1}, new [] {1000000, 4, -1, 2})]
        [InlineData(true, 3, new []{1}, new [] {1000000, 4, 3, 0})]
        public async Task Update_Coefficient_For_Contract_Test(bool isFail, int feeType, int[] pieceNumber, 
            params int[][] newPieceFunctions)
        {
            var originalCoefficients = await GetCalculateFeeCoefficientsByFeeTypeAsync(feeType);
            var newPieceCoefficientList = newPieceFunctions.Select(x => new CalculateFeePieceCoefficients
            {
                Value = {x}
            }).ToList();
            var updateInput = new UpdateCoefficientsInput
            {
                PieceNumbers = {pieceNumber},
                Coefficients = new CalculateFeeCoefficients
                {
                    FeeTokenType = feeType,
                }
            };
            updateInput.Coefficients.PieceCoefficientsList.AddRange(newPieceCoefficientList);
            var proposalId = await CreateToRootForDeveloperFeeByTwoLayerAsync(updateInput,
                nameof(TokenContractImplContainer.TokenContractImplStub.UpdateCoefficientsForContract));
            await ApproveToRootForDeveloperFeeByTwoLayerAsync(proposalId);
            var middleApproveProposalId = await ApproveToRootForDeveloperFeeByMiddleLayerAsync(proposalId);
            await ApproveThenReleaseMiddleProposalForDeveloperAsync(middleApproveProposalId);
            await ReleaseToRootForDeveloperFeeByTwoLayerAsync(proposalId);
            var updatedCoefficients = await GetCalculateFeeCoefficientsByFeeTypeAsync(feeType);
            if (!isFail)
            {
                foreach (var newPieceFunction in newPieceFunctions)
                {
                    var hasModified =
                        GetCalculateFeePieceCoefficients(updatedCoefficients.PieceCoefficientsList, newPieceFunction[0]);
                    var newCoefficient = newPieceFunction.Skip(1).ToArray();
                    hasModified.Value.Skip(1).ShouldBe(newCoefficient);
                }
            }
            else
            {
                var pieceCount = originalCoefficients.PieceCoefficientsList.Count;
                updatedCoefficients.PieceCoefficientsList.Count.ShouldBe(pieceCount);
                for (var i = 0; i < pieceCount; i++)
                {
                    originalCoefficients.PieceCoefficientsList[i]
                        .ShouldBe(updatedCoefficients.PieceCoefficientsList[i]);
                }
            }
        }

19 Source : BinaryMerkleTestTest.cs
with MIT License
from AElfProject

private Hash GetHashFromHexString(params string[] strings)
        {
            var hash = Hash.LoadFromByteArray(ByteArrayHelper.HexStringToByteArray(strings[0]));
            foreach (var s in strings.Skip(1))
            {
                hash = HashHelper.ComputeFrom(hash.ToByteArray().Concat(ByteArrayHelper.HexStringToByteArray(s)).ToArray());
            }

            return hash;
        }

19 Source : PaginationViewModel.cs
with MIT License
from AFei19911012

private void PageUpdated(FunctionEventArgs<int> info)
        {
            DataList = TotalDataList.Skip((info.Info - 1) * 10).Take(10).ToList();
        }

19 Source : IOHelper.cs
with Mozilla Public License 2.0
from agebullhu

public static string CheckPaths(string path)
        {
            if (path == null)
            {
                return null;
            }
            if (Directory.Exists(path))
            {
                return path;
            }
            var root = Path.GetPathRoot(path);
            var folders = path.Split(new char[] {'\\', '/'},StringSplitOptions.RemoveEmptyEntries).Skip(1);
            foreach (var folder in folders)
            {
                root = Path.Combine(root, folder);
                if (!Directory.Exists(root))
                {
                    Directory.CreateDirectory(root);
                }
            }
            return root;
        }

19 Source : Extension.cs
with MIT License
from Agenty

public static DataTable FileToTable(this string path, bool heading = true, char delimiter = '\t')
        {
            var table = new DataTable();
            string headerLine = File.ReadLines(path).FirstOrDefault(); // Read the first row for headings
            string[] headers = headerLine.Split(delimiter);
            int skip = 1;
            int num = 1;
            foreach (string header in headers)
            {
                if (heading)
                    table.Columns.Add(header);
                else
                {
                    table.Columns.Add("Field" + num); // Create fields header if heading is false
                    num++;
                    skip = 0; // Don't skip the first row if heading is false
                }
            }
            foreach (string line in File.ReadLines(path).Skip(skip))
            {
                if (!string.IsNullOrEmpty(line))
                {
                    table.Rows.Add(line.Split(delimiter));
                }
            }
            return table;
        }

19 Source : Extension.cs
with MIT License
from Agenty

public static DataTable FileToTable(this string path, bool heading = true, char delimiter = '\t', int offset = 0, int limit = 100000)
        {
            var table = new DataTable();
            string headerLine = File.ReadLines(path).FirstOrDefault(); // Read the first row for headings
            string[] headers = headerLine.Split(delimiter);
            int skip = 1;
            int num = 1;
            foreach (string header in headers)
            {
                if (heading)
                {
                    table.Columns.Add(header); 
                }
                else
                {
                    table.Columns.Add("Field" + num); // Create fields header if heading is false
                    num++;
                    skip = 0; // Don't skip the first row if heading is false
                }
            }

            foreach (string line in File.ReadLines(path).Skip(skip + offset).Take(limit))
            {
                if (!string.IsNullOrEmpty(line))
                {
                    table.Rows.Add(line.Split(delimiter));
                }
            }
            return table;
        }

19 Source : QueryableExtensions.cs
with Apache License 2.0
from Aguafrommars

public static IQueryable<T> GetPage<T>(this IQueryable<T> query, PageRequest request) where T : clreplaced
        {
            if (request.Skip.HasValue)
            {
                query = query.Skip(request.Skip.Value);
            }

            if (request.Take.HasValue)
            {
                query = query.Take(request.Take.Value);
            }
                
            return query;
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGroupingOrderedSecond5()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by new { sample.LastName, sample.Place } into sampleGroup
                 select
                 new
                 {
                     GroupingKey = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderByDescending(x => x.CountMembers).Skip(5).Take(5);
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGroupingOrderedLast5()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by new { sample.LastName, sample.Place } into sampleGroup
                 select
                 new
                 {
                     GroupingKey = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderByDescending(x => x.CountMembers);
            var last5AgeLastnameGroups = ageLastnameGroups.Skip(Math.Max(0, ageLastnameGroups.Count() - 5));
            //use result
            foreach (var sample in last5AgeLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : CircleButtonMenu.cs
with MIT License
from ahoefling

private async void TapRootButton(object sender, EventArgs e)
        {
            if (IsOpened)
            {
                RootImage.Source = OpenImageSource;
                for (int index = 0; index < Buttons.Count; index++)
                {
                    Buttons[index].TranslateTo(0, 0);
                }
            }
            else
            {
                RootImage.Source = CloseImageSource;
                int baseDistance = 80;
                               
                for (int index = 0; index < Buttons.Count; index++)
                {
                    (int TranslateX, int TranslateY) translation;

                    if (Direction == Direction.Circle)
                    {
                        // todo - clean up redundent logic
                        if ((Direction)index == Direction.Circle || (Direction)index == Direction.Square) continue;

                        if (Flow == Flow.Snake)
                        {
                            Direction direction = Direction.Up;
                            if (index > 0)
                            {
                                direction = (Direction)index;
                            }

                            var currentButtons = Buttons.Skip(index + 1).ToList();

                            translation = GetTranslation(baseDistance, direction);
                            foreach (var current in currentButtons)
                            {
                                current.TranslateTo(translation.TranslateX, translation.TranslateY, 125);
                            }
                            
                            await Task.Delay(125);
                        }
                        else
                        {
                            var direction = (Direction)index;
                            translation = GetTranslation(baseDistance, direction);
                        }
                    }
                    else if (Direction == Direction.Square)
                    {
                        if ((Direction)index == Direction.Circle || (Direction)index == Direction.Square) continue;

                        var direction = (Direction)index;
                        var corners = new[] { Direction.UpLeft, Direction.UpRight, Direction.DownRight, Direction.DownLeft };

                        var distance = baseDistance;
                        if (corners.Contains(direction))
                        {
                            distance = (int)(distance * 1.5);
                        }

                        translation = GetTranslation(distance, direction);
                    }
                    else
                    {
                        var distance = baseDistance * (index + 1);
                        translation = GetTranslation(distance, Direction);
                    }

                    if (Flow != Flow.Snake)
                    {
                        Buttons[index].TranslateTo(translation.TranslateX, translation.TranslateY);
                    }
                }

                Grid.IsVisible = false;
                Grid.IsVisible = true;
            }

            IsOpened = !IsOpened;
        }

19 Source : RingBuffer.cs
with MIT License
from Aiko-IT-Systems

public IEnumerator<T> GetEnumerator()
        {
            return !this._reached_end
                ? this.InternalBuffer.AsEnumerable().GetEnumerator()
                : this.InternalBuffer.Skip(this.CurrentIndex)
                .Concat(this.InternalBuffer.Take(this.CurrentIndex))
                .GetEnumerator();
        }

19 Source : CmdHandler.cs
with Apache License 2.0
from airbus-cert

internal static bool ExecuteCmd(string command)
        {
            bool isManagedCmd = false;
            string[] commands = command.Split(' ');

            string cmdName = commands.First();
            string[] args = commands.Skip(1).ToArray();

            switch (cmdName)
            {
                case "exit":
                    Environment.Exit(0);
                    break;
                case "clear":
                    Console.Clear();
                    isManagedCmd = true;
                    break;
                case "yadd":
                    isManagedCmd = true;
                    CmdAddRules(args);
                    break;
                case "sadd":
                    isManagedCmd = true;
                    CmdAddSamples(args);
                    break;
                case "ycompile":
                    isManagedCmd = true;

                    using (var compiler = new Compiler())
                    {
                        foreach (var yara in yaras.Distinct())
                        {
                            var err = ScanHelper.CheckRule(yara);

                            if (err == YARA_ERROR.SUCCESS)
                            {
                                try
                                {
                                    compiler.AddRuleFile(yara);
                                    Console.WriteLine($":Added {yara}");
                                } catch (Exception e)
                                {
                                    Console.WriteLine($"!Exception adding \"{yara}\": {e.Message}");
                                }
                            }
                            else
                                Console.WriteLine($"!Exception adding \"{yara}\": {err}");
                        }

                        try
                        {
                            rules = compiler.Compile();
                            Console.WriteLine($"* Compiled");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"!Exception compiling rules: {e.Message}");
                        }
                    }

                    break;
                case "run":
                    isManagedCmd = true;
                    CmdRun();
                    break;
            }


            return isManagedCmd;
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from airzero24

public static void ResultFormat(string column1, string column2, string column3, string column4, string column5)
        {
            int column1Width = 7;
            int column2Width = 7;
            int column3Width = 5;
            int column4Width = 25;
            int column5Width = 40;
            int loopCount = 0;

            StringBuilder output = new StringBuilder();

            while (true)
            {
                string col1 = new string(column1.Skip<char>(loopCount * column1Width).Take<char>(column1Width).ToArray()).PadRight(column1Width);
                string col2 = new string(column2.Skip<char>(loopCount * column2Width).Take<char>(column2Width).ToArray()).PadRight(column2Width);
                string col3 = new string(column3.Skip<char>(loopCount * column3Width).Take<char>(column3Width).ToArray()).PadRight(column3Width);
                string col4 = new string(column4.Skip<char>(loopCount * column4Width).Take<char>(column4Width).ToArray()).PadRight(column4Width);
                string col5 = new string(column5.Skip<char>(loopCount * column5Width).Take<char>(column5Width).ToArray()).PadRight(column5Width);

                if (String.IsNullOrWhiteSpace(col1) && String.IsNullOrWhiteSpace(col2) && String.IsNullOrWhiteSpace(col3))
                {
                    break;
                }

                output.AppendFormat("{0} {1} {2} {3} {4}", col1, col2, col3, col4, col5);
                loopCount++;
            }
            Console.WriteLine(output.ToString());
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from airzero24

public static void Main(string[] args)
        {
            try
            {
                string result = ExecuteShellCommand(Int32.Parse(args[0]), true, string.Join(" ", args.Skip(1).ToArray()));
                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

19 Source : ProbeLocator.cs
with MIT License
from AiursoftWeb

private (string siteName, string[] folders, string fileName) SplitToPath(string fullPath)
        {
            if (fullPath == null || fullPath.Length == 0)
            {
                throw new AiurAPIModelException(ErrorType.NotFound, $"Can't get your file download address from path: '{fullPath}'!");
            }
            var paths = SplitStrings(fullPath);
            var fileName = paths.Last();
            var siteName = paths.First();
            var folders = paths.Take(paths.Count() - 1).Skip(1).ToArray();
            return (siteName, folders, fileName);
        }

19 Source : EFExtends.cs
with MIT License
from AiursoftWeb

public static IQueryable<T> Page<T>(this IOrderedQueryable<T> query, IPageable pager)
        {
            return query
                .Skip((pager.PageNumber - 1) * pager.PageSize)
                .Take(pager.PageSize);
        }

19 Source : BasicTest.cs
with MIT License
from AiursoftWeb

private static async Task Monitor(ClientWebSocket socket)
        {
            var buffer = new ArraySegment<byte>(new byte[2048]);
            while (true)
            {
                var result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    MessageCount++;
                    var _ = Encoding.UTF8.GetString(buffer.Skip(buffer.Offset).Take(buffer.Count).ToArray())
                        .Trim('\0')
                        .Trim();
                }
                else
                {
                    Console.WriteLine($"[WebSocket Event] Remote wrong message. [{result.MessageType}].");
                    break;
                }
            }
        }

19 Source : EnumerableExtension.cs
with MIT License
from aishang2015

public static IEnumerable<T> PageBy<T>(this IEnumerable<T> enumerable, int page, int size)
        {
            return enumerable.Skip((page - 1) * size).Take(size);
        }

19 Source : FolderRepo.cs
with MIT License
from AiursoftWeb

public async Task<Folder> GetFolderFromPath(string[] folderNames, Folder root, bool recursiveCreate)
        {
            if (root == null) return null;
            if (!folderNames.Any())
            {
                return await GetFolderFromId(root.Id);
            }
            var subFolderName = folderNames[0];
            var subFolder = await GetSubFolder(root.Id, subFolderName);
            if (recursiveCreate && subFolder == null && !string.IsNullOrWhiteSpace(subFolderName))
            {
                subFolder = new Folder
                {
                    ContextId = root.Id,
                    FolderName = subFolderName
                };
                await _dbContext.Folders.AddAsync(subFolder);
                await _dbContext.SaveChangesAsync();
            }
            return await GetFolderFromPath(folderNames.Skip(1).ToArray(), subFolder, recursiveCreate);
        }

19 Source : BasicTests.cs
with The Unlicense
from AiursoftWeb

private static async Task Monitor(ClientWebSocket socket)
        {
            var buffer = new ArraySegment<byte>(new byte[2048]);
            while (true)
            {
                var result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    _messageCount++;
                    string message = Encoding.UTF8.GetString(
                        buffer.Skip(buffer.Offset).Take(buffer.Count).ToArray())
                        .Trim('\0')
                        .Trim();
                    Console.WriteLine(message);
                }
                else
                {
                    Console.WriteLine($"[WebSocket Event] Remote wrong message. [{result.MessageType}].");
                    break;
                }
            }
        }

19 Source : FileType.cs
with GNU General Public License v3.0
from AJMitev

public int GetMatchingNumber(Stream stream)
        {
            stream.Position = 0;

            int counter = 0;
            var buffer = new byte[ByfferDefaultSize];
            stream.Read(buffer, 0, buffer.Length);

            foreach (var bytesArr in this.Bytes)
            {
                var shrinkedBuffer = buffer.Skip(SkipBytes).Take(bytesArr.Length);

                for (int i = counter; i < bytesArr.Length; i++)
                {
                    if (!bytesArr[i].Equals(buffer[i]))
                        break;

                    counter++;
                }
            }

            return counter == 0 ? -1 : counter;
        }

19 Source : FileType.cs
with GNU General Public License v3.0
from AJMitev

private bool DoesMatchWith(byte[] buffer)
        {
            foreach (var bytesArr in this.Bytes)
            {
                if (buffer.Skip(SkipBytes).Take(bytesArr.Length).SequenceEqual(bytesArr)) 
                {
                    return true;
                }
            }
            return false;
        }

See More Examples