Example #1
0
        public void should_be_faster_than_the_fcl_json_deserializer()
        {
            var json = "[" + Enumerable.Range(0, 5).Select(x => "{" +
                    "\"Value0\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
                    "\"Value1\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
                    "\"Value2\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
                    "\"Value3\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
                    "\"Value4\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ] " +
                "}").Aggregate((a, i) => a + ", " + i) + "]";

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            for (var i = 0; i < 100; i++) Bender.Deserializer.Create().DeserializeJson<List<SpeedTestCollection>>(json);
            stopwatch.Stop();
            var benderSpeed = stopwatch.ElapsedTicks;

            var jsonSerializer = new JavaScriptSerializer();
            stopwatch.Start();
            for (var i = 0; i < 100; i++) jsonSerializer.Deserialize<List<SpeedTestCollection>>(json);
            stopwatch.Stop();
            var javascriptSerializerSpeed = stopwatch.ElapsedTicks;

            Debug.WriteLine("Bender speed (ticks): {0:#,##0}", benderSpeed);
            Debug.WriteLine("JavaScriptSerializer speed (ticks): {0:#,##0}", javascriptSerializerSpeed);
            (benderSpeed < javascriptSerializerSpeed).ShouldBeTrue();
        }
Example #2
0
	void Start() {

		System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

		sw.Reset();
		sw.Start();

		for (int i = 0; i < 100000; i++) {
			GameObject a = Instantiate(Resources.Load<GameObject>("A"));
			a.AddComponent<TestA>();
		}

		sw.Stop();


		print("1:"+sw.ElapsedMilliseconds);

		sw.Reset();
		sw.Start();

		for (int i = 0; i < 100000; i++) {
			GameObject a = Instantiate(Resources.Load<GameObject>("B"));
		}

		sw.Stop();
		print("2:" + sw.ElapsedMilliseconds);


	}
Example #3
0
 private void RunTests(Harness harness)
 {
     Clients.All.showmessage("Starting " + harness.Name + " tests...");
     var sw = new Stopwatch();
     sw.Start();
     for (var i = 0; i < OPERATIONS; i++)
     {
         var data = i.ToString();
         harness.Create(data);
     }
     sw.Stop();
     Clients.All.showmessage("Put " + OPERATIONS + " values in " + sw.ElapsedMilliseconds + "ms.");
     sw.Reset();
     sw.Start();
     for (var i = 0; i < OPERATIONS; i++)
     {
         var data = i.ToString();
         harness.Read(data);
     }
     sw.Stop();
     Clients.All.showmessage("Read " + OPERATIONS + " values in " + sw.ElapsedMilliseconds + "ms.");
     sw.Reset();
     sw.Start();
     for (var i = 0; i < OPERATIONS; i++)
     {
         var data = i.ToString();
         harness.Delete(data);
     }
     sw.Stop();
     Clients.All.showmessage("Deleted " + OPERATIONS + " values in " + sw.ElapsedMilliseconds + "ms.");
     Clients.All.showmessage("Completed " + harness.Name + " tests...");
 }
Example #4
0
        public void Performance(ICompressor compressor)
        {
            Trace.WriteLine("---------" + compressor.GetType() + "---------");
            byte[] indata = Encoding.UTF8.GetBytes(testData);

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            byte[] result = null;
            foreach (var i in Enumerable.Range(0,100))
            {
                result = compressor.Compress(indata);
            }
            stopwatch.Stop();
            long ticks = stopwatch.ElapsedTicks;
            Trace.WriteLine("Compress: " +  ticks);

            stopwatch.Reset();
            stopwatch.Start();

            byte[] resurrected;
            foreach (var i in Enumerable.Range(0, 100))
            {
                resurrected = compressor.Decompress(result);
            }
            stopwatch.Stop();
            ticks = stopwatch.ElapsedTicks;
            Trace.WriteLine("Decompress: " + ticks);
            Trace.WriteLine("Compression: " + result.Length / (1.0 * indata.Length));
        }
Example #5
0
        public void should_be_faster_than_the_fcl_xml_serializer()
        {
            var collection = new List<SpeedTestCollection>();
            collection.AddRange(Enumerable.Range(0, 5).Select(x => new SpeedTestCollection
                {
                    Value0 = Enumerable.Range(0, 5).Select(y => new SpeedTestItem {
                            Value0 = "ssdfsfsfd", Value1 = "sfdsfsdf", Value2 = "adasd", Value3 = "wqerqwe", Value4 = "qwerqwer"}).ToList(),
                    Value1 = Enumerable.Range(0, 5).Select(y => new SpeedTestItem {
                            Value0 = "ssdfsfsfd", Value1 = "sfdsfsdf", Value2 = "adasd", Value3 = "wqerqwe", Value4 = "qwerqwer"}).ToList(),
                    Value2 = Enumerable.Range(0, 5).Select(y => new SpeedTestItem {
                            Value0 = "ssdfsfsfd", Value1 = "sfdsfsdf", Value2 = "adasd", Value3 = "wqerqwe", Value4 = "qwerqwer"}).ToList(),
                    Value3 = Enumerable.Range(0, 5).Select(y => new SpeedTestItem {
                            Value0 = "ssdfsfsfd", Value1 = "sfdsfsdf", Value2 = "adasd", Value3 = "wqerqwe", Value4 = "qwerqwer"}).ToList(),
                    Value4 = Enumerable.Range(0, 5).Select(y => new SpeedTestItem {
                            Value0 = "ssdfsfsfd", Value1 = "sfdsfsdf", Value2 = "adasd", Value3 = "wqerqwe", Value4 = "qwerqwer"}).ToList()
                }));

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            for (var i = 0; i < 100; i++) Bender.Serializer.Create().SerializeXml(collection);
            stopwatch.Stop();
            var benderSpeed = stopwatch.ElapsedTicks;

            var xmlSerializer = new XmlSerializer(typeof(List<SpeedTestCollection>));
            stopwatch.Start();
            for (var i = 0; i < 100; i++) xmlSerializer.Serialize(new MemoryStream(), collection);
            stopwatch.Stop();
            var xmlSerializerSpeed = stopwatch.ElapsedTicks;

            Debug.WriteLine("Bender speed (ticks): {0:#,##0}", benderSpeed);
            Debug.WriteLine("XmlSerializer speed (ticks): {0:#,##0}", xmlSerializerSpeed);
            (benderSpeed < xmlSerializerSpeed).ShouldBeTrue();
        }
Example #6
0
        public DemoForm()
        {
            InitializeComponent();

            GraphConfiguration configuration = new GraphConfiguration();
            configuration.AxisXConfiguration.MajorGrid.LineColor = Color.FromArgb(200, 111, 135);
            configuration.Palette.Add(new PaletteItem(){Color = Color.Firebrick, HatchStyle = ChartHatchStyle.BackwardDiagonal});
            configuration.Palette.Add(new PaletteItem() { Color = Color.Black, HatchStyle = ChartHatchStyle.SolidDiamond });
            configuration.GraphSource = new XmlFileGraphSource(){DateTag = "aaa"};
            configuration.SaveToXml("qwe.xml");

            Stopwatch sw = new Stopwatch();
            sw.Start();
            GraphControl gc = graphControl;// new GraphControl();

            gc.SetConfiguration("graphConfig.xml", Size, null);
            sw.Stop();
            #if STOPWATCH
            MessageBox.Show("Time spent for data extraction: " + sw.ElapsedMilliseconds);
            #endif
            sw.Reset();
            sw.Start();
            gc.SaveImage("temp.jpg", ChartImageFormat.Jpeg);
            sw.Stop();
            #if STOPWATCH
            MessageBox.Show("Time spent for data render by Chart control: " + sw.ElapsedMilliseconds);
            #endif
        }
        public override TestResult DoTest(ITestCase testCase, int testCasesNumber, bool singleton)
        {
            var result = new TestResult { Singleton = singleton, TestCasesNumber = testCasesNumber };
            var sw = new Stopwatch();

            var c = new ServiceContainer();
            if (singleton)
            {
                sw.Start();
                c = (ServiceContainer)testCase.SingletonRegister(c);
                sw.Stop();
            }
            else
            {
                sw.Start();
                c = (ServiceContainer)testCase.TransientRegister(c);
                sw.Stop();
            }
            result.RegisterTime = sw.ElapsedMilliseconds;

            sw.Reset();
            result.ResolveTime = DoResolve(sw, testCase, c, testCasesNumber, singleton);

            c.Dispose();

            return result;
        }
Example #8
0
        public static async Task HowToUseAsyncProperly()
        {
            HttpClient client = new HttpClient();   // add System.Net.Http reference to your project
            
            Stopwatch clock = new Stopwatch();
            clock.Start();

            string microsoft = await client.GetStringAsync("http://www.microsoft.com");
            string msdn = await client.GetStringAsync("http://msdn.microsoft.com");
            string google = await client.GetStringAsync("http://www.google.com");

            clock.Stop();
            System.Console.WriteLine("Took {0:hh\\:mm\\:ss} seconds", clock.Elapsed);

            clock.Reset();
            clock.Start();

            Task microsoftTask =  client.GetStringAsync("http://www.microsoft.com");
            Task msdnTask =  client.GetStringAsync("http://msdn.microsoft.com");
            Task googleTask =  client.GetStringAsync("http://www.google.com");
            await Task.WhenAll(microsoftTask, msdnTask, googleTask);

            clock.Stop();
            System.Console.WriteLine("Took {0:hh\\:mm\\:ss} seconds", clock.Elapsed);
        }
        public void Can_bench_specification_extension_method_performance()
        {
            var stopwatch = new Stopwatch();
            const int trials = 1000;

            ISpecification<int> isGreaterThanThree = new PredicateSpecification<int>(v => v > 3);
            ISpecification<int> isLessThanFive = new PredicateSpecification<int>(v => v < 5);
            var isFour = isGreaterThanThree.And(isLessThanFive);

            stopwatch.Start();
            
            for (var i = 0; i < trials; i++)
            {
                isFour.IsSatisfiedBy(2 + 2);
            }
            stopwatch.Stop();
            Trace.WriteLine(stopwatch.Elapsed);

            stopwatch.Start();
            for (var i = 0; i < trials; i++)
            {
                (2 + 2).Satisfies(isFour);
            }
            stopwatch.Stop();
            Trace.WriteLine(stopwatch.Elapsed);
        }
    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Reset();
            // Single call test
            watch.Start ();

            SingleCall ();

            watch.Stop ();
            long elapsedSingle = watch.ElapsedTicks;
            Debug.Log ("Single call: " + elapsedSingle + " ticks");
            watch.Reset();
            // Multicall test
            watch.Start ();

            for(int t = 0; t < Iterations; ++t)
            {
                MultiCall();
            }

            watch.Stop ();
            long elapsedMulti = watch.ElapsedTicks;
            Debug.Log ("Multi call: " + elapsedMulti + " ticks");

            Debug.Log ("Ratio (Multi/Single): " + elapsedMulti / (double)elapsedSingle);

        }
    }
		/// <summary>
		/// Uruchamia grę z maksymalną wydajnością.
		/// </summary>
		public void Run()
		{
			if (!this.IsRunning)
			{
				this.IsRunning = true;
				Stopwatch elapsedTime = new Stopwatch();
				this.OnInit();
				elapsedTime.Start();
				while (this.Info.MainWindow.Exists && !this.IsExiting)
				{
					elapsedTime.Stop();
					double delta = elapsedTime.Elapsed.TotalSeconds;
					elapsedTime.Reset();
					elapsedTime.Start();

					if (delta > 1.0)
						delta = 1.0; //Przycinamy do max. 1 sekundy

					this.Info.MainWindow.ProcessEvents();
					this.OnUpdate(delta);
					this.OnRender();
					this.Info.MainWindow.Show();
				}

				if (this.IsExiting)
				{
					this.Info.MainWindow.Close();
				}
				this.OnDeinit();
			}
		}
Example #12
0
        public void Searcher_When_SearcherWarmedUp_SearchIsFaster()
        {
            // Arrange
            var stopwatch = new Stopwatch();
            var indexsource = new FeedsDbContextIndexSource(new FeedsDbEntities(), 100);
            var searcher = new Searcher<Document>(indexsource);

            // Act
            stopwatch.Start();
            var results = searcher.Search("net").ToList();
            stopwatch.Stop();

            var elapsed = stopwatch.ElapsedMilliseconds;
            stopwatch.Reset();

            Debug.WriteLine(elapsed);

            stopwatch.Start();
            results = searcher.Search("net").ToList();
            stopwatch.Stop();

            var elapsed2 = stopwatch.ElapsedMilliseconds;

            Debug.WriteLine(elapsed2);

            // Assert
            Assert.IsTrue(elapsed2 < elapsed);
        }
 public double Update()
 {
     var w = new Stopwatch();
     w.Start();
     Initialize();
     //long timeInit = w.ElapsedTicks;
     w.Reset();
     w.Start();
     ImageBuffer = Solve(Xvalues, Yvalues, MaxIterations);
     //long timeSolve = w.ElapsedTicks;
     return w.ElapsedMilliseconds*0.001;
 }
        private static void Generate()
        {
            var fileName = "premake5";

            if (UnityEngine.Application.platform == RuntimePlatform.WindowsEditor) {
                fileName = Path.Combine(RootPath, fileName + ".exe");
            }

            using (var process = new Process {
                StartInfo = new ProcessStartInfo {
                    FileName = fileName,
                    WorkingDirectory = RootPath,
                    Arguments = "--protogen",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }
            }) {
                var timer = new Stopwatch();

                DataReceivedEventHandler hander = (sender, e) => {
                    timer.Reset();
                    timer.Start();

                    if (!e.Data.Contains(": error CS001: ")) return;

                    UnityEngine.Debug.LogError(e.Data.Substring(AssetsPath.Length + 1));
                };

                process.OutputDataReceived += hander;
                process.ErrorDataReceived += hander;

                timer.Start();
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                while (!process.WaitForExit(100)) {
                    if (timer.Elapsed.TotalSeconds > 2.5) {
                        UnityEngine.Debug.LogError("Process timed out while generating ProtoBuf classes");
                        return;
                    }
                }

                if (process.ExitCode == 0) {
                    UnityEngine.Debug.Log("Successfully generated ProtoBuf classes");
                } else {
                    UnityEngine.Debug.LogError("An error occurred while generating ProtoBuf classes");
                }
            }
        }
Example #15
0
    void LateUpdate()
    {
        //Debug.Log ("Time.time - updateRateRec = " + (Time.time - updateRateRec).ToString());
        if (Time.time - updateRateRec > updateRate)
        {
            Debug.Log("Time.time - updateRateRec = " + (Time.time - updateRateRec).ToString() + "updateRate = " + updateRate.ToString() + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            updateRateRec = Time.time;

            RenderMe();

            //currentMaterial.SetTexture("_Cube", cubemap);
            //GetComponent<Renderer>().material = currentMaterial;
        }

        if (Input.GetKeyUp("space"))
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();//-------------
            RenderMe();
            stopwatch.Stop();
            sb.AppendLine("RenderMe() cost : " + stopwatch.ElapsedMilliseconds);
            stopwatch.Reset();

            stopwatch.Start();//-------------
            //SaveCubemap();
            Texture2D sphereTex = SaveCubeMap2SphericalMap.CreateSphericalMapFromCubeMap(cubemap);
            stopwatch.Stop();
            sb.AppendLine("CreateSphericalMapFromCubeMap() cost : " + stopwatch.ElapsedMilliseconds);
            stopwatch.Reset();

            stopwatch.Start();//-------------
            var bytes = sphereTex.EncodeToJPG();
            File.WriteAllBytes(Application.dataPath + "/cube2sphere.jpg", bytes);
            stopwatch.Stop();
            sb.AppendLine("EncodeToJPG() cost : " + stopwatch.ElapsedMilliseconds);

            System.IO.File.WriteAllText(Application.dataPath + "/CostTime.txt", sb.ToString());
            Debug.Log("save cube map done!!");
            DestroyImmediate(sphereTex);
        }

        bool writeDebugFile = false;
        if (Input.GetKeyUp("d"))
            writeDebugFile = true;
        SaveCubeMap2SphericalMap.RenderDebugSphericalSampleRayInfo(16, 16, writeDebugFile);

        //Debug.Log("Mathf.Sin(Mathf.PI * 0.5f)=" + Mathf.Sin(Mathf.PI * 0.25f).ToString("0.000")  );
        //Debug.Log("Mathf.Cos(Mathf.PI * 0.5f)=" + Mathf.Cos(Mathf.PI * 0.25f).ToString("0.000")  );
    }
        public async Task Invoke(HttpContext context)
        {
            var sw = new Stopwatch();
            sw.Start();

            using (var memoryStream = new MemoryStream())
            {
                var bodyStream = context.Response.Body;
                context.Response.Body = memoryStream;

                await _next(context);

                var isHtml = context.Response.ContentType?.ToLower().Contains("text/html");
                if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault())
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    using (var streamReader = new StreamReader(memoryStream))
                    {
                        var responseBody = await streamReader.ReadToEndAsync();
                        //C# 6 DEMO
                        var newFooter = string.Format($"<footer><div id='process'>Page processed in {sw.ElapsedMilliseconds} milliseconds.</div>");
                        responseBody = responseBody.Replace("<footer>", newFooter);
                        context.Response.Headers.Add("X-ElapsedTime", new[] { sw.ElapsedMilliseconds.ToString() });
                        using (var amendedBody = new MemoryStream())
                        using (var streamWriter = new StreamWriter(amendedBody))
                        {
                            streamWriter.Write(responseBody);
                            amendedBody.Seek(0, SeekOrigin.Begin);
                            await amendedBody.CopyToAsync(bodyStream);
                        }
                    }
                }
            }
        }
Example #17
0
 /// <summary>
 /// Wrap a stopwatch aroudn the execution of an action.
 /// </summary>
 /// <param name="handler">The action to be timed.</param>
 /// <returns>Time elapsed during the handler's execution.</returns>
 public static TimeSpan Stopwatch(Action handler) {
     var s = new Diagnostics.Stopwatch();
     s.Start();
     handler();
     s.Stop();
     return s.Elapsed;
 }
        public async Task<ActionResult> HourlyMaintenance(string key)
        {
            Stopwatch stopWatch = new Stopwatch();

            // Cleanse the passed string parameters to prevent XSS.
            string cleanKey = Server.HtmlEncode(key);

            if (cleanKey == doctrineShipsServices.Settings.TaskKey)
            {
                // Time the execution of the hourly maintenance.
                stopWatch.Reset();
                stopWatch.Start();

                // Run hourly maintenance tasks.
                await this.doctrineShipsServices.HourlyMaintenance();

                // Stop the clock.
                stopWatch.Stop();

                logger.LogMessage("Hourly Maintenance Successful, Time Taken: " + stopWatch.Elapsed, 2, "Message", MethodBase.GetCurrentMethod().Name);
                return Content("Hourly Maintenance Successful, Time Taken: " + stopWatch.Elapsed);
            }
            else
            {
                logger.LogMessage("Hourly Maintenance Failed, Invalid Key: " + cleanKey, 1, "Message", MethodBase.GetCurrentMethod().Name);
                return Content("Hourly Maintenance Failed, Invalid Key");
            }
        }
        public IEnumerable<long> GetPrimeFactors(long product)
        {
            var sw = new Stopwatch();
            sw.Start();

            var initialProduct = product;
            var primeFactors = new List<long>();
            while (product != 1)
            {
                long factor = 1;
                for (long potentialFactor = 2; potentialFactor <= product; potentialFactor++)
                {
                    if (primeChecker.IsPrime(potentialFactor) && (product % potentialFactor == 0))
                    {
                        factor = potentialFactor;
                        Trace.WriteLine(string.Format("Factor: {0}", factor));
                        primeFactors.Add(factor);
                        break;
                    }
                }

                product = product / factor;
                if(primeChecker.IsPrime(product))
                {
                    primeFactors.Add(product);
                    break;
                }
            }

            sw.Stop();
            Trace.WriteLine(string.Format("PrimeFactorGenerator2 - time taken to find factors for {0}: {1} ticks", initialProduct, sw.ElapsedTicks));

            return primeFactors;
        }
        public void SetUp()
        {
            var stopwatch = new Stopwatch();
            _pack = new ConventionPack();
            _pack.AddRange(new IConvention[] 
            {
                new TrackingBeforeConvention(stopwatch) { Name = "1" },
                new TrackingMemberConvention(stopwatch) { Name = "3" },
                new TrackingAfterConvention(stopwatch) { Name = "5" },
                new TrackingMemberConvention(stopwatch) { Name = "4" },
                new TrackingAfterConvention(stopwatch) { Name = "6" },
                new TrackingBeforeConvention(stopwatch) { Name = "2" },
            });
            _subject = new ConventionRunner(_pack);

            var classMap = new BsonClassMap<TestClass>(cm =>
            {
                cm.MapMember(t => t.Prop1);
                cm.MapMember(t => t.Prop2);
            });

            stopwatch.Start();
            _subject.Apply(classMap);
            stopwatch.Stop();
        }
        public ISearchResult Search(string query)
        {
            var timer = new Stopwatch();
            timer.Start();

            var directory = FSDirectory.Open(new DirectoryInfo(path));
            var analyzer = new StandardAnalyzer(Version.LUCENE_29);
            var searcher = new IndexSearcher(directory, true);

            var queryParser = new QueryParser(Version.LUCENE_29, "text", analyzer);
            var result = searcher.Search(queryParser.Parse(query), 20);

            var docs = (from scoreDoc in result.scoreDocs
                        let doc = searcher.Doc(scoreDoc.doc)
                        let fields = new Dictionary<string, string> { { "title", doc.Get("title") }, { "text", doc.Get("text") } }
                        select new LuceneDocument { Id = scoreDoc.doc.ToString(), Fields = fields }).ToList();

            var ret = new SearchResult { Query = query, Total = result.totalHits, Documents = docs, Source = Name };

            searcher.Close();
            directory.Close();

            timer.Stop();
            ret.Duration = (decimal) timer.Elapsed.TotalSeconds;

            return ret;
        }
        public ActionResult RefreshContracts(string key, string force, string batchSize)
        {
            Stopwatch stopWatch = new Stopwatch();

            // Cleanse the passed string parameters to prevent XSS.
            string cleanKey = Server.HtmlEncode(key);
            bool cleanForce = Conversion.StringToBool(Server.HtmlEncode(force), false);
            int cleanBatchSize = Conversion.StringToInt32(Server.HtmlEncode(batchSize), 10);

            if (cleanKey == doctrineShipsServices.Settings.TaskKey)
            {
                // Time the execution of the contract refresh.
                stopWatch.Reset();
                stopWatch.Start();

                // Check sales agents and refresh their contracts if required. Also update various contract counts.
                this.doctrineShipsServices.RefreshContracts(cleanForce, cleanBatchSize);
                
                // Stop the clock.
                stopWatch.Stop();

                logger.LogMessage("Contract Refresh Successful, Time Taken: " + stopWatch.Elapsed, 2, "Message", MethodBase.GetCurrentMethod().Name);
                return Content("Contract Refresh Successful, Time Taken: " + stopWatch.Elapsed);
            }
            else
            {
                logger.LogMessage("Contract Refresh Failed, Invalid Key: " + cleanKey, 1, "Message", MethodBase.GetCurrentMethod().Name);
                return Content("Contract Refresh Failed, Invalid Key");
            }
        }
        public TemplateGenerationMetadata GenerateMetadata()
        {
            var timer = new Stopwatch();
            timer.Start();

            // load the templates we'll be generating into a state storage collection
            var templateData = CreateTemplateData();

            foreach (var template in templateData.Templates)
            {
                HashSet<string> fieldKeys = GetBaseFieldSet(); // get fields on base type

                fieldKeys.Add(template.TypeName); // member names cannot be the same as their enclosing type so we add the type name to the fields collection

                foreach (var baseTemplate in template.Template.AllNonstandardBaseTemplates) // similarly names can't be the same as any of their base templates' names (this would cause an incompletely implemented interface)
                {
                    if (templateData.Contains(baseTemplate.TemplateId))
                    {
                        fieldKeys.Add(templateData[baseTemplate.TemplateId].TypeName);
                    }
                    else fieldKeys.Add(baseTemplate.Name.AsIdentifier()); // NOTE: you could break this if you have a base template called Foo and a field called Foo that IS NOT on the Foo template (but why would you have that?)
                }

                // generate item properties
                foreach (var field in template.Template.Fields)
                {
                    if (_templateInputProvider.IsFieldIncluded(field.Id)) // query the template input provider and make sure the field is included
                    {
                        string propertyName = field.Name.AsNovelIdentifier(fieldKeys);

                        var fieldInfo = new FieldPropertyInfo(field);
                        fieldInfo.FieldPropertyName = propertyName;
                        fieldInfo.SearchFieldName = _indexFieldNameTranslator.GetIndexFieldName(field.Name);
                        fieldInfo.FieldType = _fieldMappingProvider.GetFieldType(field);

                        if (fieldInfo.FieldType == null)
                        {
                            Log.Warn("Synthesis: Field type resolution for " + field.Template.Name + "::" + field.Name + " failed; no mapping found for field type " + field.Type, this);
                            continue; // skip adding the field for generation
                        }

                        // record usage of the property name
                        fieldKeys.Add(propertyName);

                        // add the field to the metadata
                        template.FieldsToGenerate.Add(fieldInfo);
                    }
                }

                // generates interfaces to represent the Sitecore template inheritance hierarchy
                TemplateInfo baseInterface = GenerateInheritedInterfaces(template.Template, templateData);
                if (baseInterface != null)
                    template.InterfacesImplemented.Add(baseInterface);
            }

            timer.Stop();
            Log.Info(string.Format("Synthesis: Generated metadata for {0} concrete templates and {1} interface templates in {2} ms", templateData.Templates.Count, templateData.Interfaces.Count, timer.ElapsedMilliseconds), this);

            return templateData;
        }
Example #24
0
		/// <summary>
		/// Optimizes a media stream and returns the optimized result. The original stream is closed if processing is successful.
		/// </summary>
		public virtual MediaStream Process(MediaStream stream, MediaOptions options)
		{
			Assert.ArgumentNotNull(stream, "stream");

			if (!stream.AllowMemoryLoading)
			{
				Tracer.Error("Could not resize image as it was larger than the maximum size allowed for memory processing. Media item: {0}", stream.MediaItem.Path);
				return null;
			}

			var optimizer = CreateOptimizer(stream);

			if (optimizer == null) return null;

			var sw = new Stopwatch();
			sw.Start();

			var result = optimizer.Optimize(stream);

			sw.Stop();

			if (result.Success)
			{
				stream.Stream.Close();

				Log.Info("Dianoga: optimized {0}.{1} [{2}] (final size: {3} bytes) - saved {4} bytes / {5:p}. Optimized in {6}ms.".FormatWith(stream.MediaItem.MediaPath, stream.MediaItem.Extension, GetDimensions(options), result.SizeAfter, result.SizeBefore - result.SizeAfter, 1 - ((result.SizeAfter / (float)result.SizeBefore)), sw.ElapsedMilliseconds), this);

				return new MediaStream(result.CreateResultStream(), stream.Extension, stream.MediaItem);
			}

			Log.Warn("Dianoga: unable to optimize {0}.{1} because {2}".FormatWith(stream.MediaItem.MediaPath, stream.MediaItem.Extension, result.ErrorMessage), this);

			return null;
		}
Example #25
0
 //https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/dotnet/Worker/Worker.cs
 static void Dequeue(string queueName, string hostName, int expected)
 {
     int count = 0;
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     var factory = new ConnectionFactory() { HostName = hostName };
     factory.UserName = "******";
     factory.Password = "******";
     using (var connection = factory.CreateConnection())
     {
         using (var channel = connection.CreateModel())
         {
             channel.QueueDeclare(queueName, true, false, false, null);
             channel.BasicQos(0, 1, false);
             var consumer = new QueueingBasicConsumer(channel);
             channel.BasicConsume(queueName, false, consumer);
             sw.Start();
             while (count < expected)
             {
                 BasicDeliverEventArgs ea = consumer.Queue.Dequeue();
                 var body = ea.Body;
                 var message = Encoding.UTF8.GetString(body);
                 channel.BasicAck(ea.DeliveryTag, false);
                 ++count;
             }
             sw.Stop();
         }
     }
     Console.WriteLine(" [x] {0} messages dequeued in time = {1} ms", count, sw.ElapsedMilliseconds);
 }
        public static void BulkMerge(int nbRecords, Stopwatch clock, StringBuilder sb)
        {
            int recordsToUpdate = nbRecords/2;
            int recordsToInsert = nbRecords - recordsToUpdate;

            var listToInsert = new List<EntitySimple>();

            for (int i = 0; i < recordsToInsert; i++)
            {
                listToInsert.Add(new EntitySimple {ColumnInt = i%5});
            }

            using (var ctx = new CodeFirstEntities())
            {
                ctx.EntitySimples.AddRange(listToInsert);

                List<EntitySimple> listToUpdate = ctx.EntitySimples.Take(recordsToUpdate).AsNoTracking().ToList();
                listToUpdate.ForEach(x => x.ColumnInt = x.ColumnInt + 1);

                sb.Append(string.Format("INSERT {0} / UPDATE {1} entities", recordsToInsert, recordsToUpdate));

                clock.Start();
                ctx.BulkMerge(listToUpdate);
                clock.Stop();
            }
        }
Example #27
0
 //https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/dotnet/NewTask/NewTask.cs
 static void Enqueue(string queueName, string hostName, string msg, int cycles)
 {
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     var factory = new ConnectionFactory() { HostName = hostName };
     factory.UserName = "******";
     factory.Password = "******";
     using (var connection = factory.CreateConnection())
     {
         using (var channel = connection.CreateModel())
         {
             byte[] body;
             QueueDeclareOk res = channel.QueueDeclare(queueName, true, false, false, null);
             if (msg != null)
                 body = Encoding.UTF8.GetBytes(msg);
             else
                 body = new byte[0];
             var properties = channel.CreateBasicProperties();
             properties.SetPersistent(true);
             sw.Start();
             for (int n = 0; n < cycles; ++n)
             {
                 channel.BasicPublish("", queueName, properties, body);
             }
             sw.Stop();
         }
     }
     Console.WriteLine(" [x] Enqueue {0} with count = {1}, time = {2} ms", "", cycles, sw.ElapsedMilliseconds);
 }
Example #28
0
        public void TestSequenceEnumerationParallel2()
        {
            var methodName = MethodBase.GetCurrentMethod().Name;
            TestUtils.ShowStarting(methodName);

            var sw = new System.Diagnostics.Stopwatch();

            const string dbFile = @"\\proto-2\UnitTest_Files\InformedProteomics_TestFiles\MSPathFinderT\ID_002216_235ACCEA.fasta";
            var db = new FastaDatabase(dbFile);
            db.Read();
            var indexedDb = new IndexedDatabase(db);
            var arr = db.Characters().ToArray();

            sw.Start();
            //var annotationsAndOffsets = indexedDb.AnnotationsAndOffsetsNoEnzyme(7, 30);
            //            var num = annotationsAndOffsets.AsParallel().LongCount(annotationsAndOffset => annotationsAndOffset.Annotation.IndexOf('W') >= 0);
            //var num = annotationsAndOffsets.LongCount(annotationsAndOffset => annotationsAndOffset.Annotation.IndexOf('W') >= 0);
            //var num = arr.AsParallel().Where(c => c == 'W').LongCount();
            var num = 0;
            var sum = 0L;
            //foreach (var c in arr)
            for (var a = 0; a < arr.Length; a++)
            {
                var c = arr[a];
                for (var i = 0; i < c * 10000; i++) sum += i;
                //                Interlocked.Increment(ref num);
                if (++num == 1000) break;
            }

            Console.WriteLine("NumPeptides: {0}", sum);
            sw.Stop();

            Console.WriteLine(@"{0:f4} sec", sw.Elapsed.TotalSeconds);
        }
        public void Should_fail_to_resolve_route_because_it_does_have_an_invalid_condition()
        {
            // Given
            var cache = new FakeRouteCache(with => {
                with.AddGetRoute("/invalidcondition", "modulekey", ctx => false);
            });

            var bootstrapper = new ConfigurableBootstrapper(with =>{
                with.RouteCache(cache);
            });

            var browser = new Browser(bootstrapper);

            // When
            var timer = new Stopwatch();
            timer.Start();

            for (var i = 0; i < numberOfTimesToResolveRoute; i++)
            {
                var result = browser.Get("/invalidcondition");
                result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);
            }

            timer.Stop();

            // Then
            Debug.WriteLine(" took {0} to execute {1} times", timer.Elapsed, numberOfTimesToResolveRoute);
        }
        public void Thirty()
        {
            TestContext.DeleteAll(x => x.Entity_Basics);
            TestContext.Insert(x => x.Entity_Basics, 50);

            using (var ctx = new TestContext())
            {
                // BEFORE
                Assert.AreEqual(1225, ctx.Entity_Basics.Sum(x => x.ColumnInt));

                // ACTION
                var clock = new Stopwatch();
                clock.Start();
                var rowsAffected = ctx.Entity_Basics.Where(x => x.ColumnInt > 10 && x.ColumnInt <= 40).Update(x => new Entity_Basic { ColumnInt = 99 }, update =>
                {
                    update.BatchDelayInterval = 50;
                    update.BatchSize = 5;
                });
                clock.Stop();

                // AFTER
                Assert.AreEqual(460, ctx.Entity_Basics.Sum(x => x.ColumnInt));
                Assert.AreEqual(30, rowsAffected);
                Assert.IsTrue(clock.ElapsedMilliseconds > 250 && clock.ElapsedMilliseconds < 600);
            }
        }
Example #31
0
        public void Inverse()
        {
            var stopWatch = new Stopwatch();
            stopWatch.Start();

            var csgA = new CSG.CSG();
            csgA.Construct(A.GetComponent<MeshFilter>().sharedMesh, A.transform, 0);

            var substract = csgA.Inverse();
            var newMesh = substract.ToMesh();

            Result = new GameObject("Inverse");
            var defObj = Result.AddComponent<DefaultObject>();
            var meshFilter = Result.AddComponent<MeshFilter>();
            meshFilter.sharedMesh = newMesh;
            var renderer = Result.AddComponent<MeshRenderer>();
            renderer.sharedMaterial = new Material(A.GetComponent<MeshRenderer>().sharedMaterial);

            if (DeleteOriginal)
            {
                Object.DestroyImmediate(A);
            }

            stopWatch.Stop();
            defObj.GenerationTimeMS = stopWatch.ElapsedMilliseconds;
        }
Example #32
0
        /// <summary>
        /// 计时器开始
        /// </summary>
        /// <returns></returns>
        public static Diagnostics.Stopwatch TimerStart()
        {
            var watch = new Diagnostics.Stopwatch();

            watch.Reset();
            watch.Start();
            return(watch);
        }
Example #33
0
 public void Reset()
 {
     oStopWatch.Reset();
     oStopWatch.Start();
 }
 public void Setup()
 {
     _watch = new Stopwatch();
     _watch.Start();
 }
Example #35
0
        public void GetReportAsExcelSpreadsheet(List <int> listOfMeterIDs, MemoryStream ms, CustomerLogic result)
        {
            timeIsolation.IsolationType = SensorAndPaymentReportEngine.TimeIsolations.None;

            // Start diagnostics timer
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            DateTime NowAtDestination = Convert.ToDateTime(this._CustomerConfig.DestinationTimeZoneDisplayName);// DateTime.Now;//Datetime.Now;//DateTime.Now;//Datetime.Now;

            // Now gather and analyze data for the report
            SensorAndPaymentReportEngine.RequiredDataElements requiredDataElements = new SensorAndPaymentReportEngine.RequiredDataElements();
            requiredDataElements.NeedsSensorData            = true;
            requiredDataElements.NeedsPaymentData           = false;
            requiredDataElements.NeedsOverstayData          = false;
            requiredDataElements.NeedsEnforcementActionData = false;
            this._ReportEngine = new SensorAndPaymentReportEngine(this._CustomerConfig, _ReportParams);
            this._ReportEngine.GatherReportData(listOfMeterIDs, requiredDataElements, result);

            OfficeOpenXml.ExcelWorksheet ws = null;

            using (OfficeOpenXml.ExcelPackage pck = new OfficeOpenXml.ExcelPackage())
            {
                // Let's create a report coversheet and overall summary page, with hyperlinks to the other worksheets
                // Create the worksheet
                ws = pck.Workbook.Worksheets.Add("Summary");

                // Render the standard report title lines
                rowIdx = 1; // Excel uses 1-based indexes
                colIdx = 1;
                RenderCommonReportTitle(ws, this._ReportName);

                // Render common report header for enforcement activity restriction filter, but only if its not for all activity
                if (this._ReportParams.ActionTakenRestrictionFilter != SensorAndPaymentReportEngine.ReportableEnforcementActivity.AllActivity)
                {
                    rowIdx++;
                    colIdx = 1;
                    RenderCommonReportFilterHeader_ActionTakenRestrictions(ws);
                }

                // Render common report header for regulated hour restriction filter
                rowIdx++;
                colIdx = 1;
                RenderCommonReportFilterHeader_RegulatedHourRestrictions(ws);

                using (OfficeOpenXml.ExcelRange rng = ws.Cells[2, 1, rowIdx, numColumnsMergedForHeader])
                {
                    rng.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;                 //Set Pattern for the background to Solid
                    rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(207, 221, 237)); //Set color to lighter blue FromArgb(184, 204, 228)
                }

                rowIdx++;
                colIdx = 1;
                int hyperlinkstartRowIdx = rowIdx;

                if (_ReportParams.IncludeMeterSummary == true)
                {
                    RenderWorksheetHyperlink(ws, "Meter Occupancy", "Meter Occupancy summary");
                }
                if (_ReportParams.IncludeSpaceSummary == true)
                {
                    RenderWorksheetHyperlink(ws, "Space Occupancy", "Space Occupancy summary");
                }
                if (_ReportParams.IncludeAreaSummary == true)
                {
                    RenderWorksheetHyperlink(ws, "Area Occupancy", "Area Occupancy summary");
                }
                if (_ReportParams.IncludeDailySummary == true)
                {
                    RenderWorksheetHyperlink(ws, "Daily Occupancy", "Daily Occupancy summary");
                }
                if (_ReportParams.IncludeMonthlySummary == true)
                {
                    RenderWorksheetHyperlink(ws, "Monthly Occupancy", "Monthly Occupancy summary");
                }
                if (_ReportParams.IncludeDetailRecords == true)
                {
                    RenderWorksheetHyperlink(ws, "Details", "Occupancy details");
                }

                rowIdx++;
                rowIdx++;
                colIdx = 1;

                using (OfficeOpenXml.ExcelRange rng = ws.Cells[hyperlinkstartRowIdx, 1, rowIdx, numColumnsMergedForHeader])
                {
                    rng.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.White);
                }


                // Now start the report data summary header
                RenderOverallReportSummary(ws);

                //  --- END OF OVERALL SUMMARY WORKSHEET ---

                // Should we include a worksheet with Meter aggregates?
                if (_ReportParams.IncludeMeterSummary == true)
                {
                    RenderMeterSummaryWorksheet(pck, "Meter Occupancy");
                }

                // Should we include a worksheet with Space aggregates?
                if (_ReportParams.IncludeSpaceSummary == true)
                {
                    RenderSpaceSummaryWorksheet(pck, "Space Occupancy");
                }

                // Should we include a worksheet with Area aggregates?
                if (_ReportParams.IncludeAreaSummary == true)
                {
                    RenderAreaSummaryWorksheet(pck, "Area Occupancy");
                }

                // Should we include a worksheet with Daily aggregates?
                if (_ReportParams.IncludeDailySummary == true)
                {
                    RenderDailySummaryWorksheet(pck, "Daily Occupancy");
                }

                // Should we include a worksheet with Monthly aggregates?
                if (_ReportParams.IncludeDailySummary == true)
                {
                    RenderMonthlySummaryWorksheet(pck, "Monthly Occupancy");
                }


                // Should we include a Details worksheet?
                if (_ReportParams.IncludeDetailRecords == true)
                {
                    // Create the worksheet
                    ws = pck.Workbook.Worksheets.Add("Details");
                    int detailColumnCount = 8;

                    // Render the header row
                    rowIdx = 1; // Excel uses 1-based indexes
                    ws.SetValue(rowIdx, 1, "Space #");
                    ws.SetValue(rowIdx, 2, "Meter #");
                    ws.SetValue(rowIdx, 3, "Area #");
                    ws.SetValue(rowIdx, 4, "Area");
                    ws.SetValue(rowIdx, 5, "Event Start");
                    ws.SetValue(rowIdx, 6, "Event End");
                    ws.SetValue(rowIdx, 7, "Occupied?");
                    ws.SetValue(rowIdx, 8, "Duration");

                    // Format the header row
                    using (OfficeOpenXml.ExcelRange rng = ws.Cells[1, 1, 1, detailColumnCount])
                    {
                        rng.Style.Font.Bold        = true;
                        rng.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;                 //Set Pattern for the background to Solid
                        rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189));  //Set color to dark blue
                        rng.Style.Font.Color.SetColor(System.Drawing.Color.White);
                    }

                    // Increment the row index, which will now be the 1st row of our data
                    rowIdx++;

                    #region Populate data for each record

                    foreach (SpaceAsset spaceAsset in this._ReportEngine.ReportDataModel.SpacesIncludedInReport)
                    {
                        List <SensorAndPaymentReportEngine.CommonSensorAndPaymentEvent> spaceRecs = this._ReportEngine.ReportDataModel.FindRecsForBayAndMeter(spaceAsset.SpaceID, spaceAsset.MeterID);
                        foreach (SensorAndPaymentReportEngine.CommonSensorAndPaymentEvent nextEvent in spaceRecs)
                        {
                            // Don't detail this item if its a "dummy" event
                            if (nextEvent.IsDummySensorEvent == true)
                            {
                                continue;
                            }

                            AreaAsset areaAsset = _ReportEngine.GetAreaAsset(spaceAsset.AreaID_PreferLibertyBeforeInternal);

                            // Output row values for data
                            ws.SetValue(rowIdx, 1, spaceAsset.SpaceID);
                            ws.SetValue(rowIdx, 2, spaceAsset.MeterID);

                            if (areaAsset != null)
                            {
                                ws.SetValue(rowIdx, 3, areaAsset.AreaID);
                                ws.SetValue(rowIdx, 4, areaAsset.AreaName);
                            }

                            ws.SetValue(rowIdx, 5, nextEvent.SensorEvent_Start);
                            ws.SetValue(rowIdx, 6, nextEvent.SensorEvent_End);

                            if (nextEvent.SensorEvent_IsOccupied == true)
                            {
                                ws.SetValue(rowIdx, 7, "Y");
                            }
                            else
                            {
                                ws.SetValue(rowIdx, 7, "N");
                            }

                            ws.SetValue(rowIdx, 8, FormatTimeSpanAsHoursMinutesAndSeconds(nextEvent.SensorEvent_Duration));

                            // Increment the row index, which will now be the next row of our data
                            rowIdx++;

                            // Is there a child "repeat" event also?
                            if (nextEvent.RepeatSensorEvents != null)
                            {
                                foreach (SensorAndPaymentReportEngine.CommonSensorAndPaymentEvent repeatEvent in nextEvent.RepeatSensorEvents)
                                {
                                    ws.SetValue(rowIdx, 1, spaceAsset.SpaceID);
                                    ws.SetValue(rowIdx, 2, spaceAsset.MeterID);

                                    if (areaAsset != null)
                                    {
                                        ws.SetValue(rowIdx, 3, areaAsset.AreaID);
                                        ws.SetValue(rowIdx, 4, areaAsset.AreaName);
                                    }

                                    ws.SetValue(rowIdx, 5, repeatEvent.SensorEvent_Start);
                                    ws.SetValue(rowIdx, 6, repeatEvent.SensorEvent_End);

                                    if (repeatEvent.SensorEvent_IsOccupied == true)
                                    {
                                        ws.SetValue(rowIdx, 7, "Y");
                                    }
                                    else
                                    {
                                        ws.SetValue(rowIdx, 7, "N");
                                    }

                                    ws.SetValue(rowIdx, 8, FormatTimeSpanAsHoursMinutesAndSeconds(repeatEvent.SensorEvent_Duration));

                                    // Increment the row index, which will now be the next row of our data
                                    rowIdx++;
                                }
                            }
                        }
                    }
                    #endregion

                    // We will add autofilters to our headers so user can sort the columns easier
                    using (OfficeOpenXml.ExcelRange rng = ws.Cells[1, 1, rowIdx, detailColumnCount])
                    {
                        rng.AutoFilter = true;
                    }

                    // Apply formatting to the columns as appropriate (Starting row is 2 (first row of data), and ending row is the current rowIdx value)

                    ApplyNumberStyleToColumn(ws, 1, 2, rowIdx, "########0", ExcelHorizontalAlignment.Left);
                    ApplyNumberStyleToColumn(ws, 2, 2, rowIdx, "########0", ExcelHorizontalAlignment.Left);
                    ApplyNumberStyleToColumn(ws, 3, 2, rowIdx, "########0", ExcelHorizontalAlignment.Left);

                    ApplyNumberStyleToColumn(ws, 5, 2, rowIdx, "yyyy-mm-dd hh:mm:ss tt", ExcelHorizontalAlignment.Right);
                    ApplyNumberStyleToColumn(ws, 6, 2, rowIdx, "yyyy-mm-dd hh:mm:ss tt", ExcelHorizontalAlignment.Right);

                    ApplyNumberStyleToColumn(ws, 7, 2, rowIdx, "@", ExcelHorizontalAlignment.Right); // String value, right-aligned
                    ApplyNumberStyleToColumn(ws, 8, 2, rowIdx, "@", ExcelHorizontalAlignment.Right); // String value, right-aligned

                    // And now lets size the columns
                    for (int autoSizeColIdx = 1; autoSizeColIdx <= detailColumnCount; autoSizeColIdx++)
                    {
                        using (OfficeOpenXml.ExcelRange col = ws.Cells[1, autoSizeColIdx, rowIdx, autoSizeColIdx])
                        {
                            col.AutoFitColumns();
                        }
                    }
                }


                // All cells in spreadsheet are populated now, so render (save the file) to a memory stream
                byte[] bytes = pck.GetAsByteArray();
                ms.Write(bytes, 0, bytes.Length);
            }

            // Stop diagnostics timer
            sw.Stop();
            System.Diagnostics.Debug.WriteLine(this._ReportName + " generation took: " + sw.Elapsed.ToString());
        }
Example #36
0
        public static void Benchmark1(int total_parents, List <long> testTimes, List <long> testTimes2, ref int rowcount, ref int rowcount2)
        {
            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();

            using (CEF.NewServiceScope())
            {
                var people = new EntitySet <PersonWrapped>();

                for (int parentcnt = 1; parentcnt <= total_parents; ++parentcnt)
                {
                    var parent = new PersonWrapped()
                    {
                        Name = $"NP{parentcnt}", Age = (parentcnt % 60) + 20, Gender = (parentcnt % 2) == 0 ? "F" : "M"
                    };

                    parent.Phones.Add(new Phone()
                    {
                        Number = "888-7777", PhoneTypeID = PhoneType.Mobile
                    });
                    parent.Phones.Add(new Phone()
                    {
                        Number = "777-6666", PhoneTypeID = PhoneType.Work
                    });

                    if ((parentcnt % 12) == 0)
                    {
                        CEF.NewObject(new Phone()
                        {
                            Number = "666-5555", PhoneTypeID = PhoneType.Home
                        });
                    }
                    else
                    {
                        parent.Phones.Add(new Phone()
                        {
                            Number = "777-6666", PhoneTypeID = PhoneType.Home
                        });
                    }

                    rowcount += 4;

                    for (int childcnt = 1; childcnt <= (parentcnt % 4); ++childcnt)
                    {
                        var child = CEF.NewObject(new PersonWrapped()
                        {
                            Name   = $"NC{parentcnt}{childcnt}",
                            Age    = parent.Age - 20,
                            Gender = (parentcnt % 2) == 0 ? "F" : "M"
                            ,
                            Phones = new Phone[] { new Phone()
                                                   {
                                                       Number = "999-8888", PhoneTypeID = PhoneType.Mobile
                                                   } }
                        });

                        parent.Kids.Add(child);
                        rowcount += 2;
                    }

                    people.Add(parent);
                }

                CEF.DBSave();
            }

            testTimes.Add(watch.ElapsedMilliseconds);
            watch.Restart();

            // For purposes of benchmarking, treat this as a completely separate operation
            using (var ss = CEF.NewServiceScope())
            {
                // For everyone who's a parent of at least 30 yo, if at least 2 children of same sex, remove work phone, increment age
                var people = new EntitySet <Person>().DBRetrieveSummaryForParents(30);

                Parallel.ForEach((from a in people let d = a.AsDynamic() where d.MaleChildren > 1 || d.FemaleChildren > 1 select a).ToList(), (p) =>
                {
                    using (CEF.UseServiceScope(ss))
                    {
                        p.Age += 1;

                        var phones = new EntitySet <Phone>().DBRetrieveByOwner(p.PersonID, PhoneType.Work);

                        if (phones.Any())
                        {
                            CEF.DeleteObject(phones.First());
                        }
                    }
                });

                rowcount2 += CEF.DBSave().Count();
            }

            watch.Stop();
            testTimes2.Add(watch.ElapsedMilliseconds);
        }
Example #37
0
        static string Clean(string input)
        {
            var lines        = input.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var ignoredLines = (from line in lines
                                where line.StartsWith("matrix-off") || line.StartsWith("noscript-spoof") || line.Contains("#")
                                select line).ToArray();
            var rules = lines.Except(ignoredLines).Select(l => new UMatrixRule(l)).ToArray();



            List <Predicate <UMatrixRule> > fixedRulePredicates = new List <Predicate <UMatrixRule> >(new Predicate <UMatrixRule>[]
            {
                r => r.ToString() == "* * * block",                     //不删除默认规则
                r => r.ToString() == "* * css allow",
                r => r.ToString() == "* * frame block",
                r => r.ToString() == "* * image allow",
                r => r.ToString() == "* 1st-party * allow",
                r => r.ToString() == "* 1st-party frame allow"
            });

            if (options.CheckLog != null)
            {
                var deletedRules = ReadHistorialDeletions();
                fixedRulePredicates.Add(rule => deletedRules.Contains(rule));
            }

            var isFixedRules = rules.ToLookup(rule => fixedRulePredicates.Any(p => p(rule)));

            HashSet <UMatrixRule> workingRules = new HashSet <UMatrixRule>();
            var random = new Random();

            foreach (var rule in isFixedRules[false])
            {
                if (options.RandomDelete > 0 && random.Next(0, 100) <= options.RandomDelete)
                {
                    logger.LogInformation("{0}被随机删除。", rule);
                }
                else
                {
                    workingRules.Add(rule);
                }
            }

            //不可删除的规则也要参与锁定
            RuleRelationshipManager ruleManager = new RuleRelationshipManager(workingRules.Union(isFixedRules[true]).ToList());
            EventsHelper            events      = options.Log != null ? new EventsHelper() : null;

            Stopwatch sw = null;

            if (logger.IsEnabled(LogLevel.Debug))
            {
                sw = new System.Diagnostics.Stopwatch();
                sw.Start();
            }

            ruleManager.MergeEvent += (sender, e) =>
            {
                if (logger.IsEnabled(LogLevel.Information))
                {
                    var info = "合并" + string.Join("、\r\n    ", e.RulesToDelete.Select(r => r.ToString("\t")));
                    info += "\r\n  为" + e.MasterRule.ToString("\t") + "。";
                    logger.LogInformation(info);
                }

                events?.Events.Add(e);
            };

            ruleManager.DedupEvent += (sender, e) =>
            {
                if (logger.IsEnabled(LogLevel.Information))
                {
                    var info = "删除    " + string.Join("、\r\n        ", e.DuplicateRules.Select(r => r.ToString("\t")));
                    info += $"\r\n因为它被{e.MasterRule.ToString("\t")}包含。";
                    logger.LogInformation(info);
                }
                events?.Events.Add(e);
            };


            var newRules = ruleManager.Clean(options.MergeThreshold);

            if (sw != null)
            {
                sw.Stop();
                logger.LogDebug("合并用时{0}毫秒", sw.ElapsedMilliseconds);
            }


            if (events != null)
            {
                SaveEvents(events);
            }
            var newWorkingRules = newRules;

            return(string.Join(Environment.NewLine, ignoredLines) + Environment.NewLine + string.Join(Environment.NewLine, isFixedRules[true].Union(newWorkingRules)));
        }
Example #38
0
        private void QueryResults()
        {
            if (!string.IsNullOrEmpty(QueryText))
            {
                var queryTimer = new System.Diagnostics.Stopwatch();
                queryTimer.Start();
                _updateSource?.Cancel();
                var currentUpdateSource = new CancellationTokenSource();
                _updateSource = currentUpdateSource;
                var currentCancellationToken = _updateSource.Token;
                _updateToken = currentCancellationToken;

                var query = QueryBuilder.Build(QueryText.Trim(), PluginManager.NonGlobalPlugins);
                if (query != null)
                {
                    _currentQuery = query;
                    Task.Run(() =>
                    {
                        Thread.Sleep(20);
                        var plugins = PluginManager.ValidPluginsForQuery(query);

                        try
                        {
                            currentCancellationToken.ThrowIfCancellationRequested();

                            var resultPluginPair = new List <(List <Result>, PluginMetadata)>();
                            foreach (PluginPair plugin in plugins)
                            {
                                if (!plugin.Metadata.Disabled)
                                {
                                    var results = PluginManager.QueryForPlugin(plugin, query);
                                    resultPluginPair.Add((results, plugin.Metadata));
                                    currentCancellationToken.ThrowIfCancellationRequested();
                                }
                            }

                            lock (_addResultsLock)
                            {
                                if (query.RawQuery == _currentQuery.RawQuery)
                                {
                                    Results.Clear();
                                    foreach (var p in resultPluginPair)
                                    {
                                        UpdateResultView(p.Item1, query, currentCancellationToken);
                                        currentCancellationToken.ThrowIfCancellationRequested();
                                    }

                                    currentCancellationToken.ThrowIfCancellationRequested();
                                    Results.Sort();
                                }
                            }

                            currentCancellationToken.ThrowIfCancellationRequested();
                            UpdateResultsListViewAfterQuery(query);

                            // Run the slower query of the DelayedExecution plugins
                            currentCancellationToken.ThrowIfCancellationRequested();
                            Parallel.ForEach(plugins, (plugin) =>
                            {
                                if (!plugin.Metadata.Disabled)
                                {
                                    var results = PluginManager.QueryForPlugin(plugin, query, true);
                                    currentCancellationToken.ThrowIfCancellationRequested();
                                    if ((results?.Count ?? 0) != 0)
                                    {
                                        lock (_addResultsLock)
                                        {
                                            if (query.RawQuery == _currentQuery.RawQuery)
                                            {
                                                currentCancellationToken.ThrowIfCancellationRequested();

                                                // Remove the original results from the plugin
                                                Results.Results.RemoveAll(r => r.Result.PluginID == plugin.Metadata.ID);
                                                currentCancellationToken.ThrowIfCancellationRequested();

                                                // Add the new results from the plugin
                                                UpdateResultView(results, query, currentCancellationToken);
                                                currentCancellationToken.ThrowIfCancellationRequested();
                                                Results.Sort();
                                            }
                                        }

                                        currentCancellationToken.ThrowIfCancellationRequested();
                                        UpdateResultsListViewAfterQuery(query, true);
                                    }
                                }
                            });
                        }
                        catch (OperationCanceledException)
                        {
                            // nothing to do here
                        }

                        queryTimer.Stop();
                        var queryEvent = new LauncherQueryEvent()
                        {
                            QueryTimeMs = queryTimer.ElapsedMilliseconds,
                            NumResults  = Results.Results.Count,
                            QueryLength = query.RawQuery.Length
                        };
                        PowerToysTelemetry.Log.WriteEvent(queryEvent);
                    }, currentCancellationToken);
                }
            }
            else
            {
                _updateSource?.Cancel();
                _currentQuery        = _emptyQuery;
                Results.SelectedItem = null;
                Results.Visibility   = Visibility.Hidden;
                Results.Clear();
            }
        }
Example #39
0
        private void Open_Click(object sender, EventArgs e)
        {
            Bitmap         image;
            OpenFileDialog open_dialog = new OpenFileDialog();

            if (open_dialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    filename  = open_dialog.FileName;
                    extension = Path.GetExtension(filename);
                    FileInfo fi = new FileInfo(open_dialog.FileName);
                    filepath = fi.DirectoryName;
                    fi.CopyTo("copy.tiff", true);
                    if (imageFormat.Contains(extension))
                    {
                        imageLoaded = true;
                        image       = new Bitmap(open_dialog.FileName);
                        string imageString = image.ToString();
                        b           = ImageToByteArray(image);
                        l           = Convert.ToInt32(fi.Length);
                        label1.Text = "Тип файла: изображение";

                        Stopwatch StopwatchRLE = new System.Diagnostics.Stopwatch();
                        StopwatchRLE.Start(); //запуск

                        b2 = ImageRLE(b);
                        int l2 = b2.Length;

                        StopwatchRLE.Stop(); //остановить
                        TimeSpan ts = StopwatchRLE.Elapsed;

                        string elapsedTime = "RLE:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                    ts.Hours, ts.Minutes, ts.Seconds,
                                                                    ts.Milliseconds / 10);
                        //  label4.Text = elapsedTime;
                        //ImageLZW();

                        Stopwatch StopwatchJPEG = new System.Diagnostics.Stopwatch();
                        StopwatchJPEG.Start(); //запуск

                        long lenghtJPG = VaryQualityLevel(filename, filepath + "\\");

                        StopwatchJPEG.Stop(); //остановить
                        TimeSpan ts1 = StopwatchJPEG.Elapsed;

                        string elapsedTime1 = "JPEG:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                      ts1.Hours, ts1.Minutes, ts1.Seconds,
                                                                      ts1.Milliseconds / 10);
                        // label5.Text = elapsedTime1;

                        Stopwatch StopwatchDeflate = new System.Diagnostics.Stopwatch();
                        StopwatchDeflate.Start(); //запуск

                        long lengthDeflate = Deflate("copy.tiff", "book.png");

                        StopwatchDeflate.Stop(); //остановить
                        TimeSpan ts2 = StopwatchDeflate.Elapsed;

                        string elapsedTime2 = "Deflate:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                         ts2.Hours, ts2.Minutes, ts2.Seconds,
                                                                         ts2.Milliseconds / 10);
                        // label6.Text = elapsedTime2;

                        Stopwatch StopwatchBWT = new System.Diagnostics.Stopwatch();
                        StopwatchBWT.Start(); //запуск

                        string outputBWT = BWT(imageString);
                        int    BWTlength = outputBWT.Length;


                        StopwatchBWT.Stop(); //остановить
                        TimeSpan ts3 = StopwatchBWT.Elapsed;

                        List <int> rawList = new List <int>();
                        rawList.Add(l);
                        List <int> rleList = new List <int>();
                        rleList.Add(l2);
                        List <int> deflateList = new List <int>();
                        deflateList.Add(Convert.ToInt32(lengthDeflate));
                        //List<int> lzwList = new List<int>();
                        //lzwList.Add(LZWlength);
                        List <int> jpegList = new List <int>();
                        jpegList.Add(Convert.ToInt32(lenghtJPG));
                        List <int> BWTList = new List <int>();
                        BWTList.Add(BWTlength);
                        chart1.Series[0].Points.DataBindY(rawList);
                        chart1.Series[1].Points.DataBindY(rleList);
                        //chart1.Series[2].Points.DataBindY(lzwList);
                        chart1.Series[3].Points.DataBindY(jpegList);
                        chart1.Series[4].Points.DataBindY(deflateList);
                        chart1.Series[5].Points.DataBindY(BWTList);

                        List <int> timeRLEList = new List <int>();
                        timeRLEList.Add(ts.Seconds / 1000 + ts.Milliseconds);
                        List <int> timeDeflateList = new List <int>();
                        timeDeflateList.Add(ts2.Seconds / 1000 + ts2.Milliseconds);
                        List <int> timeJPEGList = new List <int>();
                        timeJPEGList.Add(ts1.Seconds / 1000 + ts1.Milliseconds);
                        List <int> timeBWTList = new List <int>();
                        timeBWTList.Add(ts3.Seconds / 1000 + ts1.Milliseconds);
                        //List<int> lzwList = new List<int>();
                        //lzwList.Add(LZWlength);
                        chart2.Series[0].Points.DataBindY(timeRLEList);
                        chart2.Series[2].Points.DataBindY(timeJPEGList);
                        //chart1.Series[1].Points.DataBindY(lzwList);
                        chart2.Series[3].Points.DataBindY(timeDeflateList);
                        chart2.Series[4].Points.DataBindY(timeBWTList);
                    }
                    if (textFormat.Contains(extension))
                    {
                        textLoaded  = true;
                        text        = File.ReadAllText(filename);
                        ch          = text.ToCharArray(0, text.Length);
                        l           = text.Length;
                        label1.Text = "Тип файла: текст";

                        Stopwatch StopwatchRLE = new System.Diagnostics.Stopwatch();
                        StopwatchRLE.Start(); //запуск

                        string outputRLE = RunLengthEncoding(text);
                        int    l2        = outputRLE.Length;

                        StopwatchRLE.Stop(); //остановить
                        TimeSpan ts = StopwatchRLE.Elapsed;

                        string elapsedTime = "RLE:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                    ts.Hours, ts.Minutes, ts.Seconds,
                                                                    ts.Milliseconds / 10);
                        //   label4.Text = elapsedTime;

                        Stopwatch StopwatchLZW = new System.Diagnostics.Stopwatch();
                        StopwatchLZW.Start(); //запуск

                        TextLZW();

                        StopwatchLZW.Stop(); //остановить
                        TimeSpan ts1 = StopwatchLZW.Elapsed;

                        string elapsedTime1 = "LZW:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                     ts1.Hours, ts1.Minutes, ts1.Seconds,
                                                                     ts1.Milliseconds / 10);
                        //    label5.Text = elapsedTime1;

                        Stopwatch StopwatchDeflate = new System.Diagnostics.Stopwatch();
                        StopwatchDeflate.Start(); //запуск

                        long lengthDeflate = Deflate("text1.txt", "book.txt");

                        StopwatchDeflate.Stop(); //остановить
                        TimeSpan ts2 = StopwatchDeflate.Elapsed;

                        string elapsedTime2 = "Deflate:" + String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                         ts2.Hours, ts2.Minutes, ts2.Seconds,
                                                                         ts2.Milliseconds / 10);

                        Stopwatch StopwatchBWT = new System.Diagnostics.Stopwatch();
                        StopwatchBWT.Start(); //запуск

                        string outputBWT = BWT(text);
                        int    BWTlength = outputBWT.Length;


                        StopwatchBWT.Stop(); //остановить
                        TimeSpan ts3 = StopwatchBWT.Elapsed;

                        //long lenghtJPG = VaryQualityLevel(filename, filepath + "\\");
                        List <int> rawList = new List <int>();
                        rawList.Add(l);
                        List <int> rleList = new List <int>();
                        rleList.Add(l2);
                        List <int> lzwList = new List <int>();
                        lzwList.Add(LZWlength);

                        /*List<int> jpegList = new List<int>();
                         * jpegList.Add(Convert.ToInt32(lenghtJPG));*/
                        List <int> BWTList = new List <int>();
                        BWTList.Add(BWTlength);
                        List <int> deflateList = new List <int>();
                        deflateList.Add(Convert.ToInt32(lengthDeflate));
                        chart1.Series[0].Points.DataBindY(rawList);
                        chart1.Series[1].Points.DataBindY(rleList);
                        chart1.Series[2].Points.DataBindY(lzwList);
                        //chart1.Series[3].Points.DataBindY(jpegList);
                        chart1.Series[4].Points.DataBindY(deflateList);
                        chart1.Series[5].Points.DataBindY(BWTList);

                        List <int> timeRLEList = new List <int>();
                        timeRLEList.Add(ts.Seconds / 1000 + ts.Milliseconds);
                        List <int> timeDeflateList = new List <int>();
                        timeDeflateList.Add(ts2.Seconds / 1000 + ts2.Milliseconds);
                        List <int> timeLZWList = new List <int>();
                        timeLZWList.Add(ts1.Seconds / 1000 + ts1.Milliseconds);
                        List <int> timeBWTList = new List <int>();
                        timeBWTList.Add(ts3.Seconds / 1000 + ts1.Milliseconds);
                        chart2.Series[0].Points.DataBindY(timeRLEList);
                        chart2.Series[1].Points.DataBindY(timeLZWList);
                        chart2.Series[3].Points.DataBindY(timeDeflateList);
                        chart2.Series[4].Points.DataBindY(timeBWTList);
                    }
                }
                catch
                {
                    DialogResult rezult = MessageBox.Show("Невозможно открыть выбранный файл",
                                                          "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Example #40
0
        private void OnMouseUp(InputEventArgs e)
        {
            isMouseDown = false;
            var thread = new Thread(new ThreadStart(() =>
            {
                try
                {
                    Log.Debug(string.Format("Windows.Recording::OnMouseUp::begin"));
                    var re = new RecordEvent
                    {
                        Button = e.Button
                    }; var a = new GetElement {
                        DisplayName = e.Element.Name
                    };
                    var sw = new System.Diagnostics.Stopwatch();
                    sw.Start();
                    WindowsSelector sel = null;
                    // sel = new WindowsSelector(e.Element.rawElement, null, true);
                    sel = new WindowsSelector(e.Element.RawElement, null, PluginConfig.enum_selector_properties);
                    if (sel.Count < 2)
                    {
                        return;
                    }
                    if (sel == null)
                    {
                        return;
                    }
                    a.Selector   = sel.ToString();
                    a.MaxResults = 1;
                    a.Image      = e.Element.ImageString();
                    re.OffsetX   = e.X - e.Element.Rectangle.X;
                    re.OffsetY   = e.Y - e.Element.Rectangle.Y;
                    re.UIElement = e.Element;
                    re.Element   = e.Element;
                    re.Selector  = sel;
                    re.X         = e.X;
                    re.Y         = e.Y;
                    if (sel.Count > 3)
                    {
                        var p1 = sel[1].Properties.Where(x => x.Name == "ClassName").FirstOrDefault();
                        var p2 = sel[2].Properties.Where(x => x.Name == "AutomationId").FirstOrDefault();
                        if (p1 != null && p2 != null)
                        {
                            if (p1.Value.StartsWith("Windows.UI") && p2.Value == "SplitViewFrameXAMLWindow")
                            {
                                re.SupportVirtualClick = false;
                            }
                        }
                    }
                    re.a             = new GetElementResult(a);
                    re.SupportInput  = e.Element.SupportInput;
                    re.SupportSelect = e.Element.SupportSelect;
                    Log.Debug(string.Format("Windows.Recording::OnMouseUp::end {0:mm\\:ss\\.fff}", sw.Elapsed));
                    OnUserAction?.Invoke(this, re);
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                }
            }));

            thread.IsBackground = true;
            thread.Start();
        }
Example #41
0
 public void StartHotkeyTimer()
 {
     hotkeyTimer.Start();
 }
Example #42
0
        public static void Benchmark2(int total_parents, List <long> testTimes, List <long> testTimes2, ref int rowcount, ref int rowcount2)
        {
            MemoryFileSystemBacked.FlushAll("CEF_Demo");

            // Data set-up is not timed here...
            Benchmark2Setup(total_parents);

            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();

            // With caching enabled, we make 3 passes over the data where we a) use a query to get all parents (only), b) call a method that represents some API to get all phones for said parent, c) increment age on parents where they have a mobile phone, d) apply a possible update for the phones to modify their numbers based on another api method that only accepts a PhoneID (i.e. need to reretrieve some data)
            for (int j = 1; j <= 2; ++j)
            {
                using (CEF.NewServiceScope(new ServiceScopeSettings()
                {
                    UseAsyncSave = true
                }))
                {
                    var parents = new EntitySet <Person>().DBRetrieveSummaryForParents(30);

                    foreach (var parent in parents)
                    {
                        var phones = new EntitySet <Phone>().DBRetrieveByOwner(parent.PersonID, null);
                        rowcount += 1;

                        if ((from a in phones where a.PhoneTypeID == PhoneType.Mobile select a).Any())
                        {
                            parent.Age += 1;
                            parent.DBSave(false);
                            rowcount += 1;
                        }

                        foreach (var phone in phones)
                        {
                            string area = "";

                            switch (phone.PhoneTypeID)
                            {
                            case PhoneType.Home:
                                area = "707";
                                break;

                            case PhoneType.Mobile:
                                area = "415";
                                break;

                            case PhoneType.Work:
                                area = "800";
                                break;
                            }

                            UpdatePhoneAPITest1(phone.AsDynamic().PhoneID, area, ref rowcount);

                            if (!TestValidPhoneAPITest2(phone.AsDynamic().PhoneID, parent.PersonID, ref rowcount))
                            {
                                throw new Exception("Failure!");
                            }
                        }
                    }
                }
            }

            watch.Stop();
            testTimes.Add(watch.ElapsedMilliseconds);

            // Extra verification that results match expected
            if (!Benchmark2Verify(total_parents))
            {
                throw new Exception("Unexpected final result.");
            }
        }
Example #43
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Control.Paint"/> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs"/> that contains the event data. </param>
        protected override void OnPaint(PaintEventArgs e)
        {
            //Debug.WriteLine("OnPaint =================1");
            if (Document == null || _suspendPaintCount > 0)
            {
                return;
            }

            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();

            var offset = GetScrollOffset();
            var bounds = GetScrollClientArea();

            using (var brush = new SolidBrush(BackColor))
            {
                e.Graphics.FillRectangle(brush, e.ClipRectangle);
            }

            _visiblePageStart = -1;
            _visiblePageEnd   = -1;

            for (int page = 0; page < Document.getPageSizes().Count; page++)
            {
                var pageCache = _pageCache[page];
                var rectangle = pageCache.OuterBounds;
                rectangle.Offset(offset.Width, offset.Height);

                if (_visiblePageStart == -1 && rectangle.Bottom >= 0)
                {
                    _visiblePageStart = page;
                }
                if (_visiblePageEnd == -1 && rectangle.Top > bounds.Height)
                {
                    _visiblePageEnd = page - 1;
                }

                if (e.ClipRectangle.IntersectsWith(rectangle))
                {
                    var pageBounds = pageCache.Bounds;
                    //Debug.WriteLine("OnPaint =================2 : " + page + ",[" + pageBounds.X + "," + pageBounds.Y + "," + pageBounds.Width + "," + pageBounds.Height);
                    pageBounds.Offset(offset.Width, offset.Height);

                    e.Graphics.FillRectangle(Brushes.White, pageBounds);

                    //Debug.WriteLine("OnPaint =================3 : " + page + ",[" + pageBounds.X + "," + pageBounds.Y + "," + pageBounds.Width + "," + pageBounds.Height);
                    DrawPageImage(e.Graphics, page, pageBounds);
                }
            }

            if (_visiblePageStart == -1)
            {
                _visiblePageStart = 0;
            }
            if (_visiblePageEnd == -1)
            {
                _visiblePageEnd = Document.getPageCount() - 1;
            }

            stopwatch.Stop();
            Debug.WriteLine("OnPaint time : " + stopwatch.Elapsed.TotalSeconds); //这里是输出的总运行秒数,精确到毫秒的
        }
Example #44
0
        private void button1_Click(object sender, EventArgs e)
        {
            DataTable datatable = new DataTable();

            datatable.Clear();
            DataRow datarow;

            datatable.Columns.Add("EventRecordID");
            datatable.Columns.Add("ProcessId");
            datatable.Columns.Add("ProcessName");
            datatable.Columns.Add("AccessList");
            datatable.Columns.Add("ObjectName");
            datatable.Columns.Add("TimeCreated");

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Reset();
            watch.Start();
            //int count = 0;
            // int x = 0;
            var query = new EventLogQuery("C:\\Windows\\System\\winevt\\Logs\\Security.evtx", PathType.FilePath, "*[System/EventID=4663]");

            using (var reader = new System.Diagnostics.Eventing.Reader.EventLogReader(query))
            {
                List <EventRecord> eventList = new List <EventRecord>();
                for (EventRecord eventInstance = reader.ReadEvent();
                     null != eventInstance; eventInstance = reader.ReadEvent())
                {
                    eventInstance.FormatDescription();
                    if ((eventInstance.Id == 4663))
                    {
                        XmlDocument xmlDoc   = new XmlDocument();
                        String      eventXml = eventInstance.ToXml(); //we can read Event data from xml, Like xml file reading ;)


                        xmlDoc.LoadXml(eventXml);
                        XmlElement root = xmlDoc.DocumentElement;
                        XmlElement el   = (XmlElement)root.SelectSingleNode("Event");
                        xmlDoc.DocumentElement.SetAttribute("xmlns", "");
                        xmlDoc.LoadXml(xmlDoc.InnerXml);

                        datarow = datatable.NewRow();
                        XmlNode node_EventRecordID = xmlDoc.SelectSingleNode("Event/System/EventRecordID");
                        datarow["EventRecordID"] = node_EventRecordID.InnerText;

                        XmlNodeList nodeList = (xmlDoc.SelectNodes("Event/System/TimeCreated"));
                        foreach (XmlNode elem in nodeList)
                        {
                            datarow["TimeCreated"] = elem.Attributes["SystemTime"].Value;
                        }

                        XmlNode node_ProcessId = xmlDoc.SelectSingleNode("Event/EventData/Data[@Name='ProcessId']");
                        datarow["ProcessId"] = node_ProcessId.InnerText;

                        XmlNode node_ProcessName = xmlDoc.SelectSingleNode("Event/EventData/Data[@Name='ProcessName']");
                        datarow["ProcessName"] = node_ProcessName.InnerText;

                        XmlNode node_ObjectName = xmlDoc.SelectSingleNode("Event/EventData/Data[@Name='ObjectName']");
                        datarow["ObjectName"] = node_ObjectName.InnerText;

                        XmlNode node_AccessList = xmlDoc.SelectSingleNode("Event/EventData/Data[@Name='AccessList']");
                        if (node_AccessList.InnerText.Substring(0, 6) == "%%4423")
                        {
                            datarow["AccessList"] = "ReadAttributes";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%1538")
                        {
                            datarow["AccessList"] = "READ_CONTROL";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%4416")
                        {
                            datarow["AccessList"] = "ReadData (or ListDirectory)";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%4416")
                        {
                            datarow["AccessList"] = "ReadData (or ListDirectory)";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%4417")
                        {
                            datarow["AccessList"] = "WriteData (or AddFile)";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%4418")
                        {
                            datarow["AccessList"] = "AppendData (or AddSubdirectory or CreatePipeInstance)";
                        }
                        else if (node_AccessList.InnerText.Substring(0, 6) == "%%1537")
                        {
                            datarow["AccessList"] = "DELETE";
                        }
                        else
                        {
                            datarow["AccessList"] = node_AccessList.InnerText;
                        }

                        datatable.Rows.InsertAt(datarow, 0);
                    }
                    //x = x + 1;
                }
            }
            dataGridView1.DataSource = datatable;
            timer1.Enabled           = true;
        }
        /// <summary>
        /// Sends activities to the conversation.
        /// </summary>
        /// <param name="turnContext">The context object for the turn.</param>
        /// <param name="activities">The activities to send.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        /// <remarks>If the activities are successfully sent, the task result contains
        /// an array of <see cref="ResourceResponse"/> objects containing the IDs that
        /// the receiving channel assigned to the activities.</remarks>
        /// <seealso cref="ITurnContext.OnSendActivities(SendActivitiesHandler)"/>
        public override async Task <ResourceResponse[]> SendActivitiesAsync(ITurnContext turnContext, Activity[] activities, CancellationToken cancellationToken)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (activities == null)
            {
                throw new ArgumentNullException(nameof(activities));
            }

            if (activities.Length == 0)
            {
                throw new ArgumentException("Expecting one or more activities, but the array was empty.", nameof(activities));
            }

            var responses = new ResourceResponse[activities.Length];

            /*
             * NOTE: we're using for here (vs. foreach) because we want to simultaneously index into the
             * activities array to get the activity to process as well as use that index to assign
             * the response to the responses array and this is the most cost effective way to do that.
             */
            for (var index = 0; index < activities.Length; index++)
            {
                var activity = activities[index];
                if (string.IsNullOrWhiteSpace(activity.Id))
                {
                    activity.Id = Guid.NewGuid().ToString("n");
                }

                var response = default(ResourceResponse);

                if (activity.Type == ActivityTypesEx.Delay)
                {
                    // The Activity Schema doesn't have a delay type build in, so it's simulated
                    // here in the Bot. This matches the behavior in the Node connector.
                    var delayMs = (int)activity.Value;
                    await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false);

                    // No need to create a response. One will be created below.
                }

                // set SemanticAction property of the activity properly
                EnsureActivitySemanticAction(turnContext, activity);

                if (activity.Type != ActivityTypes.Trace ||
                    (activity.Type == ActivityTypes.Trace && activity.ChannelId == "emulator"))
                {
                    var requestPath = $"/activities/{activity.Id}";
                    var request     = StreamingRequest.CreatePost(requestPath);

                    // set callerId to empty so it's not sent over the wire
                    activity.CallerId = null;

                    request.SetBody(activity);

                    _botTelemetryClient.TrackTrace($"Sending activity. ReplyToId: {activity.ReplyToId}", Severity.Information, null);

                    var stopWatch = new Diagnostics.Stopwatch();

                    try
                    {
                        stopWatch.Start();
                        response = await SendRequestAsync <ResourceResponse>(request).ConfigureAwait(false);

                        stopWatch.Stop();
                    }
                    catch (Exception ex)
                    {
                        throw new SkillWebSocketCallbackException($"Callback failed. Verb: POST, Path: {requestPath}", ex);
                    }

                    _botTelemetryClient.TrackEvent("SkillWebSocketSendActivityLatency", null, new Dictionary <string, double>
                    {
                        { "Latency", stopWatch.ElapsedMilliseconds },
                    });
                }

                // If No response is set, then defult to a "simple" response. This can't really be done
                // above, as there are cases where the ReplyTo/SendTo methods will also return null
                // (See below) so the check has to happen here.

                // Note: In addition to the Invoke / Delay / Activity cases, this code also applies
                // with Skype and Teams with regards to typing events.  When sending a typing event in
                // these _channels they do not return a RequestResponse which causes the bot to blow up.
                // https://github.com/Microsoft/botbuilder-dotnet/issues/460
                // bug report : https://github.com/Microsoft/botbuilder-dotnet/issues/465
                if (response == null)
                {
                    response = new ResourceResponse(activity.Id ?? string.Empty);
                }

                responses[index] = response;
            }

            return(responses);
        }
Example #46
0
        static void Main(string[] args)
        {
            int min, max;

            nc = 2;
            n  = 100000000;
            A  = new int[n];
            Random r = new Random();

            for (int j = 0; j < n; j++)
            {
                A[j] = r.Next(1000);
            }
            System.Diagnostics.Stopwatch sWatch = new System.Diagnostics.Stopwatch();
            sWatch.Start();
            min = A[0];
            for (int i = 1; i < n; i++)
            {
                if (A[i] < min)
                {
                    min = A[i];
                }
            }
            max = A[0];
            for (int i = 1; i < n; i++)
            {
                if (A[i] > max)
                {
                    max = A[i];
                }
            }

            Console.WriteLine(min);
            Console.WriteLine(max);

            sWatch.Stop();

            Console.WriteLine("Sequential algorithm = {0} ms.", sWatch.ElapsedMilliseconds.ToString());


            InputData[] ClArr = new InputData[nc];
            for (int i = 0; i < nc; i++)
            {
                ClArr[i] = new InputData();
            }

            int step = (Int32)(n / nc);

            int c = -1;

            for (int i = 0; i < nc; i++)
            {
                ClArr[i].start = c + 1;
                ClArr[i].stop  = c + step;
                c = c + step;
            }
            Dispatcher      d  = new Dispatcher(nc, "Test Pool");
            DispatcherQueue dq = new DispatcherQueue("Test Queue", d);
            Port <int>      p  = new Port <int>();


            for (int i = 0; i < nc; i++)
            {
                Arbiter.Activate(dq, new Task <InputData, Port <int> >(ClArr[i], p, MinMax));
            }

            Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, p, nc, delegate(int[] array)
                                                             { }));
        }
Example #47
0
        public void ProcessReceive()
        {
            LogFiler.Log(Category.Info, MethodBase.GetCurrentMethod().DeclaringType.Name + "_" + MethodBase.GetCurrentMethod().Name + ": started receiving data.");

            try
            {
                while (!IsStopped)
                {
                    var watch = new System.Diagnostics.Stopwatch();
                    watch.Start();
                    Task <byte[]> receive = TReceive();
                    ScannerDecode Info    = new ScannerDecode().Decode(receive.Result);

                    if (Info.ID == 1)
                    {
                        RefreshScanner(Info);
                        Tuple <float, float> angleinfo = ScannerFunctionality.GetAngleId1(receive.Result);
                        Degree          = angleinfo.Item1;
                        AngleDifference = angleinfo.Item2;
                    }
                    else if (Info.ID == 6)
                    {
                        if (BlockOrderCorrect(Info.Block))
                        {
                            ExpandScanner(Info, receive.Result);

                            // if the id6 telegramblocks are finished - split the distance based on the scannergap information (not visible area)
                            // if its not getting split, the averaging will create datapoints where the scanner couldnt be able to see at all - leads to consequential errors
                            if (Id6Complete())
                            {
                                Distance = ScannerFunc.GetProcessedDistance(Id6Distance.ToList());

                                if (Mainframe.IsNormalizedbyMedian[Tag])
                                {
                                    Distance = ScannerFunc.GetMedianAverageArray(Distance.ToList());
                                }

                                XYCoord = ScannerFunc.GetXYCoordinate(Distance.ToList(), this);

                                XYCoordinate = ScannerFunctionality.MergeXYArray(XYCoord.ToList());
                                OnScannerRaw(this, XYCoordinate.ToList());

                                List <List <Tuple <int, int, int> > > Normalizer = new List <List <Tuple <int, int, int> > >();
                                List <Tuple <int, int, int> >         Normalized = new List <Tuple <int, int, int> >();

                                // try to accomplish the necessary kinds of averaging the distance sent by the scanner
                                // data averaged by time
                                if (Mainframe.IsNormalizedbyTime[Tag])
                                {
                                    List <Tuple <int, int, int> > xycollection = new List <Tuple <int, int, int> >(XYCoordinate);
                                    XYCollection[RingBufferCount] = xycollection;

                                    List <List <Tuple <int, int, int> > > xycolle = new List <List <Tuple <int, int, int> > >(XYCoord);
                                    XYColl[RingBufferCount] = xycolle;

                                    RingBufferCount++;
                                    CountTimeAverage++;

                                    if (RingBufferCount == Mainframe.NormalizebyTimeCountStoredData[Tag])
                                    {
                                        RingBufferCount = 0;
                                    }

                                    if (CountTimeAverage == Mainframe.NormalizebyTimeCountDataAverage[Tag])
                                    {
                                        Normalizer       = ScannerFunc.NormalizationByTime(RingBufferCount, XYColl);
                                        CountTimeAverage = 0;
                                    }
                                }
                                else
                                {
                                    Normalizer = XYCoord;
                                }

                                if (Normalizer.Count != 0)
                                {
                                    if (Mainframe.IsNormalizedbyTriangle[Tag])
                                    {
                                        Normalizer = ScannerFunc.Normalization(Normalizer.ToList());
                                    }

                                    Normalized = ScannerFunctionality.MergeNormalizeArray(Normalizer.ToList());

                                    Normalized = ScannerFunc.ChangePositionOfXY(Normalized.ToList());

                                    NormalizedData = Normalized;
                                    OnScannerNormalized(this, new List <Tuple <int, int, int> >(NormalizedData));

                                    List <Tuple <int, int, int> > Analyser = new List <Tuple <int, int, int> >(Normalized);
                                    AnalyseData = Analyser;
                                }

                                if (watch.IsRunning)
                                {
                                    watch.Stop();
                                    LogFiler.Log(Category.Info, "normalise" + watch.ElapsedMilliseconds.ToString());
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogFiler.Log(Category.Error, MethodBase.GetCurrentMethod().DeclaringType.Name + "_" + MethodBase.GetCurrentMethod().Name + ": " + ex.Message);
            }
        }
Example #48
0
        public static void Benchmark3SavePer(int total_parents, List <long> testTimes, List <long> testTimes2, ref int rowcount, ref int rowcount2)
        {
            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();
            long cnt1 = 0;

            var people = new EntitySet <PersonWrapped>();

            Parallel.For(1, total_parents + 1, (parentcnt) =>
            {
                using (CEF.NewServiceScope())
                {
                    var parent = CEF.NewObject(new PersonWrapped()
                    {
                        Name = $"NP{parentcnt}", Age = (parentcnt % 60) + 20, Gender = (parentcnt % 2) == 0 ? "F" : "M"
                    });

                    parent.Phones.Add(new Phone()
                    {
                        Number = "888-7777", PhoneTypeID = PhoneType.Mobile
                    });
                    parent.Phones.Add(new Phone()
                    {
                        Number = "777-6666", PhoneTypeID = PhoneType.Work
                    });

                    if ((parentcnt % 12) == 0)
                    {
                        CEF.NewObject(new Phone()
                        {
                            Number = "666-5555", PhoneTypeID = PhoneType.Home
                        });
                    }
                    else
                    {
                        parent.Phones.Add(new Phone()
                        {
                            Number = "777-6666", PhoneTypeID = PhoneType.Home
                        });
                    }

                    Interlocked.Add(ref cnt1, 4);

                    for (int childcnt = 1; childcnt <= (parentcnt % 4); ++childcnt)
                    {
                        var child = CEF.NewObject(new PersonWrapped()
                        {
                            Name   = $"NC{parentcnt}{childcnt}",
                            Age    = parent.Age - 20,
                            Gender = (parentcnt % 2) == 0 ? "F" : "M"
                            ,
                            Phones = new Phone[] { new Phone()
                                                   {
                                                       Number = "999-8888", PhoneTypeID = PhoneType.Mobile
                                                   } }
                        });

                        parent.Kids.Add(child);
                        Interlocked.Add(ref cnt1, 2);
                    }

                    CEF.DBSave();
                }
            });

            rowcount += (int)cnt1;
            testTimes.Add(watch.ElapsedMilliseconds);
            watch.Restart();
            long cnt2 = 0;

            // For purposes of benchmarking, treat this as a completely separate operation
            // For everyone who's a parent of at least 30 yo, if at least 2 children of same sex, remove work phone, increment age

            int?id = null;

            using (var ss = CEF.NewServiceScope())
            {
                var people2 = new EntitySet <Person>().DBRetrieveSummaryForParents(30);

                Parallel.ForEach((from a in people2 let d = a.AsDynamic() where d.MaleChildren > 1 || d.FemaleChildren > 1 select a).ToList(), (p) =>
                {
                    using (CEF.UseServiceScope(ss))
                    {
                        if (!id.HasValue)
                        {
                            id = p.PersonID;
                        }

                        p.AsInfraWrapped().SetValue(nameof(Person.Age), p.Age + 1);

                        var ph2 = new EntitySet <Phone>().DBRetrieveByOwner(p.PersonID, PhoneType.Work).FirstOrDefault();

                        if (ph2 != null)
                        {
                            CEF.DeleteObject(ph2);
                        }

                        p.DBSave();
                        Interlocked.Add(ref cnt2, 2);
                    }
                });

                // Simulate "later heavy read access"...
                for (int c = 0; c < 50000; ++c)
                {
                    var work = new EntitySet <Phone>().DBRetrieveByOwner(c + id.GetValueOrDefault(), PhoneType.Work).FirstOrDefault();

                    if (work != null && work.Number == "123")
                    {
                        MessageBox.Show("Found (should never!)");
                    }
                }
            }

            rowcount2 += (int)cnt2 + 50000;
            watch.Stop();

            testTimes2.Add(watch.ElapsedMilliseconds);
        }
Example #49
0
        void FileSplit()
        {
            if (Enabled)
            {
                Ui.WriteLine("Cannot split while logging. Please pause.");
            }
            else
            {
                if (LivingFile.Exists(m_filename))
                {
                    Dump();

                    var info = LivingFile.GetInfo(m_filename);
                    Ui.WriteLine("Files of names " + info.BaseName + ".YYYY-MM" + info.Extension + " will be generated");

                    System.Diagnostics.Stopwatch w = new System.Diagnostics.Stopwatch();

                    long counter = 0;
                    var  logger  = new System.Timers.Timer();
                    logger.AutoReset = true;
                    logger.Interval  = Constants.Second;
                    logger.Elapsed  += (s, e) => { Ui.SetStatus("activities: " + Tools.ToHumanString(counter).PadRight(8) + " elapsed: " + w.Elapsed.ToString()); };
                    logger.Start();

                    var backups = new Dictionary <string, string>();

                    try
                    {
                        w.Start();
                        var activities = LivingFile.ReadActivities(m_filename)
                                         .Do(() => ++ counter);

                        foreach (var activityBlock in activities.PartitionBlocks(Constants.ReadingBlockSize))
                        {
                            var groups = activityBlock
                                         .GroupBy((a) =>
                            {
                                var at = a.Timestamp.ToDateTime();
                                return(new { Year = at.Year, Month = at.Month });
                            });

                            foreach (var group in groups)
                            {
                                if (group.Any())
                                {
                                    IEnumerable <Activity> groupActivities;
                                    var item = group.First();
                                    if (!Categories.IsSync(item.Type))
                                    {
                                        // When appending activities, always start with a sync activity
                                        // This will help "resorting" activities if needed
                                        groupActivities = Enumerable.Repeat(LivingLogger.GetSync(item.Timestamp), 1).Concat(group);
                                    }
                                    else
                                    {
                                        groupActivities = group;
                                    }

                                    lock (locker)
                                    {
                                        var filename = info.Child(group.Key.Year, group.Key.Month);

                                        var backup = filename + ".bak";
                                        if (!backups.ContainsKey(filename))
                                        {
                                            if (File.Exists(filename))
                                            {
                                                if (File.Exists(backup))
                                                {
                                                    File.Delete(backup);
                                                }
                                                File.Copy(filename, backup);
                                            }
                                            backups.Add(filename, backup);
                                            Ui.WriteLine("Writing to " + filename);
                                        }

                                        Timestamp previous = groupActivities.First().Timestamp;
                                        using (var writer = new StreamWriter(File.Open(filename, FileMode.Append)))
                                        {
                                            foreach (var groupActivityBlock in groupActivities.PartitionBlocks(Constants.WritingBlockSize))
                                            {
                                                WriteText(groupActivityBlock, ref previous, writer);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        Ui.SetStatus("Split task successful.");
                        foreach (var kvp in backups)
                        {
                            counter = 0;
                            w.Restart();
                            Ui.WriteLine("Processing " + kvp.Key);

                            if (File.Exists(kvp.Value))
                            {
                                File.Delete(kvp.Value);
                            }
                            if (File.Exists(kvp.Key))
                            {
                                File.Copy(kvp.Key, kvp.Value);
                            }

                            var processed =
                                ActivityTools.Process(
                                    LivingFile
                                    .ReadActivities(kvp.Value)
                                    .Do(() => ++ counter)
                                    );
                            Timestamp previous = processed.First().Timestamp;
                            using (var writer = new StreamWriter(File.Create(kvp.Key)))
                            {
                                foreach (var pBlock in processed.PartitionBlocks(Constants.WritingBlockSize))
                                {
                                    WriteText(pBlock, ref previous, writer);
                                }
                            }
                        }
                        foreach (var kvp in backups)
                        {
                            if (File.Exists(kvp.Value))
                            {
                                File.Delete(kvp.Value);
                            }
                        }
                        using (var file = File.Create(m_filename))
                        {
                            // "using" makes sura that the file is properly closed and not still in use
                        }
                        Ui.SetStatus("Processing task successful.");
                    }
                    catch (Exception e)
                    {
                        Ui.SetStatus("Error during split task. Removing temporary files...");
                        foreach (var kvp in backups)
                        {
                            if (File.Exists(kvp.Key))
                            {
                                File.Delete(kvp.Key);
                            }
                            if (File.Exists(kvp.Value))
                            {
                                File.Move(kvp.Value, kvp.Key);
                            }
                        }
                    }
                    finally
                    {
                        logger.Stop();
                    }
                }
            }
        }
        public static void Main(string[] args)
        {
            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();
            SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);

            //if(!isclosing)
            //{
            Program obj = new Program();
            string  filepath, DownloadPath = string.Empty;
            int     threadCount = 1;

            if (args.Length == 0)
            {
                filepath     = ConfigurationManager.AppSettings["URL_FILE_PATH"];;
                DownloadPath = ConfigurationManager.AppSettings["DOWNLOAD_FILE_PATH"];
                string temp = ConfigurationManager.AppSettings["THREAD_COUNT"];

                int.TryParse(temp, out threadCount);
                if (threadCount < 0 || threadCount > 10 || threadCount == 0)
                {
                    threadCount = 1;
                }

                if (obj.verifiyFilePath(filepath) && obj.veryfyFileExt(filepath) && obj.verifyDownloadPath(DownloadPath))
                {
                    fileLogger.Instance().WriteToLog("   ## Starting Run", PARENT_THREAD);
                    List <string> listOfurls = new List <string>();
                    listOfurls = obj.getUrlsFromFile(filepath);
                    if (listOfurls.Count > 0)
                    {
                        var cts     = new CancellationTokenSource();
                        var options = new ParallelOptions()
                        {
                            MaxDegreeOfParallelism = threadCount
                        };

                        options.CancellationToken = cts.Token;
                        Parallel.ForEach(listOfurls, options, url =>
                        {
                            try
                            {
                                if (url.StartsWith("http"))
                                {
                                    download httpObj = new httpdownload(url, DownloadPath, listOfurls.IndexOf(url), "THREAD_ID_" + Thread.CurrentThread.ManagedThreadId.ToString() + "_URL_NO_" + listOfurls.IndexOf(url));
                                }
                                else if (url.StartsWith("ftp"))
                                {
                                    download ftpObj = new ftpdownload(url, DownloadPath, listOfurls.IndexOf(url), "THREAD_ID_" + Thread.CurrentThread.ManagedThreadId.ToString() + "_URL_NO_" + listOfurls.IndexOf(url));
                                }
                                else if (url.StartsWith("sftp"))
                                {
                                    download sftpObj = new sftpdownload(url, DownloadPath, listOfurls.IndexOf(url), "THREAD_ID_" + Thread.CurrentThread.ManagedThreadId.ToString() + "_URL_NO_" + listOfurls.IndexOf(url));
                                }
                                else
                                {
                                    fileLogger.Instance().WriteToLog("   Skipping URL:" + url + " as this program does not suppport it", Thread.CurrentThread.ManagedThreadId.ToString() + "_URL_NO_" + listOfurls.IndexOf(url));
                                }
                                options.CancellationToken.ThrowIfCancellationRequested();
                            }
                            catch (Exception e)
                            {
                                fileLogger.Instance().WriteToLog("   ERROR" + e.Message, PARENT_THREAD);
                            }
                        });
                        cts.Cancel();
                    }
                    else
                    {
                        Console.WriteLine("  No URLs to Process.");
                        fileLogger.Instance().WriteToLog("   No URLs to Process.", PARENT_THREAD);
                    }
                }
                else
                {
                    fileLogger.Instance().WriteToLog("   Invalid config..", PARENT_THREAD);
                }
            }
            else
            {
                Console.WriteLine("Invalid Syntax.");
                Console.WriteLine("Correct Syntax: DownloadManager.exe ");
                fileLogger.Instance().WriteToLog("   Invalid Syntax...      Correct Syntax: DownloadManager.exe ", PARENT_THREAD);
            }

            fileLogger.Instance().WriteToLog("   ## Ending Run", PARENT_THREAD);
            obj.cleanup(DownloadPath);

            watch.Stop();

            Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
            Console.WriteLine("Done.");
        }
Example #51
0
 public void Start()
 {
     sw.Start();
 }
Example #52
0
        /// <summary>
        /// Testing simulteneously open files by .NET FileStream
        /// 1MLN - OK
        /// </summary>
        private void TestQuantityOfOpenFiles()
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            /*Testing quantity of Files which can be opened by .NET*/
            FileStream fs = null;
            string     pd = @"D:\temp\DBreezeTest\1\";
            Dictionary <int, FileStream> dfs = new Dictionary <int, FileStream>();

            if (System.IO.Directory.Exists(pd))
            {
                System.IO.Directory.Delete(pd, true);
            }

            System.IO.Directory.CreateDirectory(pd);

            int t1 = 0;
            int t2 = 1000000;   //Works well

            //int t2 = 5;

            for (int i = 0; i <= t2; i++)
            {
                try
                {
                    fs = new FileStream(pd + i.ToString(), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);

                    dfs.Add(i, fs);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ERR ENDED WITH {0} open files", i);
                }
            }
            //Console.WriteLine("Done");



            //Console.WriteLine("RW " + t1.ToString());
            //dfs[t1].Write(new byte[] { 1, 2, 3 }, 0, 3);
            //dfs[t1].Flush();
            //byte[] r = new byte[3];
            //dfs[t1].Position = 0;
            //int q = dfs[t1].Read(r, 0, 3);
            //Console.WriteLine(r.ToBytesString(""));

            //dfs[t1].Close();
            //dfs[t1].Dispose();

            //Console.WriteLine("RW " + t2.ToString());
            //dfs[t2].Write(new byte[] { 1, 2, 3 }, 0, 3);
            //dfs[t2].Flush();
            ////byte[] r = new byte[3];
            //dfs[t2].Position = 0;
            //q = dfs[t2].Read(r, 0, 3);
            //Console.WriteLine(r.ToBytesString(""));

            //dfs[t2].Close();
            //dfs[t2].Dispose();


            sw.Stop();
            Console.WriteLine("CREATE FILE DONE " + sw.ElapsedMilliseconds.ToString());

            Console.WriteLine("***************   testing access");

            Random rnd = new Random();
            int    fIn = 0;

            byte[] r = null;
            int    q = 0;

            for (int i = 0; i < 20; i++)
            {
                fIn = rnd.Next(t2 - 1);

                dfs[fIn].Write(new byte[] { 1, 2, 3 }, 0, 3);
                dfs[fIn].Flush();
                r = new byte[3];
                dfs[fIn].Position = 0;
                q = dfs[fIn].Read(r, 0, 3);
                Console.WriteLine("RW: {0}; V: {1}", fIn, r.ToBytesString(""));
            }
        }
Example #53
0
 public void Start()
 {
     cnt++;
     sw.Start();
 }
Example #54
0
        public unsafe int RunVideo(int gap_h, int gap_w, int width, int height, SDLHelper sdlVideo)  //这个是用来渲染整个大画面的
        {
            int          frame_count = 0;
            Produce_data p           = new Produce_data();

            fq              = new FrameQueue();
            p.gap_h         = gap_h;
            p.gap_w         = gap_w;
            p.target_height = height;
            p.target_width  = width;
            IsRun           = true;
            exit_thread     = false;
            pause_thread    = false;
            threadVideo     = Thread.CurrentThread;
            SDL.SDL_Event even    = new SDL.SDL_Event();
            Thread        refresh = new Thread(() => sfp_refresh_thread());
            Thread        produce = new Thread(() => ProduceFrame(ref p));

            refresh.Start();
            produce.Start();
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            try
            {
                for (; ;)
                {
                    //Wait
                    SDL.SDL_WaitEvent(out even);
                    if (even.type == SFM_REFRESH_EVENT)
                    {
                        FrameBuffer fb;
                        // 退出线程
                        if (exit_thread)
                        {
                            break;
                        }
                        // 暂停解析
                        if (pause_thread)
                        {
                            while (pause_thread)
                            {
                                Thread.Sleep(1);
                            }
                        }

                        while (true)
                        {
                            GetFrame(out fb);
                            if (fb == null)
                            {
                                Thread.Sleep(1);
                            }
                            else
                            {
                                fq.Pop();
                                break;
                            }
                            // Console.WriteLine("尚味获取到帧");
                        }
                        frame_count++;
                        //SDL播放YUV数据
                        //var data = fb.outbuffer;


                        int     out_buffer_size = fb.outbuffersize;
                        AVFrame pFrameYUV       = fb.av;
                        sdlVideo.SDL_Display(width * gap_w, height * gap_h, (IntPtr)(pFrameYUV.data[0]), out_buffer_size, pFrameYUV.linesize[0]);


                        //  Console.WriteLine("渲染第" + frame_count.ToString() + "帧");
                        if (frame_count == 1)
                        {
                            stopwatch.Start();
                        }
                        if (frame_count == 1000)
                        {
                            stopwatch.Stop();
                            TimeSpan timespan = stopwatch.Elapsed;
                            Console.WriteLine(timespan.TotalSeconds.ToString());
                            Thread.Sleep(100000);
                        }
                    }
                    else if (even.type == SDL.SDL_EventType.SDL_KEYDOWN)
                    {
                        //Pause
                        if (even.key.keysym.sym == SDL.SDL_Keycode.SDLK_SPACE)
                        {
                            thread_pause = 1 - thread_pause;
                        }
                    }
                    else if (even.type == SDL.SDL_EventType.SDL_QUIT)
                    {
                        thread_exit = 1;
                    }
                    else if (even.type == SFM_BREAK_EVENT)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
            }
            IsRun = false;
            return(0);
        }
Example #55
0
        private void QueryResults()
        {
            if (!string.IsNullOrEmpty(QueryText))
            {
                var queryTimer = new System.Diagnostics.Stopwatch();
                queryTimer.Start();
                _updateSource?.Cancel();
                var currentUpdateSource = new CancellationTokenSource();
                _updateSource = currentUpdateSource;
                var currentCancellationToken = _updateSource.Token;
                _updateToken = currentCancellationToken;

                ProgressBarVisibility = Visibility.Hidden;
                _isQueryRunning       = true;
                var query = QueryBuilder.Build(QueryText.Trim(), PluginManager.NonGlobalPlugins);
                if (query != null)
                {
                    // handle the exclusiveness of plugin using action keyword
                    RemoveOldQueryResults(query);

                    _lastQuery = query;
                    var plugins = PluginManager.ValidPluginsForQuery(query);

                    Task.Run(() =>
                    {
                        // so looping will stop once it was cancelled
                        var parallelOptions = new ParallelOptions {
                            CancellationToken = currentCancellationToken
                        };
                        try
                        {
                            Parallel.ForEach(plugins, parallelOptions, plugin =>
                            {
                                if (!plugin.Metadata.Disabled)
                                {
                                    var results = PluginManager.QueryForPlugin(plugin, query);
                                    if (Application.Current.Dispatcher.CheckAccess())
                                    {
                                        UpdateResultView(results, plugin.Metadata, query);
                                    }
                                    else
                                    {
                                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                                        {
                                            UpdateResultView(results, plugin.Metadata, query);
                                        }));
                                    }
                                }
                            });
                        }
                        catch (OperationCanceledException)
                        {
                            // nothing to do here
                        }


                        // this should happen once after all queries are done so progress bar should continue
                        // until the end of all querying
                        _isQueryRunning = false;
                        if (currentUpdateSource == _updateSource)
                        { // update to hidden if this is still the current query
                            ProgressBarVisibility = Visibility.Hidden;
                        }

                        queryTimer.Stop();
                        var queryEvent = new LauncherQueryEvent()
                        {
                            QueryTimeMs = queryTimer.ElapsedMilliseconds,
                            NumResults  = Results.Results.Count,
                            QueryLength = query.RawQuery.Length
                        };
                        PowerToysTelemetry.Log.WriteEvent(queryEvent);
                    }, currentCancellationToken);
                }
            }
            else
            {
                Results.SelectedItem = null;
                Results.Clear();
                Results.Visbility = Visibility.Collapsed;
            }
        }
Example #56
0
        static void Main(string[] args)
        {
            int i, min, max;

            nc = 2;         // количество ядер
            n  = 100000000; // количество элементов в массиве
            A  = new int[n];
            B  = new int[nc];

            Random r = new Random(); // генирируем массив

            for (int j = 0; j < n; j++)
            {
                A[j] = r.Next(100);
            }
            System.Diagnostics.Stopwatch sWatch = new System.Diagnostics.Stopwatch();
            sWatch.Start();  // запуск секундомера
            min = A[0];
            for (i = 1; i < n; i++)
            {
                if (A[i] < min)
                {
                    min = A[i];
                }
            }
            max = A[0];
            for (i = 1; i < n; i++)
            {
                if (A[i] > max)
                {
                    max = A[i];
                }
            }
            Console.WriteLine(min);
            Console.WriteLine(max);
            sWatch.Stop();  // отключение секундомера
            Console.WriteLine("Последовательный алгоритм = {0} мс.", sWatch.ElapsedMilliseconds.ToString());

            // создание массива объектов для хранения параметров
            InputData[] ClArr = new InputData[nc];
            for (i = 0; i < nc; i++)
            {
                ClArr[i] = new InputData();
            }
            // делим количество элементов  в массиве на nc частей
            int step = (Int32)(n / nc);
            // заполняем массив параметров
            int c = -1;

            for (i = 0; i < nc; i++)
            {
                ClArr[i].start = c + 1;
                ClArr[i].stop  = c + step;
                ClArr[i].i     = i;
                c = c + step;
            }
            Dispatcher      d  = new Dispatcher(nc, "Test Pool"); // диспетчер с nc потоками в пуле
            DispatcherQueue dq = new DispatcherQueue("Test Queue", d);
            Port <int>      p  = new Port <int>();

            for (i = 0; i < nc; i++)
            {
                Arbiter.Activate(dq, new Task <InputData, Port <int> >(ClArr[i], p, Mul));
            }
            Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, p, nc, delegate(int[] array)
                                                             {   }));
        }
Example #57
0
        /// <summary>
        /// Builds the solution.
        /// </summary>
        /// <param name="placeholderDriver">The PlaceHolder driver.</param>
        /// <param name="jobNodes">The job nodes.</param>
        /// <param name="driverNodes">The driver nodes.</param>
        /// <returns></returns>
        public virtual Solution BuildSolution(Driver placeholderDriver, IList <INode> jobNodes, IList <DriverNode> driverNodes)
        {
            var stopWatch = new System.Diagnostics.Stopwatch();

            stopWatch.Start();

            int  iterationsSinceBestResult = 0;
            int  totalIterations           = 0;
            bool stopping = false;

            Solution bestSolution = null;
            var      subSolutions = new List <Solution>();

            // Define iteration
            Action <int, ParallelLoopState> iterationAction = (i, loopState) =>
            {
                var solution = ProcessDrivers(driverNodes, placeholderDriver, jobNodes);

                _rwLock.EnterWriteLock();

                try
                {
                    totalIterations++;
                    iterationsSinceBestResult++;
                    subSolutions.Add(solution);

                    // Update progress
                    OnProgressEvent(
                        new ProgressEventArgs()
                    {
                        PrimaryTotal = MaxIterations,
                        PrimaryValue = totalIterations
                    });

                    var oldBest = bestSolution;

                    bestSolution = bestSolution == null ? solution : _routeService.GetBestSolution(bestSolution, solution);

                    if (bestSolution != oldBest)
                    {
                        _currentBestSolution      = bestSolution;
                        iterationsSinceBestResult = 0;
                    }

                    // Check exit criteria
                    if ((loopState == null || !loopState.IsStopped) && iterationsSinceBestResult > MaxIterationSinceBestResult)
                    {
                        _logger.Info("Max iterations since best result reached ({0})", MaxIterationSinceBestResult);
                        stopping = true;
                    }

                    if ((loopState == null || !loopState.IsStopped) && stopWatch.ElapsedMilliseconds > MaxExecutionTime)
                    {
                        _logger.Info("Max execution time {0} reached", MaxExecutionTime);
                        stopping = true;
                    }

                    if (_isCancelling)
                    {
                        stopping = true;
                    }

                    if (stopping)
                    {
                        if (loopState != null)
                        {
                            loopState.Stop();
                        }
                    }
                }
                finally
                {
                    _rwLock.ExitWriteLock();
                }

                // Update Pheromone Matrix
                if (!stopping && PheromoneUpdateFrequency > 0 && i > 0 && i % PheromoneUpdateFrequency == 0)
                {
                    List <Solution> subResultCopy = null;

                    _rwLock.EnterWriteLock();
                    {
                        subResultCopy = subSolutions.ToList();
                        subSolutions.Clear();
                    }
                    _rwLock.ExitWriteLock();

                    foreach (var subSolution in subResultCopy)
                    {
                        _pheromoneMatrix.UpdatePheromoneMatrix(subSolution);
                    }
                }
            };

            // Run iterations
            //if (EnableParallelism)
            if (false)      // ajh ajh
            {
                Parallel.For(0, MaxIterations, iterationAction);
            }
            else
            {
                for (var i = 0; i < MaxIterations; i++)
                {
                    iterationAction(i, null);

                    if (stopping)
                    {
                        break;
                    }
                }
            }

            stopWatch.Stop();

            return(bestSolution);
        }
Example #58
0
        private void btnCrcFile_Click(object sender, EventArgs e)
        {
            btnFile_Click(btnCrcFile, new EventArgs());
            Application.DoEvents();
            int times = 1000;

            byte[]       bs = File.ReadAllBytes(txtCrcFile.Text);
            FileStream   fs = File.OpenRead(txtCrcFile.Text);
            MemoryStream ms = new MemoryStream(bs);

            byte[] res = null;
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            Crc16 crc16 = Crc16.Create();

            watch.Start();
            for (int i = 0; i < times; i++)
            {
                res = crc16.ComputeHash(bs);
            }
            watch.Stop();
            lab16B.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
            watch.Restart();
            for (int i = 0; i < times; i++)
            {
                res = crc16.ComputeHash(fs);
            }
            watch.Stop();
            lab16S.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
            watch.Restart();
            for (int i = 0; i < times; i++)
            {
                res = crc16.ComputeHash(ms);
            }
            watch.Stop();
            lab16M.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
            Crc32 crc32 = Crc32.Create();

            watch.Start();
            for (int i = 0; i < times; i++)
            {
                res = crc32.ComputeHash(bs);
            }
            watch.Stop();
            lab32B.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
            watch.Restart();
            for (int i = 0; i < times; i++)
            {
                res = crc32.ComputeHash(fs);
            }
            watch.Stop();
            lab32S.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
            watch.Restart();
            for (int i = 0; i < times; i++)
            {
                res = crc32.ComputeHash(ms);
            }
            watch.Stop();
            lab32M.Text = res.ToHexString("") + " > " + (watch.ElapsedTicks / times).ToString();
            Application.DoEvents();
        }
Example #59
0
 public void Restart()
 {
     shortSw.Restart();
     sw.Start();
 }
Example #60
0
        public String GetMultiLUIS(string query)
        {
            //루이스 json 선언
            JObject Luis     = new JObject();
            string  LuisName = "";

            try
            {
                int MAX = MessagesController.LUIS_APP_ID.Count(s => s != null);
                Array.Resize(ref MessagesController.LUIS_APP_ID, MAX);
                Array.Resize(ref MessagesController.LUIS_NM, MAX);

                String[]  returnLuisName = new string[MAX];
                JObject[] Luis_before    = new JObject[MAX];

                List <string[]> textList    = new List <string[]>(MAX);
                String          entitiesSum = "";

                for (int i = 0; i < MAX; i++)
                {
                    //textList.Add(LUIS_APP_ID[i] +"|"+ LUIS_SUBSCRIPTION + "|" + query);
                    textList.Add(new string[] { MessagesController.LUIS_NM[i], MessagesController.LUIS_APP_ID[i], MessagesController.LUIS_SUBSCRIPTION, query });
                }

                //병렬처리 시간 체크
                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();
                Parallel.For(0, MAX, new ParallelOptions {
                    MaxDegreeOfParallelism = MAX
                }, async async =>
                {
                    var task_luis = Task <JObject> .Run(() => GetIntentFromBotLUIS(textList[async][1], textList[async][2], textList[async][3]));

                    try
                    {
                        Task.WaitAll(task_luis);

                        Luis_before[async]    = task_luis.Result;
                        returnLuisName[async] = textList[async][0];
                    }
                    catch (AggregateException e)
                    {
                    }
                });

                watch.Stop();
                //Luis = Luis_before;

                try
                {
                    for (int i = 0; i < MAX; i++)
                    {
                        //엔티티 합치기
                        if ((int)Luis_before[i]["entities"].Count() > 0)
                        {
                            for (int j = 0; j < (int)Luis_before[i]["entities"].Count(); j++)
                            {
                                entitiesSum += (string)Luis_before[i]["entities"][j]["entity"].ToString() + ",";
                            }
                        }
                    }
                }
                catch (IndexOutOfRangeException e)
                {
                    Debug.WriteLine("error = " + e.Message);
                    return("");
                }


                string luisEntities = "";
                string luisType     = "";

                if (!String.IsNullOrEmpty(LuisName))
                {
                    if (Luis != null || Luis.Count > 0)
                    {
                        float luisScore       = (float)Luis["intents"][0]["score"];
                        int   luisEntityCount = (int)Luis["entities"].Count();

                        if (MessagesController.relationList != null)
                        {
                            if (MessagesController.relationList.Count() > 0)
                            {
                                MessagesController.relationList[0].luisScore = (int)Luis["intents"][0]["score"];
                            }
                            else
                            {
                                MessagesController.cacheList.luisScore = Luis["intents"][0]["score"].ToString();
                            }
                        }



                        if (luisScore > Convert.ToDouble(MessagesController.LUIS_SCORE_LIMIT) && luisEntityCount > 0)
                        {
                            for (int i = 0; i < luisEntityCount; i++)
                            {
                                //luisEntities = luisEntities + Luis["entities"][i]["entity"] + ",";
                                luisType     = (string)Luis["entities"][i]["type"];
                                luisType     = Regex.Split(luisType, "::")[1];
                                luisEntities = luisEntities + luisType + ",";
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(luisEntities) || luisEntities.Length > 0)
                    {
                        luisEntities = luisEntities.Substring(0, luisEntities.LastIndexOf(","));
                        luisEntities = Regex.Replace(luisEntities, " ", "");


                        luisEntities = MessagesController.db.SelectArray(luisEntities);

                        if (Luis["intents"] == null)
                        {
                            MessagesController.cacheList.luisIntent = "";
                        }
                        else
                        {
                            MessagesController.cacheList.luisIntent = (string)Luis["intents"][0]["intent"];
                        }

                        MessagesController.cacheList.luisEntities = luisEntities;
                    }

                    //MessagesController.cacheList.luisEntities = LuisName;
                }
                return(LuisName);
            }
            catch (System.Exception e)
            {
                Debug.WriteLine(e.Message);
                return("");
            }
        }