/// <summary> /// Sort the items by their priority and their index they currently exist in the collection /// </summary> /// <param name="files"></param> /// <returns></returns> public static IList<IClientDependencyFile> SortItems(IList<IClientDependencyFile> files) { //first check if each item's order is the same, if this is the case we'll make sure that we order them //by the way they were defined if (!files.Any()) return files; var firstPriority = files.First().Priority; if (files.Any(x => x.Priority != firstPriority)) { var sortedOutput = new List<IClientDependencyFile>(); //ok they are not the same so we'll need to sort them by priority and by how they've been entered var groups = files.GroupBy(x => x.Priority).OrderBy(x => x.Key); foreach (var currentPriority in groups) { //for this priority group, we'll need to prioritize them by how they are found in the files array sortedOutput.AddRange(currentPriority.OrderBy(files.IndexOf)); } return sortedOutput; } //they are all the same so we can really just return the original list since it will already be in the //order that they were added. return files; }
public static IList<int> Merge(IList<int> left, IList<int> right) { IList<int> result = new List<int>(); while (left.Any() && right.Any()) { if (left[0] < right[0]) { result.Add(left[0]); left.Remove(left[0]); } else { result.Add(right[0]); right.Remove(right[0]); } } while (left.Any()) { result.Add(left[0]); left.RemoveAt(0); } while (right.Any()) { result.Add(right[0]); right.RemoveAt(0); } return result; }
public MultilayerPerceptron(int numInputs, int numOutputs, IList<int> hiddenLayerSizes) { if (numInputs <= 0) throw new NeuralNetworkException($"Argument {nameof(numInputs)} must be positive; was {numInputs}."); if (numOutputs <= 0) throw new NeuralNetworkException($"Argument {nameof(numOutputs)} must be positive; was {numOutputs}."); if (hiddenLayerSizes == null || !hiddenLayerSizes.Any()) throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} cannot be null or empty."); if (hiddenLayerSizes.Any(h => h <= 0)) { var badSize = hiddenLayerSizes.First(h => h <= 0); var index = hiddenLayerSizes.IndexOf(badSize); throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} must contain only positive " + $"values; was {badSize} at index {index}."); } NumInputs = numInputs; NumOutputs = numOutputs; HiddenLayerSizes = hiddenLayerSizes.ToArray(); Weights = new double[hiddenLayerSizes.Count + 1][]; for (var i = 0; i < hiddenLayerSizes.Count + 1; i++) { if (i == 0) Weights[i] = new double[(numInputs + 1) * hiddenLayerSizes[0]]; else if (i < hiddenLayerSizes.Count) Weights[i] = new double[(hiddenLayerSizes[i-1] + 1) * hiddenLayerSizes[i]]; else Weights[i] = new double[(hiddenLayerSizes[hiddenLayerSizes.Count - 1] + 1) * numOutputs]; } }
/// <summary> /// 初始化降生点 /// </summary> /// <param name="points">可行走区域</param> /// <param name="pins">排除传送阵区域</param> public void InitBron(IList<Point> points, IList<Rectangle> pins) { m_bornPlace = new List<Point>(); if (m_box.Range != Rectangle.Empty) { foreach (var p in points) { if (m_box.Range.Contains(p)) { if (!pins.Any(x => x.Contains(p))) { m_bornPlace.Add(p); } } } } if (m_bornPlace.Count == 0) { foreach (var p in points) { if (!pins.Any(x => x.Contains(p))) { m_bornPlace.Add(p); } } } int index = NumberRandom.Next(m_bornPlace.Count); this.m_point = m_bornPlace[index]; }
public IList<CounterDescriptor> UpdateCounterItems(IList<CounterDescriptor> counterItems) { //get sites from IIS ServerManager iisManager = new ServerManager(); var sites = iisManager.Sites; //build list of names no longer used var countersToRemove = new List<string>(); foreach (var counterItem in counterItems) { if (!sites.Any(rd => rd.Name==counterItem.Name)) countersToRemove.Add(counterItem.Name); } //remove all contained in removal list counterItems = counterItems.Where(item => !countersToRemove.Contains(item.Name)).ToList(); //add new foreach (var iisSite in sites) { //if we don't have an item with the same name in our list, add it if (!counterItems.Any(rd => rd.Name==iisSite.Name)) { counterItems.Add(CreateDescriptor(iisSite)); } } //total if (!counterItems.Any(rd => rd.Name == "Total")) { counterItems.Add(CreateAllMethodRequestsDescriptor()); } //return return counterItems; }
private static IList<int> Merge(IList<int> left, IList<int> right) { var result = new List<int>(); while (left.Any() && right.Any()) { if (left[0] < right[0]) { result.Add(left[0]); left.Remove(left[0]); } result.Add(right[0]); right.Remove(right[0]); } while (left.Any()) { result.Add(left[0]); left.Remove(left[0]); } while (right.Any()) { result.Add(right[0]); right.Remove(right[0]); } return result; }
private string FormatDeletePatterns(IList<ITriple> deletePatterns, string updateGraphUri) { var deleteCmds = new StringBuilder(); int propId = 0; if (deletePatterns.Any(p => IsGraphTargeted(p) && IsGrounded(p))) { deleteCmds.AppendLine("DELETE DATA {"); foreach (var patternGroup in deletePatterns.Where(p => IsGraphTargeted(p) && IsGrounded(p)).GroupBy(p=>p.Graph)) { deleteCmds.AppendFormat("GRAPH <{0}> {{", patternGroup.Key); deleteCmds.AppendLine(); foreach (var deletePattern in patternGroup) { AppendTriplePattern(deletePattern, deleteCmds); } deleteCmds.AppendLine("}"); } deleteCmds.AppendLine("};"); } foreach (var deletePattern in deletePatterns.Where(p=>IsGraphTargeted(p) && !IsGrounded(p))) { deleteCmds.AppendFormat("WITH <{0}> DELETE {{ {1} }} WHERE {{ {1} }};", deletePattern.Graph, FormatDeletePattern(deletePattern, ref propId)); } if (deletePatterns.Any(p => !IsGraphTargeted(p) && IsGrounded(p))) { // Delete from default graph deleteCmds.AppendLine("DELETE DATA {"); foreach (var p in deletePatterns.Where(p => !IsGraphTargeted(p) && IsGrounded(p))) { AppendTriplePattern(p, deleteCmds); } // If an update graph is specified delete from that too if (updateGraphUri != null) { deleteCmds.AppendFormat("GRAPH <{0}> {{", updateGraphUri); deleteCmds.AppendLine(); foreach (var p in deletePatterns.Where(p => !IsGraphTargeted(p) && IsGrounded(p))) { AppendTriplePattern(p, deleteCmds); } deleteCmds.AppendLine("}"); } deleteCmds.AppendLine("};"); } foreach (var deletePattern in deletePatterns.Where(p => !IsGraphTargeted(p) && !IsGrounded(p))) { var cmd = String.Format("DELETE {{ {0} }} WHERE {{ {0} }};", FormatDeletePattern(deletePattern, ref propId)); deleteCmds.AppendLine(cmd); if (updateGraphUri != null) { deleteCmds.AppendFormat("WITH <{0}> ", updateGraphUri); deleteCmds.AppendLine(cmd); } } return deleteCmds.ToString(); }
public EntityDeleteModel(IList<PropertyDeleteOption> deleteOptions) { DisplayRecordHierarchy = deleteOptions.Any(); AssumableDeleteHierarchyWarning = deleteOptions.Any(x => x.ShowOptions); if (deleteOptions.Any(x => x.DeleteOption == CascadeOption.AskUser)) PropertiesDeleteOptions = deleteOptions.Where(x => x.Visible).ToList(); else PropertiesDeleteOptions = new List<PropertyDeleteOption>(); }
/// <summary> /// Returns the submission status for an entire assignment. /// </summary> public static SubmissionStatus ForAssignment( IList<SubmissionStatus> questionStatus) { var completion = questionStatus.All(q => q.Completion == Completion.Completed) ? Completion.Completed : questionStatus.Any(q => q.Completion != Completion.NotStarted) ? Completion.InProgress : Completion.NotStarted; var late = questionStatus.Any(q => q.Late); return new SubmissionStatus(completion, late); }
private IEnumerable<FieldDeclarationSyntax> GetRuleViolations(IList<dynamic> fieldsInfo) { if (fieldsInfo.Any(f => !f.IsCollection)) { return fieldsInfo.Where(f => f.IsCollection).Select(f => f.Syntax as FieldDeclarationSyntax); } if (fieldsInfo.Any(f => f.IsCollection)) { return fieldsInfo.Where(f => f.IsCollection).Skip(1).Select(f => f.Syntax as FieldDeclarationSyntax); } return new List<FieldDeclarationSyntax>(); }
public static Movement Analyze(IList<Movement> movements) { Movement movement; if (movements.Any(x => x > Movement.Higher)) movement = Movement.Highest; else if (movements.Any(x => x > Movement.High)) movement = Movement.High; else if (movements.Any(x => x > Movement.Med)) movement = Movement.Med; else if (movements.Average(x => (double)x) > (double)Movement.Lowest) movement = Movement.Low; else movement = Movement.Lowest; return movement; }
public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets) { if (IsHtmlFile && completionSets.Any()) { var bottomSpan = completionSets.First().ApplicableTo; if (!JScriptEditorUtil.IsInJScriptLanguageBlock(_lbm, bottomSpan.GetStartPoint(bottomSpan.TextBuffer.CurrentSnapshot))) { // This is an HTML statement completion session, so do nothing return; } } // TODO: Reflect over the ShimCompletionSet to see where the Description value comes from // as setting the property does not actually change the value. var newCompletionSets = completionSets .Select(cs => cs == null ? cs : new ScriptCompletionSet( cs.Moniker, cs.DisplayName, cs.ApplicableTo, cs.Completions .Select(c => c == null ? c : new Completion( c.DisplayText, c.InsertionText, DocCommentHelper.ProcessParaTags(c.Description), c.IconSource, c.IconAutomationText)) .ToList(), cs.CompletionBuilders)) .ToList(); completionSets.Clear(); newCompletionSets.ForEach(cs => completionSets.Add(cs)); }
public void Execute(IList<IAggregateCommand> commands, int expectedVersion) { if (!commands.Any()) { return; } var rootId = commands.First().AggregateId; if (commands.Any(x => x.AggregateId != rootId)) { throw new InvalidOperationException("Can only execute commands for a single aggregate at a time"); } var root = this.repository.GetById(rootId); if (root == null) { root = this.repository.New(); root.Identity = rootId; } if (expectedVersion != 0) { // if we using this command executor multiple times for the same aggregate, when we invoke it we will often have the // verion of the roor prior to the first invocation. Consequently when we check the expected version the second time, // we have a different version and we get an exception. This is supposed to handle that case by remembering what the // version of the root was when we first saw it. var rootVersion = root.Version; if (this.versions.ContainsKey(root.Identity)) { rootVersion = this.versions[root.Identity]; } if (rootVersion != expectedVersion) { throw new InvalidOperationException(string.Format("Not Expected Version {0}, {1}", expectedVersion, root.Version)); } } var exec = new ExecutingCommandExecutor(root); exec.Execute(commands, expectedVersion); this.repository.Save(root); if (expectedVersion != 0 && !this.versions.ContainsKey(root.Identity)) { this.versions[root.Identity] = expectedVersion; } }
public InterlockDataAdapter(OleDbDataReader dr ,IList<string> dynamicList, int startColumn) { ControlSystemName = string.Empty; InterlockTypeName = Number = string.Empty; Cause = string.Empty; Description = string.Empty; ControlSystemName = dr.SafeString((int)InterlockColumn.ControlSystemName).Trim(); InterlockTypeName = dr.SafeString((int)InterlockColumn.InterlockType).Trim(); Number = dr.SafeString((int)InterlockColumn.Number).Trim(); Cause = dr.SafeString((int)InterlockColumn.Cause).Trim(); Description = dr.SafeString((int)InterlockColumn.Description).Trim(); DynamicProperties = new List<DynamicProperty>(); if (dynamicList != null && dynamicList.Any()) { for (int d = 0; d < dynamicList.Count(); d++) { string p = dynamicList[d]; DynamicProperty property = new DynamicProperty(); property.PropertyName = p; property.PropertyValue = dr.SafeString(startColumn + d); DynamicProperties.Add(property); } } }
public InstanceConfiguration Parse(IList<string> args) { var cfg = new InstanceConfiguration { AppName = string.Empty, Help = false, Verbose = false, ExtraParams = new List<string>() }; var p = new OptionSet { {"app=", v => cfg.AppName = v}, {"i|install", v => cfg.Install = v != null}, {"v|verbose", v => cfg.Verbose = v != null}, {"h|?|help", v => cfg.Help = v != null}, }; cfg.OptionSet = p; if (args == null || !args.Any()) { cfg.Help = true; return cfg; } cfg.ExtraParams = p.Parse(args); cfg.AppName = cfg.AppName.Trim('"', '\''); return cfg; }
/// <summary> /// Exports the specified entry. /// </summary> /// <param name="entries">The entry.</param> internal void Export(IList<Entry> entries) { if (entries.Any() == false) return; // setup variable to group all error messages together var errorBuilder = new StringBuilder(); // Build a batch based update to avoid memory overhead var bulkCommand = new BulkCommand(GetIndex(), LOG_TYPE); var bulkJsons = new BulkBuilder(serializer) .PipelineCollection(entries, (builder, entity) => builder.Index(entity, id: entity.Id.ToString())) .JoinInBatches(batchSize: 1000); foreach (var bulk in bulkJsons) { string result = connection.Put(bulkCommand, bulk); var bulkResult = serializer.ToBulkResult(result); // Check for errors foreach (var operation in bulkResult.items.Where(a => a.Result.ok == false)) { errorBuilder.AppendFormat("Id: {0} Error: {1} {2}", operation.Result._id, operation.Result.error, Environment.NewLine); } } // Check for any errors that are reported by the ElasticSearch var error = errorBuilder.ToString(); if (string.IsNullOrWhiteSpace(error) == false) throw new ApplicationException(error); }
/// <summary> /// Gets a read-only cached <see cref="CultureInfo"/> for the specified name. Only names that exist in /// <paramref name="supportedCultures"/> will be used. /// </summary> /// <param name="name">The culture name.</param> /// <param name="supportedCultures">The cultures supported by the application.</param> /// <returns> /// A read-only cached <see cref="CultureInfo"/> or <c>null</c> a match wasn't found in /// <paramref name="supportedCultures"/>. /// </returns> public static CultureInfo GetCultureInfo(string name, IList<CultureInfo> supportedCultures) { // Allow only known culture names as this API is called with input from users (HTTP requests) and // creating CultureInfo objects is expensive and we don't want it to throw either. if (name == null || supportedCultures == null || !supportedCultures.Any(supportedCulture => string.Equals(supportedCulture.Name, name, StringComparison.OrdinalIgnoreCase))) { return null; } var entry = _cache.GetOrAdd(name, n => { try { return new CacheEntry(CultureInfo.ReadOnly(new CultureInfo(n))); } catch (CultureNotFoundException) { // This can still throw as the list of culture names we have is generated from latest .NET Framework // on latest Windows and thus contains names that won't be supported on lower framework or OS versions. // We can just cache the null result in these cases as it's ultimately bound by the list anyway. return new CacheEntry(cultureInfo: null); } }); return entry.CultureInfo; }
/// <summary> /// Retrives the width columns. /// </summary> /// <param name="columns">The columns.</param> /// <returns>Dictionary{System.StringSystem.Int32}.</returns> private static Dictionary<string, int> RetriveWidthColumns(IList<string> columns) { var columnWidthList = new Dictionary<string, int>(); if (columns != null && columns.Any()) { if (columns[0].Contains(Constants.SplitVerticalBar)) { for (var i = 0; i < columns.Count(); i++) { var column = columns[i].Split(Constants.SplitVerticalBar); var columnUniqName = !string.IsNullOrEmpty(column[0]) ? column[0] : string.Empty; var columnWidth = 0; try { columnWidth = !string.IsNullOrEmpty(column[1]) && column[1].Length > 1 ? Convert.ToInt32(column[1], CultureInfo.InvariantCulture) : 0; } catch { } columnWidthList[columnUniqName.Trim()] = columnWidth; } } } return columnWidthList; }
private bool IsWinner(IList<NoughtsAndCrossesButton> buttons) { if (buttons.Any(x => x.Value == null)) { return false; } return (from b in buttons group b by b.Value into g select new {g.Key}).Count() == 1; }
public override void Export(IList<BenchmarkReport> reports, IBenchmarkLogger logger, IEnumerable<IBenchmarkResultExtender> resultExtenders = null) { if(useCodeBlocks) logger.WriteLine($"```{codeBlocksSyntax}"); logger = new BenchmarkLoggerWithPrefix(logger, prefix); logger.WriteLineInfo(EnvironmentInfo.GetCurrentInfo().ToFormattedString("Host")); logger.NewLine(); var table = BenchmarkExporterHelper.BuildTable(reports, resultExtenders); // If we have Benchmarks with ParametersSets, force the "Method" columns to be displayed, otherwise it doesn't make as much sense var columnsToAlwaysShow = (reports.Any(r => r.Benchmark.Task.ParametersSets != null) ? new[] { "Method" } : new string[0]). Concat((resultExtenders ?? new IBenchmarkResultExtender[0]).Select(e => e.ColumnName)).ToArray(); PrintTable(table, logger, columnsToAlwaysShow); // TODO: move this logic to an analyser var benchmarksWithTroubles = reports.Where(r => !r.GetTargetRuns().Any()).Select(r => r.Benchmark).ToList(); if (benchmarksWithTroubles.Count > 0) { logger.NewLine(); logger.WriteLineError("Benchmarks with troubles:"); foreach (var benchmarkWithTroubles in benchmarksWithTroubles) logger.WriteLineError(" " + benchmarkWithTroubles.Caption); } }
/// <summary> /// 上传文件 /// </summary> /// <param name="files"></param> /// <returns></returns> public static IList<string> Upload(IList<FileItem> files) { if (files == null || !files.Any()) { return null; } //远程 if (_fileUploadType.Equals("REMOTE", StringComparison.CurrentCultureIgnoreCase)) { var req = YunClient.Instance.Execute(new FileUploadRequest { Images = files }); if (!req.IsError && req.Files != null && req.Files.Any()) { return req.Files; } return null; } //本地 return files.Select(file => new PictureCore(file.GetContent(), file.GetFileName())) .Select(instance => instance.Create()) .Where(result => !string.IsNullOrWhiteSpace(result)) .ToList(); }
/// <summary> /// A general method which takes a list of data and calculates its corresponding aggregate value. /// It will be used to calculate the aggregate value of each pages individually, with considering the previous pages data. /// </summary> /// <param name="columnCellsSummaryData">List of data</param> /// <returns>Aggregate value</returns> public object ProcessingBoundary(IList<SummaryCellData> columnCellsSummaryData) { if (columnCellsSummaryData == null || !columnCellsSummaryData.Any()) return 0; var list = columnCellsSummaryData; return list.Sum(item => Convert.ToDouble(item.CellData.PropertyValue, CultureInfo.InvariantCulture)); }
public bool Prepare(wnd.IDataObject ido) { currentDishes = SelectDishes(ido); PrepareDishes(currentDishes); return currentDishes.Any(); }
private string GetInternalLoadBalancerIPAddress(IList<VirtualIPAddress> virtualIPs, string ilbName) { var ilbIP = virtualIPs == null || !virtualIPs.Any() ? null : virtualIPs.FirstOrDefault(ip => string.Equals(ip.Name, ilbName, StringComparison.OrdinalIgnoreCase)); return ilbIP == null ? null : ilbIP.Address; }
private static void SeedEnemies(IList<IGameObject> entities) { int saturation = Rand.Next(MinEnemySaturationRate, MaxEnemySaturationPercentage + 1); int numberOfEnemies = saturation * Constants.MapHeight * Constants.MapWidth / 100; var enemies = Assembly.GetExecutingAssembly().GetTypes() .Where(t => t.IsClass) .Where(t => t.CustomAttributes.Any(a => a.AttributeType == typeof(EnemyAttribute))) .ToArray(); for (int i = 0; i < numberOfEnemies; i++) { int currentX = Rand.Next(1, Constants.MapWidth); int currentY = Rand.Next(1, Constants.MapHeight); while (entities.Any(e => e.Position.X == currentX && e.Position.Y == currentY)) { currentX = Rand.Next(1, Constants.MapWidth); currentY = Rand.Next(1, Constants.MapHeight); } int entityIndex = Rand.Next(0, enemies.Length); var entity = Activator.CreateInstance(enemies[entityIndex], new Position(currentX, currentY)) as IGameObject; entities.Add(entity); } }
public ProgramConstruct ProcessTokens(IList<ResolvedToken> tokens) { Contract.Requires(tokens != null); _tokens = tokens; var functions = new List<FunctionConstruct>(); ExectuableBlockConstruct block = null; while (_tokens.Any() && PeekNextToken() != Token.EOF) { switch (PeekNextToken()) { case Token.KW_FUNC: functions.Add(ProcessAsFunction()); break; case Token.EOL: GetNextToken(); break; default: block = ProcessAsBlock(true); break; } } return new ProgramConstruct(functions, block); }
public void SetNotificationTypeActions(IList<NotificationTypeAction> actions, int notificationTypeId) { Requires.NotNull("actions", actions); if (!actions.Any()) { throw new ArgumentException("Actions must contain at least one item."); } if (actions.Any(x => string.IsNullOrEmpty(x.APICall))) { throw new ArgumentException("All actions must specify an APICall"); } if (actions.Any(x => string.IsNullOrEmpty(x.NameResourceKey))) { throw new ArgumentException("All actions must specify a NameResourceKey"); } foreach (var action in actions) { action.NotificationTypeActionId = _dataService.AddNotificationTypeAction(notificationTypeId, action.NameResourceKey, action.DescriptionResourceKey, action.ConfirmResourceKey, action.APICall, GetCurrentUserId()); action.NotificationTypeId = notificationTypeId; } }
public static NamespaceDeclarationSyntax AddUsingDirectives( this NamespaceDeclarationSyntax namespaceDeclaration, IList<UsingDirectiveSyntax> usingDirectives, bool placeSystemNamespaceFirst, params SyntaxAnnotation[] annotations) { if (!usingDirectives.Any()) { return namespaceDeclaration; } var specialCaseSystem = placeSystemNamespaceFirst; var comparer = specialCaseSystem ? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance : UsingsAndExternAliasesDirectiveComparer.NormalInstance; var usings = new List<UsingDirectiveSyntax>(); usings.AddRange(namespaceDeclaration.Usings); usings.AddRange(usingDirectives); if (namespaceDeclaration.Usings.IsSorted(comparer)) { usings.Sort(comparer); } usings = usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToList(); var newNamespace = namespaceDeclaration.WithUsings(SyntaxFactory.List(usings)); return newNamespace; }
public bool Prepare(string url, string format) { currentDishes = SelectDishes(url, format); PrepareDishes(currentDishes); return currentDishes.Any(); }
private static IEnumerable<object[]> GetFilesPerTest(IList<string> tests, IList<string> skips = null) { var files = TestDocuments; if (tests == null) { yield return new object[0]; yield break; } if (skips == null) skips = new string[0]; foreach (var file in files) { var filenames = new List<string>(); var ok = false; foreach (var ext in tests) { if (!file.Value.Contains(ext)) { ok = false; break; } filenames.Add(Path.Combine("Data", file.Key + ext)); ok = true; } if (ok && !skips.Any(skip => file.Value.Contains(skip))) yield return filenames.Cast<object>().ToArray(); } }
/// <summary> /// Initializes a new instance of the <see cref="Result"/> class. /// </summary> /// <param name="failed">if set to <c>true</c> [failed].</param> /// <param name="messages">The messages.</param> public Result(bool failed, IList <string> messages) { if (failed && !(messages?.Any() == true)) { throw new ArgumentException(Properties.Resources.MissingFailureMessages, nameof(messages)); } Messages = messages ?? new List <string>(); HasFailed = failed; }
private static void SetImports(IObjectWriter writer, IList <NuGetFramework> frameworks) { if (frameworks?.Any() == true) { var imports = frameworks.Select(framework => framework.GetShortFolderName()); writer.WriteNameArray("imports", imports); } }
public static int NextNumber(this IList <int> list) { int next = 0; List <int> breaks = new List <int>(); if (!(list?.Any() ?? false)) { list.Add(next); return(next); } var listAfterSorted = list.OrderBy(e => e); int min = listAfterSorted.Min(); int max = listAfterSorted.Max() + 1; listAfterSorted.Aggregate((seed, total) => { int interval = 1; var diff = (total - seed) - interval; while (diff > 0) { breaks.Add(total -= interval); diff = (total - seed) - interval; } //if (diff > 0) //{ // breaks.Add(total - 1 ); //} return(total); }); //next = list.OrderBy(e => e).Last() + 1; //var breaks = new List<int>(); //if ((list != null) && (list.Any())) //{ // list.OrderBy(e => e).Aggregate((seed, aggr) => // { // var diff = (aggr - seed) - 1; // if (diff > 0) // breaks.Add(aggr - 1); // return aggr; // }); //} if (min != 0) { next = 0; } else { next = breaks.Any() ? breaks.OrderBy(e => e).First() : max; } list.Add(next); return(next); }
public static IList <string> GetVals(this IDictionary <Guid, string> dic, IList <Guid> keys) { IList <string> result = new List <string>(); if (keys?.Any() == true) { result = dic.Where(x => keys.Contains(x.Key)).Select(x => x.Value).ToList(); } return(result); }
private static DateTime GetLatestLastUpdated(ISolutionResult solutionResult, IList <IMarketingContactResult> contactResult) => new List <DateTime> { solutionResult.LastUpdated, solutionResult.SolutionDetailLastUpdated, contactResult?.Any() == true?contactResult.Max(x => x.LastUpdated) : DateTime.MinValue } .Max();
public async Task <IViewComponentResult> InvokeAsync(IList <string> emails, string fieldName) { var model = new EmailListModel { Value = emails?.Any() == true?JsonSerializer.Serialize(emails) : "", Name = fieldName }; return(View("Default", model)); }
public static Dictionary <string, List <string> > GroupPropertyWithErrors(this IList <ValidationFailure> failures) { if (!failures?.Any() ?? true) { return(new Dictionary <string, List <string> >()); } return(failures.GroupBy(g => g.PropertyName) .ToDictionary(g => g.Key, g => g.Select(v => v.ErrorMessage).Distinct().ToList())); }
public async Task <CtVerificationResult> IsValidAsync(IList <X509Certificate2> chain, CancellationToken cancellationToken) { if (chain?.Any() != true) { return(CtVerificationResult.NoCertificates()); } var leaf = chain.First(); var scts = leaf.GetSignedCertificateTimestamps(); if (scts?.Any() != true) { return(CtVerificationResult.NoScts()); } var logDictionary = await _logListService.GetLogDictionaryAsync(cancellationToken).ConfigureAwait(false); //foreach (var log in logDictionary) //{ // Console.WriteLine($"{BitConverter.ToString(Convert.FromBase64String(log.Key)).Replace("-", string.Empty).ToLowerInvariant()} {log.Value.Description}"); //} cancellationToken.ThrowIfCancellationRequested(); if (logDictionary?.Any() != true) { return(CtVerificationResult.LogServersFailed()); } //var sctResults = scts.Select(sct => // logDictionary.TryGetValue(sct.LogIdBase64, out var log) // ? new { LogIdBase64 = sct.LogIdBase64, Item2 = sct.VerifySignature(log, chain) } // : new { LogIdBase64 = sct.LogIdBase64, Item2 = SctVerificationResult.NoTrustedLogServerFound(sct.TimestampUtc) }) // .ToDictionary(t => t.LogIdBase64, t => t.Item2); var sctResults = new Dictionary <string, SctVerificationResult>(); foreach (var sct in scts) { SctVerificationResult result; if (logDictionary.TryGetValue(sct.LogIdBase64, out var log)) { result = sct.VerifySignature(log, chain); } else { result = SctVerificationResult.NoTrustedLogServerFound(sct.TimestampUtc); } sctResults.Add(sct.LogIdBase64, result); Console.WriteLine($"{BitConverter.ToString(Convert.FromBase64String(sct.LogIdBase64)).Replace("-", string.Empty).ToLowerInvariant()} {result}"); } return(_ctPolicy.PolicyVerificationResult(leaf, sctResults)); }
private bool Compare(IList <string> ruleValue, IList <string> customerValue) { var result = true; if (!ruleValue.IsNullOrEmpty()) { result = customerValue?.Any(x => ruleValue.Contains(x)) ?? false; } return(result); }
public TemaAçıklayıcı YazıdanTemaAçıklayıcıAl(string text) { var temaAçıklayıcı = JsonConvert.DeserializeObject <TemaAçıklayıcı>(text); if (_temaAçıklayıcı?.Any(descriptor => descriptor.SistemAdı.Equals(temaAçıklayıcı?.SistemAdı, StringComparison.InvariantCultureIgnoreCase)) ?? false) { throw new Exception($"'{temaAçıklayıcı.SistemAdı}' sistemadı zaten belirlendi"); } return(temaAçıklayıcı); }
public async Task <RulesResult> EvaluateRules(ProjectDefinition projectDefinition, IList <RecommendationRuleItem> rules) { // If there are no rules the recipe must be invalid so don't include it. if (false == rules?.Any()) { return(new RulesResult { Include = false }); } var availableTests = RecommendationTestFactory.LoadAvailableTests(); var results = new RulesResult { Include = true }; foreach (var rule in rules) { var allTestPass = true; foreach (var test in rule.Tests) { if (!availableTests.TryGetValue(test.Type, out var testInstance)) { throw new InvalidRecipeDefinitionException($"Invalid test type [{test.Type}] found in rule."); } var input = new RecommendationTestInput { Test = test, ProjectDefinition = projectDefinition, Session = _orchestratorSession }; allTestPass &= await testInstance.Execute(input); if (!allTestPass) { break; } } results.Include &= ShouldInclude(rule.Effect, allTestPass); var effectOptions = GetEffectOptions(rule.Effect, allTestPass); if (effectOptions != null) { if (effectOptions.PriorityAdjustment.HasValue) { results.PriorityAdjustment += effectOptions.PriorityAdjustment.Value; } } } return(results); }
public static List <int> Sort(IList <int> list) { if (list?.Any() != true) { return(new List <int>()); } MergeSort(list, 0, list.Count - 1); return(list.ToList()); }
/// <summary> /// Executes an ARM GET request, using the specified resource, suffix, and query string. /// For example, the following call gets the list of databases for an SQL Server resource: /// <code> /// List<JObject> databases = await ExecuteArmQueryAsync(sqlResource, "/databases", "api-version=2017-10-01-preview", cancellationToken); /// </code> /// </summary> /// <param name="resource">The resource for the request.</param> /// <param name="suffix">The resource suffix.</param> /// <param name="queryString">The query string.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>>A <see cref="Task{TResult}"/>, running the current operation, returning a list of all items returned.</returns> public async Task <List <JObject> > ExecuteArmQueryAsync(ResourceIdentifier resource, string suffix, string queryString, CancellationToken cancellationToken) { // Create the URI Uri nextLink = new Uri(this.baseUri, resource.ToResourceId() + suffix + "?" + queryString); List <JObject> allItems = new List <JObject>(); while (nextLink != null) { this.tracer.TraceVerbose($"Sending a request to {nextLink}"); HttpResponseMessage response = await this.httpRetryPolicy.RunAndTrackDependencyAsync( this.tracer, DependencyName, "ExecuteArmQueryAsync", async() => { var request = new HttpRequestMessage(HttpMethod.Get, nextLink); // Set the credentials await this.credentials.ProcessHttpRequestAsync(request, cancellationToken); // Send request and get the response as JObject return(await this.httpClientWrapper.SendAsync(request, TimeSpan.FromMinutes(HttpRequestTimeoutInMinutes), cancellationToken)); }); if (!response.IsSuccessStatusCode) { this.tracer.TraceError($"Query returned an error; Status code: {response.StatusCode}"); throw new HttpRequestException($"Query returned an error code {response.StatusCode}"); } string responseContent = await response.Content.ReadAsStringAsync(); JObject responseObject = JObject.Parse(responseContent); const string valueKey = "value"; IList <JObject> returnedObjects = null; if (responseObject.ContainsKey(valueKey)) { returnedObjects = responseObject[valueKey].ToObject <List <JObject> >(); allItems.AddRange(returnedObjects); } else { allItems.Add(responseObject); } // Link to next page string nextLinkToken = responseObject.GetValue("nextLink", StringComparison.InvariantCulture)?.ToString(); nextLink = (string.IsNullOrWhiteSpace(nextLinkToken) || !(returnedObjects?.Any() ?? false)) ? null : new Uri(nextLinkToken); } return(allItems); }
/// <summary>Creates a primitive parameter for the given parameter information reflection object.</summary> /// <param name="name">The name.</param> /// <param name="description">The description.</param> /// <param name="parameterType">Type of the parameter.</param> /// <param name="parentAttributes">The parent attributes.</param> /// <returns></returns> public async Task <SwaggerParameter> CreatePrimitiveParameterAsync(string name, string description, Type parameterType, IList <Attribute> parentAttributes) { var typeDescription = JsonObjectTypeDescription.FromType(parameterType, ResolveContract(parameterType), parentAttributes, _settings.DefaultEnumHandling); SwaggerParameter operationParameter; if (typeDescription.IsEnum) { // TODO(incompatibility): We use "schema" even it is not allowed in non-body parameters parameterType = parameterType.Name == "Nullable`1" ? parameterType.GetGenericTypeArguments().Single() : parameterType; operationParameter = new SwaggerParameter { Type = typeDescription.Type, // Used as fallback for generators which do not check the "schema" property Schema = new JsonSchema4 { SchemaReference = await _schemaGenerator.GenerateAsync(parameterType, parentAttributes, _schemaResolver).ConfigureAwait(false) } }; } else { var hasTypeMapper = _settings.TypeMappers.Any(tm => tm.MappedType == parameterType); if (!hasTypeMapper) { parameterType = typeDescription.Type.HasFlag(JsonObjectType.Object) ? typeof(string) : parameterType; // object types must be treated as string } operationParameter = await _schemaGenerator.GenerateAsync <SwaggerParameter>(parameterType, parentAttributes, _schemaResolver).ConfigureAwait(false); _schemaGenerator.ApplyPropertyAnnotations(operationParameter, new Newtonsoft.Json.Serialization.JsonProperty(), parameterType, parentAttributes, typeDescription); // check if the type mapper did not properly change the type to a primitive if (hasTypeMapper && typeDescription.Type.HasFlag(JsonObjectType.Object) && operationParameter.Type == JsonObjectType.Object) { operationParameter.Type = JsonObjectType.String; // enforce string as default } } operationParameter.Name = name; operationParameter.IsRequired = parentAttributes?.Any(a => a.GetType().Name == "RequiredAttribute") ?? false; operationParameter.IsNullableRaw = typeDescription.IsNullable; if (typeDescription.Type.HasFlag(JsonObjectType.Array)) { operationParameter.CollectionFormat = SwaggerParameterCollectionFormat.Multi; } if (description != string.Empty) { operationParameter.Description = description; } return(operationParameter); }
internal void InjectData(IList <ItemFeed> feeds) { if (feeds?.Any() == true) { foreach (var item in items) { var feed = feeds.FirstOrDefault(f => f.Key.Equals(item.DataContext) || f.Key.Equals(item.GetHashCode())); item.UpdateWith(feed); } } }
private static bool AllAreGroupElementsSameParent(IList <Element> elements) { if (elements?.Any() == false)//must be at least 1. { return(false); } if (!SameParent(elements)) { return(false); } return(elements.Count() == elements.OfType <GroupElement>().Count()); }
public ImageRef OpenImages(IList <Image> images) { if (images?.Any() != true) { return(null); } var imageRef = new ImageRef(images, this); ImagePreviewOpened?.Invoke(imageRef); return(imageRef); }
private async Task AddUserAndTbServices(User user, IList <TBService> tbServices) { user.IsCaseManager = tbServices?.Any() ?? false; user.CaseManagerTbServices = tbServices? .Select(tbs => new CaseManagerTbService { TbService = tbs, CaseManager = user }) .ToList(); _context.User.Add(user); await _context.SaveChangesAsync(); }
/// <summary> /// Get theme descriptor from the description text /// </summary> /// <param name="text">Description text</param> /// <returns>Theme descriptor</returns> public ThemeDescriptor GetThemeDescriptorFromText(string text) { //get theme description from the JSON file var themeDescriptor = JsonConvert.DeserializeObject <ThemeDescriptor>(text); //some validation if (_themeDescriptors?.Any(descriptor => descriptor.SystemName.Equals(themeDescriptor?.SystemName, StringComparison.InvariantCultureIgnoreCase)) ?? false) { throw new Exception($"A theme with '{themeDescriptor.SystemName}' system name is already defined"); } return(themeDescriptor); }
internal Predicate <object> CreatePredicate(IList <DataGridFilterColumnControl> columnFilters) { if (columnFilters?.Any() != true) { return(_globalFilter); } if (_globalFilter == null) { return(item => columnFilters.All(filter => filter.Matches(item))); } return(item => _globalFilter(item) && columnFilters.All(filter => filter.Matches(item))); }
public static CustomResponse WithAvailableStores(this CustomResponse customResponse, IList <int> selectedStores = null) { var availableStores = SelectListHelper.GetAvailableStores().Select(x => { if (selectedStores?.Any(y => y.ToString() == x.Value) ?? false) { x.Selected = true; } return(x); }).ToList(); return(customResponse.With("availableStores", availableStores)); }
private decimal CalculateTotalSalesVolume( IList <Order> activeFulfilledTradeOrders) { if (!activeFulfilledTradeOrders?.Any() ?? true) { return(0); } return(activeFulfilledTradeOrders .Where(afto => afto.OrderDirection == OrderDirections.SELL || afto.OrderDirection == OrderDirections.SHORT) .Select(afto => afto.OrderFilledVolume.GetValueOrDefault(0)) .Sum()); }
/// <summary> /// The calculate total purchase volume. /// </summary> /// <param name="activeFulfilledTradeOrders"> /// The active fulfilled trade orders. /// </param> /// <returns> /// The <see cref="decimal"/>. /// </returns> private decimal CalculateTotalPurchaseVolume(IList <Order> activeFulfilledTradeOrders) { if (!activeFulfilledTradeOrders?.Any() ?? true) { return(0); } return(activeFulfilledTradeOrders .Where(_ => _.OrderDirection == OrderDirections.BUY || _.OrderDirection == OrderDirections.COVER) .Select(_ => _.OrderFilledVolume.GetValueOrDefault(0)) .Sum()); }
public static List <int> Sort(IList <int> arr) { if (arr?.Any() != true) { return(new List <int>()); } var list = arr.ToList(); MakeHeap(list, list.Count); SortHeap(list); return(list); }
private static void AddRolePolicies(this IServiceCollection services, IList <RolePolicy> rolePolicies, string[] schemes) { if (!(rolePolicies?.Any() ?? false)) { return; } rolePolicies.Execute(r => { if (r.Groups.Any()) { services.AddAlternativeRolesPolicy(r.Name, r.Groups.ToArray(), schemes); } }); }
private IQueryable <T> ApplyOrderBy(IQueryable <T> queryable, IList <Sort> order) { if (order?.Any() == true) { var isOrdered = IsOrdered(queryable); foreach (var x in order) { queryable = isOrdered ? ((IOrderedQueryable <T>)queryable).ThenBy($"{x.Field} {x.Direction}") : queryable.OrderBy($"{x.Field} {x.Direction}"); isOrdered = true; } } return(queryable); }
/// <summary> /// determines if some of the submitted items can be added to the collection and returns a collection of these items /// </summary> /// <param name="baseCollection">The base collection.</param> /// <param name="newItems">The new items.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// CanAddRange can't return a result. There were no valid parameters - newItems /// or /// CanAddRange can't return a result. There were no valid parameters - baseCollection /// </exception> public static IEnumerable <IMediaItem> CanAddRange(this IList <IMediaItem> baseCollection, IList <IMediaItem> newItems) { if (newItems?.Any() != true) { throw new ArgumentNullException("CanAddRange can't return a result. There were no valid parameters", nameof(newItems)); } if (baseCollection == null) { throw new ArgumentNullException("CanAddRange can't return a result. There were no valid parameters", nameof(baseCollection)); } var excludedIDs = new HashSet <int>(baseCollection.Select(p => p.Id)); return(newItems.Where(p => !excludedIDs.Contains(p.Id))); }
/// <summary> /// determines if some of the submitted items can be added to the collection and returns a collection of these items /// </summary> /// <param name="baseCollection">The base collection.</param> /// <param name="newItems">The new items.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// CanAddRange can't return a result. There were no valid parameters - newItems /// or /// CanAddRange can't return a result. There were no valid parameters - baseCollection /// </exception> public static IEnumerable <IMediaItem> CanAddRange(this IList <IMediaItem> baseCollection, IList <IMediaItem> newItems) { if (baseCollection == null) { throw new ArgumentNullException(nameof(baseCollection), $"{nameof(baseCollection)} {Resources.IsRequired}"); } if (newItems?.Any() != true) { throw new ArgumentNullException(nameof(newItems), $"{nameof(newItems)} {Resources.IsRequired}"); } var excludedIDs = new HashSet <int>(baseCollection.Select(p => p.Id)); return(newItems.Where(p => !excludedIDs.Contains(p.Id))); }
public async Task CreateManyAsync(IList <IEvent> e) { if (!e?.Any() ?? true) { return; } if (e.Count == 1) { await CreateAsync(e.First()); return; } var entities = e.Where(ev => ev is EventTableEntity).Select(ev => ev as EventTableEntity); var entityGroups = entities.GroupBy(ent => ent.PartitionKey); foreach (var group in entityGroups) { var groupEntities = group.ToList(); if (groupEntities.Count == 1) { await CreateEntityAsync(groupEntities.First()); continue; } // A batch insert can only contain 100 entities at a time var iterations = groupEntities.Count / 100; for (var i = 0; i <= iterations; i++) { var batch = new TableBatchOperation(); var batchEntities = groupEntities.Skip(i * 100).Take(100); if (!batchEntities.Any()) { break; } foreach (var entity in batchEntities) { batch.InsertOrReplace(entity); } await _table.ExecuteBatchAsync(batch); } } }
private void DrawSliderPoints(IList <ChartValueItemParam> valueItems, SKCanvas canvas, SKRect chart) { if (valueItems?.Any() != true) { return; } float x = chart.GetInsideXValue(TouchedPoint.X); // Draws circle on y axis // using (var paint = new SKPaint { Style = SKPaintStyle.Stroke, StrokeWidth = 4 }) { foreach (var item in valueItems) { paint.Color = item.BackgroundColor.ToSKColor(); if (LineMode == LineMode.Straight) { var y = ChartCalculator.CalculateYPositionForStraight(item.ChartValueItem, item.NextChartValueItem, x); canvas.DrawCircle(x, y, SliderPointSize, paint); paint.Color = SKColors.White; canvas.DrawCircle(x, y, SliderPointSize / 4, paint); } else if (LineMode == LineMode.Spline) { var point = ChartCalculator.CalculateYPositionForSpline(item.ChartValueItem, item.NextChartValueItem, x); paint.Style = SKPaintStyle.Stroke; canvas.DrawCircle(point.X, point.Y, SliderPointSize, paint); //paint.Color = SKColors.White; paint.Style = SKPaintStyle.Fill; canvas.DrawCircle(point.X, point.Y, SliderPointSize / 2, paint); } } } }