public static void Invoker() { ProgressReporter method = WriteToConsole; method += WriteToFile; Util.HardWork(method); }
public int Run(IList<string> commandLineArguments, Memory memory, ProgressReporter reporter) { service = new Service(memory); ParseCommandLine(commandLineArguments, memory); new Interpreter(messenger, assemblyPaths, service).ProcessInstructions(); return 0; }
static async Task <bool> PerformCheckBitcoin(Form1 form) { ProgressReporter <ProgressStatus> progressDispa = new ProgressReporter <ProgressStatus>(); progressDispa.ProgressChanged += new EventHandler <ProgressStatus>(form.Task_ProgressChanged); //Main folder where you find the spreadsheet raw data. string localData = @"Bounties\" + form.ProjectSelected + "\\" + form.ProjectSelected + "SpreadSheet.xml"; BountyFileLoader bl = new BountyFileLoader(localData); string projectName = form.ProjectSelected; try { foreach (Campaign campaign in bl.SpreadSheetList) { campaign.Partecipants = await Task.Run(() => TextParser.GetUserCampaignBtcAddress(campaign, progressDispa)); } } catch (Exception ex) { MessageBox.Show(ex.Message); } bool result = false; File.Delete(projectName + "_results.xml"); foreach (Campaign campaign in bl.SpreadSheetList) { result = await Task.Run(() => AddressComparer.CheckAddressListBitcoin(projectName, campaign, progressDispa)); } return(result); }
public SuiteRunner(Memory memory, ProgressReporter theReporter, Func<Memory, CellProcessor> newService) { TestCounts = new TestCounts(); myReporter = theReporter; this.memory = memory; this.newService = newService; }
/// <summary> /// Shuts down the underlying ProgressReporter if this is the owner /// </summary> public void Shutdown() { if (ProxyOwnsReporter) { ProgressReporter.Shutdown(); } }
public void ProgressThrowsWithBigProgressReport() { IProgressReporter parentProgress = new FakeProgressReporter(); ProgressReporter progress = new ProgressReporter(parentProgress); progress.Report(150); }
public void reports_progress_via_progress_t() { var callback = new ProgressReporter(); Mock <Stream> mockStream; var buffer = CreateStreamMock(out mockStream); using (var progressStream = new ProgressStream(mockStream.Object, callback)) { callback.CallbackCount.Should().Be(0); callback.LastPercentage.Should().Be(0); while (true) { var bytesRead = progressStream.Read(buffer, 0, buffer.Length); if (bytesRead <= 0) { break; } } } mockStream.Verify(); callback.CallbackCount.Should().BeGreaterThan(0); callback.LastPercentage.Should().Be(100f); }
public int Run(string[] commandLineArguments, Configuration configuration, ProgressReporter reporter) { service = new Service(configuration); ParseCommandLine(commandLineArguments); new Interpreter(messenger, assemblyPaths, service).ProcessInstructions(); return 0; }
public void PostprocessFiles(ThreadWatcher watcher, ProgressReporter onProgress) { string indexPath = Path.Combine(watcher.ThreadDownloadDirectory, _indexFileName); IndexEntry[] files = ReadIndexFile(indexPath); if (files.Length == 0) { return; } string imageDir = watcher.ImageDownloadDirectory; bool useOriginalName = watcher.UseOriginalFileNames; int fileNameLengthLimit = ThreadWatcher.GetFileNameLengthLimit(imageDir); HashSet <string> processedFileNames = new HashSet <string>(StringComparer.OrdinalIgnoreCase); using (FileStream dst = File.Create(Path.Combine(imageDir, "stream.ts"))) { for (int iFile = 0; iFile < files.Length; iFile++) { onProgress((double)iFile / files.Length); IndexEntry file = files[iFile]; string fileName = ThreadWatcher.GetUniqueFileName(ImageInfo.GetEffectiveFileName( file.FileName, file.OriginalFileName, useOriginalName, fileNameLengthLimit), processedFileNames); using (FileStream src = File.OpenRead(Path.Combine(imageDir, fileName))) { src.CopyTo(dst); } } } foreach (string fileName in processedFileNames) { string path = Path.Combine(imageDir, fileName); try { File.Delete(path); } catch { } } }
public ConversionBusyWindow(CancellationTokenSource cts, ProgressReporter reporter) { CTS = cts; Reporter = reporter; InitializeComponent(); DataContext = this; }
void WriteChunkSignatures(Stream stream, ISignatureWriter signatureWriter) { var checksumAlgorithm = RollingChecksumAlgorithm; var hashAlgorithm = HashAlgorithm; //ProgressReporter.ReportProgress("Building signatures", 0, stream.Length); stream.Seek(0, SeekOrigin.Begin); long start = 0; int read; var block = new byte[ChunkSize]; while ((read = stream.Read(block, 0, block.Length)) > 0) { signatureWriter.WriteChunk(new ChunkSignature { StartOffset = start, Length = (short)read, Hash = hashAlgorithm.ComputeHash(block, 0, read), RollingChecksum = checksumAlgorithm.Calculate(block, 0, read) }); start += read; ProgressReporter.ReportProgress("Building signatures", start, stream.Length); } }
protected override void OnRun(Core core, ProgressReporter prog) { IntensityMatrix source = this.Args.SourceMatrix; double[,] results = null; for (int index = 0; index < source.NumRows; index++) { prog.SetProgress(index, source.NumRows); // Apply new trend // TODO: Should we be using core here? double[] r = this.CreateTrend(core.Observations, core.Conditions, core.Groups, source.Vectors[index]); // obs if (results == null) { results = new double[source.NumRows, r.Length]; } ArrayHelper.CopyRow(r, results, index); } IntensityMatrix.RowHeader[] rows = source.Rows; IntensityMatrix.ColumnHeader[] cols = core.Conditions.Select(z => new IntensityMatrix.ColumnHeader(z)).ToArray(); IntensityMatrix result = new IntensityMatrix(rows, cols, results); this.SetResults(new ResultTrend(result)); }
public static void HardWork(ProgressReporter p) // Method with delegate parameter. { for (int i = 0; i < 10; i++) { p(i * 10); // Invoke delegate (which know how to call method). } }
public void ForEach_reports_status_with_expected_ItemCount() { var items = Enumerable.Range(1, 4).ToList(); var progressReporter = new ProgressReporter <int>(processingStatus => { processingStatus.ItemCount.Should().Be(items.Count); }); progressReporter.ForEach(items, item => true); }
static void Main(string[] args) { ProgressReporter p = WriteProgressToConsole; p += WriteProgressToFile; Util.Hardwork(p); }
int IVsSingleFileGenerator.Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress) { ProgressReporter reporter = new ProgressReporter(pGenerateProgress); bool fail = false; string output; try { output = Generate(wszInputFilePath, bstrInputFileContents, wszDefaultNamespace, new ServiceProvider(Site as Microsoft.VisualStudio.OLE.Interop.IServiceProvider).GetService(typeof(ProjectItem)) as ProjectItem, reporter); } catch (Exception ex) { output = "An unhandled exception occurred during generation; " + ex.Message; reporter.GenerateError(ex.Message); fail = true; } byte[] bytes = Encoding.UTF8.GetBytes(output); int outputLength = bytes.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength); Marshal.Copy(bytes, 0, rgbOutputFileContents[0], outputLength); pcbOutput = (uint)outputLength; return(fail ? VSConstants.E_FAIL : VSConstants.S_OK); }
public ProgressReporterTests() { _mutantsResultReporter = new Mock <IMutantsResultReporter>(); _progressBarReporter = new Mock <IProgressBarReporter>(); _progressReporter = new ProgressReporter(_mutantsResultReporter.Object, _progressBarReporter.Object); }
public override void Generate(ICollection <Table> inputTables, Stream outputStream) { Logger.Info("Created ZIP file."); var progressReporter = new ProgressReporter("CsvExporter", Parameters.Instance.Targets.Databases.Count(), s => Console.Error.WriteLine(s)); using (var zipArchive = new ZipArchive(outputStream, ZipArchiveMode.Create)) { var tableIndex = 0; foreach (var table in inputTables) { if (!Parameters.Instance.ShowInformationMessages && table.Id == Table.InformationMessagesId && inputTables.Count > 1) { continue; } Logger.Info("Adding new CSV file."); var partName = GetPartName(table, tableIndex); AddCsv(zipArchive, table, partName); progressReporter.Increment(); tableIndex++; } progressReporter.Done(); MemoryManager.Clean(); var target = GetLogTableTarget(); // Showing built-in parts with the diagnostic. var forceBuiltInSheets = tableIndex == 0; if (forceBuiltInSheets) { Logger.Warn("No data sets to export. Forcing built-in parts."); } Logger.Info("CSV file logging horizon. Check console output to see beyond horizon."); if (Parameters.Instance.ShowLogSheet || forceBuiltInSheets) { var logTable = target.Logs; var partName = GetPartName(logTable, tableIndex++); AddCsv(zipArchive, logTable, partName); } if (Parameters.Instance.ShowParameterSheet || forceBuiltInSheets) { var parameterTable = ParametersToTable(Parameters.Instance); var partName = GetPartName(parameterTable, tableIndex++); AddCsv(zipArchive, parameterTable, partName); } MemoryManager.Clean(); Logger.Info("Finalizing CSV file writing."); } }
private static async Task ProcessDirectory(string directory) { if (!Directory.Exists(directory)) { throw new ArgumentException($"Directory {directory} doesn't exist", directory); } var files = Directory .GetFiles(directory) .Select(x => Path.Combine(directory, x)) .ToList(); // Полные пути исходных файлов var operationFactory = new MatrixOperationFactory(Logger); var streamReader = new StreamMatrixReader(operationFactory); var streamWriter = new StreamMatrixWriter(); var progressReporter = new ProgressReporter(files.Count, Logger); await files.ParallelForEachAsync(async file => { using var input = new StreamReader(file); var resultFile = Path.Combine(directory, Path.GetFileNameWithoutExtension(file) + "_result.txt"); // Полный путь до файла с результатом await using var output = new StreamWriter(resultFile); var matrices = streamReader.GetMatrices(input); await streamWriter.WriteMatricesAsync(output, matrices); progressReporter.Report(file); }); }
public static T RunPauseAndResumeMadingley <T>(Data data, int pauseIterations, int maxIterations, Action <T> optionalHalfTest) { var pathToModelSetup = "Model setup for test"; var pathToData = "Data for test"; Madingley.Test.Common.Common.CopyDirectory(pathToModelSetup, data.PathToModelSetup); Madingley.Test.Common.Environment.CreateDirectories(pathToData); Madingley.Test.Common.Environment.CreateFiles(pathToData, data.Terrestrial); var configuration = Madingley.Configuration.Loader.Load(pathToModelSetup); var environment = Madingley.Environment.Loader.Load(pathToData, pathToModelSetup); var progress = new ProgressReporter(); var cancellationToken = CancellationToken.None; var halfResult = Madingley.Model.Run <T>(null, configuration, environment, Madingley.Output.Factory.Create, progress, cancellationToken).Skip(pauseIterations - 1).Take(1).Last(); if (optionalHalfTest != null) { optionalHalfTest(halfResult.Item2); } var result = Madingley.Model.Run <T>(halfResult.Item1, configuration, environment, Madingley.Output.Factory.Create, progress, cancellationToken).Last(); return(result.Item2); }
public async Task ForEachAsync_reports_status_with_expected_ItemCount() { var items = Enumerable.Range(1, 5).ToList(); var progressReporter = new ProgressReporter <int>(processingStatus => { processingStatus.ItemCount.Should().Be(items.Count); }); await progressReporter.ForEachAsync(items, item => Task.FromResult(true)); }
private static void test_1() { Transformer t = Square; Console.WriteLine("{0}^2 = {1}", 4, t(4)); t = Cube; Console.WriteLine("{0}^3 = {1}", 4, t(4)); Printer p = printSmth_1; p += printSmth_2; // Delegate[] delegates = p.GetInvocationList(); p("Here goes printing string!\n"); ProgressReporter pr = WriteProgressToConsole; pr += WriteProgressToFile; System.IO.File.WriteAllText("progress.txt", ""); //cleaning progress.txt HardToil(pr); X x = new X(); ProgressReporter pr2 = x.InstanceProgress; pr2(99); // 99 Console.WriteLine(pr2.Target == x); // True Console.WriteLine(pr2.Method); // Void InstanceProgress(Int32) }
public async Task ExecuteAsync(IList <JsonFile> scenes, IList <FreeFilePackageMatch> matches, ExecutionOptions execution) { var matchesIndex = matches.SelectMany(m => m.FreeFiles.SelectMany(ff => ff.SelfAndChildren()).Select(ff => (m, ff))).GroupBy(x => x.ff).ToDictionary(x => x.Key, x => x.Select(z => z.m).ToList()); using (var reporter = new ProgressReporter <ProgressInfo>(StartProgress, ReportProgress, CompleteProgress)) { var processSceneBlock = new ActionBlock <JsonFile>( scene => ProcessSceneAsync(scenes, execution, matchesIndex, reporter, scene), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 }); foreach (var scene in scenes) { processSceneBlock.Post(scene); } processSceneBlock.Complete(); await processSceneBlock.Completion; } if (execution == ExecutionOptions.Noop) { Output.WriteLine($"Skipped updating {_updatedScenes} scenes since --noop was specified."); } else { Output.WriteLine($"Updated {_updatedReferences} references in {_updatedScenes} scenes."); } }
public override void ExportThread() { var progressLayoutIdx = ProgressReporter.GetProgressIndex(ProgressName.LAYOUT); var progressCardIdx = ProgressReporter.GetProgressIndex(ProgressName.CARD); ProgressReporter.ProgressReset(progressLayoutIdx, 0, ExportLayoutIndices.Length, 0); foreach (var nIdx in ExportLayoutIndices) { IssueManager.Instance.FireChangeCardInfoEvent(nIdx, 1); IssueManager.Instance.FireChangeElementEvent(string.Empty); ChangeExportLayoutIndex(nIdx); ProgressReporter.ProgressReset(progressCardIdx, 0, CurrentDeck.CardCount, 0); UpdateBufferBitmap(CurrentDeck.CardLayout.width, CurrentDeck.CardLayout.height); var zGraphics = Graphics.FromImage(m_zExportCardBuffer); for (var nCardIdx = 0; nCardIdx < CurrentDeck.CardCount; nCardIdx++) { IssueManager.Instance.FireChangeCardInfoEvent(nIdx, nCardIdx + 1); CurrentDeck.CardPrintIndex = nCardIdx; CardRenderer.DrawPrintLineToGraphics(zGraphics); ProgressReporter.ProgressStep(progressCardIdx); } ProgressReporter.ProgressStep(progressLayoutIdx); } ProgressReporter.ThreadSuccess = true; ProgressReporter.Shutdown(); }
int IVsSingleFileGenerator.Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress) { ProgressReporter reporter = new ProgressReporter(pGenerateProgress); bool fail = false; string output; try { output = Generate(wszInputFilePath, bstrInputFileContents, wszDefaultNamespace, new ServiceProvider(Site as Microsoft.VisualStudio.OLE.Interop.IServiceProvider).GetService(typeof(ProjectItem)) as ProjectItem, reporter); } catch (Exception ex) { output = "An unhandled exception occurred during generation; " + ex.Message; reporter.GenerateError(ex.Message); fail = true; } byte[] bytes = Encoding.UTF8.GetBytes(output); int outputLength = bytes.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength); Marshal.Copy(bytes, 0, rgbOutputFileContents[0], outputLength); pcbOutput = (uint)outputLength; return fail ? VSConstants.E_FAIL : VSConstants.S_OK; }
public async Task Generate( ProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result) { Bootstrapper.Initialize(); using var traceListener = new DisposableTraceListener( new LoggingServiceTraceListener( new ProgressMonitorLoggingService(monitor, "Generating code..."))); var swaggerFile = file.FilePath; var outputFile = swaggerFile.ChangeExtension(".cs"); result.GeneratedFilePath = outputFile; var customToolNamespace = file.CustomToolNamespace; if (string.IsNullOrWhiteSpace(customToolNamespace)) { customToolNamespace = CustomToolService.GetFileNamespace(file, outputFile); } var generator = GetCodeGenerator(swaggerFile, customToolNamespace); var progressReporter = new ProgressReporter(monitor); var contents = await Task.Run(() => generator.GenerateCode(progressReporter)); await Task.Run(() => File.WriteAllText(outputFile, contents)); }
public override void FinalizeReferenceLoad() { if (!m_bCacheUpdated || !CardMakerSettings.EnableGoogleCache) { return; } List <GoogleCacheItem> listCacheItems = new List <GoogleCacheItem>(); foreach (var zPair in m_dictionaryDataCache) { listCacheItems.Add(new GoogleCacheItem() { Reference = zPair.Key, Data = zPair.Value }); } var sLocalCacheFile = Path.Combine(CardMakerInstance.StartupPath, CardMakerConstants.GOOGLE_CACHE_FILE); if (!SerializationUtils.SerializeToXmlFile( sLocalCacheFile, listCacheItems, CardMakerConstants.XML_ENCODING)) { ProgressReporter.AddIssue("Failed to write cache file: {0}".FormatString(sLocalCacheFile)); } }
private void LoadCache() { if (!CardMakerSettings.EnableGoogleCache) { return; } var sLocalCacheFile = Path.Combine(CardMakerInstance.StartupPath, CardMakerConstants.GOOGLE_CACHE_FILE); List <GoogleCacheItem> listCacheItems = null; if (SerializationUtils.DeserializeFromXmlFile( sLocalCacheFile, CardMakerConstants.XML_ENCODING, ref listCacheItems)) { foreach (var zCacheItem in listCacheItems) { m_dictionaryDataCache.Add(zCacheItem.Reference, zCacheItem.Data); } } else { ProgressReporter.AddIssue("Failed to read cache file: {0}".FormatString(sLocalCacheFile)); } }
public SocketServer(FitSocket socket, CellProcessor service, ProgressReporter reporter, bool suiteSetUpIsAnonymous) { this.service = service; this.reporter = reporter; this.socket = socket; IMaybeProcessingSuiteSetup = suiteSetUpIsAnonymous; }
public SocketServer(FitSocket socket, Processor<Cell> service, ProgressReporter reporter, bool suiteSetUpIsAnonymous) { this.service = service; this.reporter = reporter; this.socket = socket; IMaybeProcessingSuiteSetup = suiteSetUpIsAnonymous; }
public int Run(IList <string> commandLineArguments, Memory memory, ProgressReporter reporter) { service = new Service(memory); ParseCommandLine(commandLineArguments); new Interpreter(messenger, assemblyPaths, service).ProcessInstructions(); return(0); }
public async Task <IList <FreeFilePackageMatch> > ExecuteAsync(IList <VarPackage> packages, IList <FreeFile> freeFiles) { var freeFilesSet = new ConcurrentDictionary <string, List <FreeFile> >(freeFiles.GroupBy(ff => ff.FilenameLower).ToDictionary(f => f.Key, f => f.ToList())); using (var reporter = new ProgressReporter <ProgressInfo>(StartProgress, ReportProgress, CompleteProgress)) { var matchPackageBlock = new ActionBlock <VarPackage>( package => MatchPackageAsync(reporter, package, packages.Count, freeFilesSet), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 }); foreach (var package in packages) { matchPackageBlock.Post(package); } matchPackageBlock.Complete(); await matchPackageBlock.Completion; } Output.WriteLine($"Matched {_matches.Count} files to duplicates in var packages."); return(_matches.ToList()); }
/// <summary> /// Runs the algorithm. /// </summary> public sealed override bool Run(Core core, ProgressReporter prog) { this.ClearResults(); try { this.OnRun(core, prog); } catch (Exception ex) { this.SetError(ex); prog.Log($"The following algorithm failed to complete: {{{this}}} due to the error {{{ex.Message}}}. Please see the algorithm results for specific details.", ELogLevel.Error); } switch (this.Status) { case EAlgoStatus.Completed: return(true); case EAlgoStatus.Failed: return(false); default: throw new ArgumentOutOfRangeException($"Expected Status to be Completed or Failed after {{{nameof( this.OnRun )}}} called, but {{{nameof( this.Status)}}} is {{{this.Status}}}."); } }
static void Main(string[] args) { // 创建一个Square的实例,这个语句其实就是下边这个 //Transformer transformer = new Transformer (Square); 和下边语句同样效果 //Transformer t = Square; //var result = t(3); //Console.WriteLine(result); int[] values = { 1, 2, 3 }; Transforme.Transform (values, Square); foreach (var item in values) { Console.WriteLine(item+" "); } NumberChang numberChang = new NumberChang(); var num1 = new NumberChanger(numberChang.AddNum); var num2 = new NumberChanger(numberChang.NulNum); Console.WriteLine($"{num1(10)},{numberChang.GetNum()}"); Console.WriteLine($"{num2(5)},{numberChang.GetNum()}"); ProgressReporter p = Write; p += writeFile; p -= writeFile; ProgressRepor.HardWork(p); ProRepotrer pro = new ProRepotrer(); ProRepo proRepo = pro.Instance; proRepo(99); Console.WriteLine(p.Target==pro); Console.WriteLine(p.Method); }
private void SaveLoad(bool save, EFlags flags) { ProgressReporter prog = ProgressReporter.GetEmpty(); // too fast to warrent dialogue if (flags.Has(EFlags.DoNotShowAgain)) { XmlSettings.SaveLoad(save, FileId.DoNotShowAgain, ref this.DoNotShowAgain, null, prog); } if (flags.Has(EFlags.RecentSessions)) { XmlSettings.SaveLoad(save, FileId.RecentSessions, ref this.RecentSessions, null, prog); } if (flags.Has(EFlags.RecentWorkspaces)) { XmlSettings.SaveLoad(save, FileId.RecentWorkspaces, ref this.RecentWorkspaces, null, prog); } if (flags.Has(EFlags.General)) { XmlSettings.SaveLoad(save, FileId.General, ref this.General, null, prog); } if (flags.Has(EFlags.FileLoadInfo)) { XmlSettings.SaveLoad(save, FileId.FileLoadInfo, ref this.FileLoadInfo, null, prog); } }
public int Run(string[] commandLineArguments, Configuration configuration, ProgressReporter reporter) { DateTime now = DateTime.Now; myProgressReporter = reporter; int result = Run(configuration, commandLineArguments); reporter.Write(string.Format("\n{0}, time: {1}\n", Results, DateTime.Now - now)); return result; }
public int Run(Configuration configuration, IEnumerable<string> arguments, ProgressReporter reporter) { ParseArguments(arguments); myReporter = reporter; Run(new StoryTestFolder(configuration, new FileSystemModel(configuration.GetItem<Settings>().CodePageNumber)), mySelection); return 0; //todo: return counts exceptions + wrong or whatever }
public int Run(string[] commandLineArguments, Configuration configuration, ProgressReporter reporter) { service = configuration.GetItem<Service>(); service.ApplicationUnderTest = configuration.GetItem<ApplicationUnderTest>(); ParseCommandLine(commandLineArguments); new Interpreter(messenger, assemblyPaths, service).ProcessInstructions(); return 0; }
public static void HardWork(ProgressReporter p) { for (int i = 0; i < 10; i++) { p(i * 10); System.Threading.Thread.Sleep(2000); } }
public static void HardWork(ProgressReporter p) { for (int i = 0; i < 10; i++) { p(i * 10); //调用委托 System.Threading.Thread.Sleep(1000); //模拟长时间运行 } }
public int Run(IList<string> commandLineArguments, Memory memory, ProgressReporter reporter) { var now = DateTime.Now; myProgressReporter = reporter; var result = Run(memory, commandLineArguments); //todo: to suiterunner? if (!memory.GetItem<Settings>().DryRun) reporter.Write(string.Format("\n{0}, time: {1}\n", Results, DateTime.Now - now)); return result; }
public static new FloatBitmapGtk FromPPM(RawLoader ppm, ProgressReporter callback) { FloatBitmapGtk fbg = new FloatBitmapGtk(); if (fbg.LoadDataFromPPM(ppm, callback)) return fbg; else return null; }
public int Run(string[] arguments, Configuration configuration, ProgressReporter reporter) { LastArguments = arguments; try { return int.Parse(ConfigurationManager.AppSettings.Get("returnCode")); } catch (Exception) { return Result; } }
public int Run(IList<string> arguments, Memory memory, ProgressReporter reporter) { LastArguments = arguments; ApartmentState = Thread.CurrentThread.GetApartmentState(); try { return int.Parse(ConfigurationManager.AppSettings.Get("returnCode")); } catch (Exception) { return Result; } }
public void Run(string[] CommandLineArguments) { ParseCommandLineArguments(CommandLineArguments); reporter = MakeReporter(); clientSocket = new FitSocket(new SocketModelImpl(host, port), reporter); EstablishConnection(); var server = new SocketServer(clientSocket, configuration.GetItem<Service>(), reporter, true); server.ProcessTestDocuments(WriteResults); clientSocket.Close(); Exit(); }
public static ConcurrentBag<FileBlock> GetDiffBlocksForFile(ConcurrentDictionary<long, FileHash> remoteHashes, string filePath, Config config) { _cancellationSource = new CancellationTokenSource(); var cancellationToken = _cancellationSource.Token; _progressReporter = new ProgressReporter(); var fileInfo = new FileInfo(filePath); var fileChunkSize = Convert.ToInt64(fileInfo.Length / config.DegreeOfParalleism); long chunkStart = 0; long chunkEnd = 0; var resultBag = new ConcurrentBag<FileBlock>(); using (var mappedFile = MemoryMappedFile.CreateFromFile(filePath)) { var taskArray = new List<Task>(); int chunkCounter = 0; for (var i = 0; i < config.DegreeOfParalleism; i++) { chunkEnd = chunkEnd + fileChunkSize; var chunkOverlap = chunkEnd; if (chunkEnd > fileInfo.Length) { chunkEnd = fileInfo.Length; chunkOverlap = chunkEnd; } if (taskArray.Count() <= config.DegreeOfParalleism) { chunkCounter++; var localChunkStart = chunkStart; var length = chunkOverlap - chunkStart; var mappedAccessor = mappedFile.CreateViewAccessor(localChunkStart, length, MemoryMappedFileAccess.Read); var chunkScanTask = Task.Factory.StartNew( () => ScanFileChunk(chunkCounter, cancellationToken, remoteHashes, mappedAccessor, localChunkStart, length, config), cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default) .ContinueWith( outHash => outHash.Result.ForEach(resultBag.Add)); taskArray.Add(chunkScanTask); } Interlocked.Add(ref chunkStart, fileChunkSize); } Task.WaitAll(taskArray.ToArray()); } return resultBag; }
/// <summary> /// Draws image into selected pixbuf /// </summary> /// <param name="callback"> /// A <see cref="ProgressReporter"/> to report drawing progress. /// </param> public unsafe void DrawToPixbuf(Gdk.Pixbuf buf, ProgressReporter callback) { double N = 1; // This is the norm. It should be equal to the // value which means the lightest point of // the screen int chan = buf.NChannels; int w = buf.Width, h = buf.Height, stride = buf.Rowstride; byte *cur_row = (byte *)buf.Pixels; for (int j = 0; j < h; j++) { if (j >= this.mHeight) { break; } if (j % REPORT_EVERY_NTH_LINE == 0 && callback != null) { if (!callback((double)j / this.mHeight)) return; } byte *cur_pixel = cur_row; for (int i = 0; i < w; i++) { if (i >= this.mWidth) { break; } double r = N * (1.0 - Math.Exp(-(double)r_chan[i, j] / N)); double g = N * (1.0 - Math.Exp(-(double)g_chan[i, j] / N)); double b = N * (1.0 - Math.Exp(-(double)b_chan[i, j] / N)); // Applying highlights r = r * (1 - hl_chan[i, j]) + 1 * hl_chan[i, j] - 0.001; g = g * (1 - hl_chan[i, j]) + 1 * hl_chan[i, j] - 0.001; b = b * (1 - hl_chan[i, j]) + 1 * hl_chan[i, j] - 0.001; cur_pixel[0] = cut(r * 255); // Red cur_pixel[1] = cut(g * 255); // Green cur_pixel[2] = cut(b * 255); // Blue cur_pixel += chan; } cur_row += stride; } }
private void PopulateMods() { this.cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = this.cancellationTokenSource.Token; var progressReporter = new ProgressReporter(); var task = Task.Factory.StartNew(() => { var webString = new WebClient().DownloadString("http://api.factoriomods.com/mods"); var result = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<RootObject[]>(webString), cancellationToken); // After all that work, cause the error if requested. if (false) { throw new InvalidOperationException("Oops..."); } // The answer, at last! return result.Result; }, cancellationToken); // ProgressReporter can be used to report successful completion, // cancelation, or failure to the UI thread. progressReporter.RegisterContinuation((Task) task, () => { // Display results. if (task.Exception != null) MessageBox.Show("Background task error: " + task.Exception.ToString()); else if (task.IsCanceled) MessageBox.Show("Background task cancelled"); else { var result = task.Result; foreach (var mod in result) { var newRow = new ExpandableRow(); newRow.DataContext = mod; newRow.Margin = new Thickness(2, 2, 2, 2); StackPanelMods.Children.Add(newRow); } } }); }
public static unsafe RawLoader FromFile(string filename, bool divide_by_2, ProgressReporter callback) { IntPtr eximg_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SSRLWrapper.ExtractedRawImage))); int err = SSRLWrapper.ExtractRawImageFromFile(filename, divide_by_2, eximg_ptr, delegate (float progress) { return callback(progress); }); #if DEBUG Console.WriteLine("ExtractRawImageFromFile returned " + err); #endif if (err != 0) { return null; } SSRLWrapper.ExtractedRawImage eximg = (SSRLWrapper.ExtractedRawImage)Marshal.PtrToStructure(eximg_ptr, typeof(SSRLWrapper.ExtractedRawImage)); RawLoader ppml = new RawLoader(eximg.width, eximg.height); if (eximg.bitsPerChannel == 16) { // Handling short[] rgb_data = new short[eximg.width * eximg.height * 3]; Marshal.Copy(eximg.data, rgb_data, 0, rgb_data.Length); for (int i = 0; i < eximg.width; i++) for (int j = 0; j < eximg.height; j++) { ppml.r_channel[i, j] = (ushort)rgb_data[3 * (i + eximg.width * j)]; ppml.g_channel[i, j] = (ushort)rgb_data[3 * (i + eximg.width * j) + 1]; ppml.b_channel[i, j] = (ushort)rgb_data[3 * (i + eximg.width * j) + 2]; } } else if (eximg.bitsPerChannel == 8) { throw new Exception("Can't handle 8 bit"); } else { throw new Exception("incorrect or unsupported bitsPerChannel value: " + eximg.bitsPerChannel); } SSRLWrapper.FreeExtractedRawImage(eximg); return ppml; }
public void Run(IList<string> CommandLineArguments) { ParseCommandLineArguments(CommandLineArguments); reporter = MakeReporter(); clientSocket = new FitSocket(new SocketModelImpl(host, port), reporter); EstablishConnection(); var service = new Service(memory); var writer = new StoryTestStringWriter(service) .ForTables(WriteTables) .ForCounts(WriteCounts); var server = new SocketServer(clientSocket, service, reporter, true); server.ProcessTestDocuments(writer); Exit(); }
private void RunSuite(ProgressReporter reporter) { var runner = new SuiteRunner(memory, reporter); runner.Run(new StoryTestFolder(memory, folders), string.Empty); }
public int Run(IList<string> commandLineArguments, Memory memory, ProgressReporter reporter) { this.memory = memory; Run(commandLineArguments); return totalCounts.FailCount; }
public SuiteRunner(Configuration configuration, ProgressReporter theReporter) { TestCounts = new TestCounts(); myReporter = theReporter; this.configuration = configuration; }
public SuiteRunner(Memory memory, ProgressReporter theReporter) { TestCounts = new TestCounts(); myReporter = theReporter; this.memory = memory; }
public ReportPage(ProgressReporter reporter) { this.reporter = reporter; }
public int Run(IList<string> commandLineArguments, Memory memory, ProgressReporter reporter) { server.Run(s => ProcessRequest(s, memory)); return 0; }
public int Run(string[] commandLineArguments, Configuration configuration, ProgressReporter reporter) { this.configuration = configuration; Run(commandLineArguments); return totalCounts.FailCount; }
public int Run(string[] commandLineArguments, Configuration configuration, ProgressReporter reporter) { IAppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; string baseDir = typeof(VerifyAppDomainRunner).Assembly.CodeBase.Substring(8); baseDir = Path.GetDirectoryName(Path.GetFullPath(baseDir)); if (setup.ApplicationBase != Path.GetDirectoryName(baseDir)) return 1; else if (setup.ApplicationName != "CustomAppDomainSetupIsUsed-test-domain") return 2; else if (setup.CachePath != Path.Combine(baseDir, "cache-tmp")) return 3; else if (setup.ConfigurationFile != Path.Combine(baseDir, "fitSharpTest.dll.alt.config")) return 4; else if (!setup.DynamicBase.StartsWith(Path.Combine(baseDir, "dynamic-tmp"))) return 5; else if (setup.PrivateBinPath != baseDir) return 6; else if (setup.PrivateBinPathProbe != "") return 7; else return 0; }
public int Run(string[] commandLineArguments, Configuration configuration, ProgressReporter reporter) { this.configuration = configuration; if(!ParseArgs(configuration, commandLineArguments)) { PrintUsage(); return ExitCode(); } clientSocket = new FitSocket(new SocketModelImpl(host, port), MakeReporter()); server = new SocketServer(clientSocket, new Service(configuration), MakeReporter(), false); clientSocket.EstablishConnection(Protocol.FormatRequest(pageName, usingDownloadedPaths, suiteFilter)); AddAssemblies(); server.ProcessTestDocuments(WriteTestRunner); HandleFinalCount(totalCounts); clientSocket.Close(); Exit(); resultWriter.Close(); return ExitCode(); }
public Guid CalculateHashesForFile(Config config, Guid sessionId) { var fileProcessor = new FileProcessor(); var filePath = @"D:\\Downloads\\en_windows_7_ultimate_rc_x64_dvd_347803.iso"; var fileId = Guid.NewGuid(); fileProcessor.GetHashesForFileBockComplete += delegate(Guid currentFileId) { using (var ds = new DataStoreEntities()) { var statusEntry = ds.FileStatuses.Where( x => x.FileId == fileId) _.FirstOrDefault; if(statusEntry != null) { } else { } } }; using (var ds = new DataStoreEntities()) { var fileSignature = ds.FileSignatures.Where(x => x.FilePath == filePath).FirstOrDefault(); if (fileSignature != null) { return fileSignature.FileId; } var progressReporter = new ProgressReporter(); Task.Factory.StartNew(() => { var fileHashes = fileProcessor.GetHashesForFile(filePath, progressReporter, config); using (var ms = new MemoryStream()) { var binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(ms, fileHashes); ds.FileSignatures.AddObject(new FileSignature() { FileId = fileId, FilePath = filePath, Signature = ms.ToArray() }); } ds.SaveChanges(); }); return fileId; } }