public static CUFsListViewModel BuildPage(int pagenr, int itemsnr, String order, IEnumerable<CufRepoModel> repository, String title, String method, Boolean hasVersion) { int amountPages = ((repository.Count() + itemsnr - 1) / itemsnr); CUFsListModel clm = new CUFsListModel(title); repository = (order == "Asc") ? repository.OrderBy(cuf => cuf.Name) : repository.OrderByDescending(cuf => cuf.Name); foreach (var cuf in repository.Skip(pagenr * itemsnr).Take(itemsnr)) { if (hasVersion) clm.AddURIParams(cuf.Name + " [ V: " + cuf.Version + " ]", method, cuf.Acr, cuf.Version); //proposal-version else clm.AddURIParams(cuf.Name, method, cuf.Acr); } CUFsListViewModel clvm = new CUFsListViewModel(); clvm.CUFList = clm.GetCUFsListModel(); clvm.PageNumber = pagenr; clvm.ItemsNumber = itemsnr; clvm.Order = order; clvm.AmountPage = amountPages; clvm.LastPage = false; clvm.ItemsPerPage = itemsPerPage; clvm.OrderPage = orderOptions; clvm.Method = hasVersion ? "PageVersion" : "Page"; if (clvm.CUFList.Count() < itemsnr || repository.Skip((pagenr + 1) * itemsnr).Take(itemsnr).Count() == 0) clvm.LastPage = true; return clvm; }
/// <summary> /// Gets whether a feature path is valid for the features in the feature set /// </summary> /// <param name="features">Top-level features</param> /// <param name="featurePath">Feature path to the highest-level feature</param> /// <returns>Value indicating whether the feature path is valid for a feature in <paramref name="features"/></returns> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="features"/> or <paramref name="featurePath"/> is null</exception> /// <exception cref="System.InvalidOperationException">Thrown when <paramref name="featurePath"/> is empty</exception> public static bool IsEnabled(IEnumerable<IFeature> features, IEnumerable<string> featurePath) { Ensure.Argument.NotNull(features, "features"); Ensure.Argument.NotNull(featurePath, "featurePath"); Ensure.That<InvalidOperationException>(featurePath.Any(), "Feature Path must contain at least one top-level feature"); // feature names are case insensitive IFeature current = FindFeature(features, featurePath.First()); // skip the first value featurePath = featurePath.Skip(1); // loop through the entire path while (featurePath.Any()) { // path was not found if (current == null) return false; // see if the feature has subfeatures (Complex) var asComplex = current as IComplexFeature; if (asComplex == null) // feature doesn't have subfeatures, it passes return true; current = FindFeature(asComplex.SubFeatures, featurePath.First()); featurePath = featurePath.Skip(1); } return current != null; }
Directory ResolveDirectory(Directory directory, IEnumerable<string> children) { if (!children.Any()) return directory; string childName = children.First(); Directory info = directory.GetDirectories() .Where(x => string.Compare(x.Name.GetName(), childName, true) == 0) .SingleOrDefault(); if (info != null) { return ResolveDirectory(info, children.Skip(1)); } File file = directory.GetFiles() .Where(x => string.Compare(x.Name.GetName(), childName, true) == 0) .SingleOrDefault(); if (file == null) throw new InvalidOperationException("Could not get directory: " + childName); if (Path.GetExtension(file.Name.GetName()) == ".zip") { var zipFileDirectory = new ZipFileDirectory(file.Name.Name); return ResolveDirectory(zipFileDirectory, children.Skip(1)); } throw new InvalidOperationException("Could not resolve the rest of the path: " + childName); }
/// <summary> /// Converts from HSB. /// </summary> public static Color FromHsb(IEnumerable<byte> source) { // http://ja.wikipedia.org/wiki/HSV%E8%89%B2%E7%A9%BA%E9%96%93 var h = Utility.ToUInt16(source.Take(2)) / 182.04; var s = Utility.ToUInt16(source.Skip(2).Take(2)) / 655.35; var b = Utility.ToUInt16(source.Skip(4).Take(2)) / 655.35; // Convert to RGB var h_i = (int)(Math.Floor(h / 60) % 6); var f = (h / 60) - h_i; var p = (int)(b * (1 - s)); var q = (int)(b * (1 - f * s)); var t = (int)(b * (1 - (1 - f) * s)); switch (h_i) { case 0: return Color.FromArgb((int)b, t, p); case 1: return Color.FromArgb(q, (int)b, p); case 2: return Color.FromArgb(p, (int)b, t); case 3: return Color.FromArgb(p, q, (int)b); case 4: return Color.FromArgb(t, p, (int)b); case 5: return Color.FromArgb((int)b, p, q); default: throw new Exception(); } }
public Context(IEnumerable<string> line) { Key = line.Skip(1).Concatenate(); Namespace = line.Skip(1).PascalCase(); MemberName = Namespace +"Context"; Scenarios = new List<Scenario>(); }
static bool SumsToMoreThan9(IEnumerable<int> p) { for (int i = 0; i < p.Count() - 2; i++) if (p.First() + p.Skip(1).First() + p.Skip(2).First() > 9) return true; return false; }
public Scenario(IEnumerable<string> line) { Key = line.Skip(1).Concatenate(); MemberName = line.Skip(1).ConcatenateWithUnderscores().InitialCap(); Givens = new List<SpecPart>(); Whens = new List<SpecPart>(); Thens = new List<SpecPart>(); }
public override void Populate(HL7Element element, IEnumerable <string> tableIds = null) { var tblsUsed = 0; VersionID = NewID(element.ElementValue(0), NextTableId(tableIds, ref tblsUsed)); Internationalization = element.IndexedElement(1).AsCE(tableIds?.Skip(tblsUsed), Tables); tblsUsed += CE_CodedElement.TotalCodedFieldCount; InternationalVersionID = element.IndexedElement(2).AsCE(tableIds?.Skip(tblsUsed), Tables); }
/// <summary> /// Converts from CMYK. /// </summary> public static Color FromCmyk(IEnumerable<byte> source) { var c = 1 - (Utility.ToUInt16(source.Take(2)) / 65535.0); var m = 1 - (Utility.ToUInt16(source.Skip(2).Take(2)) / 65535.0); var y = 1 - (Utility.ToUInt16(source.Skip(4).Take(2)) / 65535.0); var k = 1 - (Utility.ToUInt16(source.Skip(6).Take(2)) / 65535.0); return FromCmyk(c, m, y, k); }
public IEnumerable<int> Sort(IEnumerable<int> unsorted) { if(!unsorted.Any()) return unsorted; var pivot = unsorted.First(); var lesser = unsorted.Skip(1).Where(x => x <= pivot); var greater = unsorted.Skip(1).Where(x => x > pivot); return Sort(lesser).Union(new[]{pivot}).Union(Sort(greater)); }
public override ICommandResult Execute(ExecutionInformation info, IEnumerable<ICommand> arguments, IEnumerable<CommandResultType> returnTypes) { if (!arguments.Any()) return base.Execute(info, arguments, returnTypes); var result = arguments.First().Execute(info, Enumerable.Empty<ICommand>(), new CommandResultType[] { CommandResultType.Command, CommandResultType.String }); if (result.ResultType == CommandResultType.String) // Use cached result so we don't execute the first argument twice return base.Execute(info, new ICommand[] { new StringCommand(((StringCommandResult)result).Content) } .Concat(arguments.Skip(1)), returnTypes); return ((CommandCommandResult)result).Command.Execute(info, arguments.Skip(1), returnTypes); }
internal static IEnumerable<Post> InitializePagePosts(IEnumerable<string> paths, string sha, int page, int pageSize) { List<Post> posts = new List<Post>(); //todo: should be refactored (find a more clear and right way) //a hack, so that to pass a partially initialized list to PagedList in the controller var itemsBefore = paths.Take((page - 1)*pageSize); var itemsToInitialize = paths.Skip((page - 1)*pageSize).Take(pageSize); var itemsAfter = paths.Skip((page - 1)*pageSize + pageSize); posts.AddRange(itemsBefore.Select(path => new Post( ){Path = path})); posts.AddRange(Initialize(itemsToInitialize, sha)); posts.AddRange(itemsAfter.Select(path=> new Post( ){Path = path})); return posts; }
private static int Score(IEnumerable<int> pins, int frame) { if (0 <= frame && frame < 10) { if (pins.Any()) { if (pins.Take(1).Sum() == 10) return pins.Take(3).Sum() + Score(pins.Skip(1), frame + 1); if (pins.Take(2).Sum() == 10) return pins.Take(3).Sum() + Score(pins.Skip(2), frame + 1); if (pins.Take(2).Sum() < 10) return pins.Take(2).Sum() + Score(pins.Skip(2), frame + 1); throw new Exception("Too many pins"); } } return 0; }
public static Recording CreateFromIndexLine(IEnumerable<string> i) { var alias = i.Count() > 4 ? i.Skip(4).First() : ""; var oldalias = i.Count() > 5 ? i.Skip(5).First() : ""; return new Recording() { Date = Recording.ParseDate(i.Skip(3).First()), Title = i.Skip(1).First(), Url = i.Skip(2).First().Trim(), Alias = alias, OldAlias = oldalias, Category = i.First() }; }
public async Task <TData <object> > GetBlogWithPagination(string userName, Pagination pagination) { var td = new TData <object>(); var blogAll = await GetBlog(userName); if (blogAll.Status == Status.Success) { if (blogAll.Data != null) { Blog blog = blogAll.Data; IEnumerable <Post> posts = blog.Posts; pagination.Total = posts.Count(); var currentData = posts?.Skip(pagination.PageSize * (pagination.PageIndex - 1)).Take(pagination.PageSize)?.ToList(); td.Data = new { total = pagination.Total, blog, posts = currentData, }; } td.Status = Status.Success; td.Message = "查询成功"; } else { td.Status = blogAll.Status; td.Message = blogAll.Message; } return(td); }
private void UpdateComponents() { IEnumerable <ModStatus> temp = this.originalStatuses?.Select(item => item); if (temp != null && this.currentSortColumn != -1) { switch (this.currentSortColumn) { case 0: temp = temp.OrderBy(status => status.ModName); break; case 1: temp = temp.OrderBy(status => status.UpdateStatus); break; case 2: temp = temp.OrderBy(status => status.UpdateURLType); break; } if (this.currentSortDirection == 1) { temp = temp.Reverse(); } } this.UpdateComponentsImpl(temp?.Skip(this.displayIndex).ToList()); }
public IEnumerable <Path> GetChildPath(IEnumerable <Node> nodes) { if (nodes.Count() == 0 || nodes == null) { return(null); } var ancNode = nodes.First(); List <Path> result = new List <Path>(); var selfPath = GetSelfPath(ancNode); result.Add(selfPath); var chileNode = nodes?.Skip(1); var childs = GetChildPath(chileNode); if (childs == null) { return(result); } result.AddRange(childs); var hierarchyPath = childs ? .Where(n => n.Ancestor == n.Descendant) ? .Select(n => new Path() { Ancestor = ancNode.Id, Descendant = n.Descendant }); result.AddRange(hierarchyPath); return(result); }
private static IEnumerable<Tuple<SpecificationProperty, Maybe<Error>>> MapValuesImpl( IEnumerable<SpecificationProperty> specProps, IEnumerable<string> values, Func<IEnumerable<string>, System.Type, bool, Maybe<object>> converter) { if (specProps.Empty() || values.Empty()) { yield break; } var pt = specProps.First(); var taken = values.Take(pt.Specification.GetMaxValueCount().Return(n => n, values.Count())); if (taken.Empty()) { yield break; } yield return converter(taken, pt.Property.PropertyType, pt.Specification.ConversionType.IsScalar()) .Return( converted => Tuple.Create(pt.WithValue(Maybe.Just(converted)), Maybe.Nothing<Error>()), Tuple.Create<SpecificationProperty, Maybe<Error>>( pt, Maybe.Just<Error>(new BadFormatConversionError(NameInfo.EmptyName)))); foreach (var value in MapValuesImpl(specProps.Skip(1), values.Skip(taken.Count()), converter)) { yield return value; } }
private CommandSpec CreateCommandSpecWrappedWithCmd( string command, IEnumerable<string> args, CommandResolutionStrategy resolutionStrategy) { var comSpec = Environment.GetEnvironmentVariable("ComSpec") ?? "cmd.exe"; // Handle the case where ComSpec is already the command if (command.Equals(comSpec, StringComparison.OrdinalIgnoreCase)) { command = args.FirstOrDefault(); args = args.Skip(1); } var cmdEscapedArgs = ArgumentEscaper.EscapeAndConcatenateArgArrayForCmdProcessStart(args); if (ArgumentEscaper.ShouldSurroundWithQuotes(command)) { command = $"\"{command}\""; } var escapedArgString = $"/s /c \"{command} {cmdEscapedArgs}\""; return new CommandSpec(comSpec, escapedArgString, resolutionStrategy); }
public static int GetTimeDiffInMin(this IEnumerable <TimeSpan> date) { date = date?.Distinct().OrderBy(d => d); var diffInMinutes = date?.Skip(1).FirstOrDefault().TotalMinutes - date?.FirstOrDefault().TotalMinutes; return((int)(diffInMinutes ?? 0)); }
private Paginator CreatePaginator(int page, int perPage, int pages, string baseUrl, string urlFormat, IEnumerable<DocumentFile> documents) { // It is important that this query is not executed here (aka: do not add ToList() or ToArray()). This // query should be executed by the rendering engine so the returned documents are rendered first. var pagedDocuments = documents.Skip((page - 1) * perPage).Take(perPage); var pagination = new Pagination(); if (pages > 1 && !String.IsNullOrEmpty(urlFormat)) { pagination.Page = page; pagination.PerPage = perPage; pagination.TotalPage = pages; pagination.NextPageUrl = page < pages ? this.UrlForPage(page + 1, baseUrl, urlFormat) : null; pagination.PreviousPageUrl = page > 1 ? this.UrlForPage(page - 1, baseUrl, urlFormat) : null; var start = Math.Max(1, page - 3); var end = Math.Min(pages, start + 6); start = Math.Max(start, end - 6); pagination.Pages = this.CreatePages(page, start, end, baseUrl, urlFormat).ToList(); } return new Paginator(pagedDocuments, pagination); }
/// <summary> /// find all base types(types that are not derived from other types) in the specified types /// </summary> /// <param name="types"></param> /// <returns></returns> public static IEnumerable<ITypeDefinition> GetBaseTypes(IEnumerable<ITypeDefinition> types) { if (types == null) yield break; types = types.ToList(); if (!types.Any()) yield break; var baseType = types.FirstOrDefault(); var otherTypes = new List<ITypeDefinition>(); foreach (var type in types.Skip(1)) { if (baseType.IsDerivedFrom(type)) { baseType = type; } else if (!type.IsDerivedFrom(baseType)) { // this type is not directly related to baseType otherTypes.Add(type); } } yield return baseType; foreach (var type in GetBaseTypes(otherTypes)) yield return type; }
internal static dynamic Memo_übernehmen(Buchung buchung, IEnumerable<string> args) { if (args.Any()) { buchung.Memo = args.First(); return new { Buchung = buchung, Args = args.Skip(1) }; } return new { Buchung = buchung, Args = args }; }
public virtual string Build(IEnumerable<string> tickers) { if (!tickers.Any()) return ""; return "s=" + tickers.Skip(1).Aggregate(tickers.First(), (url_parameter, next_ticker) => url_parameter + "+" + next_ticker); }
public override void ExecuteCmdlet() { IEnumerable <Tile> tiles = null; using (var client = this.CreateClient()) { if (this.WorkspaceId != default) { tiles = client.Reports.GetTilesForWorkspace(workspaceId: this.WorkspaceId, dashboardId: this.DashboardId); } else { tiles = this.Scope == PowerBIUserScope.Individual ? client.Reports.GetTiles(this.DashboardId) : client.Reports.GetTilesAsAdmin(this.DashboardId); } } if (this.Id != default) { tiles = tiles?.Where(d => this.Id == d.Id); } if (this.Skip.HasValue) { tiles = tiles?.Skip(this.Skip.Value); } if (this.First.HasValue) { tiles = tiles?.Take(this.First.Value); } this.Logger.WriteObject(tiles, true); }
public static ParserResult<object> Choose( Func<IEnumerable<string>, IEnumerable<OptionSpecification>, Result<IEnumerable<Token>, Error>> tokenizer, IEnumerable<Type> types, IEnumerable<string> arguments, StringComparer nameComparer, CultureInfo parsingCulture, IEnumerable<ErrorType> nonFatalErrors) { Func<ParserResult<object>> choose = () => { var firstArg = arguments.First(); Func<string, bool> preprocCompare = command => nameComparer.Equals(command, firstArg) || nameComparer.Equals(string.Concat("--", command), firstArg); var verbs = Verb.SelectFromTypes(types); return preprocCompare("help") ? MakeNotParsed(types, MakeHelpVerbRequestedError(verbs, arguments.Skip(1).SingleOrDefault() ?? string.Empty, nameComparer)) : preprocCompare("version") ? MakeNotParsed(types, new VersionRequestedError()) : MatchVerb(tokenizer, verbs, arguments, nameComparer, parsingCulture, nonFatalErrors); }; return arguments.Any() ? choose() : MakeNotParsed(types, new NoVerbSelectedError()); }
public override void ExecuteCmdlet() { if (this.Workspace != null) { this.WorkspaceId = this.Workspace.Id; } if (this.Id != default) { this.Filter = $"id eq '{this.Id}'"; } if (this.Name != default) { this.Filter = $"tolower(name) eq '{this.Name.ToLower()}'"; } IEnumerable <Dashboard> dashboards = null; using (var client = this.CreateClient()) { if (this.WorkspaceId != default) { dashboards = this.Scope == PowerBIUserScope.Individual ? client.Reports.GetDashboardsForWorkspace(workspaceId: this.WorkspaceId) : client.Reports.GetDashboardsAsAdminForWorkspace(workspaceId: this.WorkspaceId, filter: this.Filter, top: this.First, skip: this.Skip); } else { dashboards = this.Scope == PowerBIUserScope.Individual ? client.Reports.GetDashboards() : client.Reports.GetDashboardsAsAdmin(filter: this.Filter, top: this.First, skip: this.Skip); } } if (this.Scope == PowerBIUserScope.Individual) { if (this.Id != default) { dashboards = dashboards?.Where(d => this.Id == d.Id); } if (!string.IsNullOrEmpty(this.Name)) { dashboards = dashboards?.Where(d => d.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)); } if (this.Skip.HasValue) { dashboards = dashboards?.Skip(this.Skip.Value); } if (this.First.HasValue) { dashboards = dashboards?.Take(this.First.Value); } } this.Logger.WriteObject(dashboards, true); }
static bool ProcessCommand(IEnumerable<string> args) { if (args.Count() == 0) return true; ILogger logger = new ConsoleLogger(false); var commandName = args.First().ToLowerInvariant(); args = args.Skip(1); switch (commandName) { case "quit": case "q": case "exit": case "e": return false; case "help": case "?": return HelpCommand(logger, args); default: foreach (ICommand command in _commands) if (command.Matches(commandName)) using (logger.Block) return command.Process(logger, args, _metaProjectPersistence, _components, PackagesOutputDirectory); break; } logger.Error("Unknown command '{0}'", commandName); return true; }
/// <summary> /// Takes the fields pulled from one csv line and creates a DataGroup object representation /// Parses the string values to doubles where appropriate /// </summary> /// <param name="fields">The fields pulled from a csv line</param> /// <returns>A DataGroup object with the values from fields</returns> private DataGroup ParseDataGroup(IEnumerable<string> fields) { DataGroup group = new DataGroup(); group.Name = fields.First(); group.Entries = fields.Skip(1).Select(double.Parse); return group; }
protected override Expression InternalCall(IEnumerable<Expression> args) { var firstValue = args.First().Value; if (args.Skip(1).All(x => x.Value.Equals(firstValue))) return TRUE.Instance; return FALSE.Instance; }
public bool ContainsFinishCase(IEnumerable<IndexDataSource> route) { bool result = false; foreach (var itemRoute in route.Skip(1)) { foreach (var finishCase in boardManager.firstIndex) { if (finishCase.Equals(itemRoute)) { result = true; break; } } if (result) { break; } } if (!result) { var firstIndex = route.First(); var firstCase = boardManager.FindCaseManager(firstIndex); if (firstCase.standDataSource != null) { var lastIndex = route.Last(); var lastCase = boardManager.FindCaseManager(lastIndex); if (lastCase.standDataSource == null) { result = true; } } } return result; }
public IList<Artifact> SearchArtifacts(IEnumerable<ArtifactSearch> searches) { var result = new List<Artifact>(searches.Count()); while (searches.Any()) { var request = new RestRequest(Method.POST); request.Resource = "search/artifact/"; request.RequestFormat = DataFormat.Json; request.OnBeforeDeserialization = BeforeSerialization; request.AddBody(searches.Take(this._pageSize)); var response = Execute<ArtifactResponse>(request); if (response.ResponseStatus == ResponseStatus.Error) { throw new ApiClientTransportException(response.ErrorMessage, response.ErrorException); } result.AddRange(response.Data); searches = searches.Skip(this._pageSize); } return result; }
public IWordState Reduce(IEnumerable<IWordState> set, int len) { if (len == 0) return new Chunk(""); if (len == 1) return set.First(); else { int pivot = len / 2; //var i1 = set.Take(pivot).ToList(); //var i2 = set.Skip(pivot).ToList(); //var t1 = new Task<IWordState>(() => Reduce(i1, pivot)); //var t2 = new Task<IWordState>(() => Reduce(i2, pivot + len % 2)); var firstHalf = Reduce(set.Take(pivot), pivot); var secondHalf = Reduce(set.Skip(pivot), pivot + len % 2); IWordState result = firstHalf.Combine(secondHalf); return result; } }
public static ParserResult<object> Choose( Func<IEnumerable<string>, IEnumerable<OptionSpecification>, StatePair<IEnumerable<Token>>> tokenizer, IEnumerable<Type> types, IEnumerable<string> arguments, StringComparer nameComparer, CultureInfo parsingCulture) { if (arguments.Empty()) { return MakeNotParsed(types, new NoVerbSelectedError()); } var firstArg = arguments.First(); Func<string, bool> preprocCompare = command => nameComparer.Equals(command, firstArg) || nameComparer.Equals(string.Concat("--", command), firstArg); var verbs = Verb.SelectFromTypes(types); if (preprocCompare("help")) { return MakeNotParsed(types, MakeHelpVerbRequestedError(verbs, arguments.Skip(1).SingleOrDefault() ?? string.Empty, nameComparer)); } if (preprocCompare("version")) { return MakeNotParsed(types, new VersionRequestedError()); } return MatchVerb(tokenizer, verbs, arguments, nameComparer, parsingCulture); }
public void BotAddCommand(CommandContext context, IEnumerable<string> arguments) { if (arguments.Count() < 1) { SendInContext(context, "Usage: !bot add name [nick [arguments]]"); return; } string botID = arguments.ElementAt(0); if (!GameManager.Bots.ContainsKey(botID)) { SendInContext(context, "Invalid bot!"); return; } string botNick = arguments.ElementAtOrDefault(1) ?? botID; try { Manager.AddBot(botNick, (IBot)GameManager.Bots[botID].GetConstructor(new Type[] { typeof(GameManager), typeof(IEnumerable<string>) }).Invoke(new object[] { Manager, arguments.Skip(2) })); Manager.SendPublic(context.Nick, "Added <{0}> (a bot of type {1})", botNick, botID); } catch (ArgumentException e) { SendInContext(context, "Error adding {0}: {1}", botNick, e.Message); } }
private RoadLineWrapper[] SortClockwise( IEnumerable<RoadLineWrapper> connectedRoads ) { Assert.That( connectedRoads, Is.Not.Empty ).Throw<ArgumentException>(); if ( connectedRoads.Count() == 1 ) { return connectedRoads.ToArray(); } var first = connectedRoads.First(); var firstNormalized = first.EndLocation - first.BeginLocation; var normalized = connectedRoads.Skip( 1 ).Select( t => { var vec = t.EndLocation - t.BeginLocation; vec.Normalize(); return new { Wrapper = t, NormalizedVector = vec, Angel = Math.Acos( Vector2.Dot( firstNormalized, vec ) ), }; } ); normalized.OrderBy( t => t.Angel ); //throw new Exception("Sprawdzic to !!");))) return new[] { first }.Concat( normalized.Select( t => t.Wrapper ) ).ToArray(); }
//We Fail completely if there is a parse or index error anywhere in the file //We could skip lines with parse errors, but we have no way to alert the user protected override IEnumerable<ArgosTransmission> GetTransmissions(IEnumerable<string> lines) { //Each line looks like \"abc\";\"def\";\"pdq\";\"xyz\"; int lineNumber = 1; foreach (var line in lines.Skip(1)) { lineNumber++; if (String.Equals(line.Trim(), "MAX_RESPONSE_REACHED", StringComparison.InvariantCultureIgnoreCase)) { _maxResponseReached = true; yield break; } var tokens = line.Substring(1, line.Length - 3).Split(new[] { "\";\"" }, StringSplitOptions.None); var transmission = new ArgosTransmission { LineNumber = lineNumber, ProgramId = tokens[0], PlatformId = tokens[1], DateTime = DateTime.Parse(tokens[7], CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind), Location = String.IsNullOrEmpty(tokens[13]) ? null : new ArgosTransmission.ArgosLocation { DateTime = DateTime.Parse(tokens[13], CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind), Latitude = Single.Parse(tokens[14]), Longitude = Single.Parse(tokens[15]), Altitude = Single.Parse(tokens[16]), Class = tokens[17][0] } }; transmission.AddHexString(tokens[38]); transmission.AddLine(line); yield return transmission; } _maxResponseReached = false; }
public async Task <IEnumerable <GetNewStoriesResponse> > GetNewStories(short page, short count) { string key = "All_Newest_stories"; IEnumerable <GetNewStoriesResponse> newStories = await GetStoriesAsync(key); return(newStories?.Skip(Skip(page, count))?.Take(count)); }
/// <summary> /// IPageResult<T> /// </summary> /// <typeparam name="T">值的类型</typeparam> /// <param name="data">待分页的数据</param> /// <param name="pageIndex">当前页面</param> /// <param name="pageSize">页长</param> /// <param name="maxPage">最大页数</param> /// <returns>分页结果</returns> public static IPageResult <T> PageResult <T>(this IEnumerable <T> data, int pageIndex, int pageSize, int?maxPage = null) where T : new() { pageIndex = pageIndex <= 0 ? 1 : pageIndex; pageSize = pageSize < 0 ? 1 : pageSize; int totalCount = data == null ? 0 : data.Count(); return(new PageResult <T>(pageIndex, pageSize, totalCount, data?.Skip((pageIndex - 1) * pageSize).Take(pageSize), maxPageCount: maxPage)); }
public override void Populate(HL7Element element, IEnumerable <string> tableIds = null) { var tblsUsed = 0; ID = element.ElementValue(0); CheckDigit = element.ElementValue(1); CheckDigitScheme = NewID(element.ElementValue(2), NextTableId(tableIds, ref tblsUsed), Tables); AssigningAuthority = element.AsHD(3, tableIds?.Skip(tblsUsed), Tables); tblsUsed += HD_HierarchicDesignator.TotalCodedFieldCount; IdentifierTypeCode = NewID(element.ElementValue(4), NextTableId(tableIds, ref tblsUsed), Tables); AssigningFacility = element.AsHD(5, tableIds?.Skip(tblsUsed), Tables); tblsUsed += HD_HierarchicDesignator.TotalCodedFieldCount; EffectiveDate = element.FromTS(6); ExpirationDate = element.FromTS(7); }
public PagedList(IEnumerable <T> innerList, int pageSize, int currentPage) { _pageSize = pageSize; CurrentPage = currentPage; TotalCount = innerList?.Count() ?? 0; TotalPages = (int)(TotalCount / PageSize) + (TotalCount % PageSize > 0 ? 1 : 0); _innerList = innerList?.Skip((currentPage - 1) * pageSize).Take(PageSize); }
/// <summary> /// 构造方法 /// </summary> /// <param name="dataList"></param> /// <param name="basePage"></param> public Page(IEnumerable <T> dataList, BasePage basePage) { if (basePage.PageSize != null && basePage.PageSize > 0) { PageSize = (int)basePage.PageSize; } PageIndex = basePage.Page; DataCount = dataList?.Count() ?? 0; PageCount = (int)Math.Ceiling((decimal)DataCount / PageSize); DataList = dataList?.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList(); }
public override void Populate(HL7Element element, IEnumerable <string> tableIds = null) { var tblsUsed = 0; OrganizationName = element.ElementValue(0); OrganizationNameTypeCode = NewIS(element.ElementValue(1), NextTableId(tableIds, ref tblsUsed)); ID = element.IndexedElement(2); CheckDigit = element.ElementValue(3); CheckDigitScheme = NewID(element.ElementValue(4), NextTableId(tableIds, ref tblsUsed)); AssigningAuthority = element.AsHD(5, tableIds?.Skip(tblsUsed), Tables); tblsUsed += HD_HierarchicDesignator.TotalCodedFieldCount; IdentifierTypeCode = NewIS(element.ElementValue(6), NextTableId(tableIds, ref tblsUsed)); AssigningFacility = element.AsHD(7, tableIds, Tables); }
/// <summary> /// Orders a Transaction Entry by Date and converts it to a Simple Transaction Entry model already having a string /// //var transactions = entries?.OrderBy(e => { return e.Date; }).ToLookup( => t.Date.Year).ToLookup(t => t.ToLookup(e => e.Date.Month)); /// </summary> /// <returns></returns> public IEnumerable <TransactionEntry> GetEntriesByDate(DateTime date) { if (date.Date == DateTime.MinValue.Date) { return(entries?.Skip(1).ToList() .ConvertAll( e => new TransactionEntry { Amount = e.Amount, ID = e.ID, Date = e.Date.ToString("o"), OpDate = e.OpDate.ToString("o"), Description = e.Description, Currency = e.Currency, Saldo = e.Saldo, Cur = e.Cur }) ?? new List <TransactionEntry>()); } return(entriesLookUp[new DateTime(date.Year, date.Month, 1)].ToList().ConvertAll( e => new TransactionEntry { Amount = e.Amount, ID = e.ID, Date = e.Date.ToString("o"), OpDate = e.OpDate.ToString("o"), Description = e.Description, Currency = e.Currency, Saldo = e.Saldo, Cur = e.Cur }) ?? new List <TransactionEntry>()); return(entries?.OrderBy(e => { return e.Date; }).ToList() .ConvertAll( (e) => { return new TransactionEntry { Amount = e.Amount, ID = e.ID, Date = e.Date.ToShortDateString(), OpDate = e.OpDate.ToShortDateString(), Description = e.Description, Currency = e.Currency, Saldo = e.Saldo, Cur = e.Cur }; }) ?? new List <TransactionEntry>()); }
public (IEnumerable <TEntity>, int) GetAll(uint startPage, uint countLimit, bool loadDependecies = false) { int skip = (int)(startPage * countLimit); IEnumerable <TEntity> data = dbSet.ToList(); int count = data?.Count() ?? 0; var entities = data?.Skip(skip).Take((int)countLimit); if (entities != null && loadDependecies) { foreach (var entity in entities) { LoadPropertiesEntities(entity, LoadEntities.LoadDependencies); } } return(entities, count); }
private IEnumerable <T> SliceList(ListInformation <T> listInformation, IEnumerable <T> items) { if (listInformation == null || (items?.Count() ?? 0) == 0) { return(items); } listInformation.Pager = listInformation.Pager ?? new PagerInformation(); listInformation.Pager.TotalItems = items.Count(); this.SetPagerInformation(listInformation); var pageSize = listInformation?.Pager?.PageSize ?? 0; return(pageSize > 0 ? items? .Skip(listInformation.Pager.StartItemIndex - 1) .Take(listInformation.Pager.PageSize) .ToList() : items); }
public override void ExecuteCmdlet() { if (this.Dataset != null) { this.DatasetId = this.Dataset.Id; } if (this.Workspace != null) { this.WorkspaceId = this.Workspace.Id; } IEnumerable <Table> tables = null; using (var client = this.CreateClient()) { if (this.WorkspaceId != default) { tables = client.Datasets.GetTables(this.DatasetId, this.WorkspaceId); } else { tables = client.Datasets.GetTables(this.DatasetId); } } if (!string.IsNullOrEmpty(this.Name)) { tables = tables?.Where(d => d.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)); } if (this.Skip.HasValue) { tables = tables?.Skip(this.Skip.Value); } if (this.First.HasValue) { tables = tables?.Take(this.First.Value); } this.Logger.WriteObject(tables, true); }
public override void ExecuteCmdlet() { if (this.Workspace != null) { this.WorkspaceId = this.Workspace.Id; } if (this.Id != default) { this.Filter = $"id eq '{this.Id}'"; } if (this.Name != default) { this.Filter = $"tolower(name) eq '{this.Name.ToLower()}'"; } IEnumerable <Report> reports = null; using (var client = this.CreateClient()) { if (this.WorkspaceId != default) { reports = this.Scope == PowerBIUserScope.Individual ? client.Reports.GetReportsForWorkspace(this.WorkspaceId) : client.Reports.GetReportsAsAdminForWorkspace(this.WorkspaceId, filter: this.Filter, top: this.First, skip: this.Skip); } else { reports = this.Scope == PowerBIUserScope.Individual ? client.Reports.GetReports() : client.Reports.GetReportsAsAdmin(filter: this.Filter, top: this.First, skip: this.Skip); } } // Bug in OData filter for ID, workaround is to use LINQ if (this.Id != default) { reports = reports?.Where(r => this.Id == r.Id); } if (this.Scope == PowerBIUserScope.Individual) { if (!string.IsNullOrEmpty(this.Name)) { reports = reports?.Where(r => r.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)); } if (this.Skip.HasValue) { reports = reports?.Skip(this.Skip.Value); } if (this.First.HasValue) { reports = reports?.Take(this.First.Value); } } this.Logger.WriteObject(reports, true); }
private SendMailResponse SmtpSend(Guid token, IEnumerable <MailMessage> requests) { Logger.Current.Verbose("sending an email from smtp-mail service"); var result = new SendMailResponse(); var _parallelLoad = 100; var iterations = (requests.Count() / _parallelLoad); if ((requests.Count() % _parallelLoad) > 0) { iterations++; } result.FailedRecipients = new List <string>(); for (int i = 0; i < iterations; i++) { try { Logger.Current.Verbose("Iteration: " + i); var currentIterations = requests.Skip(i * _parallelLoad).Take(_parallelLoad).ToList(); currentIterations.ForEach(s => { var failedRecipients = new List <string>(); try { result.Token = token; result.RequestGuid = Guid.NewGuid(); smtpClient.Send(s); result.StatusID = LandmarkIT.Enterprise.CommunicationManager.Responses.CommunicationStatus.Success; Logger.Current.Verbose("Sent email to: " + s.To); } catch (Exception ex) { ExceptionHandler.Current.HandleException(ex, DefaultExceptionPolicies.LOG_ONLY_POLICY, values: new object[] { requests }); try { smtpClient = new SmtpClient(this.registration.Host, this.registration.Port.Value); smtpClient.Credentials = new NetworkCredential(this.registration.UserName, this.registration.Password); smtpClient.EnableSsl = this.registration.IsSSLEnabled; if (this.registration.Port.HasValue) { smtpClient.Port = this.registration.Port.Value; } smtpClient.Send(s); } catch (Exception exception) { result.StatusID = LandmarkIT.Enterprise.CommunicationManager.Responses.CommunicationStatus.Failed; result.ServiceResponse = exception.Message; Logger.Current.Verbose("An error occured while sending an email from smtp-mail service/send-grid" + exception); ExceptionHandler.Current.HandleException(exception, DefaultExceptionPolicies.LOG_ONLY_POLICY, values: new object[] { requests }); failedRecipients.AddRange(s.To.Select(c => c.Address)); result.FailedRecipients = failedRecipients; } } }); } catch (Exception ex) { Logger.Current.Error("Exception occured in iteration: " + i, ex); } } return(result); }
public static bool IsMultiple <T>(this IEnumerable <T> collection) { return(collection?.Skip(1).Any() ?? false); }
public void TestFetch() { const string DBPath = "test2.db"; if (File.Exists(DBPath)) { File.Delete(DBPath); } using (var provider = new QueryMetadataProvider()) { // Create database and fill it provider.Create(DBPath); foreach (MetadataKey key in keys) { provider.AddKey(key); } for (int i = 0; i < 4; ++i) { provider.Write(new ObjectMetadata(urls[0], keys[i], values1[i])); provider.Write(new ObjectMetadata(urls[1], keys[i], values2[i])); } // Fetch by url IEnumerable <IObjectMetadata> result = provider.Fetch(urls[0]); Assert.NotNull(result); Assert.AreEqual(result.Count(), 4); for (int i = 0; i < 4; ++i) { IObjectMetadata obj = result.Skip(i).First(); Assert.AreEqual(obj.ObjectUrl, urls[0]); Assert.AreEqual(obj.Key, keys[i]); Assert.AreEqual(obj.Value, values1[i]); } // Fetch by key for (int j = 0; j < 4; ++j) { result = provider.Fetch(keys[j]); Assert.NotNull(result); Assert.AreEqual(result.Count(), 2); for (int i = 0; i < 2; ++i) { IObjectMetadata obj = result.Skip(i).First(); Assert.AreEqual(obj.ObjectUrl, urls[i]); Assert.AreEqual(obj.Key, keys[j]); Assert.AreEqual(obj.Value, i == 0 ? values1[j] : values2[j]); } } // Fetch by url and key for (int j = 0; j < 4; ++j) { for (int i = 0; i < 2; ++i) { IObjectMetadata obj = provider.Fetch(urls[i], keys[j]); Assert.NotNull(obj); Assert.AreEqual(obj.ObjectUrl, urls[i]); Assert.AreEqual(obj.Key, keys[j]); Assert.AreEqual(obj.Value, i == 0 ? values1[j] : values2[j]); } } provider.Close(); } }
/// <summary> /// Returns an enumerable of all elements of the given list but the first, /// keeping them in order. /// </summary> public static IEnumerable <T> ButFirst <T>(this IEnumerable <T> source) { return(source.Skip(1)); }
/// <summary> /// インデックスiの位置の要素からk個取り除く /// O(N) /// </summary> public static IEnumerable <T> TakeAwayRange <T> (this IEnumerable <T> source, int i, int count) { return(source.Take(i).Concat(source.Skip(i + count))); }
/// <summary> /// Takes the last n number of items in the array. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="count">The count.</param> /// <returns>a new collection that contains only the last count number of items</returns> public static IEnumerable <T> TakeLast <T>(this IEnumerable <T> source, int count) { return(source?.Skip(Math.Max(0, source.Count() - count))); }
public static IEnumerable <T> GetPaged <T>(this IEnumerable <T> items, int pno = 1, int psize = PdConstants.DefaultPageSize) => items?.Skip((pno - 1) * psize).Take(psize);
/// <summary> /// インデックスiの位置にシーケンスを挿入する /// O(N + K) /// </summary> public static IEnumerable <T> InsertEnumAt <T> (this IEnumerable <T> source, int i, IEnumerable <T> inserted) { return(source.Take(i).Concat(inserted).Concat(source.Skip(i))); }
public override void ExecuteCmdlet() { if (this.Workspace != null) { this.WorkspaceId = this.Workspace.Id; this.Logger.WriteDebug($"Using {nameof(this.Workspace)} object to get {nameof(this.WorkspaceId)} parameter. Value: {this.WorkspaceId}"); } if (this.Id != default) { this.Filter = $"id eq '{this.Id}'"; } if (this.Name != default) { this.Filter = $"tolower(name) eq '{this.Name.ToLower()}'"; } IEnumerable <Dataflow> dataflows = null; using (var client = this.CreateClient()) { if (this.WorkspaceId != default) { dataflows = this.Scope == PowerBIUserScope.Organization ? client.Dataflows.GetDataflowsAsAdminForWorkspace(this.WorkspaceId, filter: this.Filter, top: this.First, skip: this.Skip) : client.Dataflows.GetDataflows(this.WorkspaceId); } else if (this.Scope == PowerBIUserScope.Organization) { // No workspace id - Works only for organization scope dataflows = client.Dataflows.GetDataflowsAsAdmin(filter: this.Filter, top: this.First, skip: this.Skip); } } // In individual scope - filter the results locally if (this.Scope == PowerBIUserScope.Individual) { if (this.Id != default) { dataflows = dataflows?.Where(d => this.Id == d.Id); } if (!string.IsNullOrEmpty(this.Name)) { dataflows = dataflows?.Where(d => d.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)); } if (this.Skip.HasValue) { dataflows = dataflows?.Skip(this.Skip.Value); } if (this.First.HasValue) { dataflows = dataflows?.Take(this.First.Value); } } this.Logger.WriteObject(dataflows, true); }
private static IEnumerable <string> getNew3(IEnumerable <string> titles) => titles.Skip(Math.Max(titles.Count() - 3, 0));
internal static ExchangeRate ParseLine(IEnumerable <string> line) { return(new ExchangeRate(new Currency("CZK"), new Currency(line?.FirstOrDefault()?.ToUpper()), decimal.Parse(line?.Skip(1).FirstOrDefault() ?? "0", new CultureInfo("cs-CZ")))); }
public static IEnumerable <T> ToPageResult <T>(this IEnumerable <T> source, GetPagingModel request) { return(source?.Skip((request.Page - 1) * request.PageSize) .Take(request.PageSize)); }