/// <summary> /// Calculates the harmonic mean of the given numbers. /// The harmonic mean is defined as zero if at least one of the numbers is zero. /// </summary> /// <param name="numbers">The numbers whose harmonic mean is to be calculated.</param> /// <returns>The harmonic mean of the given numbers.</returns> /// <exception cref="System.InvalidOperationException"> /// The specified collection must not contain negative numbers and must not be empty. /// </exception> /// <exception cref="System.ArgumentNullException"> /// The specified collection must not be null. /// </exception> public static double HarmonicMean(IEnumerable<double> numbers) { if (numbers == null) { throw ArgumentNullException; } if (!numbers.Any()) { throw EmptyNumbersCollectionException; } if (numbers.Any(number => number < 0)) { throw CollectionContainingNegativeNumbersException; } if (numbers.Contains(0)) { // If one of the values strives against zero the limiting value of the harmonic mean does, too. // Therefore, it is sensible to define the harmonic mean as being zero if at least one of the values is zero. return 0; } double sumOfReciprocalValues = numbers.Sum(number => 1.0 / number); double harmonicMean = numbers.Count() / sumOfReciprocalValues; return harmonicMean; }
/// <summary> /// Gets the common prefix. /// </summary> /// <param name="values">The values.</param> /// <returns></returns> public static string GetCommonPrefix(IEnumerable<string> values) { if (values == null) { throw new ArgumentNullException("values"); } if (!values.Any()) { return null; } string commonPrefix = string.Empty; char[] firstValueChars = values.First().ToCharArray(); foreach (var currentChar in firstValueChars) { string currentPrefix = commonPrefix + currentChar; if (values.Any(v => !v.StartsWith(currentPrefix))) { return commonPrefix; } else { commonPrefix = currentPrefix; } } return commonPrefix; }
public bool ConflictsWith(Type eventToCheck, IEnumerable<Type> previousEvents) { var boundConflicts = false; var unboundConflicts = false; if (_conflictRegister.ContainsKey(eventToCheck)) { boundConflicts = previousEvents.Any( previousEvent => _conflictRegister[eventToCheck].Any(et => et == previousEvent)); } if (eventToCheck.GetTypeInfo().IsGenericType && _conflictRegister.ContainsKey(eventToCheck.Unbind())) { var unboundEventToCheck = eventToCheck.Unbind(); var eventToCheckGenericType = eventToCheck.GenericTypeArguments[0]; unboundConflicts = previousEvents.Any( previousEvent => _conflictRegister[unboundEventToCheck].Any( et => et.MakeGenericType(eventToCheckGenericType) == previousEvent)); } return boundConflicts || unboundConflicts; }
public TransactionDetailsViewItem(Model.Transaction transaction, IEnumerable<Model.TransactionItem> transactionItems, IEnumerable<Model.TransactionIgnoredItem> transactionIgnoredItems, IEnumerable<Model.License> domainlessLicenseQuery, IEnumerable<Model.License> customerapplessLicenseQuery) : base(transaction) { PurchaserEmail = transaction.PurchaserEmail; PurchaserName = (transactionItems.Any(l => l.License != null)) ? transactionItems.FirstOrDefault().License.PurchasingCustomer.Name : transaction.PurchaserName; OwnerName = (transactionItems.Any(l => l.License != null)) ? transactionItems.FirstOrDefault().License.OwningCustomer.Name : "None"; SKUSummary = (from x in transactionItems select x.Sku).ToSummary(x => x.SkuCode, 99, ", "); IgnoredSummary = (from x in transactionIgnoredItems select x.Description).ToSummary(x => x, 99, ", "); StatusName = transaction.Status.GetDescription<Model.TransactionStatus>(); DomainlessLicenses = (from x in domainlessLicenseQuery select x.ObjectId).ToList(); CustomerapplessLicenses = (from x in customerapplessLicenseQuery select x.ObjectId).ToList(); }
public static IEnumerable<TestDefinition> Generate(IEnumerable<NodeBase> nodes) { if (nodes == null) return null; var nodeIds = nodes.Select(n => n.Id); var distinctNodeIds = nodeIds.Distinct(); if (nodeIds.Count() != distinctNodeIds.Count()) throw new ArgumentException("Duplicate Node IDs detected"); if (nodes.Any(n => n.EntranceEdges.Count == 0 && n.ExitEdges.Count == 0)) { // TODO: Log warning } if (nodes.Any(n => n.EntranceEdges.Any(ee => !nodes.Any(n2 => n2.Id == ee.Key)))) throw new ArgumentException("Entrance edge found with ID, but no node with matching ID found"); if (nodes.Any(n => n.ExitEdges.Any(ee => !nodes.Any(n2 => n2.Id == ee.Key)))) throw new ArgumentException("Exit edge found with ID, but no node with matching ID found"); var testDefinitions = new List<TestDefinition>(); foreach (var node in nodes.Where(n => n.IsStartingPoint)) { testDefinitions.AddRange(GetTestDefinitions(node, nodes, new List<NodeBase>())); } return testDefinitions; }
private static IEnumerable<LaneModel> GetOrderedLanes(IEnumerable<LaneModel> laneStats) { var orderedLaneStats = new List<LaneModel>(); Func<LaneModel, bool> backLogPred = x => x.ClassType == LaneClassType.Backlog && x.Relation != "child"; Func<LaneModel, bool> activePred = x => x.ClassType == LaneClassType.Active; Func<LaneModel, bool> archivePred = x => x.ClassType == LaneClassType.Archive && x.Relation != "child"; if (laneStats.Any(backLogPred)) { orderedLaneStats.AddRange(laneStats.Where(backLogPred).OrderBy(x => x.Index)); } if (laneStats.Any(activePred)) { orderedLaneStats.AddRange(laneStats.Where(activePred).OrderBy(x => x.Index)); } if (laneStats.Any(archivePred)) { orderedLaneStats.AddRange(laneStats.Where(archivePred).OrderBy(x => x.Index)); } return orderedLaneStats; }
/// <summary> /// Adds specific destinations to a claim. /// </summary> /// <param name="claim">The <see cref="Claim"/> instance.</param> /// <param name="destinations">The destinations.</param> public static Claim SetDestinations(this Claim claim, IEnumerable<string> destinations) { if (claim == null) { throw new ArgumentNullException(nameof(claim)); } if (destinations == null || !destinations.Any()) { claim.Properties.Remove(Properties.Destinations); return claim; } if (destinations.Any(destination => destination.Contains(" "))) { throw new ArgumentException("Destinations cannot contain spaces.", nameof(destinations)); } //claim.Properties[Properties.Destinations] = // string.Join(" ", destinations.Distinct(StringComparer.Ordinal)); //TODO chage destination with destinations in rc 2 claim.Properties[Properties.Destination] = string.Join(" ", destinations.Distinct(StringComparer.Ordinal)); return claim; }
/// <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; }
/// <summary> /// Gets the longest common directory of the given paths. /// </summary> /// <param name="files">The files.</param> /// <returns>The longest common directory of the given paths.</returns> internal static string GetCommonDirectory(IEnumerable<string> files) { if (files == null) { throw new ArgumentNullException("files"); } if (!files.Any()) { return null; } string commonPrefix = string.Empty; char[] firstValueChars = files.First().ToCharArray(); foreach (var currentChar in firstValueChars) { string currentPrefix = commonPrefix + currentChar; if (files.Any(v => !v.StartsWith(currentPrefix, StringComparison.OrdinalIgnoreCase))) { return commonPrefix; } else { commonPrefix = currentPrefix; } } return commonPrefix.Substring(0, commonPrefix.LastIndexOf('\\') + 1); }
public static void ProcessCompilerResults(IEnumerable<CompilerResult> results) { var errors = results.Where(r => r.HasErrors).SelectMany(r => r.Errors); var clean = results.Where(r => !r.HasErrors).Select(r => r.FileName); if (errors.Any()) { TableDataSource.Instance.AddErrors(errors); } if (results.Any(r => r.HasErrors)) { if (results.Any(r => r.Errors.Any(e => !e.IsWarning))) { WebCompilerPackage._dte.StatusBar.Text = "Error compiling. See Error List for details"; TableDataSource.Instance.BringToFront(); } else { WebCompilerInitPackage.StatusText($"Compiled with warnings"); } } else { WebCompilerInitPackage.StatusText($"Compiled successfully"); } TableDataSource.Instance.CleanErrors(clean); }
public TryStatementAst(IScriptExtent extent, StatementBlockAst body, IEnumerable<CatchClauseAst> catchClauses, StatementBlockAst @finally) : base(extent) { if (body == null) { throw PSTraceSource.NewArgumentNullException("body"); } if (((catchClauses == null) || !catchClauses.Any<CatchClauseAst>()) && (@finally == null)) { throw PSTraceSource.NewArgumentException("catchClauses"); } this.Body = body; base.SetParent(body); if ((catchClauses != null) && catchClauses.Any<CatchClauseAst>()) { this.CatchClauses = new ReadOnlyCollection<CatchClauseAst>(catchClauses.ToArray<CatchClauseAst>()); base.SetParents((IEnumerable<Ast>) this.CatchClauses); } else { this.CatchClauses = EmptyCatchClauses; } if (@finally != null) { this.Finally = @finally; base.SetParent(@finally); } }
public IHttpActionResult Batch(IEnumerable<Recipe> recipes) { if (!recipes.Any()) return StatusCode(HttpStatusCode.NotModified); if (_shellSettings.Name != ShellSettings.DefaultName && recipes.Any(recipe => recipe.TenantName != _shellSettings.Name)) { return BadRequest(T("You can't execute recipes for other tenants on other than the Default tenant.").Text); } try { foreach (var recipe in recipes) { _recipeExecutor.ExecuteRecipe(recipe); } } catch (Exception ex) { if (ex.IsFatal()) throw; return InternalServerError(ex); } return Ok(); }
public static void RequireArgumentNotEmptyAndNonEmptyItems( string argumentName, IEnumerable<string> argumentValue) { if (!argumentValue.Any()) { throw new ArgumentException("Cannot be empty", argumentName); } if (argumentValue.Any(item => string.IsNullOrWhiteSpace(item))) { throw new ArgumentException("Items cannot be empty", argumentName); } }
public static IEnumerable<string> GetRootPaths(IEnumerable<string> directoryNames) { if ((directoryNames == null) || !directoryNames.Any() || directoryNames.Any(dn => string.IsNullOrEmpty(dn))) throw new ArgumentNullException("fileNames"); var fullDirectoryNames = directoryNames.Select(dn => Path.GetFullPath(dn)); if (fullDirectoryNames.Any(fn => Path.GetPathRoot(fn) == null)) throw new ArgumentException("all file names must contain a root path", "fileNames"); // IEnumerable<IGrouping<string, string>> var fullDirectoryNamesByRoot = fullDirectoryNames .GroupBy(fn => Path.GetPathRoot(fn).ToLower()) .OrderBy(g => g.Key) .ToList(); var result = new List<string>(); foreach (var group in fullDirectoryNamesByRoot) { var rootResult = group.Key; int minLength = group.Min(dn => dn.Length); for (int i = group.Key.Length; i < minLength; i++) { if (!group.All(dn => string.Equals(dn.Substring(0, i), group.First().Substring(0, i), StringComparison.InvariantCultureIgnoreCase))) break; char c = group.First()[i]; if (c == Path.DirectorySeparatorChar) rootResult = group.First().Substring(0, i + 1); } result.Add(rootResult); } return result; }
/// <summary> /// Calculates the geometric mean of the given numbers. /// </summary> /// <param name="numbers">The numbers whose geometric mean is to be calculated.</param> /// <returns>The geometric mean of the given numbers.</returns> /// <exception cref="System.InvalidOperationException"> /// The collection must not contain negative numbers and must not be empty. /// </exception> /// <exception cref="System.ArgumentNullException"> /// The specified collection must not be null. /// </exception> public static double GeometricMean(IEnumerable<double> numbers) { if (numbers == null) { throw ArgumentNullException; } if (!numbers.Any()) { throw EmptyNumbersCollectionException; } if (numbers.Any(number => number < 0)) { throw CollectionContainingNegativeNumbersException; } double productOfNumbers = 1; foreach (double number in numbers) { productOfNumbers *= number; } double numbersCount = numbers.Count(); double exponent = 1.0 / numbersCount; double geometricMean = Math.Pow(productOfNumbers, exponent); return geometricMean; }
public static bool IsPotentialBindingClass(IEnumerable<string> attributeTypeNames) { #if WINRT return attributeTypeNames.Any(attr => attr.Equals(BINDING_ATTR, StringComparison.Ordinal)); #else return attributeTypeNames.Any(attr => attr.Equals(BINDING_ATTR, StringComparison.InvariantCulture)); #endif }
private IEnumerable<IDbDataParameter> CreateParameters(IDbCommand command, IEnumerable<object> parameterValues) { if (!parameterValues.Any(pv => pv != null)) return Enumerable.Empty<IDbDataParameter>(); return parameterValues.Any(o => o is IEnumerable && !(o is string)) || parameterValues.Any(o => o is IRange) ? parameterValues.SelectMany((v,i) => CreateParameters(command, _parameters[i], v)) : parameterValues.Select((v, i) => CreateParameter(command, _parameters[i], v)); }
public static bool ContainsAny(this string haystack, IEnumerable<string> needles) { if (haystack == null) throw new ArgumentNullException("haystack"); if (!string.IsNullOrEmpty(haystack) || needles.Any()) { return needles.Any(haystack.Contains); } return false; }
public static bool ContainsAny(this string haystack, StringComparison comparison, IEnumerable<string> needles) { if (haystack == null) throw new ArgumentNullException("haystack"); if (!string.IsNullOrEmpty(haystack) || needles.Any()) { return needles.Any(value => haystack.IndexOf(value, comparison) >= 0); } return false; }
public static IQueryable<EventOccurrenceDate> FilterByKeywords(this IQueryable<EventOccurrenceDate> objectSet, IEnumerable<string> keywords) { if (keywords != null && keywords.Any()) { objectSet = objectSet.Where(e => keywords.Any(k => e.EventOccurrence.Event.Keywords.Contains(k))); } return objectSet; }
private bool IsRegionAvailable(string value, IEnumerable<RegionResponse> regions) { // ReSharper disable PossibleMultipleEnumeration if (regions.Any(x => x.Name.Is(value))) return true; if (regions.Any(x => IsRegionAvailable(value, x.Regions))) return true; return false; // ReSharper restore PossibleMultipleEnumeration} }
internal ForeignKeyConstraintConfiguration(IEnumerable<PropertyInfo> dependentProperties) { DebugCheck.NotNull(dependentProperties); Debug.Assert(dependentProperties.Any()); Debug.Assert(!dependentProperties.Any(p => p == null)); _dependentProperties.AddRange(dependentProperties); _isFullySpecified = true; }
public FunctionExportProvider(Assembly assembly, IEnumerable<Type> delegateTypes) { if (assembly == null) throw new ArgumentNullException("assembly"); if (delegateTypes == null) throw new ArgumentNullException("delegateTypes"); if (!delegateTypes.Any()) throw new ArgumentException("Must specify at least one delegate type."); if (delegateTypes.Any(t => !typeof(Delegate).IsAssignableFrom(t))) throw new NotSupportedException("Only delegate types are supported."); _assembly = assembly; _delegateTypes = delegateTypes; }
public void Create(IEnumerable<IBenchmark> benchmarks, IEnumerable<BenchmarkResult> benchmarkResults) { using (var fileStream = new FileStream("../../../README.md", FileMode.Create)) { using (var writer = new StreamWriter(fileStream)) { writer.WriteLine("Ioc Performance"); writer.WriteLine("==============="); writer.WriteLine(string.Empty); writer.WriteLine("Source code of my performance comparison of the most popular .NET IoC containers: "); writer.WriteLine("[www.palmmedia.de/Blog/2011/8/30/ioc-container-benchmark-performance-comparison](http://www.palmmedia.de/Blog/2011/8/30/ioc-container-benchmark-performance-comparison)"); writer.WriteLine(string.Empty); writer.WriteLine("Author: Daniel Palme "); writer.WriteLine("Blog: [www.palmmedia.de](http://www.palmmedia.de) "); writer.WriteLine("Twitter: [@danielpalme](http://twitter.com/danielpalme) "); writer.WriteLine(string.Empty); writer.WriteLine("Results"); writer.WriteLine("-------"); writer.WriteLine("### Explantions"); writer.WriteLine("**First value**: Time of single-threaded execution in [ms] "); writer.WriteLine("**Second value**: Time of multi-threaded execution in [ms] "); if (benchmarkResults.Any(b => b.SingleThreadedResult.ExtraPolated || b.MultiThreadedResult.ExtraPolated)) { writer.WriteLine("**_*_**: Benchmark was stopped after 3 minutes and result is extrapolated. "); } if (benchmarkResults.Any(b => b.SingleThreadedResult.Error == "OoM" || b.MultiThreadedResult.Error == "OoM")) { writer.WriteLine("**OoM**: Benchmark was stopped after an *OutOfMemoryException* was thrown. "); } if (benchmarkResults.Any(b => b.SingleThreadedResult.Error == "OoM" || b.MultiThreadedResult.Error == "OoM")) { writer.WriteLine("**Error**: Benchmark was stopped after an *Exception* was thrown. "); } writer.WriteLine("### Basic Features"); this.WriteBenchmarks(writer, benchmarks.Where(b => b.GetType().FullName.Contains("Basic")), benchmarkResults); writer.WriteLine("### Advanced Features"); this.WriteBenchmarks(writer, benchmarks.Where(b => b.GetType().FullName.Contains("Advanced")), benchmarkResults); writer.WriteLine("### Prepare"); this.WriteBenchmarks(writer, benchmarks.Where(b => b.GetType().FullName.Contains("Prepare")), benchmarkResults); writer.WriteLine("### Charts"); writer.WriteLine(""); writer.WriteLine(""); writer.WriteLine(""); } } }
public void Any(IEnumerable<int> source, Func<int, bool> predicate, bool expected) { if (predicate == null) { Assert.Equal(expected, source.Any()); } else { Assert.Equal(expected, source.Any(predicate)); } }
private static void CheckPatterns(IEnumerable<string> patterns) { if (patterns.Any(s => s.Contains('\\'))) { Logger.LogInfo("NOTE that `\\` in glob pattern is used as Escape character. DONOT use it as path separator."); } if (patterns.Any(s => s.Contains("../"))) { Logger.LogWarning("NOTE that `../` is currently not supported in glob pattern, please use `../` in `src` option instead."); } }
public static bool BetweenXCheck(Chuzzle chuzzle, IEnumerable<Chuzzle> allChuzzles) { var firstChuzzle = chuzzle; var secondChuzzle = allChuzzles.FirstOrDefault( ch => ch.Current.Y == firstChuzzle.Current.Y && ch.Current.X == firstChuzzle.Current.X + 2 && IsSameColor(ch, firstChuzzle)); if (secondChuzzle == null || allChuzzles.Any(x => x.Current.X == firstChuzzle.Current.X + 1 && IsLock(x))) return false; return allChuzzles.Any(x => x.Current.X == firstChuzzle.Current.X + 1 && IsSameColor(x, firstChuzzle) && !IsLock(x)); }
public void PopulateContextEntries(IEnumerable<string> contexts, List<CacheContextEntry> entries) { // User is a more generic dependency if (contexts.Any(ctx => String.Equals(ctx, "user", StringComparison.OrdinalIgnoreCase))) { return; } if (contexts.Any(ctx => String.Equals(ctx, "user.roles", StringComparison.OrdinalIgnoreCase))) { // TODO: Add actual roles entries.Add(new CacheContextEntry("administrator", "0")); } }
public static IEnumerable<string> Tokenize(string actionExpr, IEnumerable<Tuple<char, char>> depthOpenCloses, IEnumerable<string> keywords) { int depth = 0; int lastIndex = 0; List<string> ret = new List<string>(); for (int i = 0; i < actionExpr.Length; i++) { char c = actionExpr[i]; if (depthOpenCloses.Any(x => c == x.item1)) { if (depth == 0) { ret.AddRange(CutFront(actionExpr, ref lastIndex, i, 1)); } ++depth; } else if (depthOpenCloses.Any(x => c == x.item2)) { --depth; if (depth == 0) { ret.AddRange(CutFront(actionExpr, ref lastIndex, i, 1)); } } else { if (depth == 0) { foreach (var entity in keywords) { if (i + entity.Length <= actionExpr.Length) { if (actionExpr.Substring(i, entity.Length) == entity) { ret.AddRange(CutFront(actionExpr, ref lastIndex, i, entity.Length)); break; } } } } } } return ret.Select(x => x.Trim()).Where(x => x.Length > 0); }
public static IEnumerable<NamedRoute> GetRoutesForCurrentRequest(RouteCollection routes,IEnumerable<INavigationRouteFilter> routeFilters) { var navigationRoutes = routes.OfType<NamedRoute>().Where(r=> !r.IsChild).ToList(); if (routeFilters.Any()) { foreach (var route in navigationRoutes.ToArray()) { if (routeFilters.Any(filter => filter.ShouldRemove(route))) { navigationRoutes.Remove(route); } } } return navigationRoutes; }