internal static void WriteHistory(IEnumerable<IEvent> history, RoomieCommandInterpreter interpreter) { var headers = new[] {"Time Stamp", "Entity", "Type", "Source", ""}; var tableBuilder = new TextTable(new int[] { Math.Max(history.Max(x => x.TimeStamp.ToLocalTime().ToString().Length), headers[0].Length), Math.Max(history.Max(x => ((x.Entity == null || x.Entity.Name == null) ? string.Empty : x.Entity.Name).Length), headers[1].Length), Math.Max(history.Max(x => ((x.Type == null) ? string.Empty : x.Type.Name).Length), headers[2].Length), Math.Max(history.Max(x => ((x.Source == null || x.Source.Name == null) ? string.Empty : x.Source.Name).Length), headers[3].Length), ExtraLength(history) }); interpreter.WriteEvent(tableBuilder.StartOfTable(headers)); foreach (var @event in history) { var extra = GetExtra(@event); var line = tableBuilder.ContentLine( @event.TimeStamp.ToLocalTime().ToString(), (@event.Entity == null) ? string.Empty : @event.Entity.Name, (@event.Type == null) ? string.Empty : @event.Type.Name, (@event.Source == null) ? string.Empty : @event.Source.Name, extra ); interpreter.WriteEvent(line); } interpreter.WriteEvent(tableBuilder.EndOfTable()); }
protected bool ChunkIsStable(IEnumerable<Zipping.Pair<int, int>> points) { const int maxVariance = 50; var xVariance = points.Max(p => p.First) - points.Min(p => p.First); var yVariance = points.Max(p => p.Second) - points.Min(p => p.Second); return xVariance < maxVariance && yVariance < maxVariance; }
protected bool ChunkIsStable(IEnumerable<Point> points) { const int maxVariance = 50; var xVariance = points.Max(p => p.X) - points.Min(p => p.Y); var yVariance = points.Max(p => p.X) - points.Min(p => p.Y); return xVariance < maxVariance && yVariance < maxVariance; }
public static BoundingBox MinimumOf(IEnumerable<BoundingBox> boxes) { decimal northmost = boxes.Max(b => b.North); decimal southmost = boxes.Min(b => b.South); decimal eastmost = boxes.Max(b => b.East); decimal westmost = boxes.Min(b => b.West); return new BoundingBox { North = northmost, South = southmost, East = eastmost, West = westmost }; }
public SlidingBlockType(IEnumerable<Point> subBlocks, int typeID) { SubBlocks = new ObservableCollection<Point>(subBlocks); if (subBlocks.Any()) // If sequence is not empty { SizeX = subBlocks.Max(t => t.X) + 1; SizeY = subBlocks.Max(t => t.Y) + 1; TypeID = typeID; } }
public static Bitmap Overlay(IEnumerable<Bitmap> bmps, Bitmap.Config config = null) { int width = bmps.Max<Bitmap>(x => x.Width); int height = bmps.Max<Bitmap>(x => x.Height); Bitmap bmOverlay = Bitmap.CreateBitmap(width, height, config == null ? Bitmap.Config.Argb8888 : config); Canvas canvas = new Canvas(bmOverlay); foreach (var bmp in bmps) canvas.DrawBitmap(bmp, 0, 0, null); canvas.Dispose(); return bmOverlay; }
public void SetPlotModelAxes( IEnumerable<DataPoint> seriesPoints, string xAxisTitle, string yAxisTitle) { double minXVal = seriesPoints.Min<DataPoint>(dp => dp.X); double maxXVal = seriesPoints.Max<DataPoint>(dp => dp.X); double minYVal = seriesPoints.Min<DataPoint>(dp => dp.Y); double maxYVal = seriesPoints.Max<DataPoint>(dp => dp.Y); PlotType = PlotType.XY; SetXAxisForPlotModel(minXVal, maxXVal, xAxisTitle); SetYAxisForPlotModel(minYVal, maxYVal, yAxisTitle); }
public OctreeLookup(IEnumerable<float[]> points) { tree = new Octree( points.Max(p => p[0]), points.Min(p => p[0]), points.Max(p => p[1]), points.Min(p => p[1]), points.Max(p => p[2]), points.Min(p => p[2]), points.Count()); foreach (var p in points) tree.AddNode(p[0], p[1], p[2], p); }
// takes meta data from the first series public ISignalSeries Create( IEnumerable<ISignalSeries> signals ) { if ( !signals.Any() ) { return SignalSeries.Null; } var dateSignalsMap = CreateDateSignalsMap( signals ); int expectedSignalCount = signals.Count(); InterpolateMissingSignals( dateSignalsMap, expectedSignalCount ); var combinedSignals = GenerateCombinedSignals( dateSignalsMap ); var masterInputSeries = signals.FirstOrDefault( s => s.Reference.Identifier.Type.Name == DatumNames.Prices ); if ( masterInputSeries == null ) { // then lets take the reference with max points var maxPoints = signals.Max( s => s.Count); masterInputSeries = signals.First( s => s.Count == maxPoints ); // throw new Exception( "We could not find any signal series which seem to reference raw prices" ); } var identifier = new SeriesIdentifier( masterInputSeries.Identifier.Owner, new ObjectDescriptor( "Combined" ), signals.Select( s => s.Identifier ).ToArray() ); var series = new SignalSeries( masterInputSeries.Reference, identifier, combinedSignals ); return series; }
private void RefreshPlayerByList(IEnumerable<PlayerInfo> players) { foreach (var player in players.ToList()) { var playerViewModel = Players.FirstOrDefault(p => p.Index == player.Index); if (playerViewModel == null) { Players.Add(new PlayersViewModel { Index = player.Index, Name = player.Name, Duration = player.Duration, }); } else { playerViewModel.Name = player.Name; playerViewModel.Score = player.Score; playerViewModel.Duration = player.Duration; } } var maxIndex = players.Any() ? players.Max(p => p.Index) : 0; var excessPlayers = Players.Where(ep => ep.Index > maxIndex); foreach (var excessPlayer in excessPlayers.ToList()) { Players.Remove(excessPlayer); } }
public void ApplyChanges(IEnumerable<Change> changeList) { // separate var speakerChanges = changeList.Where(c => string.Compare("speaker", c.EntityType, StringComparison.OrdinalIgnoreCase) == 0).ToList(); var sessionChanges = changeList.Where(c => string.Compare("session", c.EntityType, StringComparison.OrdinalIgnoreCase) == 0).ToList(); var updateClientChangeset = false; if (speakerChanges.Count > 0) { ApplySpeakerChanges(speakerChanges); SpeakerRepository.Save(); updateClientChangeset = true; } if (sessionChanges.Count > 0) { ApplySessionChanges(sessionChanges); SessionRepository.Save(); updateClientChangeset = true; } if (updateClientChangeset) { int changeSet = changeList.Max(c => c.Changeset); UpdateClientChangesetToLatest(changeSet); } }
int[] Determine_col_widths(IEnumerable<string[]> records) { var colWidths = new List<int> (); for (var i = 0; i < records.First ().Length; i++) { colWidths.Add (records.Max(r => r[i].Length)); } return colWidths.ToArray (); }
public void ShowCommandUsage(IEnumerable<Command> availableCommands, OptionSet optionSet) { var processName = Process.GetCurrentProcess().ProcessName; var usagePreamble = String.Format("Usage: {0} ", processName); var usagePattern = GenerateUsagePattern(optionSet); new ConsoleFormatter(ConsoleWriter.Default).Write( new ConsoleTable().AddRow( new ConsoleCell(usagePreamble).WithWidth(usagePreamble.Length).WithPadding(0), new ConsoleCell(usagePattern).WithPadding(0))); var maximumCommandNameLength = availableCommands.Count() > 0 ? availableCommands.Max(c => c.Name.Length) : 0; var commandTable = new ConsoleTable(). AddEmptyRow().AddRow( new ConsoleCell("The available commands are:").WithPadding(0)); foreach (var command in availableCommands) { commandTable.AddRow( new ConsoleCell(command.Name).WithWidth(maximumCommandNameLength), new ConsoleCell(command.Description)); } new ConsoleFormatter(ConsoleWriter.Default).Write(commandTable); }
public override SqlQuery Combine(IEnumerable<SqlQuery> sqlQueries) { if (sqlQueries == null) { throw new ArgumentNullException("sqlQueries"); } int argumentsCount = 0; var sqlBuilder = new StringBuilder(sqlQueries.Sum(s => s.CommandText.Length)); foreach (var sqlQuery in sqlQueries) { argumentsCount += sqlQuery.Arguments.Count; if (sqlBuilder.Length == 0) { sqlBuilder.Append(sqlQuery.CommandText).AppendLine(this.StatementSeparator); } else { var commandText = sqlQuery.CommandText.StartsWith("EXEC", StringComparison.OrdinalIgnoreCase) ? sqlQuery.CommandText : SqlUtility.RenumberParameters(sqlQuery.CommandText, argumentsCount); sqlBuilder.Append(commandText).AppendLine(this.StatementSeparator); } } var combinedQuery = new SqlQuery(sqlBuilder.ToString(0, sqlBuilder.Length - 3), sqlQueries.SelectMany(s => s.Arguments).ToArray()); combinedQuery.Timeout = sqlQueries.Max(s => s.Timeout); return combinedQuery; }
private void UpdateLabels(IEnumerable<DataModel> records) { lbGroupUrl.Text = infoProvider.GetSavedGroupUrl(); lbGroupname.Text = infoProvider.GetSavedGroupName(); lbLastUpdate.Text = FormatDateTime(records.Max(r => r.UpdatingTime)); lbRecordsCount.Text = records.Count().ToString(); }
public static DateTime MaxDate(this IEnumerable<DateTime> left, IEnumerable<DateTime> right) { var maxLeft = left.Any() ? left.Max() : DateTime.MinValue; var maxRight = right.Any() ? right.Max() : DateTime.MinValue; return maxLeft.Ticks > maxRight.Ticks ? maxLeft : maxRight; }
public async Task Create(IProduct product) { var filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "aDigital"); TableContinuationToken token = null; IEnumerable <int> rowKeys = Enumerable.Empty <int>(); var query = new TableQuery <ProductTableEntity>().Select(new string[] { "RowKey" }).Where(filter); do { var result = await _table.ExecuteQuerySegmentedAsync(query, token); rowKeys = rowKeys.Union(result.Results.Select(i => i.Id)); } while (token != null); ProductTableEntity p = new ProductTableEntity(); p.Description = product.Description; p.Id = (rowKeys?.Max() ?? 0) + 1; p.Images = product.Images; p.MinimalAmount = product.MinimalAmount; p.PartitionKey = "aDigital"; p.PresetAmounts = product.PresetAmounts; p.StartsAt = product.StartsAt; p.Tags = product.Tags; p.Title = product.Title; p.UnitName = product.UnitName; p.Active = true; var op = TableOperation.Insert(p); await _table.ExecuteAsync(op); product.Id = p.Id; }
public AscendData(IEnumerable<long> dataPoints, string planetName, bool failedAscends) { long highestPoint = dataPoints.Max(); this._heightPoints = dataPoints.ToList(); this._planetName = planetName; this._areFailedAscends = failedAscends; StringBuilder sb = new StringBuilder(); sb = sb.Append("http://chart.apis.google.com/chart?").Append("cht=lc&chs=500x500") .Append("&chd=t:"); foreach(double dataPoint in _heightPoints) { sb = sb.Append(dataPoint.ToString("0.00")).Append(','); } sb.Replace(',', '&', sb.Length - 1, 1); this._chartName = string.Format("{0} ascends from the planet {1}", this._areFailedAscends ? "Failed" : "Successful", this._planetName); sb = sb.Append("chtt=").Append(HttpUtility.UrlEncode(this._chartName)).Append("&hAxis.title=Height from surface"); this._chartUrl = sb.ToString(); log.DebugFormat("Created new AscendData, url is '{0}'", this._chartUrl); }
private static IEnumerable<Bucket> For(IEnumerable<double> numbers) { var biggestNumber = (int)numbers.Max() + 1; return Enumerable .Range(0, biggestNumber) .Select(BucketWithTolerance); }
protected override void RenderLegend(GraphPane gp, IEnumerable<RequestDataResults> dataResults) { var hostName = new TextObj(dataResults.First().HostName, dataResults.Count() + 1, dataResults.Max(x => x.AverageResponseTime) * 1.1); hostName.FontSpec.Fill.IsVisible = false; hostName.FontSpec.Border.IsVisible = false; hostName.FontSpec.FontColor = Color.Black; hostName.FontSpec.Size = 7; gp.GraphObjList.Add(hostName); var date = new TextObj(DateTime.Now.ToString(), dataResults.Count() + 1, dataResults.Max(x => x.AverageResponseTime) * 1.05); date.FontSpec.Fill.IsVisible = false; date.FontSpec.Border.IsVisible = false; date.FontSpec.FontColor = Color.Black; date.FontSpec.Size = 7; gp.GraphObjList.Add(date); }
public static VehicleStatisticsModel Calculate(IEnumerable<Model.FillupEntry> fillUps, bool includeFirst = true) { if (!fillUps.Any()) return new VehicleStatisticsModel(); var firstFillUp = fillUps.OrderBy(x => x.Date).FirstOrDefault(); double totalFuelCost = 0.0; double totalUnits = 0.0; double totalCost = 0.0; int totalDistance = 0; foreach (var fillUp in fillUps) { if (includeFirst || fillUp != firstFillUp) { totalFuelCost += fillUp.PricePerUnit*fillUp.TotalUnits; totalUnits += fillUp.TotalUnits; totalCost += fillUp.TotalCost; totalDistance += fillUp.Distance ?? 0; } } var odometer = fillUps.Max(x => x.Odometer); var earliestEntryDate = fillUps.Min(x => x.Date).ToUniversalTime(); var today = DateTime.UtcNow.Date; var totalMonths = CalculateDifferenceInMonths(earliestEntryDate.Date, today.Date); return new VehicleStatisticsModel(totalFuelCost, totalUnits, totalCost, totalDistance, odometer, totalMonths); }
public static IEnumerable<double> Normalize(IEnumerable<double> collection) { double min = collection.Min(); double max = collection.Max(); return collection.Select(f => Normalize(f, min, max)); }
internal WhirlpoolEvent(IEnumerable<Ship> rpShips, Fleet rpEscortFleet, RawMapExploration rpData) : base(rpData) { var rMaxAmount = (double)rpShips.Max(r => LostMaterial == MaterialType.Fuel ? r.Fuel.Current : r.Bullet.Current); var rReducedRate = Amount / rMaxAmount; var rTotalAmount = 0; foreach (var rShip in rpShips) { int rReducedAmount; if (LostMaterial == MaterialType.Fuel) { rReducedAmount = (int)(rShip.Fuel.Current * rReducedRate); rShip.Fuel.Current -= rReducedAmount; } else { rReducedAmount = (int)(rShip.Bullet.Current * rReducedRate); rShip.Bullet.Current -= rReducedAmount; } rTotalAmount += rReducedAmount; } var rMessage = rpEscortFleet == null ? StringResources.Instance.Main.Sortie_Whirlpool_Message : StringResources.Instance.Main.Sortie_Whirlpool_Message_CombinedFleet; Message = string.Format(rMessage, LostMaterial == MaterialType.Fuel ? "[icon]fuel[/icon]" : "[icon]bullet[/icon]", rTotalAmount, rReducedRate); }
public static int Rating(Team team, IEnumerable <Team> teams) { var max = teams.Max (_ => Attack (_, teams) + Defence (_, teams) + Advisory (_, teams) + Task (_, teams)); if (max == 0) return 0; return ((Attack (team, teams) + Defence (team, teams) + Advisory (team, teams) + Task (team, teams)) * 100) / max; }
public static int Advisory(Team team, IEnumerable <Team> teams) { var max = teams.Max (_ => _.AdvisoryScores); if (max == 0) return 0; return (100 * team.AdvisoryScores) / max; }
private static IEnumerable<RouteCandidate> GetRouteMatchesWithMostParameterCaptures(IEnumerable<RouteCandidate> routesWithCorrectRequestMethod) { var maxParameterCount = routesWithCorrectRequestMethod.Max(x => x.Item4.Parameters.GetDynamicMemberNames().Count()); return routesWithCorrectRequestMethod.Where( x => x.Item4.Parameters.GetDynamicMemberNames().Count() == maxParameterCount); }
public static int Defence(Team team, IEnumerable <Team> teams) { var max = teams.Max (_ => _.DefenceScores); if (max == 0) return 0; return (100 * team.DefenceScores) / max; }
public TemplatesInfo(IEnumerable<FileInfo> files) { LastModified = files.Max(f => f.LastWriteTime); Templates = files .ToDictionary(f => Path.GetFileNameWithoutExtension(f.Name), f => File.ReadAllText(f.FullName)); Output = JsonConvert.SerializeObject(Templates); }
public static int Task(Team team, IEnumerable <Team> teams) { var max = teams.Max (_ => _.TaskScores); if (max == 0) return 0; return (100 * team.TaskScores) / max; }
private static IEnumerable<Tuple<RouteCacheEntry, IRoutePatternMatchResult>> GetRouteMatchesWithMostParameterCaptures(IEnumerable<Tuple<RouteCacheEntry, IRoutePatternMatchResult>> routesWithCorrectRequestMethod) { var maxParameterCount = routesWithCorrectRequestMethod.Max(x => x.Item2.Parameters.GetDynamicMemberNames().Count()); return routesWithCorrectRequestMethod.Where( x => x.Item2.Parameters.GetDynamicMemberNames().Count() == maxParameterCount); }
public PerfIteratorResult(IEnumerable<PerfRoundResult> resultsList) { this.ResultsList = resultsList; this.RepeatCount = resultsList.Count(); this.OverallAverageTicks = resultsList.Average(r => r.AverageTicks); this.OverallMaxTicks = resultsList.Max(r => r.MaxTicks); this.OverallMinTicks = resultsList.Min(r => r.MinTicks); }
private static int GetExpectedBatchesCount(bool rebuild, IEnumerable <DocumentSource> documentSources, int batchSize) { int result; if (rebuild) { // Use documents count from primary source result = GetBatchesCount(documentSources?.FirstOrDefault()?.DocumentIds.Count ?? 0, batchSize); } else { // Calculate batches count for each source and return the maximum value result = documentSources?.Max(s => GetBatchesCount(s?.Changes.Count ?? 0, batchSize)) ?? 0; } return(result); }
/// <summary> /// Return the latest version of the source /// </summary> /// <param name="source">Source to look at</param> /// <param name="logger">Logger</param> /// <param name="packageId">Package to look for</param> /// <param name="prerelease">Whether to include prerelease versions</param> /// <returns>Returns the latest version available from a source or a null if non is found.</returns> public static async Task <NuGetVersion> GetLatestVersionFromSourceAsync(PackageSource source, ILogger logger, string packageId, bool prerelease) { SourceRepository repository = Repository.Factory.GetCoreV3(source); PackageMetadataResource resource = await repository.GetResourceAsync <PackageMetadataResource>(); using (var cache = new SourceCacheContext()) { IEnumerable <IPackageSearchMetadata> packages = await resource.GetMetadataAsync( packageId, includePrerelease : prerelease, includeUnlisted : false, cache, logger, CancellationToken.None ); return(packages?.Max(x => x.Identity.Version)); } }
/// <summary> /// Pass this function as a filter parameter to a <see cref="ILoggerProvider"/> to enable filtering /// based on the specified <see cref="CategoryLevels"/>. The filter will match the longest possible key in /// <see cref="CategoryLevels"/> and return true if the level is equal to or greater than the filter. If /// there is no match, the value of <see cref="DefaultLevel"/> is used. /// </summary> /// <param name="category">The category of the current log message.</param> /// <param name="level">The <see cref="LogLevel"/> of the current log message.</param> /// <returns>True if the level is equal to or greater than the matched filter. Otherwise, false.</returns> public bool Filter(string category, LogLevel level) { // find the longest loglevel that matches the category IEnumerable <string> matches = CategoryLevels.Keys.Where(k => category.StartsWith(k, System.StringComparison.CurrentCulture)); string longestMatch = matches?.Max(); LogLevel requestedLevel; if (string.IsNullOrEmpty(longestMatch)) { requestedLevel = DefaultLevel; } else { requestedLevel = CategoryLevels[longestMatch]; } return(level >= requestedLevel); }
public static string ToBitmask(this IEnumerable <DateTime> dates, bool defaultOnEmpty = false) { var result = default(string); if (dates?.Any() ?? false) { result = dates?.ToBitmask( begin: dates?.Min() ?? DateTime.MinValue, end: dates?.Max() ?? DateTime.MinValue, defaultOnEmpty: defaultOnEmpty); } if (result == default) { result = defaultOnEmpty ? default : string.Empty; } return(result); }
private IUnitOfWorkFactory SetupUpsertShowRepository(IEnumerable <Show> shows) { _showRepository = new Mock <IShowRepository> { CallBase = false }; _showRepository.Setup(s => s.GetAll()).ReturnsAsync(shows); _showRepository.Setup(s => s.GetLastId()).ReturnsAsync(shows?.Max(s => s.ExternalId)); var mockUnitOfWork = new Mock <IUnitOfWork> { CallBase = false }; mockUnitOfWork.Setup(u => u.Show).Returns(_showRepository.Object); var mockFactory = new Mock <IUnitOfWorkFactory> { CallBase = false }; mockFactory.Setup(m => m.CreateNew()).Returns(mockUnitOfWork.Object); return(mockFactory.Object); }
protected override float AggregateValues(IEnumerable <float> values) { return(values.Max()); }
/// <summary> /// Retourne la distance entre les deux points les plus éloignés de la liste /// </summary> /// <param name="pts">Liste de points</param> /// <returns>Distance maximale</returns> public static double MaxDistance(this IEnumerable <RealPoint> pts) { return(pts.Max(p1 => pts.Max(p2 => p1.Distance(p2)))); }
public override async Task <int> UpdateRangeAsync(IEnumerable <MOND> save_items, string where = null) { string wherePointID = ""; double?whereMONG_DIS = null; int? wheregINTProjectID = null; var holes = save_items.Select(mond => new { mond.PointID }) .Distinct().ToList(); if (holes.Count == 1) { wherePointID = holes[0].PointID; } var mong_dis = save_items.Select(mond => new { mond.MONG_DIS }) .Distinct().ToList(); if (mong_dis.Count == 1) { whereMONG_DIS = mong_dis[0].MONG_DIS; } var gintprojectid = save_items.Select(mond => new { mond.gINTProjectID }) .Distinct().ToList(); if (gintprojectid.Count == 1) { wheregINTProjectID = gintprojectid[0].gINTProjectID; if (wheregINTProjectID == null) { wheregINTProjectID = _gINTProjectID; } } DateTime minDateTime = save_items.Min(e => e.DateTime).GetValueOrDefault(); DateTime maxDateTime = save_items.Max(e => e.DateTime).GetValueOrDefault(); return(await Task.Run(() => { // reduce the dataset, all logger records could be massive if (where != null && wherePointID == "") { _table.sqlWhere($"gINTProjectID={wheregINTProjectID} and {where} and DateTime>='{String.Format("{0:yyyy-MM-dd HH:mm:ss}",minDateTime)}' and DateTime<='{String.Format("{0:yyyy-MM-dd HH:mm:ss}",maxDateTime)}'"); } if (where == null && wherePointID == "") { _table.sqlWhere($"gINTProjectID={wheregINTProjectID} and DateTime>='{String.Format("{0:yyyy-MM-dd HH:mm:ss}",minDateTime)}' and DateTime<='{String.Format("{0:yyyy-MM-dd HH:mm:ss}",maxDateTime)}'"); } if (where != null && wherePointID != "" && whereMONG_DIS == null) { _table.sqlWhere($"gINTProjectID={wheregINTProjectID} and {where} and PointID='{wherePointID}' and DateTime>='{String.Format("{0:yyyy-MM-dd HH:mm:ss}",minDateTime)}' and DateTime<='{String.Format("{0:yyyy-MM-dd HH:mm:ss}",maxDateTime)}'"); } if (where != null && wherePointID != "" && whereMONG_DIS != null) { _table.sqlWhere($"gINTProjectID={wheregINTProjectID} and {where} and PointID='{wherePointID}' and DateTime>='{String.Format("{0:yyyy-MM-dd HH:mm:ss}",minDateTime)}' and DateTime<='{String.Format("{0:yyyy-MM-dd HH:mm:ss}",maxDateTime)}' and MONG_DIS={whereMONG_DIS.Value}"); } _table.getDataSet(); DataTable dt = _table.getDataTable(); Boolean checkExisting = false; if (dt.Rows.Count > 0) { checkExisting = true; } foreach (MOND item in save_items) { DataRow row = null; if (item.gINTProjectID == 0) { item.gINTProjectID = wheregINTProjectID.Value; } if (checkExisting == true) { //check for existing records if (item.GintRecID > 0) { row = dt.Select($"GintRecID={item.GintRecID}").SingleOrDefault(); } // if (row == null && item.ge_otherid!=null) { // try and check for existing ge_generated records, but some ge_source and ge_otherid // combination may results in mutiple matches in the MOND table // so this is not a reliable way of identifying singular records // try { // row = dtMOND.Select ($"ge_source='{item.ge_source}' and ge_otherId='{item.ge_otherid}' and MOND_TYPE='{item.MOND_TYPE}'").SingleOrDefault(); // } catch { // row = null; // } // } if (item.DateTime == DateTime.Parse("21 Oct 2019 12:45PM")) { Console.Write(item); } //check for unique records if (row == null) { string s1 = $"gINTProjectID={item.gINTProjectID} and PointId='{item.PointID}' and ItemKey='{item.ItemKey}' and MONG_DIS={item.MONG_DIS} and MOND_TYPE='{item.MOND_TYPE}' and DateTime='{String.Format("{0:yyyy-MM-dd HH:mm:ss}",item.DateTime)}' and MOND_REF='{item.MOND_REF}'"; if (item.MOND_REF != null) { row = dt.Select($"gINTProjectID={item.gINTProjectID} and PointId='{item.PointID}' and ItemKey='{item.ItemKey}' and MONG_DIS={item.MONG_DIS} and MOND_TYPE='{item.MOND_TYPE}' and DateTime='{String.Format("{0:yyyy-MM-dd HH:mm:ss}",item.DateTime)}' and MOND_REF='{item.MOND_REF}'").SingleOrDefault(); } if (item.MOND_REF == null) { row = dt.Select($"gINTProjectID={item.gINTProjectID} and PointId='{item.PointID}' and ItemKey='{item.ItemKey}' and MONG_DIS={item.MONG_DIS} and MOND_TYPE='{item.MOND_TYPE}' and DateTime='{String.Format("{0:yyyy-MM-dd HH:mm:ss}",item.DateTime)}' and MOND_REF is null").SingleOrDefault(); } } } if (row == null) { row = _table.NewRow(); _table.addRow(row); } set_values(item, row); } row_states ret = _table.get_row_states(); return ret.updated; })); }
// //////////////////////////////////////////////////////////////////////////////////////////////////////// // HELP STRIPE ONLINE PAYMENT // //////////////////////////////////////////////////////////////////////////////////////////////////////// public async Task <IActionResult> Charge(string stripeEmail, string StripeToken, decimal amount) { // ___________________________________________________ // To get public key // Set your secret key. Remember to switch to your live secret key in production! // ___________________________________________________ string accessToken = await HttpContext.GetTokenAsync("access_token"); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); string idUser = await client.GetStringAsync(_configuration["URLApi"] + "api/AspNetUsers/UserId/"); string uriPkey = _configuration["URLApi"] + "api/stripePay/PKey/"; string pKey = null; List <string> stripePKeys; string content = await client.GetStringAsync(uriPkey); if (content != null) { stripePKeys = JsonConvert.DeserializeObject <List <string> >(content); } else { // View ERROR return(NotFound()); } // LineItems total amount foreach (var item in stripePKeys) { if (item != null) { pKey = item; } } string publickey = pKey; ViewBag.PUBLICKEY = publickey; // ___________________________________________________ // To get ApiKey // ___________________________________________________ string uriApiKey = _configuration["URLApi"] + "api/stripePay/ApiKey"; string apiKey = null; List <string> stripeApiKeys; string contentApikey = await client.GetStringAsync(uriApiKey); if (contentApikey != null) { stripeApiKeys = JsonConvert.DeserializeObject <List <string> >(contentApikey); } else { // View ERROR return(NotFound()); } // LineItems total amount foreach (var item in stripeApiKeys) { if (item != null) { apiKey = item; } } string returnedApiKey = apiKey; ViewBag.APIKEY = returnedApiKey; StripeConfiguration.ApiKey = returnedApiKey; // ___________________________________________________ // Calculate the total amount of charge // ___________________________________________________ // Tdodo Récupérer dans lineItems /* * if (_configuration["Environnement"] == "Prod") // Windows 10 ? * { * amount = amount * 100; * }*/ amount *= 100; // Windows 7 ? long chargeAmount = Convert.ToInt64(amount); decimal montant = amount / 100; ViewBag.MONTANT = montant; // ___________________________________________________ // Create Stripe Environnement // ___________________________________________________ var customers = new CustomerService(); var Charges = new ChargeService(); var customer = customers.Create( new CustomerCreateOptions { Email = stripeEmail, Source = StripeToken }); var charge = Charges.Create( new ChargeCreateOptions { Amount = chargeAmount, Description = "Test Payment", Currency = "chf", Customer = customer.Id, ReceiptEmail = stripeEmail, Metadata = new Dictionary <string, string>() { { "integration_check", "accept_a_payment" }, { "OrderId", "111" }, { "Postcode", "3100" } } }); // ___________________________________________________ // Verify the payment // ___________________________________________________ if (charge.Status == "succeeded") { // ___________________________________________________ // Récupération des livres pour y modifier la quantité // ___________________________________________________ string uriShopcart = _configuration["URLApi"] + "api/ShoppingCarts/" + "ShoppingCart/" + idUser; ShoppingCart shoppingcart; HttpResponseMessage responseShopcart = await client.GetAsync(uriShopcart); string resultShopcart = responseShopcart.Content.ReadAsStringAsync().Result; shoppingcart = JsonConvert.DeserializeObject <ShoppingCart>(resultShopcart); string contentLineItems = await client.GetStringAsync(_configuration["URLApi"] + "api/LineItems/Items/" + shoppingcart.Id); IEnumerable <Models.LineItem> lineItems = JsonConvert.DeserializeObject <IEnumerable <Models.LineItem> >(contentLineItems); HttpResponseMessage response; string details = "Livres achetés : "; string message = "Envoyé"; foreach (Models.LineItem lineItem in lineItems) { details += lineItem.IdBookNavigation.Title + " (" + lineItem.Quantity + "x " + lineItem.UnitPrice.ToString("F2") + ") / "; lineItem.IdBookNavigation.Stock -= lineItem.Quantity; // historique du stock StockHistory sh = new StockHistory { IdBook = lineItem.IdBook, TransactionDate = DateTime.Now, TransactionStock = lineItem.IdBookNavigation.Stock, TransactionType = 1 }; HttpResponseMessage responseStock = await _client.PostAsJsonAsync(_configuration["URLApi"] + "api/StockHistories", sh);// HTTP GET responseStock.EnsureSuccessStatusCode(); string jsonString = System.Text.Json.JsonSerializer.Serialize <Book>(lineItem.IdBookNavigation); StringContent httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await client.PutAsync(_configuration["URLApi"] + "api/Books/" + lineItem.IdBookNavigation.Id, httpContent); if (response.StatusCode != HttpStatusCode.NoContent) { return(BadRequest()); } if (lineItem.IdBookNavigation.Stock < 0) { message = "En attente"; } } // ___________________________________________________ // Enregistrement de la commande dans la BD // ___________________________________________________ string contentCustomer = await client.GetStringAsync(_configuration["URLApi"] + "api/Customers/"); Models.Customer currentCustomer = JsonConvert.DeserializeObject <Models.Customer>(contentCustomer); Models.Order order = new Models.Order { UserId = idUser, OrderedDate = DateTime.Now, ShippedDate = DateTime.Now, ShippingAddress = currentCustomer.BillingAddress, Status = message, TotalPrice = montant }; response = await client.PostAsJsonAsync(_configuration["URLApi"] + "api/Orders/", order); if (response.StatusCode != HttpStatusCode.OK) { return(BadRequest()); } // ___________________________________________________ // Enregistrement du paiement dans la BD // ___________________________________________________ string contentOrders = await client.GetStringAsync(_configuration["URLApi"] + "api/Orders/"); IEnumerable <Models.Order> listOrders = JsonConvert.DeserializeObject <IEnumerable <Models.Order> >(contentOrders); int orderId = listOrders.Max(i => i.Id); Payment payment = new Payment { UserId = idUser, IdOrder = orderId, PaidDate = DateTime.Now, PriceTotal = montant, Details = details }; response = await client.PostAsJsonAsync(_configuration["URLApi"] + "api/Payments/", payment); if (response.StatusCode != HttpStatusCode.OK) { return(BadRequest()); } ViewBag.DETAILS = details; ViewBag.DATE = payment.PaidDate; // ___________________________________________________ // Récupération du Shoppingcart pour suppression des LineItems dans la BD après validation du paiement // ___________________________________________________ response = await client.GetAsync(_configuration["URLApi"] + "api/LineItems/DeleteItems/" + shoppingcart.Id); if (response.StatusCode != HttpStatusCode.OK) { return(BadRequest()); } return(View()); } else { return(View("Error")); } } // End
public static void Draw(this ZedGraphControl zedGraph, Form owner, IEnumerable <double> x, IEnumerable <Graphic> ys) { zedGraph.MasterPane.InnerPaneGap = 0; zedGraph.MasterPane.Title.IsVisible = false; zedGraph.IsSynchronizeXAxes = true; x = x ?? Enumerable.Range(0, ys.Max(y => y.Curves.Max(c => c.Count))).ToDoubles(); GraphPane pane = null; var j = 0; foreach (var graphic in ys) { pane = j == 0 ? zedGraph.GraphPane : new GraphPane(); if (j != 0) { zedGraph.MasterPane.Add(pane); } j++; pane.XAxis.Scale.Max = x.Max(); pane.YAxis.Scale.Min = 0; pane.Title.IsVisible = false; pane.XAxis.Title.IsVisible = false; pane.YAxis.Title.IsVisible = false; pane.Border.IsVisible = false; var colors = new[] { Color.Black, Color.Blue, Color.Red }; var i = 0; foreach (var y in graphic.Curves) { if (y is Curve curve) { pane.AddCurve(null, x.ToArray(), curve.Points.ToArray(), curve.Color ?? colors[i], SymbolType.None); } else if (y is Histogram histogram) { pane.AddBar(null, histogram.Points.Select((p, k) => k * histogram.BinWidth).ToArray(), histogram.Points.ToArray(), histogram.Color ?? colors[i]); } else if (y is HBarCurve curve2) { var rects = new List <PolyObj>(); var hBarHeight = curve2.Height; for (int k = 0; k < curve2.Points.Count(); k++) { Interval interval = curve2.Points.ElementAt(k); var rect = new PolyObj(); rect.Points = new[] { new PointD(interval.From, 0), new PointD(interval.From, hBarHeight), new PointD(interval.To, hBarHeight), new PointD(interval.To, 0) }; //rect.Border.IsVisible = false; rect.Fill = new Fill(curve2.Color ?? colors[i]); rect.IsClippedToChartRect = true; rect.ZOrder = ZOrder.E_BehindCurves; rects.Add(rect); } pane.GraphObjList.AddRange(rects.Cast <GraphObj>()); } else { throw new NotSupportedException(); } i++; i %= colors.Length; } } zedGraph.AxisChange(); using (Graphics g = owner.CreateGraphics()) { zedGraph.MasterPane.SetLayout(g, PaneLayout.SingleColumn); } zedGraph.Invalidate(); }
private double GetDuration(IEnumerable <HashedFingerprint> hashes, double fingerprintLengthInSeconds) { return(hashes.Max(h => h.StartsAt) + fingerprintLengthInSeconds); }
/// <summary> /// Calculates the Maximum absolute value of the <see cref="vals"/> /// </summary> /// <param name="vals">The values.</param> public static double AbsMax(this IEnumerable <double> vals) { return(Math.Max( vals.Max().Abs(), vals.Min().Abs())); }
private static string GetMaximumValue(IEnumerable <int> numbers) => numbers?.Max().ToString(CultureInfo.InvariantCulture);
public static double GetHighestBid(IEnumerable <Offer> offers) { return(offers?.Max(x => x.Sum) ?? 0); }
private Polyline[] buildIsolinesInternal(IEnumerable <Triangle> triangles, double[] zLevels) { Polyline[] result = new Polyline[zLevels.Length]; if (zLevels.Length > 0) { double minZ = zLevels.Min(); double maxZ = zLevels.Max(); double surfaceMin = triangles.Min(tr => Math.Min( Math.Min(((Coordinate3D)tr.Cell1.DataPoint).Z, ((Coordinate3D)tr.Cell2.DataPoint).Z), ((Coordinate3D)tr.Cell3.DataPoint).Z)); double surfaceMax = triangles.Max(tr => Math.Max( Math.Max(((Coordinate3D)tr.Cell1.DataPoint).Z, ((Coordinate3D)tr.Cell2.DataPoint).Z), ((Coordinate3D)tr.Cell3.DataPoint).Z)); if (surfaceMin > maxZ || surfaceMax < minZ) { return(result); } Comparison <Triangle> comparision = delegate(Triangle t1, Triangle t2) { if (t1 == t2) { return(0); } double z11 = ((Coordinate3D)t1.Cell1.DataPoint).Z; double z12 = ((Coordinate3D)t1.Cell2.DataPoint).Z; double z13 = ((Coordinate3D)t1.Cell3.DataPoint).Z; double z21 = ((Coordinate3D)t2.Cell1.DataPoint).Z; double z22 = ((Coordinate3D)t2.Cell2.DataPoint).Z; double z23 = ((Coordinate3D)t2.Cell3.DataPoint).Z; double z1 = Math.Min(Math.Min(z11, z12), z13); double z2 = Math.Min(Math.Min(z21, z22), z23); if (z1 < z2) { return(-1); } if (z1 > z2) { return(1); } return(0); }; List <Triangle> tempTriangles = triangles.ToList(); // sort triangles by minimal z-value tempTriangles.Sort(comparision); for (int i = 0; i < zLevels.Length; i++) { if (zLevels[i] < surfaceMin) { result[i] = new Polyline(); continue; } result[i] = getIsoline(tempTriangles, zLevels[i]); } } return(result); }
private Polyline[] buildIsolinesInternal(IEnumerable <Coordinate3D> surfacePoints, double[] zLevels, List <Triangle> triangles) { Polyline[] result = new Polyline[zLevels.Length]; if (zLevels.Length > 0) { double minZ = zLevels.Min(); double maxZ = zLevels.Max(); double surfaceMin = surfacePoints.Min(coord => coord.Z); double surfaceMax = surfacePoints.Max(coord => coord.Z); if (surfaceMin > maxZ || surfaceMax < minZ) { return(result); } List <ICoordinate> coords = new List <ICoordinate>(); surfacePoints.ToList().ForEach(coord => coords.Add(coord)); // build tesselation VoronoiBuilder vb = new VoronoiBuilder(); VoronoiTesselation tesselation = vb.Build(coords, true); tesselation.Triangles.ToList().ForEach(t => triangles.Add(t)); vb = null; tesselation = null; Comparison <Triangle> comparision = delegate(Triangle t1, Triangle t2) { if (t1 == t2) { return(0); } double z11 = ((Coordinate3D)t1.Cell1.DataPoint).Z; double z12 = ((Coordinate3D)t1.Cell2.DataPoint).Z; double z13 = ((Coordinate3D)t1.Cell3.DataPoint).Z; double z21 = ((Coordinate3D)t2.Cell1.DataPoint).Z; double z22 = ((Coordinate3D)t2.Cell2.DataPoint).Z; double z23 = ((Coordinate3D)t2.Cell3.DataPoint).Z; double z1 = Math.Min(Math.Min(z11, z12), z13); double z2 = Math.Min(Math.Min(z21, z22), z23); if (z1 < z2) { return(-1); } if (z1 > z2) { return(1); } return(0); }; // sort triangles by minimal z-value triangles.Sort(comparision); for (int i = 0; i < zLevels.Length; i++) { if (zLevels[i] < surfaceMin) { result[i] = new Polyline(); continue; } result[i] = getIsoline(triangles, zLevels[i]); } } return(result); }
public static float CollectionDescent <TFont, TGlyph> (this IEnumerable <IDisplay <TFont, TGlyph> > displays) where TFont : IFont <TGlyph> => displays.IsNonEmpty() ? displays.Max(display => display.Descent - display.Position.Y) : 0;
public static float CollectionWidth <TFont, TGlyph> (this IEnumerable <IDisplay <TFont, TGlyph> > displays) where TFont : IFont <TGlyph> => displays.IsNonEmpty() ? displays.Max(d => d.Position.X + d.Width) - displays.Min(d => d.Position.X) : 0;
public static object MyMax <T>(this IEnumerable <T> input) { object output = null; return(output = input.Max()); }
private void CalculateResult(IEnumerable <TimeSpan> values, Type targetType) { TimeSpan result; switch (ReductionOperation.ActualValue.Value) { case ReductionOperations.Sum: result = values.Aggregate(new TimeSpan(), (x, y) => x + y); break; case ReductionOperations.Min: result = values.Min(); break; case ReductionOperations.Max: result = values.Max(); break; case ReductionOperations.Avg: result = TimeSpan.FromMilliseconds(values.Average(x => x.TotalMilliseconds)); break; case ReductionOperations.Assign: result = values.Last(); break; default: throw new InvalidOperationException(string.Format("Operation {0} is not supported as ReductionOperation for type: {1}.", ReductionOperation.ActualValue.Value, targetType)); } TimeSpanValue target; switch (TargetOperation.ActualValue.Value) { case ReductionOperations.Sum: target = InitializeTarget <TimeSpanValue, TimeSpan>(targetType, new TimeSpan()); target.Value += result; break; case ReductionOperations.Min: target = InitializeTarget <TimeSpanValue, TimeSpan>(targetType, TimeSpan.MaxValue); target.Value = target.Value < result ? target.Value : result; break; case ReductionOperations.Max: target = InitializeTarget <TimeSpanValue, TimeSpan>(targetType, TimeSpan.MinValue); target.Value = target.Value > result ? target.Value : result; break; case ReductionOperations.Avg: target = InitializeTarget <TimeSpanValue, TimeSpan>(targetType, result); target.Value = TimeSpan.FromMilliseconds((target.Value.TotalMilliseconds + result.TotalMilliseconds) / 2); break; case ReductionOperations.Assign: target = InitializeTarget <TimeSpanValue, TimeSpan>(targetType, new TimeSpan()); target.Value = result; break; default: throw new InvalidOperationException(string.Format("Operation {0} is not supported as TargetOperation for type: {1}.", TargetOperation.ActualValue.Value, targetType)); } }
public long GetMaxId(IEnumerable <Doctor> entities) => entities.Count() == 0 ? 0 : entities.Max(entity => entity.GetId());
private void CalculateResult(IEnumerable <double> values, Type targetType) { double result; switch (ReductionOperation.ActualValue.Value) { case ReductionOperations.Sum: result = values.Sum(); break; case ReductionOperations.Product: result = values.Aggregate(1.0, (x, y) => x * y); break; case ReductionOperations.Count: result = values.Count(); break; case ReductionOperations.Min: result = values.Min(); break; case ReductionOperations.Max: result = values.Max(); break; case ReductionOperations.Avg: result = values.Average(); break; case ReductionOperations.Assign: result = values.Last(); break; default: throw new InvalidOperationException(string.Format("Operation {0} is not supported as ReductionOperation for type: {1}.", ReductionOperation.ActualValue.Value, targetType)); } DoubleValue target; switch (TargetOperation.ActualValue.Value) { case ReductionOperations.Sum: target = InitializeTarget <DoubleValue, double>(targetType, 0.0); target.Value += result; break; case ReductionOperations.Product: target = InitializeTarget <DoubleValue, double>(targetType, 1.0); target.Value = target.Value * result; break; case ReductionOperations.Min: target = InitializeTarget <DoubleValue, double>(targetType, double.MaxValue); target.Value = Math.Min(target.Value, result); break; case ReductionOperations.Max: target = InitializeTarget <DoubleValue, double>(targetType, double.MinValue); target.Value = Math.Max(target.Value, result); break; case ReductionOperations.Avg: target = InitializeTarget <DoubleValue, double>(targetType, result); target.Value = (target.Value + result) / 2.0; break; case ReductionOperations.Assign: target = InitializeTarget <DoubleValue, double>(targetType, 0.0); target.Value = result; break; default: throw new InvalidOperationException(string.Format("Operation {0} is not supported as TargetOperation for type: {1}.", TargetOperation.ActualValue.Value, targetType)); } }
private void histogramPlot(int plotType) { privateModel.LegendTitle = "Protease"; string yAxisTitle = "Count"; string xAxisTitle = ""; double binSize = -1; double labelAngle = 0; SortedList <double, double> numCategory = new SortedList <double, double>(); Dictionary <string, IEnumerable <double> > numbersByProtease = new Dictionary <string, IEnumerable <double> >(); // key is protease name, value is data from that protease Dictionary <string, Dictionary <string, int> > dictsByProtease = new Dictionary <string, Dictionary <string, int> >(); // key is protease name, value is dictionary of bins and their counts switch (plotType) { case 1: // Peptide Length xAxisTitle = "Peptide Length"; binSize = 1; foreach (string key in PeptidesByProtease.Keys) { numbersByProtease.Add(key, PeptidesByProtease[key].Select(p => Convert.ToDouble(p.Length))); var results = numbersByProtease[key].GroupBy(p => roundToBin(p, binSize)).OrderBy(p => p.Key).Select(p => p); dictsByProtease.Add(key, results.ToDictionary(p => p.Key.ToString(), v => v.Count())); } break; case 2: // Protein Sequence Coverage xAxisTitle = "Protein Sequence Coverage"; binSize = 0.1; //more complicated implementation break; case 3: // Predicted Peptide Hydrophobicity xAxisTitle = "Predicted Peptide Hydrophobicity"; binSize = 0.1; foreach (string key in PeptidesByProtease.Keys) { numbersByProtease.Add(key, PeptidesByProtease[key].Select(p => p.GetHydrophobicity())); var results = numbersByProtease[key].GroupBy(p => roundToBin(p, binSize)).OrderBy(p => p.Key).Select(p => p); dictsByProtease.Add(key, results.ToDictionary(p => p.Key.ToString(), v => v.Count())); } break; case 4: // Predicted Peptide Electrophoretic Mobility xAxisTitle = "Predicted Peptide Electrophoretic Mobility"; binSize = 0.1; foreach (string key in PeptidesByProtease.Keys) { numbersByProtease.Add(key, PeptidesByProtease[key].Select(p => p.GetElectrophoreticMobility())); var results = numbersByProtease[key].GroupBy(p => roundToBin(p, binSize)).OrderBy(p => p.Key).Select(p => p); dictsByProtease.Add(key, results.ToDictionary(p => p.Key.ToString(), v => v.Count())); } break; } String[] category; // for labeling bottom axis int[] totalCounts; // for having the tracker show total count across all files IEnumerable <double> allNumbers = numbersByProtease.Values.SelectMany(x => x); int end = roundToBin(allNumbers.Max(), binSize); int start = roundToBin(allNumbers.Min(), binSize); int numBins = end - start + 1; int minBinLabels = 22; // the number of labeled bins will be between minBinLabels and 2 * minBinLabels int skipBinLabel = numBins < minBinLabels ? 1 : numBins / minBinLabels; // assign axis labels, skip labels based on skipBinLabel, calculate bin totals across all files category = new string[numBins]; totalCounts = new int[numBins]; for (int i = start; i <= end; i++) { if (i % skipBinLabel == 0) { category[i - start] = Math.Round((i * binSize), 2).ToString(CultureInfo.InvariantCulture); } foreach (Dictionary <string, int> dict in dictsByProtease.Values) { totalCounts[i - start] += dict.ContainsKey(i.ToString(CultureInfo.InvariantCulture)) ? dict[i.ToString(CultureInfo.InvariantCulture)] : 0; } } // add a column series for each file foreach (string key in dictsByProtease.Keys) { var column = new ColumnSeries { ColumnWidth = 200, IsStacked = true, Title = key, TrackerFormatString = "Bin: {bin}\n{0}: {2}\nTotal: {total}" }; foreach (var d in dictsByProtease[key]) { int bin = int.Parse(d.Key); column.Items.Add(new HistItem(d.Value, bin - start, (bin * binSize).ToString(CultureInfo.InvariantCulture), totalCounts[bin - start])); } privateModel.Series.Add(column); } // add axes privateModel.Axes.Add(new CategoryAxis { Position = AxisPosition.Bottom, ItemsSource = category, Title = xAxisTitle, GapWidth = 0.3, Angle = labelAngle, }); privateModel.Axes.Add(new LinearAxis { Title = yAxisTitle, Position = AxisPosition.Left, AbsoluteMinimum = 0 }); }
public SetCombination(IEnumerable <Card> cards) : base(cards) { this.SetValue = cards.Max(x => x.Value); }
private void Setup() { Command(CommandName.Browse, config => { config.Out = base.Out; config.Description = "launches the default browser to the VSTS project root"; var dashboardArgument = config.Argument("dashboard", "General dashboard to view. Opionts are builds, releases, workitems, pullrequests or testmanagement"); config.HelpOption(CommandName.HelpTemplate); config.OnExecute(() => { switch (dashboardArgument.Value.Normalize()) { case CommandName.Code: vsts.BrowseCodeUri(); break; case CommandName.Builds: vsts.BrowseBuildsUri(); break; case CommandName.Releases: vsts.BrowseReleasesUri(); break; case CommandName.WorkItems: vsts.BrowseWorkItemsUri(); break; case CommandName.PullRequests: vsts.BrowsePullRequestUri(); break; case CommandName.TestManagement: vsts.BrowseTestManagementUri(); break; case CommandName.Dashboard: vsts.BrowseProjectUri(); break; default: vsts.BrowseCodeUri(); break; } return(0); }); }); var buildCommand = Command(CommandName.Builds, config => { config.Out = base.Out; config.Description = "commands for working with VSTS build definitions"; config.HelpOption(CommandName.HelpTemplate); config.OnExecute(() => { var details = vstsApiHelper.GetBuildListDetails(vsts.ProjectName); if (!details.Any()) { return(1); } var detailIdWidth = details.Max(x => x.DefinitionIdLength); var buildNameWidth = details.Max(x => x.DefinitionNameLength); var statusNameWidth = details.Max(x => x.StatusNameLength); var resultNameWidth = details.Max(x => x.ResultNameLength); foreach (var definitionGroup in details.GroupBy(x => x.definition.name).OrderBy(x => x.Key)) { BuildListItem detail = definitionGroup.OrderByDescending(x => x.id).First(); Console.WriteLine($"{detail.definition.id.ToString().PadRight(detailIdWidth, ' ')} {detail.status.PadRight(statusNameWidth)} {detail.ResultName(resultNameWidth)} {detail.definition.name.PadRight(buildNameWidth)} {detail.TimeReport} {detail.buildNumber}", detail.ConsoleColor); } return(0); }); }); buildCommand.Command(CommandName.Logs, config => { config.Out = base.Out; config.Description = "view latest build log for build definition"; var buildIdOption = config.Option(CommandOptionTemplates.IdTemplate, "build definition id", CommandOptionType.SingleValue); buildIdOption.ShortName = CommandOptionTemplates.IdTemplateShort; var buildLogDetailOption = config.Option(CommandOptionTemplates.DetailTemplate, "show the log file for the build", CommandOptionType.NoValue); buildLogDetailOption.ShortName = CommandOptionTemplates.DetailTemplateShort; config.HelpOption(CommandName.HelpTemplate); config.OnExecute(() => { if (!buildIdOption.HasValue() || !int.TryParse(buildIdOption.Value(), out int buildDefinitionId)) { buildCommand.ShowHelp(CommandName.Logs); return(1); } var detail = vstsApiHelper.GetBuildDetail(vsts.ProjectName, buildDefinitionId); if (detail == null) { return(1); } var records = vstsApiHelper.GetBuildTimeline(vsts.ProjectName, detail.id); if (!records.Any()) { return(1); } Console.WriteLine($"{records.First().resultSymbol} {records.First().name}", records.First().ConsoleColor); foreach (var record in records.Skip(1).OrderBy(x => x.order)) { Console.WriteLine($"-{record.resultSymbol} {record.name}", record.ConsoleColor); } if (buildLogDetailOption.HasValue()) { var buildLogEntry = vstsApiHelper.GetBuildLogEntry(vsts.ProjectName, detail.id, records.OrderBy(x => x.order).First().log.id); buildLogEntry.ToList().ForEach(Console.WriteLine); } return(0); }); }); buildCommand.Command(CommandName.Queue, config => { config.Out = base.Out; config.Description = "commands for queueing a new build definition"; var buildIdOption = config.Option(CommandOptionTemplates.IdTemplate, "build definition id", CommandOptionType.SingleValue); buildIdOption.ShortName = CommandOptionTemplates.IdTemplateShort; config.HelpOption(CommandName.HelpTemplate); config.OnExecute(() => { if (!int.TryParse(buildIdOption.Value(), out int buildId)) { config.ShowHelp(CommandName.Queue); return(1); } BuildListItem detail = vstsApiHelper.QueueBuildDefinition(vsts.ProjectName, new BuildDefinitionQueueResource { definition = new DefinitionId { id = buildId } }); Console.WriteLine($"{detail.definition.id} {detail.status} {detail.result} {detail.definition.name} {detail.TimeReport} {detail.buildNumber}", detail.ConsoleColor); return(0); }); }); var codeCommand = Command(CommandName.Code, config => { config.Out = base.Out; config.Description = "launches the default browser to the current repos code dashboard"; config.HelpOption(CommandName.HelpTemplate); config.OnExecute(() => { vsts.BrowseCodeBranchUri(); return(0); }); }); var workItemsCommand = Command(CommandName.WorkItems, config => { config.Out = base.Out; config.Description = "commands for working with VSTS work items"; var id = config.Argument("work item identifier", "work item id or type, such as epic, user story, task or bug"); id.ShowInHelpText = true; var stateOption = config.Option(CommandOptionTemplates.StatesTemplate, "filter by states such as new, active, resolved, closed or removed", CommandOptionType.MultipleValue); stateOption.ShortName = CommandOptionTemplates.StatesTemplateShort; var tagOption = config.Option(CommandOptionTemplates.TagTemplate, "filter by any tag that assigned to work items", CommandOptionType.MultipleValue); tagOption.ShortName = CommandOptionTemplates.TagTemplateShort; var descriptionOption = config.Option(CommandOptionTemplates.DescriptionTemplate, "include description", CommandOptionType.NoValue); descriptionOption.ShortName = CommandOptionTemplates.DescriptionTemplateShort; var myWorkItemOption = config.Option(CommandOptionTemplates.MyTemplate, "only return open work items assigned to me", CommandOptionType.NoValue); myWorkItemOption.ShortName = CommandOptionTemplates.MyTemplateShort; var browseOption = config.Option(CommandOptionTemplates.BrowseTemplate, "browse specific work item in VSTS", CommandOptionType.NoValue); browseOption.ShortName = CommandOptionTemplates.BrowseTemplateShort; config.HelpOption(CommandName.HelpTemplate); config.OnExecute(() => { IEnumerable <Fields> details = null; bool singleWorkItem = false; var stateArgumentValues = stateOption.AsStateDefault(); if (myWorkItemOption.HasValue()) { IEnumerable <WorkItem> searchWorkItems = vstsApiHelper.SearchWorkItems(vsts.ProjectName, id.Value, stateArgumentValues, tagOption.Values, vsts.FullName); details = vstsApiHelper.GetWorkItemDetail(searchWorkItems.Select(x => x.id)); } else if (Int32.TryParse(id.Value, out int workItemId)) { if (browseOption.HasValue()) { vsts.WorkItemUri(workItemId).Browse(); return(0); } details = vstsApiHelper.GetWorkItemDetail(workItemId); singleWorkItem = true; } else { IEnumerable <WorkItem> searchWorkItems = vstsApiHelper.SearchWorkItems(vsts.ProjectName, id.Value, stateArgumentValues, tagOption.Values); details = vstsApiHelper.GetWorkItemDetail(searchWorkItems.Select(x => x.id)); } if (!details.Any()) { return(0); } var detailIdWidth = details.Max(x => x.WorkItemIdLength); var stateWidth = details.Max(x => x.StateLength); var assignedToNameWidth = details.Max(x => x.AssignedToNameLength); var workItemTypeWidth = details.Max(x => x.WorkItemTypeLength); // this sort just happens to work out for the Epic/Feature/Story level but it may not work for other project types foreach (Fields detail in details.OrderBy(x => x.WorkItemType).ThenBy(x => x.CreatedDate)) { var assignedTo = $"{detail.AssignedToName ?? CommandName.Unassigned}"; var color = string.IsNullOrWhiteSpace(detail.AssignedToName) ? ConsoleColor.DarkYellow : ConsoleColor.Green; Console.WriteLine($"#{detail.Id.ToString().PadRight(detailIdWidth)} {detail.State.PadRight(stateWidth)} {detail.WorkItemType.PadRight(workItemTypeWidth)} {detail.CreatedDate.ToLocalTime():yyyy/MM/dd} {assignedTo.PadRight(assignedToNameWidth)} {detail.Title.Trim()} : {detail.Tags ?? "no tags"}", color); if (singleWorkItem || descriptionOption.HasValue()) { Console.WriteLine($"{" ".PadRight(detailIdWidth + 1)} {detail.Description ?? "no description provided"}", color); } } return(0); }); }); workItemsCommand.Command(CommandName.Add, config => { config.Out = base.Out; config.Description = "command for adding new work items to the current project"; var typeOption = config.Option("--workitemtype", "work item type [required]", CommandOptionType.SingleValue); typeOption.ShortName = "w"; var titleOption = config.Option(CommandOptionTemplates.TitleTemplate, "work item title [required] ", CommandOptionType.SingleValue); titleOption.ShortName = CommandOptionTemplates.TitleTemplateShort; var descriptionOption = config.Option(CommandOptionTemplates.DescriptionTemplate, "work item description", CommandOptionType.SingleValue); descriptionOption.ShortName = CommandOptionTemplates.DescriptionTemplateShort; var priorityOption = config.Option(CommandOptionTemplates.PriorityTemplate, "work item priority", CommandOptionType.SingleValue); priorityOption.ShortName = CommandOptionTemplates.PriorityTemplateShort; var tagsOption = config.Option(CommandOptionTemplates.TagTemplate, "work item tags", CommandOptionType.MultipleValue); tagsOption.ShortName = CommandOptionTemplates.TagTemplateShort; config.HelpOption(CommandName.HelpTemplate); config.OnExecute(() => { if (!typeOption.HasValue() || !titleOption.HasValue()) { config.ShowHelp(CommandName.Add); return(0); } var document = new List <Object>(); document.Add(new { op = "add", path = "/fields/System.Title", value = titleOption.Value() }); if (descriptionOption.HasValue()) { document.Add(new { op = "add", path = "/fields/System.Description", value = descriptionOption.Value() }); } if (priorityOption.HasValue()) { document.Add(new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = priorityOption.Value() }); } if (tagsOption.HasValue()) { document.Add(new { op = "add", path = "/fields/System.Tags", value = String.Join(";", tagsOption.Values) }); } var detail = vstsApiHelper.CreateWorkItem(vsts.ProjectName, typeOption.Value(), document); Console.WriteLine($"#{detail.Id} {detail.Fields.State} {detail.Fields.CreatedDate.ToLocalTime():yyyy/MM/dd} - {detail.Fields.Title.Trim()}"); return(0); }); }); var pullRequestsCommand = Command(CommandName.PullRequests, config => { config.Out = base.Out; config.Description = "commands for working with VSTS pull requests"; var id = config.Argument("pull request identifier", "pull request id to browse to"); id.ShowInHelpText = true; config.HelpOption(CommandName.HelpTemplate); config.OnExecute(() => { if (Int32.TryParse(id.Value, out int pullRequestId)) { vsts.PullRequestIdUri(pullRequestId).Browse(); return(0); } IEnumerable <PullRequest> detail = vstsApiHelper.GetPullRequests(vsts.RepositoryId); foreach (var pullRequest in detail.OrderBy(x => x.CreationDate)) { Console.WriteLine($"#{pullRequest.PullRequestId} {pullRequest.Title} by {pullRequest.CreatedBy.DisplayName}"); } return(0); }); }); var pullRequestCreateCommand = pullRequestsCommand.Command(CommandName.Create, config => { config.Out = base.Out; config.Description = "commands for creating a pull request"; config.HelpOption(CommandName.HelpTemplate); var titleOption = config.Option(CommandOptionTemplates.TitleTemplate, "pull request title [required] ", CommandOptionType.SingleValue); titleOption.ShortName = CommandOptionTemplates.TitleTemplateShort; titleOption.ShowInHelpText = true; var descriptionOption = config.Option(CommandOptionTemplates.DescriptionTemplate, "pull request description", CommandOptionType.SingleValue); descriptionOption.ShortName = CommandOptionTemplates.DescriptionTemplateShort; descriptionOption.ShowInHelpText = true; var sourceRefNameOption = config.Option(CommandOptionTemplates.SourceReferenceNameTemplate, "source branch", CommandOptionType.SingleValue); sourceRefNameOption.ShortName = CommandOptionTemplates.SourceReferenceNameTemplateShort; sourceRefNameOption.ShowInHelpText = true; var targetRefNameOption = config.Option(CommandOptionTemplates.TargetReferenceNameTemplate, "target branch", CommandOptionType.SingleValue); targetRefNameOption.ShortName = CommandOptionTemplates.TargetReferenceNameTemplateShort; targetRefNameOption.ShowInHelpText = true; config.OnExecute(() => { var title = titleOption.HasValue() ? titleOption.Value() : vsts.LastCommit.Split(Environment.NewLine.ToCharArray()).FirstOrDefault(); if (string.IsNullOrWhiteSpace(title)) { Console.Write("Pull request title missing", ConsoleColor.Yellow); return(1); } var description = descriptionOption.HasValue() ? descriptionOption.Value() : vsts.LastCommit; var source = sourceRefNameOption.HasValue() ? sourceRefNameOption.Value() : vsts.RepositoryBranchName; var target = targetRefNameOption.HasValue() ? targetRefNameOption.Value() : "master"; Console.WriteLine($"Create New Pull Request", ConsoleColor.Gray); Console.WriteLine($"-----------------------", ConsoleColor.Gray); Console.WriteLine($"Title: {title}", ConsoleColor.Gray); Console.WriteLine($"From: {source}", ConsoleColor.Gray); Console.WriteLine($"To: {target}", ConsoleColor.Gray); Console.WriteLine($"Description: {description}", ConsoleColor.Gray); Console.Write($"Submit this pull request y/[n] ", ConsoleColor.Yellow); var result = System.Console.ReadLine(); if (result.Equals("yes", StringComparison.OrdinalIgnoreCase) || result.Equals("y", StringComparison.OrdinalIgnoreCase)) { var detail = vstsApiHelper.CreatePullRequest(vsts.RepositoryId, title, description, source, target); Console.WriteLine($"#{detail.PullRequestId} {detail.Title} by {detail.CreatedBy.DisplayName}"); } return(0); }); }); }
private static void AutoBasillius() { if (!ItemKeyItem.GetValue <AbilityToggler>().IsEnabled("item_ring_of_basilius") || !me.IsAlive) { return; } if (!me.IsAlive) { return; } Item bas = me.FindItem("item_ring_of_basilius"); Item aqu = me.FindItem("item_ring_of_aquila"); Item ring = bas != null ? bas : aqu; if ((bas != null || aqu != null)) { IEnumerable <Creep> creeps = ObjectManager.GetEntitiesParallel <Creep>().Where(x => x.Team == me.Team && x.IsAlive && x.IsVisible && x.IsSpawned && x.Health > 0 && x.Distance2D(me) <= 900); IEnumerable <Hero> enemies = ObjectManager.GetEntitiesParallel <Hero>().Where(x => x.Team != me.Team && x.IsAlive && x.Health > 0 && x.IsSpawned && x.IsVisible && x.Distance2D(me) <= 2000); if (creeps != null && creeps.Any() && enemies != null && enemies.Any()) { int maxDmg = enemies.Max(x => x.MaximumDamage + x.BonusDamage); int minDmg = enemies.Min(x => x.MinimumDamage + x.BonusDamage); //No Quelling Blade Support Console.WriteLine("Min: " + minDmg); Console.WriteLine("Max: " + maxDmg); foreach (Hero enemy in enemies) { if (creeps.All(creep => !(minDmg < CreepEHPCalculationBas(creep) && CreepEHPCalculationBas(creep) <= maxDmg + 1) && ring.IsToggled == false && Utils.SleepCheck("close")) && creeps != null) { Console.WriteLine("Close"); ring.ToggleAbility(); Utils.Sleep(200, "close"); } foreach (Creep creep in creeps) { if (creep.Distance2D(enemy) <= enemy.GetAttackRange() && (minDmg < CreepEHPCalculationBas(creep) && CreepEHPCalculationBas(creep) <= maxDmg + 1)) { if (Utils.SleepCheck("ring") && ring.IsToggled == true) { Console.WriteLine(ring.Name + " " + ring.IsToggled); ring.ToggleAbility(); Utils.Sleep(200, "ring"); } } } } } } //item_ring_of_basilius //item_ring_of_aquila }
public FuelEfficiencyCalculator(IEnumerable <int> crabs) { this.crabs = crabs; this.min = crabs.Min(); this.max = crabs.Max(); }
public int GetHashCode(IEnumerable <T> obj) { return(obj?.Max(t => t.GetHashCode()) ?? 0); }
public static decimal MaxDecimal <T>(this IEnumerable <T> values, string expression, string item = "p") { var predicate = _interpreter.ParseAsDelegate <Func <T, decimal> >(expression, item); return(values.Max(predicate)); }