Here are the examples of the csharp api double.ToString(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1350 Examples
19
Source : DownloadHandle.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
void ws_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
try
{
if (UpdateCompleted != null)
{
if (e.Cancelled)
{
((WebClientEx)sender).Dispose();
TimeSpan ts = (DateTime.Now - totalDatetime);
string speed = string.Format("{0} M/s", (totalBytesToReceive / ts.TotalMilliseconds / 1000).ToString("#0.0"));
UpdateCompleted(this, new ResultEventArgs(true, speed.PadLeft(8, ' ')));
return;
}
if (e.Error == null
|| Utils.IsNullOrEmpty(e.Error.ToString()))
{
TimeSpan ts = (DateTime.Now - totalDatetime);
string speed = string.Format("{0} M/s", (totalBytesToReceive / ts.TotalMilliseconds / 1000).ToString("#0.0"));
UpdateCompleted(this, new ResultEventArgs(true, speed.PadLeft(8, ' ')));
}
else
{
throw e.Error;
}
}
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
Error?.Invoke(this, new ErrorEventArgs(ex));
}
}
19
Source : HSVUtil.cs
with MIT License
from 734843327
with MIT License
from 734843327
public override string ToString()
{
return "{" + H.ToString("f2") + "," + S.ToString("f2") + "," + V.ToString("f2") + "}";
}
19
Source : ActiveValueLabel.cs
with MIT License
from a1xd
with MIT License
from a1xd
public void SetValue(double value)
{
SetValue(value.ToString(FormatString));
}
19
Source : Field.cs
with MIT License
from a1xd
with MIT License
from a1xd
private string DecimalString(double value)
{
return value.ToString(FormatString);
}
19
Source : DoubleExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static string FormatChance(this double chance)
{
if (chance == 1)
{
return "100%";
}
if (chance == 0)
{
return "0%";
}
double r = (chance * 100);
string p = r.ToString("F99").TrimEnd('0');
if (!p.StartsWith("0."))
{
int extra = 2;
if (p.IndexOf(".0") > -1 || p.EndsWith("."))
{
extra = 0;
}
return p.Substring(0, p.IndexOf('.') + extra) + "%";
}
int i = p.IndexOfAny(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' });
if (i < 0)
{
return "0%";
}
return p.Substring(0, i + 1) + "%";
}
19
Source : DatabasePerfTest.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static void ReportResult(Session session, string testDescription, int biotasPerTest, TimeSpan duration, TimeSpan queueWaitTime, TimeSpan totalQueryExecutionTime, long trueResults, long falseResults)
{
if (session != null && !SessionIsStillInWorld(session))
return;
CommandHandlerHelper.WriteOutputInfo(session, $"{biotasPerTest} {testDescription.PadRight(17)} Duration: {duration.TotalSeconds.ToString("N1").PadLeft(5)} s. Queue Wait Time: {queueWaitTime.TotalMilliseconds.ToString("N0").PadLeft(3)} ms. Average Execution Time: {(totalQueryExecutionTime.TotalMilliseconds / biotasPerTest).ToString("N0").PadLeft(3)} ms. Success/Fail: {trueResults}/{falseResults}.", ChatMessageType.System);
}
19
Source : BaseballStatValueConverter.cs
with MIT License
from Actipro
with MIT License
from Actipro
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
#endif
if(value is double) {
var doubleValue = (double)value;
return doubleValue.ToString("0.000");
}
return value;
}
19
Source : HeadingConverter.cs
with MIT License
from Actipro
with MIT License
from Actipro
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (!(value is double))
throw new ArgumentException("The value preplaceded to this converter must be a Double.");
var doubleValue = (double)value;
if (doubleValue < 0.0)
doubleValue += 360.0;
if (doubleValue >= 360.0)
doubleValue -= 360.0;
return doubleValue.ToString("N0");
}
19
Source : MiniJson.cs
with MIT License
from AdamCarballo
with MIT License
from AdamCarballo
void SerializeOther(object value) {
// NOTE: decimals lose precision during serialization.
// They always have, I'm just letting you know.
// Previously floats and doubles lost precision too.
if (value is float) {
builder.Append(((float) value).ToString("R"));
} else if (value is int
|| value is uint
|| value is long
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong) {
builder.Append(value);
} else if (value is double
|| value is decimal) {
builder.Append(Convert.ToDouble(value).ToString("R"));
} else {
SerializeString(value.ToString());
}
}
19
Source : Global.cs
with MIT License
from adamped
with MIT License
from adamped
public static string ToStringAsFixed(this double d, int value) => d.ToString($"N{value}");
19
Source : Helper.cs
with MIT License
from adamped
with MIT License
from adamped
public static string toStringAsFixed(this double value, int points)
{
return value.ToString($"N{points}");
}
19
Source : MainWindow.xaml.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
private void UpdateVolume(double volume)
{
Dispatcher.Invoke(new Action(() =>
{
UpdateVolumeGlyph(volume);
_isInCodeValueChange = true;
VolumeSlider.Value = Math.Round(volume);
_isInCodeValueChange = false;
textVal.Text = Math.Round(volume).ToString("00");
}));
}
19
Source : FileSize.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public string ToString(int precision, IFormatProvider formatProvider = null)
{
var pow = Math.Floor((_value > 0 ? Math.Log(_value) : 0) / Math.Log(1024));
pow = Math.Min(pow, _units.Length - 1);
var value = _value / Math.Pow(1024, pow);
var precisionString = formatProvider == null
? precision.ToString(CultureInfo.CurrentCulture)
: precision.ToString(formatProvider);
return value.ToString(Math.Abs(pow - 0) < double.Epsilon ? "F0" : "F" + precisionString) + " " + _units[(int)pow];
}
19
Source : EngineMain.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public override string ToString()
{
return "FPS: " + fps.ToString("0.") +
"\t countMeshesRendered: " + countMeshesRendered;
}
19
Source : Profiler.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
static string TimeSpanToString(TimeSpan timeSpan)
{
return timeSpan.TotalMilliseconds + "ms";
if (timeSpan.TotalMinutes > 1) return timeSpan.TotalMinutes.ToString("0.##") + "m";
if (timeSpan.TotalSeconds > 1) return timeSpan.TotalSeconds.ToString("0.##") + "s";
double ms = timeSpan.TotalMilliseconds;
if (ms > 1) return ms.ToString("0.##") + "ms";
ms *= 1000.0;
if (ms > 1) return ms.ToString("0.##") + "μs";
ms *= 1000.0;
return ms.ToString("0.##") + "ns";
}
19
Source : ExcelImporter.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
protected static string GetNumericValue(ICell cell, double vl)
{
if (DateUtil.IsCellDateFormatted(cell)) return ExcelHelper.ExcelBaseDate.AddDays(vl).ToString("s");
return (decimal)vl == (int)vl ? ((int)vl).ToString() : vl.ToString("s");
}
19
Source : StringHelper.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static string ToFixLenString(this double d, int len, int dit)
{
var s = d.ToString("F" + dit);
var sb = new StringBuilder();
var l = len - s.Length;
if (l > 0)
sb.Append(' ', l);
sb.Append(s);
return sb.ToString();
}
19
Source : ExcelImporter.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
protected static string GetNumericValue(ICell cell, double vl)
{
if (DateUtil.IsCellDateFormatted(cell))
{
return ExcelHelper.ExcelBaseDate.AddDays(vl).ToString("s");
}
return (decimal)vl == (int)vl ? ((int)vl).ToString() : vl.ToString("s");
}
19
Source : NumericManipulator.cs
with MIT License
from akaskela
with MIT License
from akaskela
public string RoundToDecimalPlaces(string input, int places)
{
string displayValue = String.Empty;
double inputAsDouble = new double();
if (double.TryParse(input, out inputAsDouble))
{
displayValue = Math.Round(inputAsDouble, places, MidpointRounding.AwayFromZero).ToString("N" + places.ToString());
}
return displayValue;
}
19
Source : PerformanceGauge.cs
with MIT License
from alaabenfatma
with MIT License
from alaabenfatma
private void CountRam()
{
Task.Factory.StartNew(() =>
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
//This code can be used to mimick a real-life experience
//memsize += 1;
//Ram = memsize + " MB";
//ReBuild();
_pc.InstanceName = _proc.ProcessName;
_memsize = Convert.ToDouble(_pc.NextValue() / 1048576);
Ram = _memsize.ToString("#.0") + " MB";
ReBuild();
}));
});
}
19
Source : NumericExtensions.cs
with MIT License
from albyho
with MIT License
from albyho
public static string ToFloatFileSize(this long size)
{
double fSize = size;
var i = 0;
while (fSize >= FileSizeMod)
{
fSize /= FileSizeMod;
i++;
}
return fSize.ToString("f2") + FileSizeUnits[i];
}
19
Source : UpdatePriceSettings.cs
with GNU Affero General Public License v3.0
from alexander-pick
with GNU Affero General Public License v3.0
from alexander-pick
private void trackBarPriceEstAvg_ValueChanged(object sender, EventArgs e)
{
priceByAvg = (double)trackBarPriceEstAvg.Value / (trackBarPriceEstAvg.Maximum - trackBarPriceEstAvg.Minimum);
if (priceByAvg == 1)
labelPriceEstSliderValue.Text = "Max Price";
else if (priceByAvg > 0.5)
labelPriceEstSliderValue.Text = "AVG + " + ((priceByAvg - 0.5) * 2).ToString("f2") + " * (Max Price - AVG)";
else if (priceByAvg == 0)
labelPriceEstSliderValue.Text = "Min Price";
else if (priceByAvg < 0.5)
labelPriceEstSliderValue.Text = "Min Price + " + ((priceByAvg) * 2).ToString("f2") + " * (AVG - Min Price)";
else
labelPriceEstSliderValue.Text = "AVG";
}
19
Source : UpdatePriceSettings.cs
with GNU Affero General Public License v3.0
from alexander-pick
with GNU Affero General Public License v3.0
from alexander-pick
private void trackBarPriceEstAvgWorld_ValueChanged(object sender, EventArgs e)
{
priceByAvg = (double)trackBarPriceEstAvgWorld.Value / (trackBarPriceEstAvgWorld.Maximum - trackBarPriceEstAvgWorld.Minimum);
if (priceByAvg == 1)
labelPriceEstSliderValueWorld.Text = "Max Price";
else if (priceByAvg > 0.5)
labelPriceEstSliderValueWorld.Text = "AVG + " + ((priceByAvg - 0.5) * 2).ToString("f2") + " * (Max Price - AVG)";
else if (priceByAvg == 0)
labelPriceEstSliderValueWorld.Text = "Min Price";
else if (priceByAvg < 0.5)
labelPriceEstSliderValueWorld.Text = "Min Price + " + ((priceByAvg) * 2).ToString("f2") + " * (AVG - Min Price)";
else
labelPriceEstSliderValueWorld.Text = "AVG";
}
19
Source : PerformanceAnalyzer.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public static string GenerateReport(double totalTime)
{
StringBuilder sb = new StringBuilder();
int len = 0;
foreach (PerformanceInfo info in Performances)
len = Math.Max(info.Name.Length, len);
sb.AppendLine("Name".PadRight(len) + " Count Total Time, ms Avg. Time, ms Percentage, %");
sb.AppendLine("----------------------------------------------------------------------------------------------");
foreach (PerformanceInfo info in Performances)
{
sb.Append(info.Name.PadRight(len));
double p = 0;
double avgt = 0;
if (totalTime != 0)
p = info.TotalTime / totalTime;
if (info.Count > 0)
avgt = info.TotalTime * 1000 / info.Count;
string c = info.Count.ToString("0,0").PadRight(20);
string tt = (info.TotalTime * 1000).ToString("0,0.00").PadRight(20);
string t = avgt.ToString("0.0000").PadRight(20);
string sp = (p * 100).ToString("###").PadRight(20);
sb.AppendFormat(" " + c + tt + t + sp + "\n");
}
return sb.ToString();
}
19
Source : DoubleExtensions.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public static double RemoveNoise(this double value, int maxDigits = 8)
{
return double.Parse(value.ToString("e" + maxDigits));
}
19
Source : FormatHelper.cs
with Apache License 2.0
from alexyakunin
with Apache License 2.0
from alexyakunin
public static string ToString(this double? value, string format, string unit) =>
value.HasValue ? (value.Value.ToString(format) + " " + unit) : "n/a";
19
Source : WMIRealtimeReader.cs
with GNU General Public License v3.0
from Alois-xx
with GNU General Public License v3.0
from Alois-xx
private void Parser_OnProcessEndedWithDuration(Microsoft.Diagnostics.Tracing.Parsers.Kernel.ProcessTraceData endEvent, TimeSpan processDuration)
{
var kvp = new KeyValuePair<string, int>(endEvent.CommandLine, endEvent.ProcessID);
if( myProcessCmdLineWithPids.Contains(kvp))
{
myProcessCmdLineWithPids.Remove(kvp);
string msg = Row.Print(
DateString(endEvent.TimeStamp),
TimeString(endEvent.TimeStamp),
WMIOperation.ProcessEnd.ToString(),
endEvent.CommandLine,
endEvent.ProcessID.ToString(),
null,
null,
null,
null,
null,
processDuration.TotalSeconds.ToString("F1"));
FileLogger.Logger.Log(msg);
}
}
19
Source : JobBase.cs
with MIT License
from alonsoalon
with MIT License
from alonsoalon
public async Task<string> ExecuteJob(IJobExecutionContext context, Func<Task> func)
{
string jobHistory = $"【{DateTime.Now}】执行任务【Id:{context.JobDetail.Key.Name},组别:{context.JobDetail.Key.Group}】";
try
{
var s = context.Trigger.Key.Name;
//记录Job时间
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
await func();//执行任务
stopwatch.Stop();
jobHistory += $",【执行成功】,完成时间:{stopwatch.Elapsed.TotalMilliseconds.ToString("00")}毫秒";
}
catch (Exception ex)
{
JobExecutionException e2 = new JobExecutionException(ex);
//true 是立即重新执行任务
e2.RefireImmediately = true;
jobHistory += $",【执行失败】,异常日志:{ex.Message}";
}
Console.Out.WriteLine(jobHistory);
return jobHistory;
}
19
Source : IsNumberIntConverter.cs
with MIT License
from Altevir
with MIT License
from Altevir
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int number;
int.TryParse(value.ToString(), out number);
return number == 0 ? System.Convert.ToDouble(value).ToString("N1") : number.ToString();
}
19
Source : PerformanceResizeAnalyze.cs
with MIT License
from AlturosDestinations
with MIT License
from AlturosDestinations
public void Start()
{
var yoloWrapper = new YoloWrapper("yolov2-tiny-voc.cfg", "yolov2-tiny-voc.weights", "voc.names");
var files = Directory.GetFiles(@".\Images");
var imageResizer = new ImageResizer();
var retrys = 10;
Console.WriteLine(string.Format("|{0,20}|{1,29}|{2,43}|", "", "Resize with yolo", "Resize before yolo"));
Console.WriteLine(string.Format("|{0,20}|{1,15}|{2,13}|{3,15}|{4,13}|{5,13}|{6,10}|{7,10}|", "Image", "detected items", "elapsed (ms)", " detected items", "resize (ms)", "yolo (ms)", "diff (ms)", "faster"));
foreach (var file in files)
{
for (var i = 0; i < retrys; i++)
{
var fileInfo = new FileInfo(file);
var imageData = File.ReadAllBytes(file);
var result1 = this.ProcessResizeAfter(yoloWrapper, imageData);
var result2 = this.ProcessResizeBefore(yoloWrapper, imageResizer, imageData);
var diff = result1.Item3 - result2.Item4;
Console.WriteLine(string.Format("|{0,20}|{1,15}|{2,13}|{3,15}|{4,13}|{5,13}|{6,10}|{7,10}|", fileInfo.Name, result1.Item1.Count, result1.Item2, result2.Item1.Count, result2.Item2, result2.Item3, diff.ToString("0.00"), diff > 0));
}
}
yoloWrapper.Dispose();
}
19
Source : NumberToHumanReadableConverter.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return null;
double number = System.Convert.ToDouble(value);
int b = parameter != null ? System.Convert.ToInt32(parameter) : Base;
if (number <= 0.5 && EmptyIfZero)
return "";
int n = number > 0.5 ? Math.Min((int)Math.Truncate(Math.Log(Math.Abs(number)) / Math.Log(b)), Prefixes.Length) : 0;
double x = number / Math.Pow(b, n);
return string.Format(
Views.Resources.Strings.NumberToHumanReadable,
n > 0 && Math.Abs(x) < 10 ?
(Math.Truncate(x * 10) / 10).ToString("N1") :
Math.Truncate(x).ToString(),
Prefixes[n],
Unit);
}
19
Source : NumericTextBox.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
private void SetText(double dValue)
{
//Use "R" to use the max precision necessary
string strValue = dValue.ToString("R");
if (strValue != base.Text)
{
base.Text = strValue;
}
}
19
Source : NumberBox.cs
with MIT License
from amwx
with MIT License
from amwx
private void UpdateTextToValue()
{
if (_textBox == null)
return;
string newText = "";
if (!double.IsNaN(_value))
{
// Round to 12 digits (standard .net rounding per WinUI in the NumberBox source)
// We do this to prevent weirdness from floating point imprecision
var newValue = Math.Round(_value, 12);
if (SimpleNumberFormat != null)
{
newText = newValue.ToString(_simpleFormat);
}
else if (NumberFormatter != null)
{
newText = NumberFormatter(newValue);
}
else
{
newText = newValue.ToString();
}
}
_textBox.Text = newText;
try
{
_textUpdating = true;
Text = newText;
}
finally
{
_textUpdating = false;
MoveCaretToTextEnd(); //Add this
}
}
19
Source : StringPresenter.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
[NotNull]
public static string Present([NotNull] this IEnumerable<double> values, string format = "N2")
{
return "[" + string.Join("; ", values.Select(x => x.ToString(format))) + "]";
}
19
Source : QuantileCiSimulation.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
public void Run(string[] args)
{
var random = new Random(42);
var sampleSizes = Enumerable.Range(2, 49).ToList();
var confidenceLevels = new[] { ConfidenceLevel.L95 };
var probabilities = new Probability[] { 0.5, 0.7, 0.9, 0.95, 0.99 };
string tableHeader = "Dist " + string.Join(" ", sampleSizes.Select(it => it.ToString().PadLeft(4)));
using var writer = new Writer();
foreach (var probability in probabilities)
foreach (var confidenceLevel in confidenceLevels)
{
writer.SectionStart();
writer.WriteLine($" Quantile = {probability.Value:N2}, ConfidenceLevel = {confidenceLevel}");
writer.WriteLine(tableHeader);
foreach (var referenceDistribution in SyntheticLatencyBrendanGreggSet.Instance.Distributions)
{
writer.Write(referenceDistribution.Key.PadRight(5));
foreach (int sampleSize in sampleSizes)
{
double rate = GetCoveragePercentage(referenceDistribution.Distribution, probability, confidenceLevel, random,
sampleSize, 10_000);
string rateMessage = rate.ToString("N3") + " ";
if (rate > confidenceLevel.Value)
writer.WriteGood(rateMessage);
else if (rate > confidenceLevel.Value * 0.98)
writer.WriteMedium(rateMessage);
else
writer.WriteBad(rateMessage);
}
writer.WriteLine();
}
writer.SectionEnd();
writer.WriteLine();
}
}
19
Source : CpdTestDataVerification.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
public static CpdTestDataVerification Verify(CpdTestData testData, int[] actualIndexes)
{
var expectedChangePoints = testData.ExpectedChangePoints;
var penalties = testData.Penalties;
int actualCount = actualIndexes.Length;
int expectedCount = expectedChangePoints.Count;
int maxAcceptableMissingPointCount = testData.MaxAcceptableMissingPointCount;
int indexMaxWidth = Math.Max(testData.Values.Count.ToString().Length, 3);
double penalty = 0;
int missingPointCounter = 0;
var report = new StringBuilder();
report.AppendLine($"*** Report for {testData.Name} ***");
report.AppendLine($"{"Exp".PadRight(indexMaxWidth)} {"Act".PadRight(indexMaxWidth)} Penalty");
void AddPenalty(int expectedIndex, int actualIndex, double indexPenalty, string comment)
{
penalty += indexPenalty;
string expectedMessage = (expectedIndex == -1 ? "-" : expectedIndex.ToString()).PadRight(indexMaxWidth);
string actualMessage = (actualIndex == -1 ? "-" : actualIndex.ToString()).PadRight(indexMaxWidth);
string penaltyMessage = indexPenalty.ToString("0.00").PadLeft(7);
string commentMessage = string.IsNullOrEmpty(comment) ? "" : $" {comment}";
report.AppendLine($"{expectedMessage} {actualMessage} {penaltyMessage}{commentMessage}");
}
int actualPointer = 0;
for (int expectedPointer = 0; expectedPointer < expectedCount; expectedPointer++)
{
var expectedPoint = expectedChangePoints[expectedPointer];
int expectedIndex = expectedPoint.Index;
while (actualPointer < actualCount - 1 &&
Math.Abs(expectedIndex - actualIndexes[actualPointer]) >
Math.Abs(expectedIndex - actualIndexes[actualPointer + 1]))
{
AddPenalty(-1, actualIndexes[actualPointer], penalties.ExtraPoint, "ExtraPoint");
actualPointer++;
}
if (actualPointer < actualCount && Math.Abs(expectedIndex - actualIndexes[actualPointer]) <= expectedPoint.MaxDisplacement)
{
int displacement = Math.Abs(expectedIndex - actualIndexes[actualPointer]);
int extraDisplacement = Math.Max(0, displacement - expectedPoint.AcceptableDisplacement);
AddPenalty(expectedIndex, actualIndexes[actualPointer],
penalties.Displacement * extraDisplacement * expectedPoint.Importance,
displacement > 0 ? $"Displacement(Max={expectedPoint.AcceptableDisplacement})" : "");
actualPointer++;
}
else
{
if (missingPointCounter++ < maxAcceptableMissingPointCount)
AddPenalty(expectedIndex, -1, penalties.AcceptableMissingPoint, "AcceptableMissingPoint");
else
{
if (Math.Abs(expectedPoint.Importance - 1) < 1e-9)
AddPenalty(expectedIndex, -1, penalties.MissingPoint, "MissingPoint");
else
AddPenalty(expectedIndex, -1, penalties.MissingPoint * expectedPoint.Importance,
$"MissingPoint(Importance={expectedPoint.Importance:0.00})");
}
}
}
while (actualPointer < actualCount)
{
AddPenalty(-1, actualIndexes[actualPointer], penalties.ExtraPoint, "ExtraPoint");
actualPointer++;
}
return new CpdTestDataVerification(penalty, report.ToString().Trim());
}
19
Source : ScrappedData.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
public IEnumerator DownloadScrappedDataCoroutine(Action<List<ScrappedSong>> callback)
{
Plugin.log.Info("Downloading scrapped data...");
UnityWebRequest www;
bool timeout = false;
float time = 0f;
UnityWebRequestAsyncOperation asyncRequest;
try
{
www = SongDownloader.GetRequestForUrl(scrappedDataURL);
asyncRequest = www.SendWebRequest();
}
catch (Exception e)
{
Plugin.log.Error(e);
yield break;
}
while (!asyncRequest.isDone)
{
yield return null;
time += Time.deltaTime;
if (time >= 5f && asyncRequest.progress <= float.Epsilon)
{
www.Abort();
timeout = true;
Plugin.log.Error("Connection timed out!");
}
}
if (www.isNetworkError || www.isHttpError || timeout)
{
Plugin.log.Error("Unable to download scrapped data! " + (www.isNetworkError ? $"Network error: {www.error}" : (www.isHttpError ? $"HTTP error: {www.error}" : "Unknown error")));
}
else
{
Plugin.log.Info("Received response from github.com!");
Task parsing = new Task( () => { Songs = JsonConvert.DeserializeObject<List<ScrappedSong>>(www.downloadHandler.text); });
parsing.ConfigureAwait(false);
Plugin.log.Info("Parsing scrapped data...");
Stopwatch timer = new Stopwatch();
timer.Start();
parsing.Start();
yield return new WaitUntil(() => parsing.IsCompleted);
timer.Stop();
Downloaded = true;
callback?.Invoke(Songs);
Plugin.log.Info($"Scrapped data parsed! Time: {timer.Elapsed.TotalSeconds.ToString("0.00")}s");
}
}
19
Source : AnimeScraperService.cs
with GNU General Public License v3.0
from AniAPI-Team
with GNU General Public License v3.0
from AniAPI-Team
public override async Task Work()
{
await base.Work();
try
{
foreach (string formatFilter in this._formatsFilter)
{
this._anilistQuery.Variables["format"] = formatFilter;
for (int currentPage = 1; currentPage <= this._totalPages; currentPage++)
{
this._anilistQuery.Variables["page"] = currentPage;
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = new StringContent(JsonConvert.SerializeObject(this._anilistQuery), Encoding.UTF8, "application/json")
};
try
{
using (var response = await this._anilistClient.SendAsync(request))
{
try
{
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
{
this._rateLimitReset = Convert.ToInt64(((string[])response.Headers.GetValues("X-RateLimit-Reset"))[0]);
}
throw new HttpRequestException("RateLimit superato", ex);
}
AnilistResponse anilistResponse = JsonConvert.DeserializeObject<AnilistResponse>(await response.Content.ReadreplacedtringAsync());
if (currentPage == 1)
{
this._totalPages = anilistResponse.Data.Page.PageInfo.LastPage;
}
foreach (AnilistResponse.ResponseMedia m in anilistResponse.Data.Page.Media)
{
Anime anime = new Anime(m);
if (this._animeCollection.Exists(ref anime))
{
this._animeCollection.Edit(ref anime);
}
else
{
this._animeCollection.Add(ref anime);
}
}
this._rateLimitRemaining = Convert.ToInt32(((string[])response.Headers.GetValues("X-RateLimit-Remaining"))[0]);
this.Log($"Format {formatFilter} done {GetProgress(currentPage, this._totalPages)}%", true);
}
}
catch (HttpRequestException ex)
{
currentPage--;
DateTime timeOfReset = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
timeOfReset = timeOfReset.AddSeconds(this._rateLimitReset).ToLocalTime();
TimeSpan timeToWait = timeOfReset - DateTime.Now;
this.Log($"Waiting {timeToWait.TotalMilliseconds.ToString("F0")} ms!", true);
Thread.Sleep((int)timeToWait.TotalMilliseconds + 1000);
}
if (_cancellationToken.IsCancellationRequested)
{
throw new TaskCanceledException("Process cancellation requested!");
}
}
}
}
catch(Exception ex)
{
throw;
}
}
19
Source : IService.cs
with GNU General Public License v3.0
from AniAPI-Team
with GNU General Public License v3.0
from AniAPI-Team
public string GetProgressD(double actualValue, double maxValue)
{
double progress = (actualValue / maxValue) * 100;
this.ServiceStatus.Progress = progress;
ServicesStatus servicesStatus = this.ServiceStatus;
this._serviceStatusCollection.Edit(ref servicesStatus);
if (progress < 10)
{
return "0" + progress.ToString("F2");
}
return progress.ToString("F2");
}
19
Source : WebsiteScraperService.cs
with GNU General Public License v3.0
from AniAPI-Team
with GNU General Public License v3.0
from AniAPI-Team
public override async Task Work()
{
await base.Work();
try
{
this._workers = new List<IWebsiteScraper>()
{
new DreamsubScraper(this),
new AnimeworldScraper(this),
new GogoanimeScraper(this)
};
foreach(IWebsiteScraper scraper in this._workers)
{
Task.Run(async () => await scraper.Start());
}
while (true)
{
Thread.Sleep(1000 * 5);
double avg = this._workers.Sum(x => x.Progress) / this._workers.Count;
this.Log($"Done {avg.ToString("F2")}%", true);
int working = this._workers.Count(x => x.Working == true);
if(working == 0)
{
break;
}
}
}
catch(Exception ex)
{
throw;
}
}
19
Source : PriorityQueuesTest.cs
with Apache License 2.0
from AnkiUniversal
with Apache License 2.0
from AnkiUniversal
public override string ToString()
{
return "(" + lastName + ", " + priority.ToString("F1") + ")";
}
19
Source : Converters.cs
with Apache License 2.0
from anmcgrath
with Apache License 2.0
from anmcgrath
public object Convert (object value, Type targetType, object parameter, CultureInfo culture) {
if ( value != null && value is double ) {
double val =System.Convert.ToDouble (value) ;
string strValue =val.ToString ("N0") ;
return (strValue) ;
}
return (value) ;
}
19
Source : Converters.cs
with Apache License 2.0
from anmcgrath
with Apache License 2.0
from anmcgrath
public object Convert (object [] values, Type targetType, object parameter, CultureInfo culture) {
double value =System.Convert.ToDouble (values [0]) ;
double minValue =System.Convert.ToDouble (values [1]) ;
double maxValue =System.Convert.ToDouble (values [2]) ;
if ( minValue == maxValue )
return ("~%") ;
double val =100 * (value - minValue) / (maxValue - minValue) ;
string strValue =val.ToString ("N0") + "%" ;
return (strValue) ;
}
19
Source : FandomExporter.cs
with MIT License
from AnnoDesigner
with MIT License
from AnnoDesigner
private StringBuilder addWorkforceInfo(StringBuilder exportString, List<AnnoObject> placedObjects, BuildingPresets buildingPresets, WikiBuildingInfoPresets wikiBuildingInfoPresets)
{
double farmers = 0;
double workers = 0;
double artisans = 0;
double engineers = 0;
double jornaleros = 0;
double obreros = 0;
double explorers = 0;
double technicians = 0;
var groupedBuildings = placedObjects.Where(x => !x.Road && !string.IsNullOrWhiteSpace(x.Identifier) && !x.Identifier.Equals("Unknown Object", StringComparison.OrdinalIgnoreCase)).GroupBy(x => x.Identifier);
foreach (var curGroup in groupedBuildings)
{
var buildingIdentifier = curGroup.Key;
var buildingCount = curGroup.Count();
var foundWikiBuildingInfo = getWikiBuildingInfo(buildingIdentifier, buildingPresets, wikiBuildingInfoPresets);
if (foundWikiBuildingInfo == null || foundWikiBuildingInfo.MaintenanceInfos.Count == 0)
{
//no info found -> skip
logger.Trace($"found no wiki info for identifier: {buildingIdentifier}");
continue;
}
//get farmers
var foundFarmersEntry = foundWikiBuildingInfo.MaintenanceInfos.FirstOrDefault(x => x.Unit.Name.Equals("Workforce Farmers", StringComparison.OrdinalIgnoreCase));
if (foundFarmersEntry != null)
{
farmers += (foundFarmersEntry.Value * buildingCount);
}
//get workers
var foundWorkersEntry = foundWikiBuildingInfo.MaintenanceInfos.FirstOrDefault(x => x.Unit.Name.Equals("Workforce Workers", StringComparison.OrdinalIgnoreCase));
if (foundWorkersEntry != null)
{
workers += (foundWorkersEntry.Value * buildingCount);
}
//get artisans
var foundArtisansEntry = foundWikiBuildingInfo.MaintenanceInfos.FirstOrDefault(x => x.Unit.Name.Equals("Workforce Artisans", StringComparison.OrdinalIgnoreCase));
if (foundArtisansEntry != null)
{
artisans += (foundArtisansEntry.Value * buildingCount);
}
//get engineers
var foundEngineersEntry = foundWikiBuildingInfo.MaintenanceInfos.FirstOrDefault(x => x.Unit.Name.Equals("Workforce Engineers", StringComparison.OrdinalIgnoreCase));
if (foundEngineersEntry != null)
{
engineers += (foundEngineersEntry.Value * buildingCount);
}
//get jornaleros
var foundJornalerosEntry = foundWikiBuildingInfo.MaintenanceInfos.FirstOrDefault(x => x.Unit.Name.Equals("Workforce Jornaleros", StringComparison.OrdinalIgnoreCase));
if (foundJornalerosEntry != null)
{
jornaleros += (foundJornalerosEntry.Value * buildingCount);
}
//get obreros
var foundObrerosEntry = foundWikiBuildingInfo.MaintenanceInfos.FirstOrDefault(x => x.Unit.Name.Equals("Workforce Obreros", StringComparison.OrdinalIgnoreCase));
if (foundObrerosEntry != null)
{
obreros += (foundObrerosEntry.Value * buildingCount);
}
//get explorers
var foundExplorersEntry = foundWikiBuildingInfo.MaintenanceInfos.FirstOrDefault(x => x.Unit.Name.Equals("Workforce Explorers", StringComparison.OrdinalIgnoreCase));
if (foundExplorersEntry != null)
{
explorers += (foundExplorersEntry.Value * buildingCount);
}
//get technicians
var foundTechniciansEntry = foundWikiBuildingInfo.MaintenanceInfos.FirstOrDefault(x => x.Unit.Name.Equals("Workforce Technicians", StringComparison.OrdinalIgnoreCase));
if (foundTechniciansEntry != null)
{
technicians += (foundTechniciansEntry.Value * buildingCount);
}
}
//add info to template
exportString.Append(TEMPLATE_LINE_START).Append(HEADER_FARMERS_WORKFORCE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(farmers != 0 ? farmers.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_WORKERS_WORKFORCE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(workers != 0 ? workers.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_ARTISANS_WORKFORCE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(artisans != 0 ? artisans.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_ENGINEERS_WORKFORCE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(engineers != 0 ? engineers.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_JORNALEROS_WORKFORCE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(jornaleros != 0 ? jornaleros.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_OBREROS_WORKFORCE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(obreros != 0 ? obreros.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_OBREROS_WORKFORCE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(obreros != 0 ? obreros.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_EXPLORERS_WORKFORCE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(explorers != 0 ? explorers.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_TECHNICIANS_WORKFORCE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(technicians != 0 ? technicians.ToString("0") : string.Empty);
return exportString;
}
19
Source : FandomExporter.cs
with MIT License
from AnnoDesigner
with MIT License
from AnnoDesigner
private StringBuilder addInfluence(StringBuilder exportString, List<AnnoObject> placedObjects, BuildingPresets buildingPresets, WikiBuildingInfoPresets wikiBuildingInfoPresets)
{
double influence = 0;
var groupedBuildings = placedObjects.Where(x => !x.Road && !string.IsNullOrWhiteSpace(x.Identifier) && !x.Identifier.Equals("Unknown Object", StringComparison.OrdinalIgnoreCase)).GroupBy(x => x.Identifier);
foreach (var curGroup in groupedBuildings)
{
var buildingIdentifier = curGroup.Key;
var buildingCount = curGroup.Count();
var foundWikiBuildingInfo = getWikiBuildingInfo(buildingIdentifier, buildingPresets, wikiBuildingInfoPresets);
if (foundWikiBuildingInfo == null || foundWikiBuildingInfo.MaintenanceInfos.Count == 0)
{
//no info found -> skip
logger.Trace($"found no wiki info for identifier: {buildingIdentifier}");
continue;
}
//get influence
var foundInfluenceEntry = foundWikiBuildingInfo.MaintenanceInfos.FirstOrDefault(x => x.Unit.Name.StartsWith("Influence", StringComparison.OrdinalIgnoreCase));
if (foundInfluenceEntry != null)
{
influence = influence + (foundInfluenceEntry.Value * buildingCount);
}
}
exportString.Append(TEMPLATE_LINE_START).Append(HEADER_INFLUENCE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(influence != 0 ? influence.ToString("0") : string.Empty);
return exportString;
}
19
Source : FandomExporter.cs
with MIT License
from AnnoDesigner
with MIT License
from AnnoDesigner
private StringBuilder addAttractiveness(StringBuilder exportString, List<AnnoObject> placedObjects, BuildingPresets buildingPresets, WikiBuildingInfoPresets wikiBuildingInfoPresets)
{
double attractiveness = 0;
var groupedBuildings = placedObjects.Where(x => !x.Road && !string.IsNullOrWhiteSpace(x.Identifier) && !x.Identifier.Equals("Unknown Object", StringComparison.OrdinalIgnoreCase)).GroupBy(x => x.Identifier);
foreach (var curGroup in groupedBuildings)
{
var buildingIdentifier = curGroup.Key;
var buildingCount = curGroup.Count();
var foundWikiBuildingInfo = getWikiBuildingInfo(buildingIdentifier, buildingPresets, wikiBuildingInfoPresets);
if (foundWikiBuildingInfo == null || foundWikiBuildingInfo.MaintenanceInfos.Count == 0)
{
//no info found -> skip
logger.Trace($"found no wiki info for identifier: {buildingIdentifier}");
continue;
}
//get attractiveness
var foundAttractivenessEntry = foundWikiBuildingInfo.MaintenanceInfos.FirstOrDefault(x => x.Unit.Name.StartsWith("Attractiveness", StringComparison.OrdinalIgnoreCase));
if (foundAttractivenessEntry != null)
{
attractiveness = attractiveness + (foundAttractivenessEntry.Value * buildingCount);
}
}
exportString.Append(TEMPLATE_LINE_START).Append(HEADER_ATTRACTIVENESS).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(attractiveness != 0 ? attractiveness.ToString("0") : string.Empty);
return exportString;
}
19
Source : FandomExporter.cs
with MIT License
from AnnoDesigner
with MIT License
from AnnoDesigner
private StringBuilder addBalance(StringBuilder exportString, List<AnnoObject> placedObjects, BuildingPresets buildingPresets, WikiBuildingInfoPresets wikiBuildingInfoPresets)
{
double balance = 0;
var groupedBuildings = placedObjects.Where(x => !x.Road && !string.IsNullOrWhiteSpace(x.Identifier) && !x.Identifier.Equals("Unknown Object", StringComparison.OrdinalIgnoreCase)).GroupBy(x => x.Identifier);
foreach (var curGroup in groupedBuildings)
{
var buildingIdentifier = curGroup.Key;
var buildingCount = curGroup.Count();
var foundWikiBuildingInfo = getWikiBuildingInfo(buildingIdentifier, buildingPresets, wikiBuildingInfoPresets);
if (foundWikiBuildingInfo == null || foundWikiBuildingInfo.MaintenanceInfos.Count == 0)
{
//no info found -> skip
continue;
}
//get balance
var foundBalanceEntry = foundWikiBuildingInfo.MaintenanceInfos.FirstOrDefault(x => x.Unit.Name.Equals("Balance", StringComparison.OrdinalIgnoreCase));
if (foundBalanceEntry != null)
{
balance = balance + (foundBalanceEntry.Value * buildingCount);
}
}
exportString.Append(TEMPLATE_LINE_START).Append(HEADER_BALANCE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(balance != 0 ? balance.ToString("0") : string.Empty);
return exportString;
}
19
Source : FandomExporter.cs
with MIT License
from AnnoDesigner
with MIT License
from AnnoDesigner
private StringBuilder addConstructionInfo(StringBuilder exportString, List<AnnoObject> placedObjects, BuildingPresets buildingPresets, WikiBuildingInfoPresets wikiBuildingInfoPresets)
{
double credits = 0;
double timber = 0;
double bricks = 0;
double steelBeams = 0;
double windows = 0;
double reinforcedConcrete = 0;
var groupedBuildings = placedObjects.Where(x => !x.Road && !string.IsNullOrWhiteSpace(x.Identifier) && !x.Identifier.Equals("Unknown Object", StringComparison.OrdinalIgnoreCase)).GroupBy(x => x.Identifier);
foreach (var curGroup in groupedBuildings)
{
var buildingIdentifier = curGroup.Key;
var buildingCount = curGroup.Count();
var foundWikiBuildingInfo = getWikiBuildingInfo(buildingIdentifier, buildingPresets, wikiBuildingInfoPresets);
if (foundWikiBuildingInfo == null || foundWikiBuildingInfo.ConstructionInfos.Count == 0)
{
//no info found -> skip
logger.Trace($"found no wiki info for identifier: {buildingIdentifier}");
continue;
}
//get credits
var foundCreditsEntry = foundWikiBuildingInfo.ConstructionInfos.FirstOrDefault(x => x.Unit.Name.Equals("Credits", StringComparison.OrdinalIgnoreCase));
if (foundCreditsEntry != null)
{
credits += (foundCreditsEntry.Value * buildingCount);
}
//get timber
var foundTimberEntry = foundWikiBuildingInfo.ConstructionInfos.FirstOrDefault(x => x.Unit.Name.Equals("Timber", StringComparison.OrdinalIgnoreCase));
if (foundTimberEntry != null)
{
timber += (foundTimberEntry.Value * buildingCount);
}
//get bricks
var foundBricksEntry = foundWikiBuildingInfo.ConstructionInfos.FirstOrDefault(x => x.Unit.Name.Equals("Bricks", StringComparison.OrdinalIgnoreCase));
if (foundBricksEntry != null)
{
bricks += (foundBricksEntry.Value * buildingCount);
}
//get steel beams
var foundSteelBeamsEntry = foundWikiBuildingInfo.ConstructionInfos.FirstOrDefault(x => x.Unit.Name.Equals("Steel Beams", StringComparison.OrdinalIgnoreCase));
if (foundSteelBeamsEntry != null)
{
steelBeams += (foundSteelBeamsEntry.Value * buildingCount);
}
//get windows
var foundWindowsEntry = foundWikiBuildingInfo.ConstructionInfos.FirstOrDefault(x => x.Unit.Name.Equals("Windows", StringComparison.OrdinalIgnoreCase));
if (foundWindowsEntry != null)
{
windows += (foundWindowsEntry.Value * buildingCount);
}
//get reinforced concrete
var foundReinforcedConcreteEntry = foundWikiBuildingInfo.ConstructionInfos.FirstOrDefault(x => x.Unit.Name.Equals("Reinforced Concrete", StringComparison.OrdinalIgnoreCase));
if (foundReinforcedConcreteEntry != null)
{
reinforcedConcrete += (foundReinforcedConcreteEntry.Value * buildingCount);
}
}
//add info to template
exportString.Append(TEMPLATE_LINE_START).Append(HEADER_CREDITS).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(credits > 0 ? credits.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_TIMBER).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(timber > 0 ? timber.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_BRICKS).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(bricks > 0 ? bricks.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_STEEL_BEAMS).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(steelBeams > 0 ? steelBeams.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_WINDOWS).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(windows > 0 ? windows.ToString("0") : string.Empty)
.Append(TEMPLATE_LINE_START).Append(HEADER_REINFORCED_CONCRETE).Append(TEMPLATE_ENTRY_DELIMITER).AppendLine(reinforcedConcrete > 0 ? reinforcedConcrete.ToString("0") : string.Empty);
return exportString;
}
19
Source : AccCompiler.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public override bool Run()
{
ProcessStartInfo processinfo;
Process process;
TimeSpan deltatime;
int line = 0;
string sourcedir = Path.GetDirectoryName(sourcefile);
// Create parameters
string args = this.parameters;
args = args.Replace("%FI", inputfile);
args = args.Replace("%FO", outputfile);
args = args.Replace("%FS", sourcefile);
args = args.Replace("%PT", this.tempdir.FullName);
args = args.Replace("%PS", sourcedir);
// Setup process info
processinfo = new ProcessStartInfo();
processinfo.Arguments = args;
processinfo.FileName = Path.Combine(this.tempdir.FullName, info.ProgramFile);
processinfo.CreateNoWindow = false;
processinfo.ErrorDialog = false;
processinfo.UseShellExecute = true;
processinfo.WindowStyle = ProcessWindowStyle.Hidden;
processinfo.WorkingDirectory = this.workingdir;
// Output info
Logger.WriteLogLine("Running compiler...");
Logger.WriteLogLine("Program: " + processinfo.FileName);
Logger.WriteLogLine("Arguments: " + processinfo.Arguments);
try
{
// Start the compiler
process = Process.Start(processinfo);
}
catch(Exception e)
{
// Unable to start the compiler
General.ShowErrorMessage("Unable to start the compiler (" + info.Name + "). " + e.GetType().Name + ": " + e.Message, MessageBoxButtons.OK);
return false;
}
// Wait for compiler to complete
process.WaitForExit();
deltatime = TimeSpan.FromTicks(process.ExitTime.Ticks - process.StartTime.Ticks);
Logger.WriteLogLine("Compiler process has finished.");
Logger.WriteLogLine("Compile time: " + deltatime.TotalSeconds.ToString("########0.00") + " seconds");
// Now find the error file
string errfile = Path.Combine(this.workingdir, ACS_ERROR_FILE);
if(File.Exists(errfile))
{
try
{
// Regex to find error lines
Regex errlinematcher = new Regex(":[0-9]+: ", RegexOptions.Compiled | RegexOptions.CultureInvariant);
// Read all lines
string[] errlines = File.ReadAllLines(errfile);
while(line < errlines.Length)
{
// Check line
string linestr = errlines[line];
Match match = errlinematcher.Match(linestr);
if(match.Success && (match.Index > 0))
{
CompilerError err = new CompilerError();
// The match without spaces and semicolon is the line number
string linenr = match.Value.Replace(":", "").Trim();
if(!int.TryParse(linenr, out err.linenumber))
err.linenumber = CompilerError.NO_LINE_NUMBER;
else
err.linenumber--;
// Everything before the match is the filename
err.filename = linestr.Substring(0, match.Index);
if(!Path.IsPathRooted(err.filename))
{
// Add working directory to filename
err.filename = Path.Combine(processinfo.WorkingDirectory, err.filename);
}
// Everything after the match is the description
err.description = linestr.Substring(match.Index + match.Length).Trim();
// Report the error
ReportError(err);
}
// Next line
line++;
}
}
catch(Exception e)
{
// Error reading errors (ironic, isn't it)
ReportError(new CompilerError("Failed to retrieve compiler error report. " + e.GetType().Name + ": " + e.Message));
}
}
return true;
}
19
Source : NodesCompiler.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public override bool Run()
{
ProcessStartInfo processinfo;
Process process;
TimeSpan deltatime;
// Create parameters
string args = this.parameters;
args = args.Replace("%FI", inputfile);
args = args.Replace("%FO", outputfile);
// Setup process info
processinfo = new ProcessStartInfo();
processinfo.Arguments = args;
processinfo.FileName = Path.Combine(this.tempdir.FullName, info.ProgramFile);
processinfo.CreateNoWindow = false;
processinfo.ErrorDialog = false;
processinfo.UseShellExecute = true;
processinfo.WindowStyle = ProcessWindowStyle.Hidden;
processinfo.WorkingDirectory = this.workingdir;
// Output info
Logger.WriteLogLine("Running compiler...");
Logger.WriteLogLine("Program: " + processinfo.FileName);
Logger.WriteLogLine("Arguments: " + processinfo.Arguments);
try
{
// Start the compiler
process = Process.Start(processinfo);
}
catch(Exception e)
{
// Unable to start the compiler
General.ShowErrorMessage("Unable to start the compiler (" + info.Name + "). " + e.GetType().Name + ": " + e.Message, MessageBoxButtons.OK);
return false;
}
// Wait for compiler to complete
process.WaitForExit();
deltatime = TimeSpan.FromTicks(process.ExitTime.Ticks - process.StartTime.Ticks);
Logger.WriteLogLine("Compiler process has finished.");
Logger.WriteLogLine("Compile time: " + deltatime.TotalSeconds.ToString("########0.00") + " seconds");
return true;
}
See More Examples