private IList<TripleExponentialEntry> BuildLastSeason(IList<TripleExponentialEntry> currSeason, IEnumerable<DataEntry> dataEntries, int currPeriod) { //building the last season is similar to NextSeason, but uses the same Ft and Tt once calculated for the first entry. var currentFt = currSeason.Last().Ft; var currentTt = currSeason.Last().Tt; double currentSt = currSeason.Last().St, lastSt = currSeason.Last().St; var lastActual = dataEntries.Last().Value; IList<TripleExponentialEntry> newSeason = new List<TripleExponentialEntry>(); currentFt = (_alpha*(lastActual/lastSt)) + ((1 - _alpha)*(currentTt + currentFt)); currentTt = (_beta*(currentFt - currSeason.Last().Ft)) + ((1 - _beta)*currentTt); for (var currSeasonIndex = 1; currSeasonIndex <= _periodsPerSeason; currSeasonIndex++) { var lastPeriodActual = dataEntries.ElementAt((currPeriod + currSeasonIndex) - _periodsPerSeason - 2).Value; var lastPeriodFt = currSeason.ElementAt(currSeasonIndex - 1).Ft; var lastPeriodSt = currSeason.ElementAt(currSeasonIndex - 1).St; currentSt = (_gamma*(lastPeriodActual/lastPeriodFt)) + ((1 - _gamma)*lastPeriodSt); newSeason.Add(new TripleExponentialEntry { Ft = currentFt, Tt = currentTt, St = currentSt, Forecast = (currentFt + (currentTt*currSeasonIndex))*currentSt }); } return newSeason; }
// ReSharper restore InconsistentNaming #pragma warning restore 169 static void Verify(IEnumerable<Tuple<string, int>> tuples, string item1, int item2) { tuples.Count().ShouldEqual(item2); tuples.First().Item1.ShouldEqual("I"); tuples.First().Item2.ShouldEqual(1); tuples.Last().Item1.ShouldEqual(item1); tuples.Last().Item2.ShouldEqual(item2); }
public static double DistanceBetweenLineSegments(IEnumerable<Coordinate> linesegment1, IEnumerable<Coordinate> linesegment2) { double perpendicularDist = WEIGHT_PERPENIDCULAR * perpendicularDistance (linesegment1.First(), linesegment1.Last(), linesegment2.First(), linesegment2.Last()); double parallelDist = WEIGHT_PARALLEL * parallelDistance (linesegment1, linesegment2); double angleDist = WEIGHT_ANGLE * angleDistance(linesegment1.First(), linesegment1.Last(), linesegment2.First(), linesegment2.Last()); Console.WriteLine("PerpendicularDistance: " + perpendicularDist); Console.WriteLine("ParallelDistance: " + parallelDist); Console.WriteLine("AngleDistance: " + angleDist); return perpendicularDist + parallelDist + angleDist; }
private static void WriteCalls(IEnumerable<CallInfo> callInfos, IOutputWriter writer) { var lastCall = callInfos.Last(); var numberOfDigitsInLastCallNumber = lastCall.NumberOfDigitsInCallNumber(); foreach (var call in callInfos) { if (call.CallNumber > 1) { writer.WriteLine(); } writer.Write(call.CallNumber); writer.Write(": "); WriteSpaces(writer, numberOfDigitsInLastCallNumber - call.NumberOfDigitsInCallNumber()); using (writer.Indent()) { writer.Write(call.StringRepresentation); } if (call.Repeat > 1) { writer.Write(" repeated "); writer.Write(call.Repeat); writer.Write(" times"); writer.WriteLine(); writer.Write("..."); } } }
/// <summary> /// Parses the object. /// </summary> /// <param name="relativePaths">The relative paths. <example>{"site1","themes","default"}</example></param> /// <returns>the remaining paths. <example>{"site1"}</example></returns> internal override IEnumerable<string> ParseObject(IEnumerable<string> relativePaths) { var index = Array.LastIndexOf(relativePaths.Select(it => it.ToLower()).ToArray(), PATH_NAME.ToLower()); relativePaths = relativePaths.Take(index + 2); this.Name = relativePaths.Last(); return relativePaths.Take(relativePaths.Count() - 2); }
public bool ContainsFinishCase(IEnumerable<IndexDataSource> route) { bool result = false; foreach (var itemRoute in route.Skip(1)) { foreach (var finishCase in boardManager.firstIndex) { if (finishCase.Equals(itemRoute)) { result = true; break; } } if (result) { break; } } if (!result) { var firstIndex = route.First(); var firstCase = boardManager.FindCaseManager(firstIndex); if (firstCase.standDataSource != null) { var lastIndex = route.Last(); var lastCase = boardManager.FindCaseManager(lastIndex); if (lastCase.standDataSource == null) { result = true; } } } return result; }
public ForecastEntry Forecast(IEnumerable<DataEntry> dataEntries, int period, dynamic strategyParameters) { if (period - 1 < 0) return null; double alpha = strategyParameters.Alpha; double beta = strategyParameters.Beta; double value; if (dataEntries.Count() < 3 || period < 3) value = dataEntries.ElementAt(0).Value; else if (dataEntries.Count() > 1 && period <= dataEntries.Count() + 1) value = GenerateForecast(3, period, alpha, beta, dataEntries, dataEntries.First().Value, 0); else value = GenerateForecast(3, dataEntries.Count() + 1, alpha, beta, dataEntries, dataEntries.First().Value, 0); return new ForecastEntry { Period = period, DataEntry = period > dataEntries.Count() ? dataEntries.Last() : dataEntries.ElementAt(period - 1), ForecastValue = value, ConfidenceIntervalLow = value, ConfidenceIntervalHigh = value, IsHoldout = period > dataEntries.Count()*0.7 //holdout data is always 70 percent }; }
private static string buildMessage(string address, IEnumerable<INetwork> networks) { StringBuilder result = new StringBuilder(); result.Append("\""); result.Append(address); result.Append("\""); result.Append(" could refer to multiple devices: "); if (networks == null || !networks.Any()) { result.Append("(no devices given)"); } else { result.Append("{"); //TODO: use TextUtilities foreach (var network in networks) { result.Append("\""); result.Append(network.Name); result.Append("\""); if (network != networks.Last()) { result.Append(", "); } } result.Append("}"); } return result.ToString(); }
public Message( Guid id, string name, string description, Color backgroundColor, IEnumerable<IMessagePart> parts, EventHandlerCollection eventHandlerCollection = null) { name.ThrowIfNull("name"); description.ThrowIfNull("description"); parts.ThrowIfNull("parts"); parts = parts.ToArray(); IMessagePart question = parts.SingleOrDefault(arg => arg is MessageMananger); if (question != null && parts.Last() != question) { throw new ArgumentException("When a MessageQuestion is present, it must be the last part.", "parts"); } _id = id; Name = name; Description = description; _backgroundColor = backgroundColor; _parts = parts; _eventHandlerCollection = eventHandlerCollection; }
/// <summary> /// Get coords and altitude for point by it time and track /// </summary> /// <param name="pointTimeGTC">time for point</param> /// <param name="track">track</param> /// <returns>geo information for point</returns> public GeoData? GetGeoForPointByTime(DateTime pointTimeGTC, IEnumerable<GeoData> track) { if (pointTimeGTC > track.Last().CreatingDate) return null; if (pointTimeGTC < track.First().CreatingDate) return null; var trackArray = track.OrderBy(el=> el.CreatingDate).ToArray(); for (int i = 0; i < trackArray.Length - 1; i++) { var before = trackArray[i]; var after = trackArray[i + 1]; if (after.CreatingDate.Ticks == before.CreatingDate.Ticks) continue; if (pointTimeGTC >= before.CreatingDate && pointTimeGTC <= after.CreatingDate) { // acount real coords by time var koef = (double)(pointTimeGTC.Ticks- before.CreatingDate.Ticks) / (double)(after.CreatingDate.Ticks - before.CreatingDate.Ticks); return new GeoData() { Latitude = getRatioValue(before.Latitude, after.Latitude, koef), Longitude = getRatioValue(before.Longitude, after.Longitude, koef), Altitude = getRatioValue(before.Altitude, after.Altitude, koef), CreatingDate = pointTimeGTC }; } } return null; }
private static void CalculatePath(IEnumerable<int> indices) { double path = 0; int prev = -1; foreach (var current in indices) { if (prev > -1) { path += Distance(points[prev], points[current]); } prev = current; } var last = points[indices.Last()]; var first = points[indices.First()]; path += Distance(last, first); if (path < minLength) { minLength = path; shortestPath = PathToString(indices); } }
private static string buildMessage(string address, IEnumerable<IDeviceState> devices) { var result = new StringBuilder(); result.Append("\""); result.Append(address); result.Append("\""); result.Append(" could refer to multiple devices: "); if (devices == null || !devices.Any()) { result.Append("(no devices given)"); } else { result.Append("{"); foreach (var device in devices) { result.Append("\""); result.Append(device.Name); result.Append("\""); if (device != devices.Last()) { result.Append(", "); } } result.Append("}"); } return result.ToString(); }
public string ComposeUri(string baseUri, string location, object[] functionParameters, IEnumerable<KeyValuePair<string, string>> queryDictionary) { //Part 1 the basics http://thing.com/base/ + the nouns "/test" var part1 = (baseUri != null ? baseUri + "/" : "") + location; //Part 2 the parameters passed to the function call that aren't needed for the //output editor. var part2 = functionParameters == null || !functionParameters.Any() ? "" : "/" + functionParameters.Aggregate ((l, r) => l + "/" + r) + "/"; //Part 3 the querystring var part3 = ""; if (queryDictionary != null && queryDictionary.Any()) { part3 += "?"; foreach (var element in queryDictionary) { if (element.Equals (queryDictionary.Last ())) part3 += element.Key + "=" + element.Value; else part3 += element.Key + "=" + element.Value + "&"; } } return part1 + part2 + part3; }
private static int GetPartCount(IEnumerable<string> path, IEnumerable<string[]> lines) { return path.Where(e => e != "_") .Select(id => lines.Last(l => l[0] == id)) .Where(l => l[2].Contains("UnsafeResection")) .Count(); }
private static Cell MixedSelection(IEnumerable<Cell> list) { var rnd = GetRandomNumber(2); return (rnd == 0) ? list.Last() : list.Sample(); // list.First(); }
public ForecastEntry Forecast(IEnumerable<DataEntry> dataEntries, int period, dynamic strategyParameters) { if (period - 1 < 0) return null; int numberOfPeriods = strategyParameters.PeriodCount; if (numberOfPeriods > dataEntries.Count()) throw new ArgumentException("The number of periods can not be greater than the number of entries."); double value; if (dataEntries.Count() == 1 || period == 1) value = dataEntries.ElementAt(0).Value; else if (period < numberOfPeriods) value = dataEntries.ElementAt(period - 1).Value; else if (dataEntries.Count() > 1 && period <= dataEntries.Count() + 1) value = dataEntries.Take(period - 1).Reverse().Take(numberOfPeriods).Reverse().Sum(entry => (entry.Value))/ numberOfPeriods; else value = dataEntries.Reverse().Take(numberOfPeriods).Reverse().Sum(entry => (entry.Value))/ numberOfPeriods; return new ForecastEntry { Period = period, DataEntry = period > dataEntries.Count() ? dataEntries.Last() : dataEntries.ElementAt(period - 1), ForecastValue = value, ConfidenceIntervalLow = value, ConfidenceIntervalHigh = value, IsHoldout = period > dataEntries.Count()*0.7 //holdout data is always 70 percent }; }
Expression CompileNullGuard(IEnumerable<Expression> progression) { var last = progression.Last(); var lastType = last.Type; if(!_guardNulls) return last; Expression allTests = null; foreach(var i in progression) { if(i == last) break; var type = i.Type; if(!Utils.CanAssignNull(type)) continue; var test = Expression.Equal(i, Expression.Constant(null, type)); if(allTests == null) allTests = test; else allTests = Expression.OrElse(allTests, test); } return Expression.Condition( allTests, Expression.Constant(Utils.GetDefaultValue(lastType), lastType), last ); }
IPackageInfo PackageInfo(IEnumerable<IPackageInfo> packageInfos) { if (Version != null) return packageInfos.OrderByDescending(x => x.Version).FirstOrDefault(x => x.Version.Major.Equals(Version.Major) && x.Version.Major.Equals(Version.Major)); return packageInfos.Last(); }
public ExternVariableToken(Token parent, Scope scope, IEnumerable<Token> tokens, Token dataTypeToken, IEnumerable<WordToken> nameTokens) : base(parent, scope, new Span(tokens.First().Span.Start, tokens.Last().Span.End)) { _tokens = tokens.ToArray(); _dataTypeToken = dataTypeToken; _nameTokens = nameTokens.ToArray(); }
/// <summary> /// 专门生成为MiniUi生成json数据(List->json) /// </summary> /// <typeparam name="T">泛型</typeparam> /// <param name="list">实现了Ilist接口的list</param> /// <param name="total">记录总数</param> /// <param name="paramMaxMin">这里放排序的参数例如,string para=""maxAge":37,"avgAge":27,"minAge":24"</param> /// <returns>返回json数据</returns> public static string MiniUiListToJson(IEnumerable<SystemLog> SystemLogInfo, int total, string paramMaxMinAvg) { StringBuilder Json = new StringBuilder(); Json.Append("{\"total\":" + total + ",\"data\":"); Json.Append("["); foreach (SystemLog Info in SystemLogInfo) { Json.Append("{"); Json.Append("\"Id\":\"" + Info.Id + "\""); Json.Append(","); Json.Append("\"Title\":\"" + Info.Title + "\""); Json.Append(","); Json.Append("\"AddTime\":\"" + Info.AddTime.Value.GetDateTimeFormats('s')[0].ToString() + "\""); Json.Append(","); Json.Append("\"Url\":\"" + Info.Url + "\""); Json.Append(","); Json.Append("\"UserName\":\"" + Info.UserName + "\""); Json.Append("}"); if (Info != SystemLogInfo.Last()) { Json.Append(","); } } Json.Append("]}"); return Json.ToString(); }
public ExternFunctionToken(Token parent, Scope scope, IEnumerable<Token> tokens, Token dataTypeToken, IdentifierToken nameToken, BracketsToken argsToken) : base(parent, scope, new Span(tokens.First().Span.Start, tokens.Last().Span.End)) { _tokens = tokens.ToArray(); _dataTypeToken = dataTypeToken; _nameToken = nameToken; _argsToken = argsToken; }
public IEnumerable<string> FilesToDelete(IEnumerable<string> duplicates) { var keep = duplicates .FirstOrDefault(x => InPath(_keepDirectory, x)) ?? duplicates.Last(); return duplicates.Except(new[] { keep }); }
public static QueryBodySyntax WithAllClauses( this QueryBodySyntax body, IEnumerable<SyntaxNode> allClauses) { var clauses = SyntaxFactory.List(allClauses.Take(allClauses.Count() - 1).Cast<QueryClauseSyntax>()); var selectOrGroup = (SelectOrGroupClauseSyntax)allClauses.Last(); return body.WithClauses(clauses).WithSelectOrGroup(selectOrGroup); }
public void LoadsFromHistory(IEnumerable<DomainEvent> history) { foreach (var e in history) ApplyChange(e, false); Version = history.Last().Version; EventVersion = Version; }
public Task BulkSend(IEnumerable<Marble> items) { _marbles.AddRange(items); if (items.LastOrDefault()?.Kind == NotificationKind.OnCompleted) _completion.SetResult(null); else if (items.LastOrDefault()?.Kind == NotificationKind.OnError) _completion.SetException(new Exception(items.Last().Value.ToString())); return Task.CompletedTask; }
public override Character GetTarget(IEnumerable<Character> targetsList) { var enemies = targetsList.Where(target => target.Team != this.Team && target.IsAlive); if (enemies.Count() < 0) { return enemies.Last(); } return targetsList.Last(target => target.Team != this.Team); }
public string ExecuteCommand(IRemoteClient remoteClient, IEnumerable<string> parameters) { if (!parameters.Any()) { return "Missing parameters"; } var sourceFilePath = parameters.First(); var targetDirectory = parameters.Count() == 2 ? parameters.Last() : string.Empty; var filePath = remoteClient.UploadFile(sourceFilePath, targetDirectory); return string.Format("Le fichier '{0}' a bien été uploadé à l'emplacement '{1}'.", Path.GetFileName(sourceFilePath), filePath); }
public static long FindRootId(IEnumerable<Files> fileList, string subPathAgg) { long id = fileList.Last().GetfileId(); foreach (var item in fileList) { if (string.CompareOrdinal(item.GetsubPathAgg(), subPathAgg) == 0) id = item.GetfileId(); } return id; }
private bool HasCorrectStartAndEndClause(IEnumerable<string> allLines) { if (!allLines.First().Equals("digraph G {")) return false; if (!allLines.Last().Equals("}")) return false; return true; }
private VariableDeclarationToken(Token parent, Scope scope, IEnumerable<Token> tokens, Token dataTypeToken, List<IdentifierToken> nameTokens) : base(parent, scope, new Span(tokens.First().Span.Start, tokens.Last().Span.End)) { _dataTypeToken = dataTypeToken; _dataTypeToken.Parent = this; _nameTokens = nameTokens; _tokens = tokens.ToArray(); foreach (Token tok in _tokens) tok.Parent = this; }
private static double CalculateWeight(Player player, Player playerToPair, GameColorResult wantedColorResult, IEnumerable <Round> previousRounds, IEnumerable <RoundResult> standings) { var weight = 1d; if (player.PlayerId == playerToPair.PlayerId) { return(1000000); } var lastStandings = standings?.Last(); var roundNumber = previousRounds.Any() ? previousRounds.Last().RoundNumber + 1 : 1; var playerGames = GetAllPreviousGames(previousRounds, player); weight += ScorePenalty(roundNumber, lastStandings, player, playerToPair); weight += FloatingPenalty(previousRounds, standings, player, playerToPair); weight += OpponentPenalty(NumberOfTimesPlayerMetPreviously(playerToPair, playerGames)); weight += ColorPenalty(wantedColorResult, MostlyPlayedAs(playerGames, player)); weight += CountryPenalty(roundNumber, player, playerToPair); return(weight); }
public IEnumerable <TeamFeedModel> Get(HtmlNode matchContainer) { IEnumerable <string> names = ParseNames(matchContainer); if (!HasTeamNames(names)) { return(null); } IEnumerable <HtmlNode> scoreNodes = matchContainer.SelectNodes(TeamXPaths.SCORE); TeamFeedModel homeTeam = BuildTeam(names.First(), scoreNodes?.First(), matchContainer); TeamFeedModel awayTeam = BuildTeam(names.Last(), scoreNodes?.Last(), matchContainer); return(new List <TeamFeedModel>() { homeTeam, awayTeam }); }
private async Task GetAllPosts(string baseUrl) { var url = baseUrl; var count = 0; IEnumerable <RedditPostData> posts = null; do { try { posts = await _reddit.GetPosts(url); if (posts.Any()) { foreach (var post in posts.Where(p => p.CreatedUtc.FromUnixTime() >= _minimumDate)) { _posts.OnNext(post); } count += 25; var lastPost = posts?.Last(); url = $"{baseUrl}&count={count}&after={lastPost?.Name}"; _stop = posts == null || posts.Any(p => p.CreatedUtc.FromUnixTime() < _minimumDate); } else { _stop = true; } } catch (Exception ex) { _logError(ex, "Error retrieving posts"); } }while (!_stop && posts != null && posts.Any()); }
public IEnumerable <RatioAnalysis> Predict(IEnumerable <RatioAnalysis> data) { var mlContext = new MLContext(seed: 1); IEstimator <ITransformer> costofgoodsForcaster = mlContext.Forecasting.ForecastBySsa( outputColumnName: nameof(RatioAnalysisPrediction.Forecasted), inputColumnName: nameof(RatioAnalysis.CostOfGoods), // This is the column being forecasted. windowSize: 12, // Window size is set to the time period represented in the product data cycle; our product cycle is based on 12 months, so this is set to a factor of 12, e.g. 3. seriesLength: data.Count(), // This parameter specifies the number of data points that are used when performing a forecast. trainSize: data.Count(), // This parameter specifies the total number of data points in the input time series, starting from the beginning. horizon: 3, // Indicates the number of values to forecast; 3 indicates that the next 3 months of product units will be forecasted. confidenceLevel: 0.75f, // Indicates the likelihood the real observed value will fall within the specified interval bounds. confidenceLowerBoundColumn: nameof(RatioAnalysisPrediction.ConfidenceLowerBound), //This is the name of the column that will be used to store the lower interval bound for each forecasted value. confidenceUpperBoundColumn: nameof(RatioAnalysisPrediction.ConfidenceUpperBound)); //This is the name of the column that will be used to store the upper interval bound for each forecasted value. IEstimator <ITransformer> inventoryForcaster = mlContext.Forecasting.ForecastBySsa( outputColumnName: nameof(RatioAnalysisPrediction.Forecasted), inputColumnName: nameof(RatioAnalysis.Inventory), // This is the column being forecasted. windowSize: 12, // Window size is set to the time period represented in the product data cycle; our product cycle is based on 12 months, so this is set to a factor of 12, e.g. 3. seriesLength: data.Count(), // This parameter specifies the number of data points that are used when performing a forecast. trainSize: data.Count(), // This parameter specifies the total number of data points in the input time series, starting from the beginning. horizon: 3, // Indicates the number of values to forecast; 3 indicates that the next 3 months of product units will be forecasted. confidenceLevel: 0.75f, // Indicates the likelihood the real observed value will fall within the specified interval bounds. confidenceLowerBoundColumn: nameof(RatioAnalysisPrediction.ConfidenceLowerBound), //This is the name of the column that will be used to store the lower interval bound for each forecasted value. confidenceUpperBoundColumn: nameof(RatioAnalysisPrediction.ConfidenceUpperBound)); //This is the name of the column that will be used to store the upper interval bound for each forecasted value. IEstimator <ITransformer> turnoverForcaster = mlContext.Forecasting.ForecastBySsa( outputColumnName: nameof(RatioAnalysisPrediction.Forecasted), inputColumnName: nameof(RatioAnalysis.Turnover), // This is the column being forecasted. windowSize: 12, // Window size is set to the time period represented in the product data cycle; our product cycle is based on 12 months, so this is set to a factor of 12, e.g. 3. seriesLength: data.Count(), // This parameter specifies the number of data points that are used when performing a forecast. trainSize: data.Count(), // This parameter specifies the total number of data points in the input time series, starting from the beginning. horizon: 3, // Indicates the number of values to forecast; 3 indicates that the next 3 months of product units will be forecasted. confidenceLevel: 0.75f, // Indicates the likelihood the real observed value will fall within the specified interval bounds. confidenceLowerBoundColumn: nameof(RatioAnalysisPrediction.ConfidenceLowerBound), //This is the name of the column that will be used to store the lower interval bound for each forecasted value. confidenceUpperBoundColumn: nameof(RatioAnalysisPrediction.ConfidenceUpperBound)); //This is the name of the column that will be used to store the upper interval bound for each forecasted value. // Fit the forecasting model to the specified product's data series. ITransformer costofgoodsTransformer = costofgoodsForcaster.Fit(mlContext.Data.LoadFromEnumerable(data)); ITransformer inventoryTransformer = inventoryForcaster.Fit(mlContext.Data.LoadFromEnumerable(data)); ITransformer turnoverTransformer = turnoverForcaster.Fit(mlContext.Data.LoadFromEnumerable(data)); // Create the forecast engine used for creating predictions. TimeSeriesPredictionEngine <RatioAnalysis, RatioAnalysisPrediction> inventoryEngine = inventoryTransformer.CreateTimeSeriesEngine <RatioAnalysis, RatioAnalysisPrediction>(mlContext); TimeSeriesPredictionEngine <RatioAnalysis, RatioAnalysisPrediction> turneroverEngine = turnoverTransformer.CreateTimeSeriesEngine <RatioAnalysis, RatioAnalysisPrediction>(mlContext); TimeSeriesPredictionEngine <RatioAnalysis, RatioAnalysisPrediction> costofgoodEngine = costofgoodsTransformer.CreateTimeSeriesEngine <RatioAnalysis, RatioAnalysisPrediction>(mlContext); // Get the prediction; this will include the forecasted turnover for the next 3 months since this //the time period specified in the `horizon` parameter when the forecast estimator was originally created. var turnoverPrediction = turneroverEngine.Predict(); var costPrediction = costofgoodEngine.Predict(); var inventoryPrediction = inventoryEngine.Predict(); var last = data.Last(); var retVal = data.ToList(); for (int i = 0; i < turnoverPrediction.Forecasted.Count(); i++) { retVal.Add(new RatioAnalysis { Date = last.Date.AddMonths(i + 1), CostOfGoods = costPrediction.Forecasted[i], CostOfGoodsDelta = costPrediction.ConfidenceUpperBound[i] - costPrediction.Forecasted[i], Inventory = inventoryPrediction.Forecasted[i], InventoryDelta = inventoryPrediction.ConfidenceUpperBound[i] - inventoryPrediction.Forecasted[i], Turnover = turnoverPrediction.Forecasted[i], TurnoverDelta = turnoverPrediction.ConfidenceUpperBound[i] - turnoverPrediction.Forecasted[i] }); } return(retVal); }
private Token Peek(int ahead) { return(_tokens.ElementAtOrDefault(_index + ahead) ?? _tokens.Last()); }
/// <summary> /// Returns a string representing the list of items in the form "one, two, three and four". /// </summary> public static string GetEnglishListPhrase(IEnumerable <string> items, bool useSerialComma) { items = items.Where(i => i.Any()).ToArray(); switch (items.Count()) { case 0: return(""); case 1: return(items.First()); case 2: return(items.First() + " and " + items.ElementAt(1)); default: return(ConcatenateWithDelimiter(", ", items.Take(items.Count() - 1).ToArray()) + (useSerialComma ? ", and " : " and ") + items.Last()); } }
public static async Task <MSBuildProj> ParseAsync(string projectText, string projectFullPath, ILogger logger, CancellationToken cancellationToken) { using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, $"Parsing project {Path.GetFileName(projectFullPath)}").ConfigureAwait(false)) { projectFullPath = Path.GetFullPath(projectFullPath); MSBuildProj msbuildProj = new MSBuildProj { FileName = Path.GetFileName(projectFullPath), DirectoryPath = Path.GetDirectoryName(projectFullPath) }; XDocument projDefinition = XDocument.Parse(projectText); var msbuildNS = XNamespace.None; if (projDefinition.Root != null && projDefinition.Root.Name != null) { msbuildNS = projDefinition.Root.Name.Namespace; } msbuildProj._msbuildNS = msbuildNS; msbuildProj.ProjectNode = projDefinition.Element(msbuildNS + "Project"); if (msbuildProj.ProjectNode == null) { throw new Exception(Shared.Resources.ErrorInvalidProjectFormat); } // The user project can declare TargetFramework and/or TargetFrameworks property. If both are provided, TargetFramework wins. // When TargetFrameworks is provided, the project is built for every entry specified in the TargetFramework property. IEnumerable <XElement> targetFrameworkElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "PropertyGroup", "TargetFramework"); if (targetFrameworkElements.Count() > 0) { // If property is specified more than once, MSBuild will resolve it by overwriting it with the last value. var targetFramework = targetFrameworkElements.Last().Value.Trim().ToLowerInvariant(); if (!string.IsNullOrWhiteSpace(targetFramework)) { var tfx = targetFramework.Split('-'); if (tfx.Length > 1 && (tfx[0] == "net5.0" || tfx[0] == "net6.0")) { targetFramework = tfx[0]; } msbuildProj._targetFrameworks.Add(targetFramework); } } if (msbuildProj._targetFrameworks.Count == 0) { // TargetFramework was not provided, check TargetFrameworks property. IEnumerable <XElement> targetFrameworksElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "PropertyGroup", "TargetFrameworks"); if (targetFrameworksElements.Count() > 0) { var targetFrameworks = targetFrameworksElements.Last().Value; foreach (var targetFx in targetFrameworks.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim())) { if (!string.IsNullOrWhiteSpace(targetFx)) { msbuildProj._targetFrameworks.Add(targetFx); } } } } msbuildProj._targetFramework = TargetFrameworkHelper.GetBestFitTargetFramework(msbuildProj._targetFrameworks); // Ensure target framework is valid. FrameworkInfo frameworkInfo = TargetFrameworkHelper.GetValidFrameworkInfo(msbuildProj.TargetFramework); IEnumerable <XElement> runtimeIdentifierElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "PropertyGroup", "RuntimeIdentifier"); if (runtimeIdentifierElements.Count() > 0) { msbuildProj.RuntimeIdentifier = runtimeIdentifierElements.Last().Value.Trim(); } IEnumerable <XElement> packageReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "PackageReference"); foreach (XElement reference in packageReferenceElements) { if (!TryGetItemIdentity(reference, out var packageName)) { continue; } string version = GetItemValue(reference, "Version"); if (!ProjectDependency.IsValidVersion(version)) { version = ""; } ProjectDependency packageDep = ProjectDependency.FromPackage(packageName, version); msbuildProj._dependencies.Add(packageDep); } IEnumerable <XElement> toolReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "DotNetCliToolReference"); foreach (XElement reference in toolReferenceElements) { if (!TryGetItemIdentity(reference, out var packageName)) { continue; } string version = GetItemValue(reference, "Version"); ProjectDependency packageDep = ProjectDependency.FromCliTool(packageName, version); msbuildProj._dependencies.Add(packageDep); } IEnumerable <XElement> projectReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "ProjectReference"); foreach (XElement reference in projectReferenceElements) { string projectPath = GetItemValue(reference, "Include", throwIfMissing: true); ProjectDependency projectDep = ProjectDependency.FromProject(projectPath); msbuildProj._dependencies.Add(projectDep); } IEnumerable <XElement> binReferenceElements = GetSubGroupValues(msbuildProj.ProjectNode, msbuildNS, "ItemGroup", "Reference"); foreach (XElement reference in binReferenceElements) { //Find hint path or path string binReference = GetItemIdentity(reference); if (!Path.IsPathRooted(binReference)) { string fullPath = null; bool fullPathFound = true; XElement hintPath = reference.Element("HintPath"); XElement path = reference.Element("Path"); if (path != null) { fullPath = path.Value; } else if (hintPath != null) { fullPath = hintPath.Value; } else { try { fullPath = new FileInfo(Path.Combine(msbuildProj.DirectoryPath, binReference)).FullName; } catch { } if (fullPath == null || !File.Exists(fullPath)) { fullPathFound = false; // If we're only targeting .NET Core or .NET Standard projects we throw if we can't find the full path to the assembly. if (!TargetFrameworkHelper.ContainsFullFrameworkTarget(msbuildProj._targetFrameworks)) { throw new Exception(string.Format(CultureInfo.CurrentCulture, Shared.Resources.ErrorProjectReferenceMissingFilePathFormat, binReference)); } } } if (fullPathFound) { if (System.IO.Directory.Exists(fullPath)) // IsDir? { fullPath = Path.Combine(fullPath, binReference); } else if (Directory.Exists(Path.Combine(msbuildProj.DirectoryPath, fullPath))) { fullPath = Path.Combine(msbuildProj.DirectoryPath, fullPath, binReference); } binReference = fullPath; } } ProjectDependency projectDep = ProjectDependency.FromAssembly(binReference); msbuildProj._dependencies.Add(projectDep); } // ensure we have a working directory for the ProcessRunner (ProjectPropertyResolver).. if (!Directory.Exists(msbuildProj.DirectoryPath)) { Directory.CreateDirectory(msbuildProj.DirectoryPath); msbuildProj._ownsDirectory = true; } var sdkVersion = await ProjectPropertyResolver.GetSdkVersionAsync(msbuildProj.DirectoryPath, logger, cancellationToken).ConfigureAwait(false); msbuildProj.SdkVersion = sdkVersion ?? string.Empty; return(msbuildProj); } }
public static int GetNewAppointmentID() { IEnumerable <Appointment> appointments = GetAppointments(); return((appointments.Count() > 0) ? appointments.Last().ID + 1 : 0); }
private void LateUpdate() //This could be changed to a InvokeRepeating method to save processing. { float scale = 0f; if (!_firstLoad) { scale = Settings.Instance.PastNotesGridScale; _canvas.enabled = scale != 0f; transform.localScale = Vector3.one * (scale + 0.25f); if (scale == 0f) { return; } } _firstLoad = false; try { IEnumerable <BeatmapNoteContainer> allNotes = notesContainer.LoadedContainers.Where(x => x.objectData._time < atsc.CurrentBeat).Cast <BeatmapNoteContainer>(); if (!allNotes.Any() || allNotes.Last().objectData._time == lastInTime?.objectData?._time) { return; } foreach (Transform child in notes) { child.gameObject.SetActive(false); } lastInTime = allNotes.Last(); var grouped = allNotes.GroupBy(x => x.mapNoteData._type, x => x.objectData._time, (type, time) => new { LastTimes = time.Last(), Notes = allNotes.Where(x => x.mapNoteData._type == type && x.objectData._time == time.Last()) }).ToList(); List <BeatmapNoteContainer> lastNotes = new List <BeatmapNoteContainer>(); grouped.ForEach(x => lastNotes.AddRange(x.Notes)); foreach (BeatmapNoteContainer o in lastNotes) //Pulls all notes on the same grid line { if (o.mapNoteData._type == BeatmapNote.NOTE_TYPE_BOMB) { continue; } float gridPosX = o.mapNoteData._lineIndex, gridPosY = o.mapNoteData._lineLayer; if (gridPosX >= 1000) { gridPosX = gridPosX / 1000 - 1f; } else if (gridPosX <= -1000f) { gridPosX = gridPosX / 1000f + 1f; } if (gridPosY >= 1000) { gridPosY = gridPosY / 1000f - 1f; //todo: Fix this so it works! } else if (gridPosY <= -1000f) { gridPosY = gridPosY / 1000f + 1f; //todo: Fix this so it works! } GameObject g; //Instead of instantiating new objects every frame (Bad on performance), we are instead using a pooled system to use Image img; //Already existing notes, and only create ones we need. if (InstantiatedNotes.Any(x => !x.Key.activeSelf)) { g = InstantiatedNotes.First(x => !x.Key.activeSelf).Key; img = InstantiatedNotes[g]; g.SetActive(true); foreach (Transform child in g.transform) { child.gameObject.SetActive(true); } } else { g = Instantiate(gridNotePrefab, notes.transform, true); img = g.GetComponent <Image>(); InstantiatedNotes.Add(g, img); } var transform1 = img.transform; transform1.localPosition = new Vector3(_gridSize * gridPosX, _gridSize * gridPosY, 1); float sc = scale / 10f + .06f; transform1.localScale = new Vector3(sc, sc); //I have to do this because the UI scaling is weird //transform1.rotation = o.transform.rotation; //This code breaks when using 360 maps; use local rotation instead. transform1.localEulerAngles = Vector3.forward * o.transform.localEulerAngles.z; //Sets the rotation of the image to match the same rotation as the block img.color = o.transform.GetChild(0).GetComponent <MeshRenderer>().materials.FirstOrDefault(x => x.shader.name.Contains("Note")).color; //Sets the color to the same color the block is bool dotEnabled = o.transform.GetChild(1).GetComponent <SpriteRenderer>().enabled; //Checks to see if the Dot is visible on the block if (dotEnabled) { g.transform.GetChild(0).gameObject.SetActive(false); } else { g.transform.GetChild(1).gameObject.SetActive(false); } img.enabled = true; } } catch (NullReferenceException) {} }
private static string JoinUsingWritingStyle(IEnumerable <string> fragments) { return(string.Join(", ", AllButLastFragment(fragments)) + " and " + fragments.Last()); }
public void the_filter_should_not_interfere_with_script_order() { Assert.That(filesToExecute.First().Name.EndsWith("20110301_1_Test1.sql")); Assert.That(filesToExecute.Last().Name.EndsWith("Script20130525_2_Test5.sql")); }
public void the_files_should_be_correctly_ordered() { Assert.That(filesToExecute.First().Name.EndsWith("20110301_1_Test1.sql")); Assert.That(filesToExecute.Last().Name.EndsWith("Script20130525_2_Test5.sql")); }
private void GameLoop_UpdateTicked(object sender, StardewModdingAPI.Events.UpdateTickedEventArgs e) { if (waveStarted) { Game1.timeOfDay = 100 * (Game1.timeOfDay / 100); } if (!Context.IsWorldReady || !Game1.player.IsMainPlayer || !(Game1.player.currentLocation is Farm)) { return; } Farm farm = Game1.getFarm(); if (farm == null) { return; } IEnumerable <Vector2> monsterPosList = farm.characters.Where(n => n is Monster && (n as Monster).health > 0).Select(m => m.position.Value); if (!monsterPosList.Any()) { return; } foreach (Vector2 pos in monsterPosList) { KeyValuePair <Vector2, TerrainFeature> kvp = farm.terrainFeatures.Pairs.FirstOrDefault(k => k.Value is HoeDirt && (k.Value as HoeDirt).crop != null && k.Key == pos / Game1.tileSize); if (!kvp.Equals(default(KeyValuePair <Vector2, TerrainFeature>))) { (farm.terrainFeatures[kvp.Key] as HoeDirt).destroyCrop(kvp.Key, false, farm); } } foreach (KeyValuePair <Vector2, Object> crow in farm.objects.Pairs.Where(s => s.Value.bigCraftable && s.Value.Name.Contains("arecrow"))) { MurderCrow mc = murderCrows[crow.Value.Name]; IEnumerable <Vector2> monsters = monsterPosList.Where(m => Vector2.Distance(m, crow.Key * Game1.tileSize) < mc.range * Game1.tileSize).OrderBy(m => Vector2.Distance(m, crow.Key)); if (monsters.Any() && ticksSinceMorning % (1000 / mc.rate) == 0) { Vector2 dir = (monsters.Last() - crow.Key * Game1.tileSize); dir.Normalize(); if (mc.name == "Rarecrow" || mc.name == "Iridium Scarecrow") { if (ticksSinceMorning % 1000 == 0) { farm.playSound("furnace"); } float fire_angle = (float)Math.Atan2(dir.Y, dir.X); if (mc.name == "Iridium Scarecrow") { fire_angle += (float)Math.Sin((double)((float)ticksSinceMorning % 180f) * 3.1415926535897931 / 180.0) * 25f; } else { fire_angle += (float)Math.Sin((double)((float)ticksSinceMorning % 10f) * 3.1415926535897931 / 180.0); } Vector2 shot_velocity = new Vector2((float)Math.Cos((double)fire_angle), (float)Math.Sin((double)fire_angle)); shot_velocity *= 10f; BasicProjectile projectile = new BasicProjectile(mc.damage, 10, 0, 1, 0.196349546f, shot_velocity.X, shot_velocity.Y, crow.Key * Game1.tileSize, "", "", false, true, farm, Game1.MasterPlayer, false, null); projectile.ignoreTravelGracePeriod.Value = true; projectile.maxTravelDistance.Value = mc.range * 64; farm.projectiles.Add(projectile); } else { farm.projectiles.Add(new BasicProjectile(mc.damage, mc.ammoIndex, 0, 0, 0.3f, dir.X * shotVelocity, dir.Y * shotVelocity, crow.Key * Game1.tileSize, mc.hitSound, mc.fireSound, mc.explode, true, farm, Game1.MasterPlayer, mc.useTileSheet)); } } } ticksSinceMorning++; }
protected virtual void CreateFromLog(string LogContents, string InTitle) { UnrealLogParser Parser = new UnrealLogParser(LogContents); if (string.IsNullOrEmpty(InTitle)) { InTitle = "=== Snapshot: "; } try { // Find all end of match reports string[] SessionSnapshots = Parser.GetGroupsOfLinesStartingWith(InTitle, 16); SampleCount = SessionSnapshots.Length; SessionTime = 0; // convert these blocks into snapshot info Snapshots = SessionSnapshots.Select(S => { var Snapshot = new TSnapshotClass(); Snapshot.CreateFromString(S); return(Snapshot); }).ToList(); // get average MVP, GT, RT, GPU times foreach (UnrealHealthSnapshot Snap in Snapshots) { SessionTime += Snap.ProfileLength; MVP.Add(Snap.MVP); if (Snap.AvgFps > 0) { AvgFps.Add(Snap.AvgFps); } Hitches.Add(Snap.Hitches); AvgHitches.Add(Snap.AvgHitches); if (Snap.GTTime > 0) { GTTime.Add(Snap.GTTime); } if (Snap.RTTime > 0) { RTTime.Add(Snap.RTTime); } if (Snap.GPUTime > 0) { GPUTime.Add(Snap.GPUTime); } if (Snap.FTTime > 0) { FTTime.Add(Snap.FTTime); } if (Snap.RHIT > 0) { RHIT.Add(Snap.RHIT); } if (Snap.DrawCalls > 0) { DrawCalls.Add(Snap.DrawCalls); DrawnPrims.Add(Snap.DrawnPrims); } if (Snap.UnbuiltHLODs > 0) { UnbuiltHLODs.Add(Snap.UnbuiltHLODs); } } // Now get peak memory from the last health report if (Snapshots.Count() > 0) { var LastSnapshot = Snapshots.Last(); float SnapshotPeakMemory = LastSnapshot.PhysicalPeakMemory; //if PeakMemory is reporting as 0, use Memory if it's higher than our last if (SnapshotPeakMemory == 0) { Log.Info("PeakMemory reported as 0mb"); } else { PeakMemory = SnapshotPeakMemory; } } } catch (Exception Ex) { Log.Info("Failed parsing PerformanceSummary: " + Ex.ToString()); } }
public Range(IEnumerable <decimal> source) : this(source.First(), source.Last()) { }
private static Session GetLastRequestForValidation(IEnumerable <AbstractFollowRedirect> followRedirects) { return(followRedirects.Last().FiddlerSession); }
public void WhenUsingCustomSinkBuiltInSinksForSameSource() { string fileName1 = "multipleFlatFile.log"; File.Delete(fileName1); string fileName2 = "multipleMockFlatFile.log"; File.Delete(fileName2); var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString; DatabaseHelper.CleanLoggingDB(validConnectionString); var logger = MockEventSourceOutProc.Logger; string message = string.Concat("Message ", Guid.NewGuid()); string message2 = string.Concat("Message2 ", Guid.NewGuid()); IEnumerable <string> entries = null; IEnumerable <string> entries2 = null; var svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\CustomSink\\Multiple.xml"); using (TraceEventService collector = new TraceEventService(svcConfiguration)) { try { collector.Start(); logger.LogSomeMessage(message); logger.LogSomeMessage(message2); entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName1, 2, "--==--"); entries2 = FlatFileHelper.PollUntilTextEventsAreWritten(fileName2, 2, "==-=="); DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 4); } finally { collector.Stop(); } } Assert.IsTrue(File.Exists(fileName1)); Assert.AreEqual <int>(2, entries.Count()); StringAssert.Contains(entries.First().ToString(), message); StringAssert.Contains(entries.Last().ToString(), message2); Assert.IsTrue(File.Exists(fileName2)); Assert.AreEqual <int>(2, entries.Count()); StringAssert.Contains(entries.First().ToString(), message); StringAssert.Contains(entries.Last().ToString(), message2); var dt = DatabaseHelper.GetLoggedTable(validConnectionString); Assert.AreEqual(4, dt.Rows.Count); var rowsWithMessage1 = dt.Select(string.Format("Payload like '%{0}%'", message)); Assert.AreEqual(2, rowsWithMessage1.Count()); var dr = rowsWithMessage1[0]; Assert.AreEqual(4, (int)dr["Level"]); Assert.AreEqual(8, (int)dr["EventID"]); Assert.AreEqual("testingInstance", dr["InstanceName"].ToString()); StringAssert.Contains((string)dr["Payload"], message); dr = rowsWithMessage1[1]; Assert.AreEqual(4, (int)dr["Level"]); Assert.AreEqual(8, (int)dr["EventID"]); Assert.AreEqual("testingInstance", dr["InstanceName"].ToString()); StringAssert.Contains((string)dr["Payload"], message); var rowsWithMessage2 = dt.Select(string.Format("Payload like '%{0}%'", message2)); Assert.AreEqual(2, rowsWithMessage2.Count()); dr = rowsWithMessage2[0]; Assert.AreEqual(4, (int)dr["Level"]); Assert.AreEqual(8, (int)dr["EventID"]); Assert.AreEqual("testingInstance", dr["InstanceName"].ToString()); StringAssert.Contains((string)dr["Payload"], message2); dr = rowsWithMessage2[1]; Assert.AreEqual(4, (int)dr["Level"]); Assert.AreEqual(8, (int)dr["EventID"]); Assert.AreEqual("testingInstance", dr["InstanceName"].ToString()); StringAssert.Contains((string)dr["Payload"], message2); }
private MemberAccessPath FollowPathUnflattening(Type type, IEnumerable <string> memberNames, ITargetMemberProvider memberProvider) { var accessPath = new MemberAccessPath(type); foreach (var splitName in memberNames.Take(memberNames.Count() - 1)) { var members = memberProvider.GetMembers(type) .Where(m => m.Name == splitName).ToArray(); if (members.Length == 0) { var getMethodPrefixes = new string[] { "Get_", "Get", "get", "get_" }; foreach (var prefix in getMethodPrefixes) { members = memberProvider.GetMembers(type) .Where(m => m.Name == prefix + splitName).ToArray(); if (members.Length > 0) { break; } } if (members.Length == 0) { return(null); } } var sourceMember = members?[0]; type = sourceMember.GetMemberType(); accessPath.Add(sourceMember); } { var members = memberProvider.GetMembers(type) .Where(m => m.Name == memberNames.Last()).ToArray(); if (members.Length == 0) { var getMethodPrefixes = new string[] { "Set_", "Set", "set", "set_" }; foreach (var prefix in getMethodPrefixes) { members = memberProvider.GetMembers(type) .Where(m => m.Name == prefix + memberNames.Last()).ToArray(); if (members.Length > 0) { break; } } if (members.Length == 0) { return(null); } } var sourceMember = members?[0]; type = sourceMember.GetMemberType(); accessPath.Add(sourceMember); } return(accessPath); }
private void UpdateCardDisplay() { spExtraStuff.Visibility = System.Windows.Visibility.Visible; spExtraStuff.Children.Clear(); this.Tokens.ForEach(t => spExtraStuff.Children.Add(new Controls.ucTokenIcon { Token = t, Size = CardSize.Text })); if (spExtraStuff.Children.Count == 0) { spExtraStuff.Visibility = System.Windows.Visibility.Collapsed; } Size stackOffset = new Size(); switch (this.CardSize) { case NET_WPF.CardSize.Text: break; case NET_WPF.CardSize.SmallText: dpName.Height = 16; lCount.Margin = new Thickness(0); lName.Padding = new Thickness(0); lName.Margin = new Thickness(0, 0, 2, 0); this.Padding = new Thickness(0); break; case NET_WPF.CardSize.Small: stackOffset = new Size(12, 6); break; case NET_WPF.CardSize.Medium: stackOffset = new Size(24, 10); break; } lCount.Visibility = System.Windows.Visibility.Collapsed; if (_CardCollection.Count() > 4 || (gImages.Visibility == System.Windows.Visibility.Collapsed && _CardCollection.Count() > 1)) { lCount.Visibility = System.Windows.Visibility.Visible; if (IsCardsVisible && PileVisibility == DominionBase.Piles.Visibility.All) { lCount.Content = String.Format("{0}x", _CardCollection.Count()); } stackOffset.Width = 0.75 * stackOffset.Width; } //else if (this.CardSize == NET_WPF.CardSize.SmallText) //{ // lCount.Visibility = System.Windows.Visibility.Collapsed; //} if (_CardCollection.Count() > 6 && stackOffset.Height > 0) { float verticalScale = 56f / (_CardCollection.Count() - 1); stackOffset = new Size((int)(0.625 * stackOffset.Width * verticalScale / stackOffset.Height), (int)verticalScale); } if (this.PileVisibility != DominionBase.Piles.Visibility.All) { stackOffset.Width = 0; } for (int index = 0; index < _CardCollection.Count(); index++) { DominionBase.ICard card = _CardCollection.ElementAt(index); if (card == null) { continue; } if (IsCardsVisible && PileVisibility == DominionBase.Piles.Visibility.All || PileVisibility == DominionBase.Piles.Visibility.Top) { DominionBase.Cards.Category category = card.Category; if (card is DominionBase.Cards.Card) { category = ((DominionBase.Cards.Card)card).PhysicalCategory; } lName.Background = Caching.BrushRepository.GetBackgroundBrush(category); lName.Foreground = Caching.BrushRepository.GetForegroundBrush(category); if ((category & DominionBase.Cards.Category.Reaction) == DominionBase.Cards.Category.Reaction) { tbName.Effect = Caching.DropShadowRepository.GetDSE(8, Colors.White, 1d); } } if (gImages.Visibility == System.Windows.Visibility.Visible) { Image newImage = new Image(); Caching.ImageRepository repo = Caching.ImageRepository.Acquire(); switch (this.CardSize) { case NET_WPF.CardSize.Small: if (IsCardsVisible && (PileVisibility == DominionBase.Piles.Visibility.All || PileVisibility == DominionBase.Piles.Visibility.Top) && card.CardType != DominionBase.Cards.Universal.TypeClass.Dummy) { newImage.Source = repo.GetBitmapImage(card.Name.Replace(" ", "").Replace("'", ""), "small"); } else { switch (card.CardBack) { case DominionBase.Cards.CardBack.Standard: newImage.Source = repo.GetBitmapImage("back", "small"); break; case DominionBase.Cards.CardBack.Red: newImage.Source = repo.GetBitmapImage("back_red", "small"); break; } } break; case NET_WPF.CardSize.Medium: if (IsCardsVisible && (PileVisibility == DominionBase.Piles.Visibility.All || PileVisibility == DominionBase.Piles.Visibility.Top) && card.CardType != DominionBase.Cards.Universal.TypeClass.Dummy) { newImage.Source = repo.GetBitmapImage(card.Name.Replace(" ", "").Replace("'", ""), "medium"); } else { switch (card.CardBack) { case DominionBase.Cards.CardBack.Standard: newImage.Source = repo.GetBitmapImage("back", "medium"); break; case DominionBase.Cards.CardBack.Red: newImage.Source = repo.GetBitmapImage("back_red", "medium"); break; } } break; } Caching.ImageRepository.Release(); if (newImage.Source != null) { newImage.Width = newImage.Source.Width; newImage.Height = newImage.Source.Height; } newImage.HorizontalAlignment = HorizontalAlignment.Left; newImage.VerticalAlignment = VerticalAlignment.Top; newImage.Margin = new Thickness(index * stackOffset.Width, index * stackOffset.Height, 0, 0); newImage.Tag = card; gImages.Children.Insert(gImages.Children.Count - 1, newImage); } } this.Title = String.Empty; if (_CardCollection.Count() > 0 && IsCardsVisible) { if (PileVisibility == DominionBase.Piles.Visibility.All || PileVisibility == DominionBase.Piles.Visibility.Top) { DominionBase.ICard card = _CardCollection.Last(); if (card != null) { this.Title = card.Name; ttcCard.ICard = card; } } } UpdateGlowEffectAll(); if (!IsCardsVisible || PileVisibility == DominionBase.Piles.Visibility.None) { int count = _CardCollection.Count(); if (this.ExactCount || count <= 1) { this.Title = StringUtility.Plural("Card", count); } } }
private void storeLastGlucoseInfo(IEnumerable <ILogLine> glucoseLines) { LastGlucoseTimestamp = glucoseLines.Last().Timestamp; LastGlucoseValue = getAverageGlucose(glucoseLines); }
/// <summary> /// Checks if the formula is a valid input, if not it will throw an error /// </summary> /// <param name="tokens"></param> private void IsValidInput(IEnumerable <string> tokens) { bool prenth = false; bool firstToken = true; bool IsOpenParenthOrOp = false; bool isOtherFollowingRule = false; int rightPrenth = 0; int leftPrenth = 0; int operators = 0; foreach (string input in tokens) { //if firest token, must be number, variable, or open parenth if (firstToken) { if (!(Regex.IsMatch(input, @"-?\d+(?:\.\d+)?") || Regex.IsMatch(input, "[a-zA-Z]") || input == "(")) { throw new FormulaFormatException("Incorrect Input"); } firstToken = false; } //must be number, variable, op, or parenth if (!(Regex.IsMatch(input, @"-?\d+(?:\.\d+)?") || Regex.IsMatch(input, "[a-zA-Z]") || input == "+" || input == "-" || input == "*" || input == "/" || input == "(" || input == ")")) { throw new FormulaFormatException("Incorrect Input"); } //balancing of parenth if (input == "(") { leftPrenth++; prenth = true; } else if (input == ")") { rightPrenth++; if (rightPrenth > leftPrenth) { throw new FormulaFormatException("Incorrect Input"); } prenth = false; } else if (prenth && input == "+" || input == "-" || input == "*" || input == "/") { operators++; } //parenth following rule if (IsOpenParenthOrOp) { if (input == "+" || input == "-" || input == "*" || input == "/" || input == ")") { throw new FormulaFormatException("Incorrect Input"); } } IsOpenParenthOrOp = false; //extra following rule if (isOtherFollowingRule) { if (!(input == "+" || input == "-" || input == "*" || input == "/" || input == ")")) { throw new FormulaFormatException("Incorrect Input"); } } isOtherFollowingRule = false; if (Regex.IsMatch(input, @"-?\d+(?:\.\d+)?") || Regex.IsMatch(input, "[a-zA-Z]") || input == ")") { isOtherFollowingRule = true; } //checks to see if it is another open parenth, if so isOpenParenthOrOp is true if (input == "(" || input == "+" || input == "-" || input == "*" || input == "/") { IsOpenParenthOrOp = true; } } //last checks before it is a valid formula if (tokens.Last() == "+" || tokens.Last() == "-" || tokens.Last() == "*" || tokens.Last() == "/" || tokens.Last() == "(") { throw new FormulaFormatException("Incorrect Input"); } if (rightPrenth != leftPrenth) { throw new FormulaFormatException("Incorrect Input"); } if (rightPrenth > 0 && operators == 0) { throw new FormulaFormatException("Incorrect Input"); } if (tokens.Count() < 1) { throw new FormulaFormatException("Incorrect Input"); } }
/// <summary> /// Queues a collection of measurements for processing. /// </summary> /// <param name="measurements">Measurements to queue for processing.</param> public override void QueueMeasurementsForProcessing(IEnumerable <IMeasurement> measurements) { base.QueueMeasurementsForProcessing(measurements); ManageThrottleAdjustments((int)measurements.Last().Value); }
public async Task <RedirectToRouteResult> UpdateProject(ManageProjectManagementModel model, List <string> idTasks, List <string> idTeamMember, List <string> idRoleInProject) { var projects = await unitOfWork.ProjectRepository.GetByID(model.ProjectId); if (projects == null) { IEnumerable <AccountEntity> allAccountEntity = await unitOfWork.AccountRepository.GetAll(); IEnumerable <TaskEntity> allTaskEntity = await unitOfWork.TaskRepository.GetAll(); IEnumerable <RoleEntity> roleByProjectEntity = await unitOfWork.RoleRepository.GetAll(); ProjectEntity projectEntity = new ProjectEntity(); projectEntity.ProjectId = model.ProjectId; projectEntity.Name = model.ProjectName; projectEntity.Description = model.Description; IList <TaskEntity> tasksInProject = new List <TaskEntity>(); IList <Teammate> teammatesInProject = new List <Teammate>(); foreach (var task in idTasks) { tasksInProject.Add(new TaskEntity { TaskId = allTaskEntity.Count() + 1, Title = allTasks.FirstOrDefault(m => m.Key == int.Parse(task)).Value, ProjectId = model.ProjectId }); } int i = 0; foreach (var teammate in idTeamMember) { teammatesInProject.Add(new Teammate { AccountId = int.Parse(teammate), ProjectId = model.ProjectId, RoleId = int.Parse(idRoleInProject[i++]) }); } projectEntity.Tasks = tasksInProject; projectEntity.Teammates = teammatesInProject; unitOfWork.ProjectRepository.Insert(projectEntity); unitOfWork.Save(); } else { IEnumerable <AccountEntity> allAccountEntity = await unitOfWork.AccountRepository.GetAll(); IEnumerable <TaskEntity> allTaskEntity = await unitOfWork.TaskRepository.GetAll(); IEnumerable <RoleEntity> roleByProjectEntity = await unitOfWork.RoleRepository.GetAll(); ProjectEntity projectEntity = await unitOfWork.ProjectRepository.GetByID(model.ProjectId); projectEntity.ProjectId = model.ProjectId; projectEntity.Name = model.ProjectName; projectEntity.Description = model.Description; if (idTasks != null) { for (int j = 0; j < projectEntity.Tasks.Count; j++) { if (idTasks.FirstOrDefault(m => int.Parse(m) == projectEntity.Tasks.ElementAt(j).TaskId) == null) { unitOfWork.TaskRepository.Delete(projectEntity.Tasks.ElementAt(j)); unitOfWork.Save(); } } foreach (var task in idTasks) { if (projectEntity.Tasks.FirstOrDefault(m => m.TaskId == int.Parse(task)) == null) { projectEntity.Tasks.Add(new TaskEntity { TaskId = allTaskEntity.Last().TaskId + 1, Title = allTasks.FirstOrDefault(m => m.Key == int.Parse(task)).Value, ProjectId = model.ProjectId, Description = "" }); } } } else { for (int j = 0; j < projectEntity.Tasks.Count; j++) { unitOfWork.TaskRepository.Delete(projectEntity.Tasks.ElementAt(j)); unitOfWork.Save(); } } if (idTeamMember != null) { for (int j = 0; j < projectEntity.Teammates.Count; j++) { if (idTeamMember.FirstOrDefault(m => int.Parse(m) == projectEntity.Teammates.ElementAt(j).AccountId) == null) { projectEntity.Teammates.Remove(projectEntity.Teammates.ElementAt(j)); } } int i = 0; foreach (var teammate in idTeamMember) { var proj = await unitOfWork.ProjectRepository.GetAll(); if (proj.FirstOrDefault(x => x.ProjectId == model.ProjectId).Teammates.FirstOrDefault(m => m.AccountId == int.Parse(teammate)) == null) { projectEntity.Teammates.Add(new Teammate { AccountId = int.Parse(teammate), ProjectId = model.ProjectId, RoleId = int.Parse(idRoleInProject[i]), Account = await unitOfWork.AccountRepository.GetByID(int.Parse(teammate)), Project = await unitOfWork.ProjectRepository.GetByID(model.ProjectId), Role = await unitOfWork.RoleRepository.GetByID(int.Parse(idRoleInProject[i++])) }); } } } else { for (int j = 0; j < projectEntity.Teammates.Count; j++) { projectEntity.Teammates.Remove(projectEntity.Teammates.ElementAt(j)); } } unitOfWork.ProjectRepository.Update(projectEntity); unitOfWork.Save(); } return(RedirectToAction("Index")); }
public async Task PerformShopCommand(UserViewModel user, IEnumerable <string> arguments = null) { try { if (ChannelSession.Chat != null && ChannelSession.Settings.Currencies.ContainsKey(this.ShopCurrencyID)) { UserCurrencyViewModel currency = ChannelSession.Settings.Currencies[this.ShopCurrencyID]; if (arguments != null && arguments.Count() > 0) { string arg1 = arguments.ElementAt(0); if (arguments.Count() == 1 && arg1.Equals("list", StringComparison.InvariantCultureIgnoreCase)) { List <string> items = new List <string>(); foreach (UserInventoryItemViewModel item in this.Items.Values) { if (item.HasBuyAmount || item.HasSellAmount) { items.Add(item.Name); } } await ChannelSession.Chat.Whisper(user.UserName, "Items Available to Buy/Sell: " + string.Join(", ", items)); return; } else if (arguments.Count() >= 2 && (arg1.Equals("buy", StringComparison.InvariantCultureIgnoreCase) || arg1.Equals("sell", StringComparison.InvariantCultureIgnoreCase))) { int amount = 1; IEnumerable <string> itemArgs = arguments.Skip(1); UserInventoryItemViewModel item = this.GetItem(string.Join(" ", itemArgs)); if (item == null && itemArgs.Count() > 1) { itemArgs = itemArgs.Take(itemArgs.Count() - 1); item = this.GetItem(string.Join(" ", itemArgs)); if (item != null) { if (!int.TryParse(arguments.Last(), out amount) || amount <= 0) { await ChannelSession.Chat.Whisper(user.UserName, "A valid amount greater than 0 must be specified"); return; } } } if (item == null) { await ChannelSession.Chat.Whisper(user.UserName, "The item you specified does not exist"); return; } int totalcost = 0; CustomCommand command = null; if (arg1.Equals("buy", StringComparison.InvariantCultureIgnoreCase)) { if (item.HasBuyAmount) { totalcost = item.BuyAmount * amount; if (user.Data.HasCurrencyAmount(currency, totalcost)) { user.Data.SubtractCurrencyAmount(currency, totalcost); user.Data.AddInventoryAmount(this, item.Name, amount); command = this.ItemsBoughtCommand; } else { await ChannelSession.Chat.Whisper(user.UserName, string.Format("You do not have the required {0} {1} to purchase this item", totalcost, currency.Name)); } } else { await ChannelSession.Chat.Whisper(user.UserName, "This item is not available for buying"); } } else if (arg1.Equals("sell", StringComparison.InvariantCultureIgnoreCase)) { if (item.HasSellAmount) { totalcost = item.SellAmount * amount; if (user.Data.HasInventoryAmount(this, item.Name, amount)) { user.Data.SubtractInventoryAmount(this, item.Name, amount); user.Data.AddCurrencyAmount(currency, totalcost); command = this.ItemsSoldCommand; } else { await ChannelSession.Chat.Whisper(user.UserName, string.Format("You do not have the required {0} {1} to sell", amount, item.Name)); } } else { await ChannelSession.Chat.Whisper(user.UserName, "This item is not available for selling"); } } else { await ChannelSession.Chat.Whisper(user.UserName, "You must specify either \"buy\" & \"sell\""); } if (command != null) { Dictionary <string, string> specialIdentifiers = new Dictionary <string, string>(); specialIdentifiers["itemtotal"] = amount.ToString(); specialIdentifiers["itemname"] = item.Name; specialIdentifiers["itemcost"] = totalcost.ToString(); specialIdentifiers["currencyname"] = currency.Name; await command.Perform(user, arguments : arguments, extraSpecialIdentifiers : specialIdentifiers); } return; } else { UserInventoryItemViewModel item = this.GetItem(string.Join(" ", arguments)); if (item != null) { if (item.HasBuyAmount || item.HasSellAmount) { StringBuilder itemInfo = new StringBuilder(); itemInfo.Append(item.Name + ": "); if (item.HasBuyAmount) { itemInfo.Append(string.Format("Buy = {0} {1}", item.BuyAmount, currency.Name)); } if (item.HasBuyAmount && item.HasSellAmount) { itemInfo.Append(string.Format(", ")); } if (item.HasSellAmount) { itemInfo.Append(string.Format("Sell = {0} {1}", item.SellAmount, currency.Name)); } await ChannelSession.Chat.Whisper(user.UserName, itemInfo.ToString()); } else { await ChannelSession.Chat.Whisper(user.UserName, "This item is not available to buy/sell"); } } else { await ChannelSession.Chat.Whisper(user.UserName, "The item you specified does not exist"); } return; } } StringBuilder storeHelp = new StringBuilder(); storeHelp.Append(this.ShopCommand + " list = Lists all the items available for buying/selling ** "); storeHelp.Append(this.ShopCommand + " <ITEM NAME> = Lists the buying/selling price for the item ** "); storeHelp.Append(this.ShopCommand + " buy <ITEM NAME> [AMOUNT] = Buys 1 or the amount specified of the item ** "); storeHelp.Append(this.ShopCommand + " sell <ITEM NAME> [AMOUNT] = Sells 1 or the amount specified of the item"); await ChannelSession.Chat.Whisper(user.UserName, storeHelp.ToString()); } } catch (Exception ex) { Logger.Log(ex); } }
public async Task GetTransactionOnTransactionReceivedToMultipleAddressesAsync() { using (NodeBuilder builder = NodeBuilder.Create(this)) { // Arrange. // Create a sending and a receiving node. CoreNode sendingNode = builder.CreateStratisPosNode(this.network).WithReadyBlockchainData(ReadyBlockchain.StratisRegTest150Miner).Start(); CoreNode receivingNode = builder.CreateStratisPosNode(this.network).WithReadyBlockchainData(ReadyBlockchain.StratisRegTest150Listener).Start(); TestHelper.ConnectAndSync(sendingNode, receivingNode); // Get an address to send to. IEnumerable <string> unusedaddresses = await $"http://localhost:{receivingNode.ApiPort}/api" .AppendPathSegment("wallet/unusedAddresses") .SetQueryParams(new { walletName = "mywallet", accountName = "account 0", count = 2 }) .GetJsonAsync <IEnumerable <string> >(); // Build and send the transaction with an Op_Return. WalletBuildTransactionModel buildTransactionModel = await $"http://localhost:{sendingNode.ApiPort}/api" .AppendPathSegment("wallet/build-transaction") .PostJsonAsync(new BuildTransactionRequest { WalletName = "mywallet", AccountName = "account 0", FeeType = "low", Password = "******", ShuffleOutputs = false, AllowUnconfirmed = true, Recipients = unusedaddresses.Select(address => new RecipientModel { DestinationAddress = address, Amount = "1" }).ToList() }) .ReceiveJson <WalletBuildTransactionModel>(); await $"http://localhost:{sendingNode.ApiPort}/api" .AppendPathSegment("wallet/send-transaction") .PostJsonAsync(new SendTransactionRequest { Hex = buildTransactionModel.Hex }) .ReceiveJson <WalletSendTransactionModel>(); uint256 txId = buildTransactionModel.TransactionId; // Mine and sync so that we make sure the receiving node is up to date. TestHelper.MineBlocks(sendingNode, 1); TestHelper.WaitForNodeToSync(sendingNode, receivingNode); // Get the block that was mined. string lastBlockHash = await $"http://localhost:{sendingNode.ApiPort}/api" .AppendPathSegment("consensus/getbestblockhash") .GetJsonAsync <string>(); BlockModel tip = await $"http://localhost:{sendingNode.ApiPort}/api" .AppendPathSegment("blockstore/block") .SetQueryParams(new { hash = lastBlockHash, outputJson = true }) .GetJsonAsync <BlockModel>(); Transaction trx = this.network.Consensus.ConsensusFactory.CreateTransaction(buildTransactionModel.Hex); RPCClient rpcReceivingNode = receivingNode.CreateRPCClient(); RPCResponse txReceivingWallet = rpcReceivingNode.SendCommand(RPCOperations.gettransaction, txId.ToString()); RPCClient rpcSendingNode = sendingNode.CreateRPCClient(); RPCResponse txSendingWallet = rpcSendingNode.SendCommand(RPCOperations.gettransaction, txId.ToString()); // Assert. GetTransactionModel resultSendingWallet = txSendingWallet.Result.ToObject <GetTransactionModel>(); resultSendingWallet.Amount.Should().Be((decimal) - 2.00000000); resultSendingWallet.Fee.Should().Be((decimal) - 0.0001); resultSendingWallet.Confirmations.Should().Be(1); resultSendingWallet.Isgenerated.Should().BeNull(); resultSendingWallet.TransactionId.Should().Be(txId); resultSendingWallet.BlockHash.Should().Be(uint256.Parse(tip.Hash)); resultSendingWallet.BlockIndex.Should().Be(1); resultSendingWallet.BlockTime.Should().Be(tip.Time.ToUnixTimeSeconds()); resultSendingWallet.TimeReceived.Should().BeGreaterThan((DateTimeOffset.Now - TimeSpan.FromMinutes(1)).ToUnixTimeSeconds()); resultSendingWallet.TransactionTime.Should().Be(trx.Time); resultSendingWallet.Details.Count.Should().Be(2); GetTransactionDetailsModel detailsSendingWalletFirstRecipient = resultSendingWallet.Details.Single(d => d.Address == unusedaddresses.First()); detailsSendingWalletFirstRecipient.Address.Should().Be(unusedaddresses.First()); detailsSendingWalletFirstRecipient.Amount.Should().Be((decimal) - 1.00000000); detailsSendingWalletFirstRecipient.Fee.Should().Be((decimal) - 0.0001); detailsSendingWalletFirstRecipient.Category.Should().Be(GetTransactionDetailsCategoryModel.Send); detailsSendingWalletFirstRecipient.OutputIndex.Should().Be(1); // Output at index 0 contains the change. GetTransactionDetailsModel detailsSendingWalletSecondRecipient = resultSendingWallet.Details.Single(d => d.Address == unusedaddresses.Last()); detailsSendingWalletSecondRecipient.Address.Should().Be(unusedaddresses.Last()); detailsSendingWalletSecondRecipient.Amount.Should().Be((decimal) - 1.00000000); detailsSendingWalletSecondRecipient.Fee.Should().Be((decimal) - 0.0001); detailsSendingWalletSecondRecipient.Category.Should().Be(GetTransactionDetailsCategoryModel.Send); detailsSendingWalletSecondRecipient.OutputIndex.Should().Be(2); // Checking receiver. GetTransactionModel resultReceivingWallet = txReceivingWallet.Result.ToObject <GetTransactionModel>(); resultReceivingWallet.Amount.Should().Be((decimal)2.00000000); resultReceivingWallet.Fee.Should().BeNull(); resultReceivingWallet.Confirmations.Should().Be(1); resultReceivingWallet.Isgenerated.Should().BeNull(); resultReceivingWallet.TransactionId.Should().Be(txId); resultReceivingWallet.BlockHash.Should().Be(uint256.Parse(tip.Hash)); resultReceivingWallet.BlockIndex.Should().Be(1); resultReceivingWallet.BlockTime.Should().Be(tip.Time.ToUnixTimeSeconds()); resultReceivingWallet.TimeReceived.Should().BeGreaterThan((DateTimeOffset.Now - TimeSpan.FromMinutes(1)).ToUnixTimeSeconds()); resultReceivingWallet.TransactionTime.Should().BeGreaterThan((DateTimeOffset.Now - TimeSpan.FromMinutes(1)).ToUnixTimeSeconds()); resultReceivingWallet.Details.Count.Should().Be(2); GetTransactionDetailsModel firstDetailsReceivingWallet = resultReceivingWallet.Details.Single(d => d.Address == unusedaddresses.First()); firstDetailsReceivingWallet.Address.Should().Be(unusedaddresses.First()); firstDetailsReceivingWallet.Amount.Should().Be((decimal)1.00000000); firstDetailsReceivingWallet.Fee.Should().BeNull(); firstDetailsReceivingWallet.Category.Should().Be(GetTransactionDetailsCategoryModel.Receive); firstDetailsReceivingWallet.OutputIndex.Should().Be(1); // Output at index 0 contains the change. GetTransactionDetailsModel secondDetailsReceivingWallet = resultReceivingWallet.Details.Single(d => d.Address == unusedaddresses.Last()); secondDetailsReceivingWallet.Address.Should().Be(unusedaddresses.Last()); secondDetailsReceivingWallet.Amount.Should().Be((decimal)1.00000000); secondDetailsReceivingWallet.Fee.Should().BeNull(); secondDetailsReceivingWallet.Category.Should().Be(GetTransactionDetailsCategoryModel.Receive); secondDetailsReceivingWallet.OutputIndex.Should().Be(2); } }
// getting a list of daily data NASA (1983-2005) public ActionResult ParseNASA1983Daily(bool?post) { string report = ""; DateTime start = DateTime.Now; int count = 0; decimal longitude_min = 45 - 0.5m, longitude_max = 95 + 0.5m, latitude_min = 39 - 0.5m, latitude_max = 56 + 0.5m; List <MeteoDataType> meteodatatypes = new List <MeteoDataType>(); using (var db = new NpgsqlContext()) { meteodatatypes = db.MeteoDataTypes .Where(m => m.MeteoDataSource.Code == "NASA (1983-2005)" && m.MeteoDataPeriodicity.Code == "Daily") .ToList(); db.Dispose(); GC.Collect(); } List <int> meteodatatypeids = meteodatatypes .Select(m => m.Id) .ToList(); string CurrentUserId = User.Identity.GetUserId(); string path = "~/Upload/" + CurrentUserId; bool error = false; try { if (!Directory.Exists(Server.MapPath(path))) { DirectoryInfo di = Directory.CreateDirectory(Server.MapPath(path)); } } catch (Exception e) { report += "<br/>" + e.Message; error = true; } if (!error) { bool go = false; for (decimal latitude = latitude_min; latitude <= latitude_max; latitude++) { for (decimal longitude = longitude_min; longitude <= longitude_max; longitude++) { string filenameout = Path.Combine(Server.MapPath(path), $"From NASA (1983-2005) {latitude.ToString()} - {longitude.ToString()}.txt"); using (StreamWriter sw = System.IO.File.AppendText(filenameout)) { if (!go) { using (var db = new NpgsqlContext()) { if (db.MeteoDatas.Where(m => m.Longitude == longitude && m.Latitude == latitude && meteodatatypeids.Contains(m.MeteoDataTypeId)).FirstOrDefault() != null) { db.Dispose(); GC.Collect(); continue; } go = true; db.Dispose(); GC.Collect(); } } string url = "https://eosweb.larc.nasa.gov/cgi-bin/sse/daily.cgi?email=skip%40larc.nasa.gov&step=1&lat=" + latitude.ToString().Replace(",", ".") + "&lon=" + longitude.ToString().Replace(",", ".") + "&sitelev=&ms=1&ds=1&ys=1983&me=12&de=31&ye=2005&p=swv_dwn&p=avg_kt&p=clr_sky&p=clr_dif&p=clr_dnr&p=clr_kt&p=lwv_dwn&p=toa_dwn&p=PS&p=TSKIN&p=T10M&p=T10MN&p=T10MX&p=Q10M&p=RH10M&p=DFP10M&submit=Submit&plot=swv_dwn"; HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument(); html.LoadHtml(new WebClient().DownloadString(url)); HtmlAgilityPack.HtmlNode root = html.DocumentNode; string slat = "", slon = ""; foreach (HtmlAgilityPack.HtmlNode td in root.Descendants("td")) { if (td.InnerText.IndexOf("Center") >= 0) { IEnumerable <HtmlAgilityPack.HtmlNode> bs = td.Descendants("b"); slat = bs.First().InnerText; slon = bs.Last().InnerText; break; } } string file_url = "https://eosweb.larc.nasa.gov"; foreach (HtmlAgilityPack.HtmlNode node in root.Descendants()) { if ((node.Name == "a") && (node.InnerText == "Download a text file")) { file_url += node.GetAttributeValue("href", ""); break; } } string file = (new WebClient()).DownloadString(file_url); string[] lines = file.Split('\n'); List <string> columns = new List <string>(); foreach (string line in lines) { if (line.Length == 0) { continue; } string s = line; while (s.Contains(" ")) { s = s.Replace(" ", " "); } string[] linecolumns = s.Split(' '); if (columns.Count > 0) { for (int c = 3; c < columns.Count; c++) { sw.WriteLine(meteodatatypes.Where(m => m.Code == columns[c]).FirstOrDefault().Id.ToString() + "\t" + linecolumns[0] + "\t" + linecolumns[1] + "\t" + linecolumns[2] + "\t" + "\t" + slon + "\t" + slat + "\t" + ((linecolumns[c] == "-") ? "" : linecolumns[c]) ); count++; } } if (line.Contains("YEAR MO DY")) { foreach (string linecolumn in linecolumns) { columns.Add(linecolumn); } } } } } } for (decimal latitude = latitude_min; latitude <= latitude_max; latitude++) { for (decimal longitude = longitude_min; longitude <= longitude_max; longitude++) { string filenameout = Path.Combine(Server.MapPath(path), $"From NASA (1983-2005) {latitude.ToString()} - {longitude.ToString()}.txt"); using (var db = new NpgsqlContext()) { string query = "COPY \"MeteoData\" (\"MeteoDataTypeId\", \"Year\", \"Month\", \"Day\", \"Hour\", \"Longitude\", \"Latitude\", \"Value\") FROM '" + filenameout + "' WITH NULL AS ''"; try { db.MeteoDatas.SqlQuery(query).SingleOrDefault(); } catch (Exception ex) { if (ex.Message != "The data reader is incompatible with the specified 'AtlasSolar.Models.MeteoData'. A member of the type, 'Id', does not have a corresponding column in the data reader with the same name.") { int re = 5; } } db.Dispose(); GC.Collect(); } } } } TimeSpan time = DateTime.Now - start; report += "<br/>Time: " + time.ToString() + "<br/>Count: " + count.ToString() + "<br/>"; ViewBag.Report = report; return(View()); }
private int GetFinalJumpCount(ASMachine machine, Jumper jumper, List <ASInstruction> cleaned, Dictionary <int, List <ASInstruction> > localReferences, Stack <ASInstruction> valuePushers) { var magicCount = 0; var locals = new List <Local>(); var pushers = new List <ASInstruction>(); bool?isJumping = jumper.RunCondition(machine); // Get the instructions that pushed the values the jump instruction used. int popCount = jumper.GetPopCount(); for (int i = 0; i < popCount; i++) { ASInstruction pusher = valuePushers.Pop(); if (!pushers.Contains(pusher)) { pushers.Add(pusher); // Get the instructions that were pushed by a GetLocal/N. // These are used to determine whether the jump should be kept, since a local register could change within the jump body. if (Local.IsValid(pusher.OP)) { locals.Add((Local)pusher); } else if (Primitive.IsValid(pusher.OP) || pusher.OP == OPCode.Dup) { magicCount++; } } } // Output is not known, keep the instruction. if (isJumping == null) { cleaned.Add(jumper); return(0); } if (pushers.Count != (magicCount + locals.Count)) { // One or more push instructions are wildcards, they have a 'history' of being modified. // Keep this jump instruction, result could change. cleaned.Add(jumper); return(0); } // Gather information about the jump instruction, and it's 'block' of instructions that are being jumped over(if 'isJumping = true'). ASInstruction exit = null; bool isBackwardsJump = false; IEnumerable <ASInstruction> block = null; if (!JumpExits.TryGetValue(jumper, out exit)) { // This jump instruction should not be 'cleaned', keep it. cleaned.Add(jumper); return(0); } if (IsBackwardsJump(jumper)) { isBackwardsJump = true; block = cleaned .Skip(cleaned.IndexOf(exit) + 1) .TakeWhile(i => i != jumper); } else { block = (jumper.Offset > 0 ? GetJumpBlock(jumper) : null); } if (isJumping == true && block != null) { if (isBackwardsJump) { // Check if any of the locals used by the jump instruction is being set within the body. // If the anwser is yes, removing the jump instruction is a bad idea, since the output of the condition could change. foreach (Local local in locals) { foreach (ASInstruction instruction in block) { if (!Local.IsValid(instruction.OP)) { continue; } if (Local.IsGetLocal(instruction.OP)) { continue; } var bodyLocal = (Local)instruction; if (bodyLocal.Register == local.Register) { // Do not remove the jump instruction, condition result may change. cleaned.Add(jumper); return(0); } } } } foreach (KeyValuePair <Jumper, ASInstruction> jumpExit in JumpExits) { if (jumpExit.Key == jumper) { continue; } bool hasEntry = block.Contains(jumpExit.Key); // Does a jump instruction begin somewhere in the block? bool hasExit = block.Contains(jumpExit.Value); // Does the jump instruction end somewhere in the block? ASInstruction afterLast = _instructions[_indices[block.Last()] + 1]; bool isExitAfterLast = (jumpExit.Value == afterLast); // Does the exit of the jump that is in the block come after the final instruction of the current block? if (hasEntry && !hasExit && !isExitAfterLast || hasExit && !hasEntry) { // Keep the jump instruction, since it will corrupt the other jump instruction that is using it. cleaned.Add(jumper); return(0); } } foreach (KeyValuePair <LookUpSwitchIns, ASInstruction[]> switchExit in SwitchExits) { foreach (ASInstruction caseExit in switchExit.Value) { if (block.Contains(caseExit)) { cleaned.Add(jumper); return(0); } } } } foreach (Local local in locals) { List <ASInstruction> references = localReferences[local.Register]; references.Remove(local); } // Remove the instructions that pushed values for the jump instruction that is to be removed. foreach (ASInstruction pusher in pushers) { cleaned.Remove(pusher); } if (isJumping == false || isBackwardsJump) { block = null; } JumpExits.Remove(jumper); return(block?.Count() ?? 0); }
// getting a list of monthly average data NASA (1983-2005) public ActionResult ParseNASA1983Monthly(bool?post) { string report = ""; DateTime start = DateTime.Now; List <MeteoDataType> meteodatatypes = new List <MeteoDataType>(); using (var db = new NpgsqlContext()) { meteodatatypes = db.MeteoDataTypes .Where(m => m.MeteoDataSource.Code == "NASA (1983-2005)" && m.MeteoDataPeriodicity.Code == "Monthly average") .ToList(); db.Dispose(); GC.Collect(); } decimal longitude_min = 45 - 0.5m, longitude_max = 95 + 0.5m, latitude_min = 39 - 0.5m, latitude_max = 56 + 0.5m; int count = 0; for (decimal latitude = latitude_min; latitude <= latitude_max; latitude++) { for (decimal longitude = longitude_min; longitude <= longitude_max; longitude++) { string url = "https://eosweb.larc.nasa.gov/cgi-bin/sse/grid.cgi?&num=225129&lat=" + latitude.ToString().Replace(",", ".") + "&hgt=100&submit=Submit&veg=17&sitelev=&[email protected]&p=grid_id&step=2&lon=" + longitude.ToString().Replace(",", "."); HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument(); html.LoadHtml(new WebClient().DownloadString(url)); HtmlAgilityPack.HtmlNode root = html.DocumentNode; string slat = "", slon = ""; foreach (HtmlAgilityPack.HtmlNode td in root.Descendants("td")) { if (td.InnerText.IndexOf("Center") >= 0) { IEnumerable <HtmlAgilityPack.HtmlNode> bs = td.Descendants("b"); slat = bs.First().InnerText; slon = bs.Last().InnerText; break; } } string current_table_name = ""; using (var db = new NpgsqlContext()) { db.Configuration.AutoDetectChangesEnabled = false; foreach (HtmlAgilityPack.HtmlNode node in root.Descendants()) { if (node.Name == "a") { if (node.GetAttributeValue("name", "") != "") { current_table_name = HttpUtility.HtmlDecode(node.GetAttributeValue("name", "").Trim()); } } if ((current_table_name != "") && (node.Name == "div")) { int current_tr_i = 0; foreach (HtmlAgilityPack.HtmlNode tr in node.Descendants("tr")) { current_tr_i++; if (current_tr_i > 1) { int current_td_i = 0; string row_name = ""; foreach (HtmlAgilityPack.HtmlNode td in tr.Descendants("td")) { current_td_i++; if (current_td_i == 1) { row_name = HttpUtility.HtmlDecode(td.InnerText.Trim()); } else { decimal out_decimal = 0; int MeteoDataTypeId = meteodatatypes .Where(m => m.Code == current_table_name && m.AdditionalEN == row_name) .FirstOrDefault() .Id; string V = td.InnerText.Replace("*", "").Trim(); db.MeteoDatas.Add(new MeteoData() { Latitude = Convert.ToDecimal(slat.Replace(".", ",")), Longitude = Convert.ToDecimal(slon.Replace(".", ",")), Year = null, Month = current_td_i - 1, Day = null, MeteoDataTypeId = MeteoDataTypeId, Value = decimal.TryParse(V.Replace(".", ","), out out_decimal) ? Convert.ToDecimal(V.Replace(".", ",")) : (decimal?)null }); count++; } } } } current_table_name = ""; } } db.SaveChanges(); db.Dispose(); GC.Collect(); } } } TimeSpan time = DateTime.Now - start; report += "<br/>Time: " + time.ToString() + "<br/>Count: " + count.ToString() + "<br/>"; ViewBag.Report = report; return(View()); }
public static void GenerateItems() { // Last string[] is 1 length for some reason string[][] ids = new WebClient().DownloadString("https://raw.githubusercontent.com/veekun/pokedex/master/pokedex/data/csv/item_game_indices.csv").Split('\n').Skip(1).Select(s => s.Split(',')).Where(s => s.Length != 1).ToArray(); string[][] names = new WebClient().DownloadString("https://raw.githubusercontent.com/veekun/pokedex/master/pokedex/data/csv/item_names.csv").Split('\n').Skip(1).Select(s => s.Split(',')).ToArray(); IEnumerable <PBEItem> allItems = Enum.GetValues(typeof(PBEItem)).Cast <PBEItem>().Except(new[] { PBEItem.None }).OrderBy(e => e.ToString()); var sb = new StringBuilder(); sb.AppendLine("using Kermalis.PokemonBattleEngine.Data;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using System.Collections.ObjectModel;"); sb.AppendLine(); sb.AppendLine("namespace Kermalis.PokemonBattleEngine.Localization"); sb.AppendLine("{"); sb.AppendLine(" public static class PBEItemLocalization"); sb.AppendLine(" {"); sb.AppendLine(" public static ReadOnlyDictionary<PBEItem, PBELocalizedString> Names { get; } = new ReadOnlyDictionary<PBEItem, PBELocalizedString>(new Dictionary<PBEItem, PBELocalizedString>()"); sb.AppendLine(" {"); sb.AppendLine(" { PBEItem.None, new PBELocalizedString(\"--\", \"--\", \"--\", \"--\", \"--\", \"--\", \"--\") },"); foreach (PBEItem item in allItems) { string theirID = ids.Single(s => s[1] == "5" && s[2] == ((ushort)item).ToString())[0]; string japanese = names.Single(s => s[0] == theirID && s[1] == "1")[2]; string korean = names.Single(s => s[0] == theirID && s[1] == "3")[2]; string french = names.Single(s => s[0] == theirID && s[1] == "5")[2]; string german = names.Single(s => s[0] == theirID && s[1] == "6")[2]; string spanish = names.Single(s => s[0] == theirID && s[1] == "7")[2]; string italian = names.Single(s => s[0] == theirID && s[1] == "8")[2]; string english = names.Single(s => s[0] == theirID && s[1] == "9")[2]; switch (item) { case PBEItem.AmuletCoin: spanish = "Mon. Amuleto"; break; case PBEItem.ArmorFossil: french = "Foss. Armure"; break; case PBEItem.BalmMushroom: english = "BalmMushroom"; break; case PBEItem.BigRoot: french = "Grosseracine"; break; case PBEItem.BindingBand: french = "B. Étreinte"; spanish = "Ban. Atadura"; break; case PBEItem.BlackBelt: french = "Ceint.Noire"; break; case PBEItem.BlackGlasses: french = "Lunet.Noires"; english = "BlackGlasses"; break; case PBEItem.BlkApricorn: spanish = "Bonguri Neg"; italian = "Ghic. Nera"; english = "Blk Apricorn"; break; case PBEItem.BluApricorn: spanish = "Bonguri Azu"; italian = "Ghic. Blu"; english = "Blu Apricorn"; break; case PBEItem.BrightPowder: french = "Poudreclaire"; english = "BrightPowder"; break; case PBEItem.BugGem: french = "Joyau Insect"; spanish = "G. Bicho"; italian = "Bijoucoleot."; break; case PBEItem.ChoiceBand: french = "Band. Choix"; spanish = "Cin. Elegida"; break; case PBEItem.ChoiceScarf: french = "Mouch. Choix"; spanish = "Pañ. Elegido"; break; case PBEItem.ChoiceSpecs: french = "Lunet. Choix"; break; case PBEItem.CleanseTag: french = "Rune Purif."; break; case PBEItem.ClawFossil: french = "Foss. Griffe"; break; case PBEItem.CleverWing: spanish = "P. Mente"; break; case PBEItem.CometShard: french = "Morc. Comète"; spanish = "Frag. Cometa"; break; case PBEItem.CoverFossil: french = "Foss. Plaque"; break; case PBEItem.DarkGem: french = "Joyau Ténèbr"; spanish = "G. Siniestra"; break; case PBEItem.DeepSeaScale: french = "Écailleocéan"; english = "DeepSeaScale"; break; case PBEItem.DeepSeaTooth: italian = "Denteabissi"; english = "DeepSeaTooth"; break; case PBEItem.DireHit: japanese = "クリティカッター"; break; case PBEItem.DomeFossil: french = "Fossile Dome"; break; case PBEItem.DragonFang: spanish = "Colmillodrag"; break; case PBEItem.DragonGem: spanish = "G. Dragón"; break; case PBEItem.DragonScale: french = "Ecailledraco"; break; case PBEItem.ElectricGem: spanish = "G. Eléctrica"; break; case PBEItem.EnergyPowder: french = "Poudrénergie"; spanish = "Polvoenergía"; english = "EnergyPowder"; break; case PBEItem.EnergyRoot: french = "Racinénergie"; break; case PBEItem.Everstone: spanish = "Piedraeterna"; break; case PBEItem.ExpShare: italian = "Condiv. Esp."; break; case PBEItem.FightingGem: spanish = "G. Lucha"; break; case PBEItem.FireGem: spanish = "G. Fuego"; break; case PBEItem.FlyingGem: spanish = "G. Voladora"; break; case PBEItem.FocusSash: french = "Ceint. Force"; break; case PBEItem.FullHeal: spanish = "Restau. Todo"; break; case PBEItem.FullIncense: spanish = "Incie. Lento"; break; case PBEItem.GeniusWing: spanish = "P. Intelecto"; break; case PBEItem.GhostGem: french = "Joyau Spectr"; german = "Geistjuwel"; spanish = "G. Fantasma"; break; case PBEItem.GrassGem: german = "Pflanzjuwel"; spanish = "G. Planta"; break; case PBEItem.GrnApricorn: spanish = "Bonguri Ver"; italian = "Ghic. Verde"; english = "Grn Apricorn"; break; case PBEItem.GroundGem: spanish = "G. Tierra"; break; case PBEItem.HealthWing: spanish = "P. Vigor"; break; case PBEItem.HeartScale: french = "Écaillecœur"; spanish = "Esc. Corazón"; break; case PBEItem.IceGem: spanish = "G. Hielo"; italian = "Bijoughiac."; break; case PBEItem.LaxIncense: spanish = "Incie. Suave"; break; case PBEItem.LeafStone: french = "Pierreplante"; break; case PBEItem.LuckIncense: spanish = "Incie. Duplo"; break; case PBEItem.MachoBrace: french = "Brac. Macho"; spanish = "Vestidura"; break; case PBEItem.MaxRepel: spanish = "Máx. Repel"; italian = "Repell. Max"; break; case PBEItem.MaxRevive: spanish = "Máx. Revivir"; italian = "Revital. Max"; break; case PBEItem.MentalHerb: spanish = "Hier. Mental"; break; case PBEItem.MetalCoat: spanish = "Rev. Metálico"; break; case PBEItem.MiracleSeed: french = "Grain Miracl"; break; case PBEItem.MuscleBand: french = "Band. Muscle"; break; case PBEItem.MuscleWing: spanish = "P. Músculo"; break; case PBEItem.MysticWater: italian = "Acquamagica"; break; case PBEItem.NeverMeltIce: french = "Glacéternel"; english = "NeverMeltIce"; break; case PBEItem.NormalGem: spanish = "G. Normal"; break; case PBEItem.OddIncense: french = "Bizar. Encens"; spanish = "Incie. Raro"; break; case PBEItem.OddKeystone: spanish = "P. Espíritu"; break; case PBEItem.ParalyzeHeal: spanish = "Antiparaliz"; break; case PBEItem.PlumeFossil: french = "Foss. Plume"; break; case PBEItem.PnkApricorn: spanish = "Bonguri Ros"; italian = "Ghic. Rosa"; english = "Pnk Apricorn"; break; case PBEItem.PoisonGem: spanish = "G. Veneno"; break; case PBEItem.PowerAnklet: french = "Chaîne. Pouv."; break; case PBEItem.PowerBand: french = "Band. Pouv."; break; case PBEItem.PowerBelt: french = "Ceint. Pouv."; break; case PBEItem.PowerBracer: french = "Poign. Pouv."; break; case PBEItem.PowerHerb: french = "Herbe Pouv."; break; case PBEItem.PowerLens: french = "Lent. Pouv."; break; case PBEItem.PowerWeight: french = "Poids Pouv."; break; case PBEItem.PPMax: spanish = "Máx. PP"; break; case PBEItem.PrettyWing: spanish = "P. Bella"; break; case PBEItem.PsychicGem: spanish = "G. Psíquica"; break; case PBEItem.PureIncense: spanish = "Incie. Puro"; break; case PBEItem.RazorClaw: spanish = "Garrafilada"; break; case PBEItem.RazorFang: spanish = "Colmillagudo"; break; case PBEItem.ReaperCloth: spanish = "Telaterrible"; break; case PBEItem.RedApricorn: spanish = "Bonguri Roj"; italian = "Ghic. Rossa"; break; case PBEItem.RelicCrown: spanish = "Cor. Antigua"; break; case PBEItem.RelicStatue: spanish = "Efi. Antigua"; break; case PBEItem.ResistWing: spanish = "P. Aguante"; break; case PBEItem.Revive: italian = "Revitaliz."; break; case PBEItem.RingTarget: french = "Pt de Mire"; break; case PBEItem.RockGem: german = "Gesteinjuwel"; spanish = "G. Roca"; break; case PBEItem.RockyHelmet: spanish = "Cas. Dentado"; break; case PBEItem.RootFossil: french = "Foss. Racine"; break; case PBEItem.RoseIncense: spanish = "Inc. Floral"; break; case PBEItem.SacredAsh: french = "Cendresacrée"; break; case PBEItem.SeaIncense: spanish = "Incie. Mar."; break; case PBEItem.ShoalShell: french = "Co. Trefonds"; spanish = "C. Cardumen"; break; case PBEItem.SilkScarf: french = "Mouch. Soie"; italian = "Sciarpaseta"; break; case PBEItem.SilverPowder: french = "Poudre Arg."; english = "SilverPowder"; break; case PBEItem.SkullFossil: french = "Foss. Crâne"; break; case PBEItem.SoftSand: italian = "Sabbiasoffice"; break; case PBEItem.StableMulch: spanish = "Ab. Fijador"; break; case PBEItem.Stardust: french = "Pouss.Étoile"; break; case PBEItem.StarPiece: french = "Morc. Étoile"; spanish = "Tr. Estrella"; break; case PBEItem.SteelGem: spanish = "G. Acero"; break; case PBEItem.SunStone: french = "Pierresoleil"; break; case PBEItem.SuperRepel: spanish = "Superrepel"; italian = "Superrepell."; break; case PBEItem.SweetHeart: spanish = "Cor. Dulce"; break; case PBEItem.SwiftWing: spanish = "P. Ímpetu"; break; case PBEItem.Thunderstone: french = "Pierrefoundr"; spanish = "Piedratrueno"; english = "Thunderstone"; break; case PBEItem.TinyMushroom: english = "TinyMushroom"; break; case PBEItem.TwistedSpoon: french = "Cuillertordu"; italian = "Cucchiaiotorto"; english = "TwistedSpoon"; break; case PBEItem.WaterGem: spanish = "G. Agua"; break; case PBEItem.WhiteFlute: french = "Flûteblanche"; break; case PBEItem.WhiteHerb: french = "Herbeblanche"; spanish = "Hier. Blanca"; break; case PBEItem.WiseGlasses: french = "Lunet. Sages"; spanish = "Gafas Esp."; break; case PBEItem.WhtApricorn: spanish = "Bongui Bla"; italian = "Ghic. Biana"; english = "Wht Apricorn"; break; case PBEItem.XDefend: english = "X Defend"; break; case PBEItem.XSpecial: italian = "Special X"; english = "X Special"; break; case PBEItem.YellowFlute: spanish = "Fl. Amarilla"; italian = "Flauto Gial."; break; case PBEItem.YellowShard: spanish = "P. Amarilla"; italian = "Coccio Gial."; break; case PBEItem.YlwApricorn: spanish = "Bonguri Ama"; italian = "Ghic. Gialla"; english = "Ylw Apricorn"; break; case PBEItem.ZoomLens: french = "Lentil. Zoom"; break; } sb.AppendLine($" {{ PBEItem.{item}, new PBELocalizedString(\"{japanese}\", \"{korean}\", \"{french}\", \"{german}\", \"{spanish}\", \"{italian}\", \"{english}\") }}{(item == allItems.Last() ? string.Empty : ",")}"); } sb.AppendLine(" });"); sb.AppendLine(" }"); sb.AppendLine("}"); File.WriteAllText(@"D:\Development\GitHub\PokemonBattleEngine\PokemonBattleEngine\Localization\ItemLocalization.cs", sb.ToString()); }
public static void GenerateAbilities() { string[][] names = new WebClient().DownloadString("https://raw.githubusercontent.com/veekun/pokedex/master/pokedex/data/csv/ability_names.csv").Split('\n').Skip(1).Select(s => s.Split(',')).ToArray(); IEnumerable <PBEAbility> allAbilities = Enum.GetValues(typeof(PBEAbility)).Cast <PBEAbility>().Except(new[] { PBEAbility.None, PBEAbility.MAX }).OrderBy(e => e.ToString()); var sb = new StringBuilder(); sb.AppendLine("using Kermalis.PokemonBattleEngine.Data;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using System.Collections.ObjectModel;"); sb.AppendLine(); sb.AppendLine("namespace Kermalis.PokemonBattleEngine.Localization"); sb.AppendLine("{"); sb.AppendLine(" public static class PBEAbilityLocalization"); sb.AppendLine(" {"); sb.AppendLine(" public static ReadOnlyDictionary<PBEAbility, PBELocalizedString> Names { get; } = new ReadOnlyDictionary<PBEAbility, PBELocalizedString>(new Dictionary<PBEAbility, PBELocalizedString>()"); sb.AppendLine(" {"); sb.AppendLine(" { PBEAbility.None, new PBELocalizedString(\"--\", \"--\", \"--\", \"--\", \"--\", \"--\", \"--\") },"); foreach (PBEAbility ability in allAbilities) { string abilityID = ((byte)ability).ToString(); string japanese = names.Single(s => s[0] == abilityID && s[1] == "1")[2]; string korean = names.Single(s => s[0] == abilityID && s[1] == "3")[2]; string french = names.Single(s => s[0] == abilityID && s[1] == "5")[2]; string german = names.Single(s => s[0] == abilityID && s[1] == "6")[2]; string spanish = names.Single(s => s[0] == abilityID && s[1] == "7")[2]; string italian = names.Single(s => s[0] == abilityID && s[1] == "8")[2]; string english = names.Single(s => s[0] == abilityID && s[1] == "9")[2]; switch (ability) { case PBEAbility.Analytic: spanish = "Cálc. Final"; break; case PBEAbility.ArenaTrap: french = "Piège"; break; case PBEAbility.BattleArmor: spanish = "Armad. Bat."; break; case PBEAbility.Chlorophyll: french = "Chlorophyle"; break; case PBEAbility.Compoundeyes: spanish = "Ojocompuesto"; english = "Compoundeyes"; break; case PBEAbility.CursedBody: spanish = "Cue. Maldito"; break; case PBEAbility.EffectSpore: spanish = "Efec. Espora"; break; case PBEAbility.FlareBoost: spanish = "Ím. Ardiente"; break; case PBEAbility.FlashFire: spanish = "Absor. Fuego"; break; case PBEAbility.HeavyMetal: spanish = "Met. Pesado"; break; case PBEAbility.InnerFocus: italian = "Fuocodentro"; break; case PBEAbility.LeafGuard: french = "Feuil. Garde"; break; case PBEAbility.LightMetal: spanish = "Met. Liviano"; break; case PBEAbility.Lightningrod: english = "Lightningrod"; break; case PBEAbility.MagicBounce: spanish = "Espejomágico"; break; case PBEAbility.MarvelScale: french = "Écaille Spé."; spanish = "Escama Esp."; break; case PBEAbility.ShadowTag: spanish = "Sombratrampa"; break; case PBEAbility.SheerForce: spanish = "Pot. Bruta"; break; case PBEAbility.Sniper: spanish = "Francotirad."; break; case PBEAbility.Static: spanish = "Elec. Estát."; break; case PBEAbility.ToxicBoost: spanish = "Ím. Tóxico"; break; case PBEAbility.VitalSpirit: spanish = "Espír. Vital"; break; case PBEAbility.VoltAbsorb: spanish = "Absor. Elec."; break; case PBEAbility.WaterAbsorb: spanish = "Absor. Agua"; break; case PBEAbility.WeakArmor: spanish = "Arm. Frágil"; break; } sb.AppendLine($" {{ PBEAbility.{ability}, new PBELocalizedString(\"{japanese}\", \"{korean}\", \"{french}\", \"{german}\", \"{spanish}\", \"{italian}\", \"{english}\") }}{(ability == allAbilities.Last() ? string.Empty : ",")}"); } sb.AppendLine(" });"); sb.AppendLine(" }"); sb.AppendLine("}"); File.WriteAllText(@"D:\Development\GitHub\PokemonBattleEngine\PokemonBattleEngine\Localization\AbilityLocalization.cs", sb.ToString()); }