private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 });
            var ControllerPort = 40001;
            var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort);
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            var header = "@";
            var command = "00C";
            var checksum = "E3";
            var end = "\r\n";
            var data = header + command + checksum + end;
            byte[] bytes = new byte[1024];

            //Start Connect
            _connectDone.Reset();
            watch.Start();
            _client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client);
            //wait 2s
            _connectDone.WaitOne(2000, false);

            var text = (_client.Connected) ? "ok" : "ng";
            richTextBox1.AppendText(text + "\r\n");
            watch.Stop();
            richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n");
        }
        /// <summary>
        /// Tests for Vektor class
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnVector_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            txtVector.Text = "Starting test suite for the Vektor class.\r\n\r\n";

            // Sample data
            List<Eksam.Vektor> vectors = new List<Vektor>{
                new Vektor(),
                new Vektor(1,1),
                new Vektor(0,1),
                new Vektor(2.2, 1.2),
                new Vektor(10,-4),
                null
            };

            // Go over all defined operations and input combinations
            foreach (Vektor vector in vectors)
            {
                foreach (Vektor secondVector in vectors)
                {
                    txtVector.Text += vector + " + " + secondVector + " = " + (vector + secondVector) + "\r\n";
                    txtVector.Text += vector + " - " + secondVector + " = " + (vector - secondVector) + "\r\n";
                    txtVector.Text += vector + " == " + secondVector + " ... " + (vector == secondVector) + "\r\n";
                    txtVector.Text += vector + vector + " (length " + (vector == null ? 0 : vector.Length()) + ") > " + secondVector + " (length " + (secondVector == null ? 0 : secondVector.Length()) + ")" + " ... " + (vector > secondVector) + "\r\n";
                    txtVector.Text += vector + vector + " (length " + (vector == null ? 0 : vector.Length()) + ") < " + secondVector + " (length " + (secondVector == null ? 0 : secondVector.Length()) + ")" + " ... " + (vector < secondVector) + "\r\n";
                }
            }

            watch.Stop();
            double elapsed = watch.ElapsedMilliseconds;
            txtVector.Text += "\r\nTest suite finished, time elapsed: " + elapsed + "ms.";
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            var reader = new TextFileLineByLineReader(@"Z:\ClueWeb09_WG_50m.graph-txt", 1);
            //reader.PrependLineNumber = true;
            reader.LinesPerRecord = 10000;

            var keyword = "11";

            var mr = new TextMapReduce<string, long>(reader, @"z:\pashm");
            mr.MapFunc = (s, context) =>
            {
                context.Emit("found", Regex.Matches(s, keyword).Count);
            };

            mr.CombineFunc = (list) => { return list.Sum(); };
            mr.ReduceFunc = (reduce_obj, reduce_context) =>
            {
                var all = reduce_obj.ReadAll();
                reduce_context.Emit(reduce_obj.Key + ":" + all.First().ToString());
            };

            mr.Run(1);

            watch.Stop();
            Console.WriteLine("Took: " + watch.Elapsed);
        }
        static void Main(string[] args)
        {

            TwitchPlays.ChannelName = "fluzzarn";
            TwitchPlays.NickName = "Fluzzarn";
            TwitchPlays.Password = Password.OAuthPWord;
            TwitchPlays.ServerAddress = "irc.twitch.tv";

            TwitchPlays.Connect();
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();

            kappa k = printKapps;
            TwitchPlays.AddCommandToFunction("Kappa",printKapps);
            TwitchPlays.AddCommandToFunction("exit", quit);
            TwitchPlays.AddCommandToFunction("quit", quit);
            while(true)
            {
                if(timer.ElapsedMilliseconds > 5000)
                {

                    string command = TwitchPlays.GetMostCommonCommand();
                    int amount = TwitchPlays.GetFrequencyOfCommand(command);
                    Console.WriteLine("Most common input was: " + command + " with " + amount + " instances");
                    TwitchPlays.ExecuteCommand(command);
                    TwitchPlays.ClearCommands();
                    timer.Reset();
                    timer.Start();
                }


            }
        }
		protected override async void OnAppearing ()
		{
			base.OnAppearing ();

 
			// testare se utente autenticato
			if (!App.SeUtenteAutenticato) {
				// Navigation.PushModalAsync (new LoginPage());
			}

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


			await _viewModel.LoadCategorieAsync ();
		
			foreach (var categoria in _viewModel.ListaCategorie)
			{ 
				PickerCategoria.Items.Add(categoria.cat_DESC);
			}

			this.PickerCategoria.SelectedIndex = -1;
 
			_viewModel.FiltroDescArticolo = "";
			_viewModel.FiltroCodiceCategoria = "";
			await _viewModel.LoadDataAsync ();

			sw.Stop ();

			this.info.Text = "Tempo : " + sw.Elapsed.TotalMilliseconds + " nro art: " + _viewModel.Lista.Count;
		}
        public void AsyncHTTPSICmd()
        {
            FileStream stream;
            stream = File.Create(outputFileHTTPSAsync);
            results = new StreamWriter(stream);
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();

            ICmd validICmd = new ICmd(TestGlobals.testServer, TestGlobals.validSerial);
            Test validTest = new Test(validICmd);
            validTest.setTestName("ValidSerial");
            validTest.setExpectedResult ("200");
            validTest.setType ("performance");
            List<Test> tests = new List<Test>();
            tests.Add(validTest);

            // Construct started tasks
            Task<double>[] tasks = new Task<double>[TestGlobals.maxReps];
            for (int i = 0; i < TestGlobals.maxReps; i++)
            {
                System.Threading.Thread.Sleep(TestGlobals.delay);
                tasks[i] = new HTTPSCalls().runTest(validTest, HTTPOperation.GET);
                Console.WriteLine("Test starting:" + i.ToString());
            }
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("All tests initialized, waiting on them to run as async");
            Console.WriteLine("------------------------------------------------------");
            Task.WaitAll(tasks);

            foreach (Task<double> nextResult in tasks)
            {
                results.WriteLine("Test Time," + nextResult.Result);
            }

            results.Close();
        }
		//[TestMethod]
		public void Performance()
		{
			var sw = new System.Diagnostics.Stopwatch();
			sw.Start();
			for (var i = 0; i < 200; i++) this.DefinedIPlugin();
			Assert.IsTrue(sw.ElapsedMilliseconds < 2000);
		}
Beispiel #8
0
		static Block ()
		{
#if !MF_FRAMEWORK_VERSION_V4_3
			sw = new System.Diagnostics.Stopwatch ();
			sw.Start ();
#endif
		}
 public void InterOpSpeed()
 {
     const int TESTSIZE = 100;
     count = 0;
     // get some random prices
     Tick[] data = RandomTicks.GenerateSymbol(sym, TESTSIZE);
     // track the time
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     int bad = 0;
     sw.Start();
     for (int i = 0; i < data.Length; i++)
     {
         int err = SendOrder(sym, true, 300, (double)data[i].trade, 0, 1, "TESTACCOUNT", "TESTDEST");
         if (err!=0) bad++;
     }
     sw.Stop();
     long elapms = sw.ElapsedMilliseconds;
     double elap = (double)elapms/1000;
     double rate = TESTSIZE / elap;
     Console.WriteLine("InterOpSpeed elap: " + elap.ToString("N1") + " rate: " + rate.ToString("N0") + " orders/sec");
     // make sure orders received
     Assert.AreEqual(data.Length, count);
     // make sure no bad orders
     Assert.AreEqual(0,bad);
     // make sure fast
     Assert.LessOrEqual(elap, .5);
 }
Beispiel #10
0
 public BodyForm()
 {
     InitializeComponent();
     i = 0;
     UnNum = 0;
     Time = new System.Diagnostics.Stopwatch();
 }
Beispiel #11
0
		private static void InvokeBatch(IRemoteServ1 service)
		{
			try
			{
				service.DoSomethingWrong();
				Assert.Fail("Expecting exception here");
			}
			catch (Exception ex)
			{
				Assert.AreEqual("Remote server or invoker threw Exception with message simple message", ex.Message);
			}

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

			// 1000
			for (var i = 0; i < 100; i++)
			{
				if (i % 1000 == 0)
				{
					var collCount0 = GC.CollectionCount(0);
					var collCount1 = GC.CollectionCount(1);
					var collCount2 = GC.CollectionCount(2);

					Console.WriteLine("Collections on Gen 0 {0}, Gen 1 {1}, Gen 2 {2} ", collCount0, collCount1, collCount2);
				}

				// Console.WriteLine("new batch ");

				service.NoParamsOrReturn();
				service.JustParams("1");
				Assert.IsTrue(service.JustReturn().Equals("abc"));
				service.ParamsWithStruct(new MyCustomStruct() { Name = "1", Age = 30 });
				service.ParamsWithCustomType1(new Impl1() { });
				service.ParamsWithCustomType2(new Contract1Impl() { Name = "2", Age = 31 });
				service.ParamsAndReturn(Guid.NewGuid(), "", 1, DateTime.Now, 102.2m, FileAccess.ReadWrite, 1, 2, 3.0f, 4.0);
				service.WithInheritanceParam(new Derived1() { Something = 10, DerivedProp1 = 20 });

				var b = service.WithInheritanceRet();
				Assert.IsNotNull(b);
				Assert.IsInstanceOf(typeof(Derived2), b);
				Assert.AreEqual(10, (b as Derived2).Something);
				Assert.AreEqual("test", (b as Derived2).DerivedProp2);

				var enu = service.UsingEnumerators();
				Assert.IsNotNull(enu);
				Assert.AreEqual(2, enu.Count());

				var array = service.UsingArray();
				Assert.IsNotNull(array);
				Assert.AreEqual(2, array.Length);

				service.ReturningNull1();
				service.ReturningNull2();
			}

			watch.Stop();

			Console.WriteLine("took " + watch.ElapsedMilliseconds);
		}
Beispiel #12
0
        private void LoadDatafromAHRS()
        {
            updateTimer.Enabled = false;
            try
            {
                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();
                UAVParameter speedparam = (UAVParameter)GPS["lbRMCSpeed"];
                UAVParameter altparam = (UAVParameter)GPS["lbGGAAltitude"];
                UAVParameter phiparam = (UAVParameter)AHRS["phi"];
                UAVParameter thetaparam = (UAVParameter)AHRS["theta"];
                UAVParameter psiparam = (UAVParameter)AHRS["psi"];

                    if (speedparam != null) if (!speedparam.Value.Equals("N/A")) airSpeedIndicator.SetAirSpeedIndicatorParameters(Convert.ToInt32(speedparam.Value));
                    if ((thetaparam != null) && (phiparam != null)) attitudeIndicator.SetAttitudeIndicatorParameters(Convert.ToDouble(thetaparam.Value), Convert.ToDouble(phiparam.Value));
                // Änderungsrate berechnen
                // Turn Quality berechnen
                // this.vspeed = vspeed + Convert.ToInt32(mycore.currentUAV.uavData["lbGGAAltitude"].Value)*0.9;
                    if ((psiparam != null) && (psiparam != null)) this.Compass.SetHeadingIndicatorParameters(Convert.ToInt32(Convert.ToDouble(psiparam.Value)));
                //  if (mycore.currentUAV.uavData.ContainsKey("yaw")) Compass.SetHeadingIndicatorParameters(Convert.ToInt32(mycore.currentUAV.uavData["yaw"].Value));
               //     if (mycore.currentUAV.uavData.ContainsKey("vspeed")) verticalSpeedIndicator.SetVerticalSpeedIndicatorParameters(Convert.ToInt32(mycore.currentUAV.uavData["vspeed"].Value));
                if (altparam != null) altimeter.SetAlimeterParameters(Convert.ToInt32(Convert.ToDouble(altparam.Value)));
            //    if (mycore.currentUAV.uavData.ContainsKey("turnrate") && mycore.currentUAV.uavData.ContainsKey("turnquality")) turnCoordinator.SetTurnCoordinatorParameters(Convert.ToSingle(mycore.currentUAV.uavData["turnrate"].Value), Convert.ToSingle(mycore.currentUAV.uavData["turnquality"].Value));
                this.Invalidate();
                Console.WriteLine("time update:"+watch.ElapsedMilliseconds);
                watch.Stop();
            }
            catch (Exception ex) {

            }
            updateTimer.Enabled = true;
        }
        public MainWindow()
        {
            InitializeComponent();
             double ticks = 0L;
             System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

             int frameCount = 0;

             //There is a textbox "txtTicks" which accept a millisecond value
             //And a button "btn", by clicking the button the dispatchertimer &
             //stopwatcher are started.
             _timer.Tick += (sender, e) =>
             {
            frameCount++;
            //System.Diagnostics.Debug.WriteLine(watch.ElapsedMilliseconds);
            if (watch.ElapsedMilliseconds > 1000)
            {
               _timer.Stop();
               watch.Reset();
               MessageBox.Show(string.Format("Already 1 second! FrameCount: {0}", frameCount));
               frameCount = 0;
            }
             };

             this.btn.Click += (sender, e) =>
             {
            double.TryParse(this.txtTicks.Text, out ticks);
            if (ticks != 0.0)
            {
               _timer.Interval = TimeSpan.FromMilliseconds(ticks);
            }
            _timer.Start();
            watch.Start();
             };
        }
Beispiel #14
0
        public void TestFromTxtFile(string file)
        {
            var wordUtil = new WordDict();
            var expectWordCount = 0;
            using (var sr = new StreamReader(file, Encoding.UTF8))
            {
                string line = null;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line == string.Empty) continue;
                    wordUtil.Add(line);
                    expectWordCount++;
                }
            }

            var watcher = new System.Diagnostics.Stopwatch();
            watcher.Start();
            var ms = new MemoryStream();
            wordUtil.SaveTo(ms);
            watcher.Stop();

            Console.WriteLine("build dawg elapsed time:" + watcher.Elapsed.TotalMilliseconds + "'ms");

            watcher.Reset();
            watcher.Start();
            ms.Position = 0;
            wordUtil = WordDict.LoadFrom(ms);
            watcher.Stop();
            Console.WriteLine("load dawg file elapsed time:" + watcher.Elapsed.TotalMilliseconds + "'ms");
            Assert.AreEqual(expectWordCount, wordUtil.Count);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ExecutionContext"/> class.
 /// </summary>
 public ExecutionContext()
 {
     #if STOPWATCH
     _stopwatch = new System.Diagnostics.Stopwatch();
     _stopwatch.Start();
     #endif
 }
Beispiel #16
0
        static void acceptIncomingConnection(IAsyncResult ar)
        {
            Socket mainsock = (Socket)ar.AsyncState;
            Socket incomingsock = mainsock.EndAccept(ar);
            Donify.Set();

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

            logger.log("Got connection from: " + incomingsock.RemoteEndPoint, Logging.Priority.Notice);
            if (socketfunctions.waitfordata(incomingsock, 10000, true))
            {
                string[] incomingstring = socketfunctions.receivestring(incomingsock, true).Replace("\r\n", "\n").Split('\n');
                try
                {
                    string response = bstuff.OnyEvents.NewMessage(incomingstring, (IPEndPoint)incomingsock.RemoteEndPoint);
                    logger.log("got from plugins: " + response, Logging.Priority.Notice);
                    if (response == null || response == "")
                        socketfunctions.sendstring(incomingsock, "Blargh.");
                    else
                        socketfunctions.sendstring(incomingsock, response);
                }
                catch (Exception ex)
                { logger.logerror(ex); }

                incomingsock.Shutdown(SocketShutdown.Both);
                incomingsock.Close();

                swatch.Stop();

                logger.log("Session time: " + swatch.ElapsedMilliseconds, Logging.Priority.Info);

                bstuff.OnyVariables.amountloops++;
            }
        }
Beispiel #17
0
        static private void WorkerEvents()
        {
            Tuple<EventDelegate, Effect, Effect> cEvent;
			System.Diagnostics.Stopwatch cWatch = new System.Diagnostics.Stopwatch();
			while (true)
			{
				try
				{
					cEvent = _aqEvents.Dequeue();
					cWatch.Reset();
					cWatch.Restart();
					cEvent.Item1(cEvent.Item2, cEvent.Item3);
					(new Logger()).WriteDebug3("event sended [hc = " + cEvent.Item3.GetHashCode() + "][" + cEvent.Item1.Method.Name + "]");
					cWatch.Stop();
					if (40 < cWatch.ElapsedMilliseconds)
						(new Logger()).WriteDebug3("duration: " + cWatch.ElapsedMilliseconds + " queue: " + _aqEvents.nCount);
					if (0 < _aqEvents.nCount)
						(new Logger()).WriteDebug3(" queue: " + _aqEvents.nCount);
                }
                catch (System.Threading.ThreadAbortException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    (new Logger()).WriteError(ex);
                }
            }
        }
Beispiel #18
0
		protected void SetUp()
		{
	        base_cycle_metric_header header = new base_cycle_metric_header();
		    if(metrics.Count == 0)
		    {
                System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
                timer.Start();
                float[] focus1 = new float[]{2.24664021f, 2.1896739f, 0, 0};
                ushort[] p90_1  = new ushort[]{302, 273, 0, 0};
                for(uint lane = 1;lane <=8;lane++)
                {
                    for(uint tile = 1;tile <=TileCount;tile++)
                    {
                        for(uint cycle = 1;cycle <=318;cycle++)
                        {
                            metrics.Add(new extraction_metric(lane, tile, cycle, new csharp_date_time(9859129975844165472ul), (p90_1), (focus1), 4));
                        }
                    }
                }
                extraction_metric_set = new base_extraction_metrics(metrics, Version, header);
                timer.Stop();
                System.Console.WriteLine("Setup: " + timer.Elapsed.Hours +" : " + timer.Elapsed.Minutes +" : " + timer.Elapsed.Seconds);
                System.Console.WriteLine("Size: " + metrics.Count + " - " + extraction_metric_set.size());
		    }
		}
		public Tester (Action onOpen)
		{
			OnOpen = onOpen;
			client = new WebSocket.Portable.WebSocketClient ();
			watch = new System.Diagnostics.Stopwatch ();
			client.FrameReceived += OnFrame;
		}
		public SpeedTest(){
			hc = new HttpClient(hch);
			sw = new System.Diagnostics.Stopwatch();
			hc.BaseAddress = speedTestBaseUri;
			hc.DefaultRequestHeaders.Add("Accept-Encoding", "identity");
			hc.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.2; rv:27.0) Gecko/20100101 Firefox/27.0");
			hc.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			//wc.Headers["Accept-Language"] = "q=0.8,en-us;q=0.5,en;q=0.3";
			//wc.Headers["Cache-Control"] = "max-age=0";
			hc.DefaultRequestHeaders.Add("DNT", "1");
			hch.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.None;
			hch.UseCookies = false;
			#if DEBUG
			{
				var processes = System.Diagnostics.Process.GetProcessesByName("Fiddler");
				if (processes.Length != 0) {
					try {
						var port = (int) Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Fiddler2", "ListenPort", 4444);
						hch.Proxy = new WebProxy("127.0.0.1", port);
					}
					catch (Exception) {}
				}
			}
			#endif
			//wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(progressProcesser);
			//wc.UploadProgressChanged += new UploadProgressChangedEventHandler(progressProcesser);
			
		}
        public void Given_A_Checklist_Is_Being_Saved_Then_Returns_Status_OK()
        {
            // Given
            var client = new RestClient(Url.AbsoluteUri);
            client.Authenticator = new NtlmAuthenticator( "continuous.int","is74rb80pk52" );

            const int numberOfRequestsToSend = 15;
            var stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
            var parallelLoopResult = Parallel.For(0, numberOfRequestsToSend, x =>
                                                                                 {
                                                                                     //GIVEN
                                                                                     var model = CreateChecklistViewModel();
                                                                                     var resourceUrl = string.Format("{0}{1}/{2}", ApiBaseUrl, "checklists", model.Id.ToString());
                                                                                     var request = new RestRequest(resourceUrl);
                                                                                     request.AddHeader("Content-Type", "application/json");
                                                                                     request.RequestFormat = DataFormat.Json;
                                                                                     request.Method = Method.POST;
                                                                                     request.AddBody(model);

                                                                                     // When
                                                                                     var response = client.Execute(request);

                                                                                     //THEN
                                                                                     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                                                                                 });

            stopWatch.Stop();

            var processingSeconds = TimeSpan.FromMilliseconds(stopWatch.ElapsedMilliseconds).TotalSeconds;
            Assert.That(parallelLoopResult.IsCompleted);
            Console.WriteLine(string.Format("average: {0}", processingSeconds / numberOfRequestsToSend));
        }
Beispiel #22
0
        public Renard(string portName)
        {
            this.serialPort = new SerialPort(portName, 57600);
            this.renardData = new byte[24];

            this.cancelSource = new System.Threading.CancellationTokenSource();
            this.firstChange = new System.Diagnostics.Stopwatch();

            this.senderTask = new Task(x =>
                {
                    while (!this.cancelSource.IsCancellationRequested)
                    {
                        bool sentChanges = false;

                        lock (lockObject)
                        {
                            if (this.dataChanges > 0)
                            {
                                this.firstChange.Stop();
                                //log.Info("Sending {0} changes to Renard. Oldest {1:N2}ms",
                                //    this.dataChanges, this.firstChange.Elapsed.TotalMilliseconds);
                                this.dataChanges = 0;
                                sentChanges = true;

                                SendSerialData(this.renardData);
                            }
                        }

                        if(!sentChanges)
                            System.Threading.Thread.Sleep(10);
                    }
                }, this.cancelSource.Token, TaskCreationOptions.LongRunning);

            Executor.Current.Register(this);
        }
Beispiel #23
0
        static void Run(string filename, bool verbose)
        {
            if (!File.Exists(filename))
            {
                Console.WriteLine("Cannot find file " + filename);
                return;
            }

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

            var opts = new Options();
            opts.ExecutionMode = ExecutionMode.Serial;
            ProtoCore.Core core = new Core(opts);
            core.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(core));
            core.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(core));
            core.Options.DumpByteCode = verbose;
            core.Options.Verbose = verbose;
            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());

            ProtoScriptRunner runner = new ProtoScriptRunner();

            runner.LoadAndExecute(filename, core);
            long ms = sw.ElapsedMilliseconds;
            sw.Stop();
            Console.WriteLine(ms);
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            var stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();

            Action<CancellationToken> longRunning = async (token) =>
            {
                for (int i = 0; i < 100; i++)
                {
                    Console.WriteLine("{0} {1}", i, stopwatch.Elapsed.TotalMilliseconds); 
                    await Task.Delay(new Random().Next(3, 100));
                    if (token.IsCancellationRequested)
                        break;
                }
            };

            // start with cancel option
            var source = new CancellationTokenSource();
            longRunning.Invoke(source.Token);

            // wait for a second 
            Thread.Sleep(1000);

            // top processing
            source.Cancel();

            Console.Read();
        }
Beispiel #25
0
        public void PerfAtLeastOnceSend()
        {
            string testName = "PerfAtLeastOnceSend";
            Connection connection = new Connection(address);
            Session session = new Session(connection);
            this.sender = new SenderLink(session, "sender-" + testName, "q1");

            this.onOutcome = OnSendComplete;
            this.done = new ManualResetEvent(false);
            this.totalCount = 1000000;
            this.completedCount = 0;
            this.initialCount = 300;
            this.batchCount = 100;
            Trace.TraceLevel = TraceLevel.Information;

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

            this.SendMessages(initialCount);

            this.done.WaitOne();
            watch.Stop();
            Trace.WriteLine(TraceLevel.Information, "total: {0}, time: {1}ms", this.totalCount, watch.ElapsedMilliseconds);

            connection.Close();
        }
 protected void Page_Load( object sender, EventArgs e )
 {
     var url = ConfigurationManager.AppSettings.Get( "CLOUDANT_URL" );
     var connection = new Connection( new Uri( url ) );
     if ( !connection.ListDatabases().Contains( "gmkreports" ) )
     {
         connection.CreateDatabase( "gmkreports" );
     }
     var repository = new Repository<Report>( connection.CreateSession( "gmkreports" ) );
     var report = new Report { ID = Guid.NewGuid(), Type = 1, AccessionNumber = "123", Contents = "abcd" };
     System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
     watch.Reset();
     watch.Start();
     var id = repository.Save( report ).Id;
     var retrievedReport = repository.Get( id );
     watch.Stop();
     if ( retrievedReport.ID == report.ID && retrievedReport.Type == report.Type && retrievedReport.AccessionNumber == report.AccessionNumber && retrievedReport.Contents == report.Contents )
     {
         _label.Text = watch.ElapsedMilliseconds.ToString();
     }
     else
     {
         _label.Text = "Error";
     }
 }
Beispiel #27
0
        public int MINIMAX_DECISION(Game game)
        {
            _stopwatch = new System.Diagnostics.Stopwatch();
            _stopwatch.Start();

            int maxValue = int.MinValue;
            List<int> colOptions = new List<int>();

            List<int> actions = ACTIONS(game);
            int iterationCounter = 0;
            foreach (int column in actions)
            {
                iterationCounter++;
                int v = MIN_VALUE(RESULT(game, column, _max), 1);

                if (v > maxValue)
                {
                    maxValue = v;
                    colOptions.Clear();
                    colOptions.Add(column);
                }
                else if (v == maxValue)
                {
                    colOptions.Add(column);
                }

                if (_stopwatch.Elapsed.Seconds > (game.TimeLimitSeconds - 1)) break;
            }

            int c = colOptions[_rnd.Next(colOptions.Count)];
            Console.WriteLine("Column selection: {0} / Elapsed: {1} / Total Actions: {2} / Actions Evaluated: {3}", c, _stopwatch.Elapsed, actions.Count, iterationCounter);
            return c;
        }
        public void TestExecuteIntersectionQuery()
        {
            NUnit.Framework.Assert.IsTrue(System.IO.File.Exists(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp")),
                                          "Specified shapefile is not present!");

            var shp = new SharpMap.Data.Providers.ShapeFile(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp"), false, false);
            shp.Open();

            var fds = new SharpMap.Data.FeatureDataSet();
            var bbox = shp.GetExtents();
            //narrow it down
            bbox.ExpandBy(-0.425*bbox.Width, -0.425*bbox.Height);

            //Just to avoid that initial query does not impose performance penalty
            shp.DoTrueIntersectionQuery = false;
            shp.ExecuteIntersectionQuery(bbox, fds);
            fds.Tables.RemoveAt(0);

            //Perform query once more
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            shp.ExecuteIntersectionQuery(bbox, fds);
            sw.Stop();
            System.Console.WriteLine("Queried using just envelopes:\n" + fds.Tables[0].Rows.Count + " in " +
                                     sw.ElapsedMilliseconds + "ms.");
            fds.Tables.RemoveAt(0);

            shp.DoTrueIntersectionQuery = true;
            sw.Reset();
            sw.Start();
            shp.ExecuteIntersectionQuery(bbox, fds);
            sw.Stop();
            System.Console.WriteLine("Queried using prepared geometries:\n" + fds.Tables[0].Rows.Count + " in " +
                                     sw.ElapsedMilliseconds + "ms.");
        }
        public void CountWords()
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            if (!string.IsNullOrWhiteSpace(this.Text))
            {
                var allWords = this.Text.Split(new string[] { SPACE, NEW_LINE, TAB, CARRIEGE_RETURN, DOT, SEMI_COLON, COLON, TWO_POINT }, StringSplitOptions.RemoveEmptyEntries);
                if (!this.DetailedStats)
                {
                    this.NumberOfWords = allWords.LongLength;
                }
                else
                {
                    for (long cursor = 0; cursor < allWords.LongLength; ++cursor)
                    {
                        if (!string.IsNullOrWhiteSpace(allWords[cursor]))
                        {
                            ++this.NumberOfWords;
                            if (!this.Stats.ContainsKey(allWords[cursor]))
                            {
                                this.Stats[allWords[cursor]] = 1;

                            }
                            else
                            {
                                ++this.Stats[allWords[cursor]];
                            }
                        }
                    }
                }
            }
            watch.Stop();
            this.CountTime = watch.ElapsedMilliseconds;
        }
Beispiel #30
0
        static void DevRun()
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();


            var opts = new Options();
            opts.ExecutionMode = ExecutionMode.Serial;
            ProtoCore.Core core = new Core(opts);
            core.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(core));
            core.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(core));
#if DEBUG
            core.Options.DumpByteCode = true;
            core.Options.Verbose = true;
#else
            core.Options.DumpByteCode = false;
            core.Options.Verbose = false;
#endif
            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());
            ProtoScriptRunner runner = new ProtoScriptRunner();

            // Assuming current directory in test/debug mode is "...\Dynamo\bin\AnyCPU\Debug"
            runner.LoadAndExecute(@"..\..\..\test\core\dsevaluation\DSFiles\test.ds", core);

            long ms = sw.ElapsedMilliseconds;
            sw.Stop();
            Console.WriteLine(ms);
            Console.ReadLine();
        }
Beispiel #31
0
        public void groupTSP()
        {
            // start our timer
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();

            // constants used in heuristics
            const int    ITERATIONS = 50;
            const double Q0         = 0.9;
            const double BETA       = 50.0;
            const double ALPHA      = 0.1;

            // get cost from nearest neighbor, used in our heuristic
            greedy();

            double nnCost = costOfBssf();

            // our fastest ant through all the iterations
            Ant    bestAnt  = null;
            double bestCost = Double.PositiveInfinity;

            // initialize pheramone level matrix
            double[,] pheromoneLevels = new double[Cities.Length, Cities.Length];
            for (int i = 0; i < Cities.Length; i++)
            {
                for (int j = 0; j < Cities.Length; j++)
                {
                    pheromoneLevels[i, j] = 1.0 / Cities.Length;
                }
            }

            // start iterations
            for (int h = 0; h < ITERATIONS; h++)
            {
                // our fastest ant in the iteration
                Ant    bestAntIter  = null;
                double bestCostIter = Double.PositiveInfinity;

                // initialize ants
                List <Ant> ants = new List <Ant>();
                for (int i = 0; i < Cities.Length; i++)
                {
                    ants.Add(new Ant(Cities.Length, i));
                }

                // iterate through each time step
                for (int i = 0; i < Cities.Length - 1; i++)
                {
                    // determine each ants next move
                    List <Ant> remainingAnts = new List <Ant>(ants);
                    foreach (Ant ant in remainingAnts)
                    {
                        int    nextCity     = -1;
                        double nextDistance = Double.PositiveInfinity;

                        Random random = new Random();
                        double q      = random.NextDouble();
                        if (q < Q0)
                        {
                            // select next city based on distance / pheramone only
                            double bestScore = Double.NegativeInfinity;
                            foreach (int city in ant.unvisited)
                            {
                                double distance = Cities[ant.curCity].costToGetTo(Cities[city]);
                                double score    = pheromoneLevels[ant.curCity, city] * Math.Pow(1 / distance, BETA);
                                if (score > bestScore)
                                {
                                    nextCity     = city;
                                    bestScore    = score;
                                    nextDistance = distance;
                                }
                            }
                        }
                        else
                        {
                            // select city randomly with different weights given to each city based on distance / pheramone
                            double runningTotal = 0.0;
                            double randomValue  = random.NextDouble();

                            // get sum of scores
                            double summedScores = 0.0;
                            foreach (int city in ant.unvisited)
                            {
                                double distance = Cities[ant.curCity].costToGetTo(Cities[city]);
                                summedScores += pheromoneLevels[ant.curCity, city] * Math.Pow(1 / distance, BETA);
                            }

                            // determine probability for each city
                            foreach (int city in ant.unvisited)
                            {
                                double distance = Cities[ant.curCity].costToGetTo(Cities[city]);
                                runningTotal += (pheromoneLevels[ant.curCity, city] * Math.Pow(1 / distance, BETA)) / summedScores;
                                if (runningTotal > randomValue)
                                {
                                    nextCity     = city;
                                    nextDistance = distance;
                                    break;
                                }
                            }
                        }

                        if (nextCity != -1)
                        {
                            // apply local trail updating
                            pheromoneLevels[ant.curCity, nextCity] += (1 - ALPHA) * pheromoneLevels[ant.curCity, nextCity] + ALPHA * (1 / (Cities.Length * nnCost));

                            // add the picked city to the tour
                            ant.tour[ant.curCity] = nextCity;
                            ant.unvisited.Remove(nextCity);
                            ant.curCost += nextDistance;
                            ant.prevCity = ant.curCity;
                            ant.curCity  = nextCity;
                        }
                        else
                        {
                            //deal with stuck ant
                            ants.Remove(ant);
                        }
                    }
                }

                // finalize tours and find best ant
                foreach (Ant ant in ants)
                {
                    // finalize tour
                    ant.tour[ant.curCity] = ant.startCity;
                    ant.curCost          += Cities[ant.curCity].costToGetTo(Cities[ant.startCity]);

                    // check against current best cost
                    if (ant.curCost < bestCostIter)
                    {
                        bestAntIter  = ant;
                        bestCostIter = ant.curCost;
                    }
                }

                if (bestAntIter != null)
                {
                    // apply global trail updating
                    int current = bestAntIter.startCity;
                    do
                    {
                        pheromoneLevels[current, bestAntIter.tour[current]] += (1 - ALPHA) * pheromoneLevels[current, bestAntIter.tour[current]] + ALPHA * (1 / bestCostIter);
                        current = bestAntIter.tour[current];
                    } while (current != bestAntIter.startCity);

                    // see if it is the best ant through all iterations so far
                    if (bestCostIter < bestCost)
                    {
                        bestAnt  = bestAntIter;
                        bestCost = bestCostIter;
                    }
                }
            }

            if (bestAnt != null)
            {
                ArrayList route   = new ArrayList();
                int       curCity = bestAnt.startCity;
                do
                {
                    route.Add(Cities[curCity]);
                    curCity = bestAnt.tour[curCity];
                } while (curCity != bestAnt.startCity);
                bssf = new TSPSolution(route);
            }

            timer.Stop();

            Program.MainForm.tbCostOfTour.Text  = " " + bssf.costOfRoute();
            Program.MainForm.tbElapsedTime.Text = Convert.ToString(timer.Elapsed);

            // do a refresh.
            Program.MainForm.Invalidate();
        }
Beispiel #32
0
        public void AddBlock(string block, Action action)
        {
            if (action == Action.New)
            {
                if (Loaded)
                {
                    gcode.Rows.Clear();
                }

                Reset();
                commands.Clear();
                gcode.BeginLoadData();

                filename = block;
            }
            else if (block != null && block.Trim().Length > 0)
            {
                try
                {
                    block = block.Trim();
                    if (Parser.ParseBlock(ref block, false))
                    {
                        gcode.Rows.Add(new object[] { LineNumber++, block, block.Length + 1, true, Parser.ProgramEnd, "", false });
                        while (commands.Count > 0)
                        {
                            gcode.Rows.Add(new object[] { LineNumber++, commands.Dequeue(), 20, true, false, "", false });
                        }
                    }
                }
                catch //(Exception e)
                {
                    //
                }
            }

            if (action == Action.End)
            {
                gcode.EndLoadData();

#if DEBUG
                System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
                stopWatch.Start();
#endif

                // Calculate program limits (bounding box)

                GCodeEmulator emu = new GCodeEmulator();

                foreach (var cmd in emu.Execute(Tokens))
                {
                    if (cmd.Token is GCArc)
                    {
                        BoundingBox.AddBoundingBox((cmd.Token as GCArc).GetBoundingBox(emu.Plane, new double[] { cmd.Start.X, cmd.Start.Y, cmd.Start.Z }, emu.DistanceMode == DistanceMode.Incremental));
                    }
                    else if (cmd.Token is GCSpline)
                    {
                        BoundingBox.AddBoundingBox((cmd.Token as GCSpline).GetBoundingBox(emu.Plane, new double[] { cmd.Start.X, cmd.Start.Y, cmd.Start.Z }, emu.DistanceMode == DistanceMode.Incremental));
                    }
                    else
                    {
                        BoundingBox.AddPoint(cmd.End);
                    }
                }

                BoundingBox.Conclude();

#if DEBUG
                stopWatch.Stop();
#endif

                //GCodeParser.Save(@"d:\tokens.xml", Parser.Tokens);
                //GCodeParser.Save(@"d:\file.nc", GCodeParser.TokensToGCode(Parser.Tokens));

                FileChanged?.Invoke(filename);
            }
        }
Beispiel #33
0
 public Timer(IGauge gauge)
 {
     _gauge     = gauge;
     _stopwatch = System.Diagnostics.Stopwatch.StartNew();
 }
Beispiel #34
0
        static Emojis LoadEmojis(bool forceDownload = false)
        {
            var emojiList = new Emojis()
            {
                LastUpdate = DateTime.UtcNow
            };

            var url          = "https://unicode.org/emoji/charts/emoji-list.html";
            var htmlFilePath = Path.Combine(AppContext.BaseDirectory, "emoji.html");

            if (forceDownload || !File.Exists(htmlFilePath))
            {
                Console.WriteLine($"Downloading '{url}' (~25MB might take a while!)");
                var sw = new System.Diagnostics.Stopwatch();

                using (var client = new HttpClient())
                {
                    var rawHtml = client.GetStringAsync(url).Result;
                    File.WriteAllText(htmlFilePath, rawHtml);
                }

                sw.Stop();
                Console.WriteLine($"Document downloaded ({sw.ElapsedMilliseconds}ms), processing...");
            }

            var doc = new HtmlDocument();

            using (var fs = new FileStream(htmlFilePath, FileMode.Open, FileAccess.Read))
            {
                doc.Load(fs);
            }

            var header = doc.DocumentNode.SelectSingleNode("//h1");

            emojiList.Version = header?.InnerText ?? string.Empty;

            foreach (var row in doc.DocumentNode.SelectNodes("//tr"))
            {
                if (row.ChildNodes.Count == 1)
                {
                    var categoryNode = row.FirstChild;
                    var categoryName = HtmlEntity.DeEntitize(categoryNode.InnerText);
                    if (!string.IsNullOrEmpty(categoryName))
                    {
                        if (categoryNode.HasClass("bighead"))
                        {
                            Console.WriteLine($"#{categoryName}#");
                            emojiList.Groups.Add(new Group(categoryName));
                        }
                        else if (categoryNode.HasClass("mediumhead"))
                        {
                            Console.WriteLine($"  ##{categoryName}##");
                            emojiList.Groups
                            .Last()
                            .SubGroups
                            .Add(new SubGroup(categoryName));
                        }
                    }
                }
                else
                {
                    var emojiRow = row.SelectNodes("td");
                    if (emojiRow?.Count == 5)
                    {
                        var id          = int.Parse(emojiRow[0].InnerText);
                        var codes       = emojiRow[1].InnerText.Split(" ").Select(c => c.Remove(0, 2));
                        var imgNode     = emojiRow[2].SelectSingleNode("a/img");
                        var emoji       = imgNode.GetAttributeValue("alt", string.Empty);
                        var imageBase64 = imgNode.GetAttributeValue("src", string.Empty)
                                          .Replace("data:image/png;base64,", string.Empty);
                        var cldr     = HtmlEntity.DeEntitize(emojiRow[3].InnerText).TrimStart("⊛ ".ToArray());
                        var keywords = emojiRow[4].InnerText
                                       .Split(" | ")
                                       .Select(s => HtmlEntity.DeEntitize(s));
                        var isNew = emojiRow[3].InnerText.StartsWith("⊛");

                        var newEmoji = new Symbol()
                        {
                            Id          = id,
                            Codes       = codes.ToList(),
                            Emoji       = emoji,
                            ImageBase64 = imageBase64,
                            Cldr        = cldr,
                            Keywords    = keywords.ToList(),
                            IsNew       = isNew
                        };
                        Console.WriteLine($"    {newEmoji}");
                        emojiList.Groups.Last().SubGroups.Last().Emojis.Add(newEmoji);
                    }
                }
            }

            var serializerSettings = new JsonSerializerSettings();

            serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            var prettySerializerSettings = new JsonSerializerSettings();

            prettySerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            prettySerializerSettings.Formatting       = Formatting.Indented;

            var baseDirectory = Path.Combine(AppContext.BaseDirectory, "../../../../EmojiSharp/");

            File.WriteAllText(
                Path.Combine(baseDirectory, "emoji.json"),
                JsonConvert.SerializeObject(emojiList, serializerSettings));

            File.WriteAllText(
                Path.Combine(baseDirectory, "emoji.pretty.json"),
                JsonConvert.SerializeObject(emojiList, prettySerializerSettings));

            var moji = emojiList.Groups.Select(g =>
                                               string.Join(string.Empty,
                                                           g.SubGroups.SelectMany(sg => sg.Emojis.Select(e => e.Emoji))));

            File.WriteAllLines(
                Path.Combine(baseDirectory, "emoji.palette.txt"),
                moji);

            var emojiLookup = (from g in emojiList.Groups
                               from sg in g.SubGroups
                               from e in sg.Emojis
                               let groupId = emojiList.Groups.IndexOf(g)
                                             let emojiId = e.Id
                                                           select new { Emoji = e.Emoji, GroupId = groupId, EmojiId = emojiId });

            File.WriteAllLines(
                Path.Combine(baseDirectory, "emojiLookup.txt"),
                emojiLookup.Select(i => $"{{@\"{i.Emoji}\",({i.GroupId}, {i.EmojiId})}},"));

            var groupsAndIdRange = (from g in emojiList.Groups
                                    let ids = g.SubGroups.SelectMany(sg => sg.Emojis.Select(e => e.Id))
                                              let groupName = g.Name.Replace(" & ", "-").ToLower()
                                                              let minId = ids.Min()
                                                                          let maxId = ids.Max()
                                                                                      select new { GroupName = groupName, Range = $"{minId}:{maxId}" });

            File.WriteAllLines(
                Path.Combine(baseDirectory, "groups.txt"),
                groupsAndIdRange.Select(g => g.GroupName));

            File.WriteAllLines(
                Path.Combine(baseDirectory, "groupsWithRange.txt"),
                groupsAndIdRange.Select(g => $"{g.GroupName},{g.Range}"));

            File.WriteAllLines(
                Path.Combine(baseDirectory, "subGroups.txt"),
                emojiList.Groups.SelectMany(g => g.SubGroups.Select(sg => sg.Name)));

            return(emojiList);
        }
Beispiel #35
0
        async static Task CreateTableAndPopulate(Emojis emojisToLoad)
        {
            var table    = EmojiTable.Get();
            var imgTable = EmojiTable.GetImg();

            // Drop and recreate table
            await table.DeleteIfExistsAsync();

            await table.CreateIfNotExistsAsync();

            await imgTable.DeleteIfExistsAsync();

            await imgTable.CreateIfNotExistsAsync();

            //Entities
            var emojis = new List <EmojiEntity>();
            //Create the batch operation
            var batchOps    = new List <TableBatchOperation>();
            var imgBatchOps = new List <TableBatchOperation>();

            foreach (var g in emojisToLoad.Groups)
            {
                var batchOp    = new TableBatchOperation();
                var imgBatchOp = new TableBatchOperation();
                var groupId    = emojisToLoad.Groups.IndexOf(g).ToString(EmojiMetadata.IdFormat);

                foreach (var sg in g.SubGroups)
                {
                    foreach (var e in sg.Emojis)
                    {
                        var entity = new EmojiEntity(groupId, e.Id.ToString(EmojiMetadata.IdFormat))
                        {
                            Group    = g.Name,
                            SubGroup = sg.Name,
                            Code     = e.CodeString,
                            Emoji    = e.Emoji,
                            Cldr     = e.Cldr,
                            Keywords = e.Haystack,
                            IsNew    = e.IsNew
                        };
                        emojis.Add(entity);
                        batchOp.Insert(entity);

                        if (!string.IsNullOrWhiteSpace(e.ImageBase64))
                        {
                            var imgEntity = new EmojiImageEntity(groupId, e.Id.ToString(EmojiMetadata.IdFormat))
                            {
                                Emoji       = e.Emoji,
                                ImageBase64 = e.ImageBase64
                            };

                            imgBatchOp.Insert(imgEntity);
                        }

                        // Maximum operations in a batch
                        if (batchOp.Count == 100)
                        {
                            batchOps.Add(batchOp);
                            batchOp = new TableBatchOperation();

                            imgBatchOps.Add(imgBatchOp);
                            imgBatchOp = new TableBatchOperation();
                        }
                    }
                }

                // Batch can only contain operations in the same partition
                if (batchOp.Count > 0)
                {
                    batchOps.Add(batchOp);
                }
            }

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

            foreach (var bo in batchOps)
            {
                sw.Reset();
                Console.WriteLine($"Inserting batch for group {bo.First().Entity.PartitionKey}, {bo.Count} entries");
                sw.Start();
                var result = await table.ExecuteBatchAsync(bo);

                processedCount += bo.Count;
                sw.Stop();
                Console.WriteLine($"  Insert complete: {sw.ElapsedMilliseconds}ms");
                Console.WriteLine($"  Processed: {processedCount} emojis");
            }

            processedCount = 0;
            Console.WriteLine($"###IMAGES###");
            foreach (var bo in imgBatchOps)
            {
                sw.Reset();
                Console.WriteLine($"Inserting image batch for group {bo.First().Entity.PartitionKey}, {bo.Count} entries");
                sw.Start();
                var result = await imgTable.ExecuteBatchAsync(bo);

                sw.Stop();
                processedCount += bo.Count;
                Console.WriteLine($"  Insert complete: {sw.ElapsedMilliseconds}ms");
                Console.WriteLine($"  Processed: {processedCount} emojis");
            }
        }
Beispiel #36
0
        protected void ProcessRequest(Request request, IDownloader downloader)
        {
            Page page = null;

#if TEST
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
#endif

            try
            {
#if TEST
                sw.Reset();
                sw.Start();
#endif
                page = downloader.Download(request, this);

#if TEST
                sw.Stop();
                Console.WriteLine("Download:" + (sw.ElapsedMilliseconds).ToString());
#endif
                if (page.IsSkip)
                {
                    return;
                }

                if (PageHandlers != null)
                {
                    foreach (var pageHandler in PageHandlers)
                    {
                        pageHandler?.Invoke(page);
                    }
                }

#if TEST
                sw.Reset();
                sw.Start();
#endif
                PageProcessor.Process(page);
#if TEST
                sw.Stop();
                Console.WriteLine("Process:" + (sw.ElapsedMilliseconds).ToString());
#endif
            }
            catch (DownloadException de)
            {
                if (Site.CycleRetryTimes > 0)
                {
                    page = AddToCycleRetry(request, Site);
                }
                Logger.Warn(de.Message);
            }
            catch (Exception e)
            {
                if (Site.CycleRetryTimes > 0)
                {
                    page = AddToCycleRetry(request, Site);
                }
                Logger.Warn("解析页数数据失败: " + request.Url + ", 请检查您的数据抽取设置.");
            }

            //watch.Stop();
            //Logger.Info("dowloader cost time:" + watch.ElapsedMilliseconds);

            if (page == null)
            {
                OnError(request);
                return;
            }

            if (page.IsNeedCycleRetry)
            {
                ExtractAndAddRequests(page, true);
                return;
            }

            //watch.Stop();
            //Logger.Info("process cost time:" + watch.ElapsedMilliseconds);

            if (!page.MissTargetUrls)
            {
                if (!(SkipWhenResultIsEmpty && page.ResultItems.IsSkip))
                {
                    ExtractAndAddRequests(page, SpawnUrl);
                }
            }
#if TEST
            sw.Reset();
            sw.Start();
#endif
            if (!page.ResultItems.IsSkip)
            {
                foreach (IPipeline pipeline in Pipelines)
                {
                    pipeline.Process(page.ResultItems, this);
                }
            }
            else
            {
                var message = $"页面 {request.Url} 解析结果为 0.";
                Logger.Warn(message);
            }
            Logger.Info($"采集: {request.Url} 成功.");
#if TEST
            sw.Stop();
            Console.WriteLine("IPipeline:" + (sw.ElapsedMilliseconds).ToString());
#endif
        }
Beispiel #37
0
        public void Run()
        {
            CheckIfRunning();

            Stat     = Status.Running;
            IsExited = false;

#if !NET_CORE
            // 开启多线程支持
            System.Net.ServicePointManager.DefaultConnectionLimit = 1000;
#endif

            InitComponent();

            IMonitorableScheduler monitor = (IMonitorableScheduler)Scheduler;

            if (StartTime == DateTime.MinValue)
            {
                StartTime = DateTime.Now;
            }

            Parallel.For(0, ThreadNum, new ParallelOptions
            {
                MaxDegreeOfParallelism = ThreadNum
            }, i =>
            {
                int waitCount  = 0;
                bool firstTask = false;

                var downloader = Downloader.Clone();

                while (Stat == Status.Running)
                {
                    Request request = Scheduler.Poll(this);

                    if (request == null)
                    {
                        if (waitCount > _waitCountLimit && IsExitWhenComplete)
                        {
                            Stat = Status.Finished;
                            break;
                        }

                        // wait until new url added
                        WaitNewUrl(ref waitCount);
                    }
                    else
                    {
                        Log.WriteLine($"Left: {monitor.GetLeftRequestsCount(this)} Total: {monitor.GetTotalRequestsCount(this)} Thread: {ThreadNum}");

                        waitCount = 0;

                        try
                        {
                            ProcessRequest(request, downloader);
                            Thread.Sleep(Site.SleepTime);
#if TEST
                            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                            sw.Reset();
                            sw.Start();
#endif

                            OnSuccess(request);
#if TEST
                            sw.Stop();
                            Console.WriteLine("OnSuccess:" + (sw.ElapsedMilliseconds).ToString());
#endif
                        }
                        catch (Exception e)
                        {
                            OnError(request);
                            Logger.Error("采集失败: " + request.Url + ".", e);
                        }
                        finally
                        {
#if !NET_CORE
                            if (Site.HttpProxyPoolEnable && request.GetExtra(Request.Proxy) != null)
                            {
                                Site.ReturnHttpProxyToPool((HttpHost)request.GetExtra(Request.Proxy), (int)request.GetExtra(Request.StatusCode));
                            }
#endif
                            FinishedPageCount.Inc();
                        }

                        if (!firstTask)
                        {
                            Thread.Sleep(3000);
                            firstTask = true;
                        }
                    }
                }
            });

            FinishedTime = DateTime.Now;

            foreach (IPipeline pipeline in Pipelines)
            {
                SafeDestroy(pipeline);
            }

            if (Stat == Status.Finished)
            {
                OnClose();

                Logger.Info($"任务 {Identity} 结束.");
            }

            if (Stat == Status.Stopped)
            {
                Logger.Info("任务 " + Identity + " 停止成功!");
            }

            SpiderClosingEvent?.Invoke();

            Log.WaitForExit();

            if (Stat == Status.Exited)
            {
                Logger.Info("任务 " + Identity + " 退出成功!");
            }

            IsExited = true;
        }
Beispiel #38
0
 public static void Setup()
 {
     Stopwatch = new Stopwatch();
     Stopwatch.Start();
 }
Beispiel #39
0
        public JavaSelector(JavaElement element, JavaSelector anchor, bool doEnum)
        {
            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            Log.Selector(string.Format("Javaselector::AutomationElement::begin {0:mm\\:ss\\.fff}", sw.Elapsed));
            Log.Selector(string.Format("Javaselector::GetControlVJavawWalker::end {0:mm\\:ss\\.fff}", sw.Elapsed));

            JavaElement root        = null;
            JavaElement baseElement = null;
            var         pathToRoot  = new List <JavaElement>();

            while (element != null)
            {
                // Break on circular relationship (should not happen?)
                //if (pathToRoot.Contains(element) || element.Equals(_rootElement)) { break; }
                // if (pathToRoot.Contains(element)) { break; }
                if (element.Parent != null)
                {
                    pathToRoot.Add(element);
                }
                if (element.Parent == null)
                {
                    root = element;
                }
                try
                {
                    element = element.Parent;
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                    return;
                }
            }
            pathToRoot.Reverse();

            if (anchor != null)
            {
                var anchorlist = anchor.Where(x => x.Enabled && x.Selector == null).ToList();
                for (var i = 0; i < anchorlist.Count; i++)
                {
                    //if (((JavaSelectorItem)anchorlist[i]).Match(pathToRoot[0]))
                    if (JavaSelectorItem.Match(anchorlist[i], pathToRoot[0]))
                    {
                        pathToRoot.Remove(pathToRoot[0]);
                    }
                    else
                    {
                        Log.Warning("Element does not match the anchor path");
                        return;
                    }
                }
            }
            if (pathToRoot.Count == 0)
            {
                Log.Error("Element is same as annchor");
                return;
            }

            baseElement = pathToRoot.First();
            element     = pathToRoot.Last();
            Clear();
            JavaSelectorItem item;

            if (anchor == null)
            {
                item            = new JavaSelectorItem(root, true);
                item.Enabled    = true;
                item.canDisable = false;
                Items.Add(item);
            }
            for (var i = 0; i < pathToRoot.Count(); i++)
            {
                var o = pathToRoot[i];
                item = new JavaSelectorItem(o, false);
                if (i == 0 || i == (pathToRoot.Count() - 1))
                {
                    item.canDisable = false;
                }
                if (doEnum)
                {
                    item.EnumNeededProperties(o, o.Parent);
                }
                Items.Add(item);
            }
            pathToRoot.Reverse();

            Log.Selector(string.Format("Javaselector::EnumNeededProperties::end {0:mm\\:ss\\.fff}", sw.Elapsed));
            OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Count"));
            OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Item[]"));
            OnCollectionChanged(new System.Collections.Specialized.NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction.Reset));
        }
Beispiel #40
0
 public RealtimeClock()
 {
     this.stopwatch = Stopwatch.StartNew();
 }
        //TODO: REMOVE LATER: This method is never called because the DirectReplyToStrategy is used when the client decides to use
        //the direct reply to feature.
        /// <summary>
        /// Discovers the Direct reply-to queue name ( https://www.rabbitmq.com/direct-reply-to.html ) by messaging itself.
        /// </summary>
        private static string DiscoverDirectReplyToQueueName(IModel channel, string indirectReplyToQueueName)
        {
            DeclareIndirectReplyToQueue(channel, indirectReplyToQueueName);

            var receiver    = new ConcurrentQueueingConsumer(channel);
            var receiverTag = channel.BasicConsume(indirectReplyToQueueName, true, receiver);

            channel.BasicPublish(String.Empty, indirectReplyToQueueName, true, new BasicProperties {
                ReplyTo = RPCStrategyHelpers.DIRECT_REPLY_TO_QUEUENAME_ARG
            }, new byte[0]);

            BasicDeliverEventArgs delivery;

            using (ManualResetEventSlim messageReturned = new ManualResetEventSlim())
            {
                EventHandler <BasicReturnEventArgs> returnHandler = null;
                Interlocked.Exchange(ref returnHandler, (a, e) => { messageReturned.Set(); try { receiver.Model.BasicReturn -= returnHandler; } catch { } });
                receiver.Model.BasicReturn += returnHandler;

                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();
                while (!receiver.TryInstantDequeue(out delivery, throwIfClosed: false))
                {
                    Thread.Sleep(1);
                    if (watch.Elapsed > TimeSpan.FromSeconds(10) || messageReturned.IsSet)
                    {
                        break;
                    }
                }
                watch.Stop();

                if (!messageReturned.IsSet)
                {
                    try
                    {
                        receiver.Model.BasicReturn -= returnHandler;
                    }
                    catch { }
                }

                try
                {
                    channel.BasicCancel(receiverTag);
                }
                catch { }
            }

            if (delivery == null)
            {
                throw new InvalidOperationException("Unable to determine direct reply-to queue name.");
            }

            var result = delivery.BasicProperties.ReplyTo;

            if (result == null || result == RPCStrategyHelpers.DIRECT_REPLY_TO_QUEUENAME_ARG || !result.StartsWith(RPCStrategyHelpers.DIRECT_REPLY_TO_QUEUENAME_ARG))
            {
                throw new InvalidOperationException("Discovered direct reply-to queue name (" + (result ?? "null") + ") was not in expected format.");
            }

            return(result);
        }
Beispiel #42
0
        private static JavaElement[] GetElementsWithuiSelector(WindowsAccessBridgeInterop.AccessibleJvm jvm, JavaSelector selector, IElement fromElement, int maxresults)
        {
            JavaElement[] result       = null;
            JavaElement   _fromElement = fromElement as JavaElement;
            var           selectors    = selector.Where(x => x.Enabled == true && x.Selector == null).ToList();
            var           current      = new List <JavaElement>();
            JavaElement   startfrom    = null;

            if (_fromElement != null)
            {
                startfrom = _fromElement;
            }
            if (startfrom == null)
            {
                startfrom = new JavaElement(jvm);
            }
            current.Add(startfrom);
            var _children = jvm.GetChildren();

            foreach (var e in Plugin.EnumRoots(jvm))
            {
                current.Add(e);
            }
            for (var i = 0; i < selectors.Count; i++)
            {
                var sw = new System.Diagnostics.Stopwatch();
                sw.Start();
                var s = new JavaSelectorItem(selectors[i]);
                Log.Selector(string.Format("OpenRPA.Java::GetElementsWithuiSelector::Find for selector {0} {1}", i, s.ToString()));
                var elements = new List <JavaElement>();
                elements.AddRange(current);
                current.Clear();
                foreach (var _element in elements)
                {
                    result = ((JavaSelectorItem)s).matches(_element);
                    current.AddRange(result);
                }
                if (current.Count == 0)
                {
                    // TODO: Figure out, why this is needed when working with Java Menu's
                    foreach (var _e in elements)
                    {
                        if (s.Match(_e))
                        {
                            current.Add(_e);
                        }
                    }
                }
                if (i == (selectors.Count - 1))
                {
                    result = current.ToArray();
                }
                if (current.Count == 0 && Config.local.log_selector)
                {
                    var _c      = new JavaSelectorItem(selectors[i]);
                    var message = "needed to find " + Environment.NewLine + _c.ToString() + Environment.NewLine + "but found only: " + Environment.NewLine;
                    foreach (var element in elements)
                    {
                        var children = element.Children;
                        foreach (var c in children)
                        {
                            try
                            {
                                message += c.ToString() + Environment.NewLine;
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    Log.Selector(message);
                    return(new JavaElement[] { });
                }
                Log.Selector(string.Format("OpenRPA.Java::GetElement::found {1} for selector {2} in {0:mm\\:ss\\.fff}", sw.Elapsed, elements.Count(), i));
            }
            if (result == null)
            {
                return new JavaElement[] { }
            }
            ;
            return(result);
        }
Beispiel #43
0
 private Job(string name)
 {
     this._name      = name;
     this._stopwatch = System.Diagnostics.Stopwatch.StartNew();
     System.Console.WriteLine("[{0} started]", this._name);
 }
Beispiel #44
0
        private void DoExecute()    // MAIN thread only..
        {
            executing = true;

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

            while (true)
            {
                if (progcurrent != null)
                {
                    if (progcurrent.GetErrorList != null)       // any errors pending, handle
                    {
                        actioncontroller.LogLine("Error: " + progcurrent.GetErrorList + Environment.NewLine + StackTrace());
                        TerminateToCloseAtEnd();            // terminate up to a close at end entry, which would have started this stack
                    }
                    else if (progcurrent.IsProgramFinished) // if current program ran out, cancel it
                    {
                        // this catches a LOOP without a statement at the end..  or a DO without a WHILE at the end..
                        if (progcurrent.ExecLevel > 0 && progcurrent.LevelUp(progcurrent.ExecLevel, null)) // see if we have any pending LOOP (or a DO without a while) and continue..
                        {
                            continue;                                                                      // errors or movement causes it to go back.. errors will be picked up above
                        }
                        TerminateCurrent();
                    }
                }

                while (progcurrent == null && progqueue.Count > 0)    // if no program,but something in queue
                {
                    progcurrent = progqueue[0];
                    progqueue.RemoveAt(0);

                    if (progcurrent.variables != null)                         // if not null, its because its just been restarted after a call.. reset globals
                    {
                        progcurrent.Add(actioncontroller.Globals);             // in case they have been updated...
                        progcurrent.Add(progcurrent.actionfile.filevariables); // in case they have been updated...
                    }
                    else
                    {
                        progcurrent.PrepareToRun(
                            new Variables(progcurrent.inputvariables, actioncontroller.Globals, progcurrent.actionfile.filevariables),
                            new FunctionPersistentData(),
                            new Dictionary <string, ExtendedControls.ConfigurableForm>(), true);    // with new file handles and close at end..
                    }

                    if (progcurrent.IsProgramFinished)          // reject empty programs..
                    {
                        TerminateCurrent();
                        continue;       // and try again
                    }
                }

                if (progcurrent == null)        // Still nothing, game over
                {
                    break;
                }

                ActionBase ac = progcurrent.GetNextStep();      // get the step. move PC on.

                //System.Diagnostics.Debug.WriteLine((Environment.TickCount % 10000).ToString("00000") + " @ " + progcurrent.Location +" Lv " + progcurrent.ExecLevel + " e " + (progcurrent.IsExecuteOn ? "1" : "0") + " up " + ac.LevelUp + " " + progcurrent.PushPos + " " + ac.Name);

                if (ac.LevelUp > 0 && progcurrent.LevelUp(ac.LevelUp, ac))         // level up..
                {
                    //System.Diagnostics.Debug.WriteLine((Environment.TickCount % 10000).ToString("00000") + " Abort Lv" + progcurrent.ExecLevel + " e " + (progcurrent.IsExecuteOn ? "1" : "0") + " up " + ac.LevelUp + ": " + progcurrent.StepNumber + " " + ac.Name + " " + ac.DisplayedUserData);
                    continue;
                }

                if (logtologline || logger != null)
                {
                    string t     = (Environment.TickCount % 10000).ToString("00000") + " ";
                    string index = string.Concat(Enumerable.Repeat(". ", progcurrent.ExecLevel));
                    string s     = progcurrent.GetLastStep().LineNumber.ToString() + (progcurrent.IsExecuteOn ? "+" : "-") + ":" + index + ac.Name + " " + ac.DisplayedUserData;
                    System.Diagnostics.Debug.WriteLine(t + s);
                    if (logtologline)
                    {
                        actioncontroller.LogLine(t + s);
                    }
                    if (logger != null)
                    {
                        logger.WriteLine(s);
                    }
                }

                if (progcurrent.DoExecute(ac))                 // execute is on..
                {
                    if (ac.Type == ActionBase.ActionType.Call) // Call needs to pass info back up thru to us, need a different call
                    {
                        ActionCall acall = ac as ActionCall;
                        string     prog;
                        Variables  paravars;
                        if (acall.ExecuteCallAction(progcurrent, out prog, out paravars)) // if execute ok
                        {
                            //System.Diagnostics.Debug.WriteLine("Call " + prog + " with " + paravars.ToString());

                            Tuple <ActionFile, ActionProgram> ap = actionfilelist.FindProgram(prog, progcurrent.actionfile);          // find program using this name, prefer this action file first

                            if (ap != null)
                            {
                                Run(true, ap.Item1, ap.Item2, paravars, progcurrent.functions.persistentdata, progcurrent.dialogs, false);   // run now with these para vars
                            }
                            else
                            {
                                progcurrent.ReportError("Call cannot find " + prog);
                            }
                        }
                    }
                    else if (ac.Type == ActionBase.ActionType.Return)     // Return needs to pass info back up thru to us, need a different call
                    {
                        ActionReturn ar = ac as ActionReturn;
                        string       retstr;
                        if (ar.ExecuteActionReturn(progcurrent, out retstr))
                        {
                            TerminateCurrent();

                            // if a new program is queued, but not prepared, and this program returns to finish, make sure we don't
                            // screw up since the variables are not preparred yet - they will be above in PrepareToRun

                            if (progqueue.Count > 0 && progqueue[0].variables != null)         // pass return value if program is there AND its prepared
                            {
                                progqueue[0]["ReturnValue"] = retstr;
                            }

                            continue;       // back to top, next action from returned function.
                        }
                    }
                    else if (!ac.ExecuteAction(progcurrent)) // if execute says, stop, i'm waiting for something
                    {
                        return;                              // exit, with executing set true.  ResumeAfterPause will restart it.
                    }
                }

                if (AsyncMode && timetaken.ElapsedMilliseconds > 150)  // no more than ms per go to stop the main thread being blocked
                {
                    //System.Diagnostics.Debug.WriteLine((Environment.TickCount % 10000).ToString("00000") + " *** SUSPEND");
                    restarttick.Start();
                    break;
                }
            }

            executing = false;
        }
Beispiel #45
0
        /// <summary>
        ///  Glowna funkcja
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void TimerTick(object sender, EventArgs e)
        {
            if (_tmpForTest == true)
            {
                MoveSnake();
            }
            UpdateSnake();

            if (_gameMode == 0)
            {
                CollisionSnakeFood();
            }
            else
            {
                CollisionSnakeFoodInMulti();
            }

            CollisionSnakeBoard();
            CollisionSnakeYourself();


            // Wysylanie danych o snake'u do serwera:
            if (_gameMode != 0 && _isKilled == false)
            {
                // Przygotowujemy dane (nick, wspolrzedne, rodzaj tekstury) do wyslania:
                PrepareDataAboutSnake();

                // Wysylamy dane o snake'u do serwera:
                SendDataToServer(_coordinatesToSend);

                // Odbieramy dane od serwera:
                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();
                BinaryReader readerSize    = new BinaryReader(serverStream);
                int          sizeReceived  = readerSize.ReadInt32();
                Byte[]       receiveBuffer = new Byte[sizeReceived];
                Int32        sData;
                sData = serverStream.Read(receiveBuffer, 0, receiveBuffer.Length);

                string fromServerAtBeginning = string.Empty;
                fromServerAtBeginning = Encoding.ASCII.GetString(receiveBuffer, 0, sData);
                fromServerAtBeginning = fromServerAtBeginning.Split('&')[0];


                char typeOfMessage = fromServerAtBeginning[0]; // Sprawdzamy pierwszy znak odczytanej wiadomosci i
                                                               // na jego podstawie rozpoznajemy rodzaj wiadomosci
                                                               // co pozwala na wykonanie odpowiedniej akcji

                if (typeOfMessage == 'S')                      // Aktualizacja pozycji snake'a (S - Snake)
                {
                    string[]   split1       = fromServerAtBeginning.Remove(0, 2).Split('*');
                    int        id           = Int32.Parse(split1[0].ToString()); //id gracza od ktorego dostalismy dane
                    string[]   split2       = split1[1].Split('!');
                    string     nick         = split2[0];
                    string[]   split3       = split2[1].Split('$');
                    int        skin         = Int32.Parse(split3[0].ToString());
                    string[]   positions    = split3[1].Split(';');
                    ImageBrush imgSkinEnemy = new ImageBrush
                    {
                        ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(System.IO.Path.GetFullPath("../../" + Options.Textures[skin]), UriKind.RelativeOrAbsolute))
                    };
                    Rectangle addNewHead = new Rectangle();
                    addNewHead.Width = addNewHead.Height = 10;
                    addNewHead.Fill  = Brushes.Black;
                    string[] positionsXYHead = positions[0].Split(',');
                    if (positionsXYHead.Length > 1)
                    {
                        Canvas.SetLeft(addNewHead, Int32.Parse(positionsXYHead[0]));
                        Canvas.SetTop(addNewHead, Int32.Parse(positionsXYHead[1]));
                        BoardCanvas.Children.Add(addNewHead);
                    }
                    for (int i = 1; i < positions.Length; i++)
                    {
                        Rectangle addNew = new Rectangle();
                        addNew.Width = addNew.Height = 10;
                        addNew.Fill  = imgSkinEnemy;
                        string[] positionsXY = positions[i].Split(',');
                        if (positionsXY.Length > 1)
                        {
                            Canvas.SetLeft(addNew, Int32.Parse(positionsXY[0]));
                            Canvas.SetTop(addNew, Int32.Parse(positionsXY[1]));
                            BoardCanvas.Children.Add(addNew);
                        }
                    }
                    if (_dataAboutEnemies.Count == 0)
                    {
                        DataEnemies newDataEnemy = new DataEnemies(id, nick, skin, 0);
                        _dataAboutEnemies.Add(newDataEnemy);
                    }
                    if (infoAboutPlayers.Items.Count == 1)
                    {
                        infoAboutPlayers.Items.Add(PlayerData.SetItemEnemy(_dataAboutEnemies[0].Nick));
                        infoAboutPlayers.HorizontalAlignment = HorizontalAlignment.Center;
                    }
                }
                if (typeOfMessage == 'F') // Nowe pozycje i rodzaj owoca (F - Food)
                {
                    Console.WriteLine(fromServerAtBeginning);
                    string[] splitf1 = fromServerAtBeginning.Remove(0, 2).Split('@');
                    _typeOfFood = Int32.Parse(splitf1[0].ToString());
                    string[] splitf2 = splitf1[1].Split(',');
                    _xFood = Int32.Parse(splitf2[0].ToString());
                    _yFood = Int32.Parse(splitf2[1].ToString());

                    UpdateFoodInMulti(_xFood, _yFood, _typeOfFood);
                    _isFirstFood = true;
                }
                if (typeOfMessage == 'P') // Aktualizacja punktow na tablicy przeciwnika (P - Points)
                {
                    string splitp     = fromServerAtBeginning.Remove(0, 1);
                    int    scoreEnemy = Int32.Parse(splitp.ToString());
                    PlayerData.UpdateScoreEnemy(scoreEnemy);
                }
                watch.Stop();
                Console.WriteLine("czas wykonania w ms: " + watch.ElapsedMilliseconds);
                //Console.WriteLine("czas w taktach procka: " + watch.ElapsedTicks);
                if (typeOfMessage == 'K') // Wymazanie informacji o przeciwniku (nick, points) po jego odejsciu z gry (K - Kill)
                {
                    if (infoAboutPlayers.Items.Count > 1)
                    {
                        infoAboutPlayers.Items.RemoveAt(0);
                        infoAboutPlayers.Items.Add(PlayerData.SetItem());
                        PlayerData.UpdateScore(_score);
                    }
                    _dataAboutEnemies.RemoveAt(0);
                }
                if (typeOfMessage == 'C')
                {
                    CollisionBetweenSnakes();
                }
            }
        }
        public override void ExecuteCommand(ClientManager clientManager, Common.Protobuf.Command command)
        {
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
            int    overload         = 1;
            bool   subscribed       = false;
            string exceptionMessage = null;

            try
            {
                NCache nCache           = clientManager.CmdExecuter as NCache;
                var    operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                if (command.commandVersion < 1)
                {
                    operationContext.Add(OperationContextFieldName.ClientLastViewId, forcedViewId);
                }
                else //NCache 4.1 SP1 or later
                {
                    operationContext.Add(OperationContextFieldName.ClientLastViewId, command.clientLastViewId.ToString(CultureInfo.InvariantCulture));
                }
                if (nCache != null)
                {
                    _command = command.subscribeTopicCommand;

                    SubscriptionInfo subscriptionInfo = new SubscriptionInfo()
                    {
                        SubscriptionId = _command.subscriptionName, ClientId = clientManager.ClientID, Type = (SubscriptionType)_command.pubSubType, SubPolicyType = (SubscriptionPolicyType)_command.subscriptionPolicy, CreationTime = _command.creationTime, Expiration = _command.expirationTime
                    };
                    SubscriptionOperation subOperation = new SubscriptionOperation(_command.topicName, TopicOperationType.Subscribe, subscriptionInfo);
                    subscribed = nCache.Cache.TopicOpertion(subOperation, operationContext);
                    stopWatch.Stop();
                    //Common.Protobuf.Response response = new Common.Protobuf.Response();
                    Common.Protobuf.SubscribeTopicResponse subscribeTopicResponse = new Common.Protobuf.SubscribeTopicResponse();
                    subscribeTopicResponse.success = subscribed;
                    if (clientManager.ClientVersion >= 5000)
                    {
                        Common.Util.ResponseHelper.SetResponse(subscribeTopicResponse, command.requestID, command.commandID);
                        _serializedResponsePackets.Add(Common.Util.ResponseHelper.SerializeResponse(subscribeTopicResponse, Common.Protobuf.Response.Type.SUBSCRIBE_TOPIC));
                    }
                    else
                    {
                        //PROTOBUF:RESPONSE
                        Common.Protobuf.Response response = new Common.Protobuf.Response();
                        response.subscribeTopicResponse = subscribeTopicResponse;
                        Common.Util.ResponseHelper.SetResponse(response, command.requestID, command.commandID, Common.Protobuf.Response.Type.SUBSCRIBE_TOPIC);
                        _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
                    }
                }
            }
            catch (Exception exc)
            {
                exceptionMessage = exc.ToString();
                _serializedResponsePackets.Add(ResponseHelper.SerializeExceptionResponseWithType(exc, command.requestID, command.commandID, clientManager.ClientVersion));
            }
            finally
            {
                TimeSpan executionTime = stopWatch.Elapsed;
                try
                {
                    if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging)
                    {
                        APILogItemBuilder log = new APILogItemBuilder(MethodsName.CreateTopicSubscriptoin);
                        log.GenerateSubscribeToTopicAPILogItem(_command.topicName, (SubscriptionType)_command.pubSubType, executionTime, clientManager.ClientID, clientManager.ClientIP, overload, subscribed, exceptionMessage, APIClassNames.TOPIC);
                    }
                }
                catch
                {
                }
            }
        }
Beispiel #47
0
        private static void Main(string[] args)
        {
            var stopWatch = new Stopwatch();
            stopWatch.Start();

            // Set up the STATSD telemtery
            var statsdConfig = new StatsdConfig
            {
                StatsdServerName = "docker04.concordservicing.com",
                StatsdPort = 8125, // Optional; default is 8125
                Prefix = "akka-kafka-producer" // Optional; by default no prefix will be prepended
            };
            DogStatsd.Configure(statsdConfig);

            // Load the configration
            var config = ConfigurationFactory.ParseString("log-config-on-start = on \n" +
                                                          "Akka.NumAccountPublisherActor = 10 \n" +
                                                          "Akka.NumPortfolioPublisherActor = 10 \n" +
                                                          //                "Kafka.BrokerList = \"docker07.dest.internal:9092,docker08.dest.inmternal:9092,docker09.dest.internal:9092\" \n" +
                                                          "Kafka.BrokerList = \"docker01.concordservicing.com:29092,docker02.concordservicing.com:29092,docker03.concordservicing.com:29092\" \n" +
                                                          "stdout -loglevel = INFO \n" +
                                                          "loglevel=INFO, " +
                                                          "loggers=[\"Akka.Logger.Serilog.SerilogLogger, Akka.Logger.Serilog\"]}");

            //
            var NumAccountPublishers = Convert.ToInt32(config.GetString("Akka.NumAccountPublisherActor"));
            var NumPortfolioPublishers = Convert.ToInt32(config.GetString("Akka.NumPortfolioPublisherActor"));
            var BrokerList = config.GetString("Kafka.BrokerList");

            var AccountStateTopicName = "jontest103";

            Console.WriteLine(NumAccountPublishers);
            Console.WriteLine(NumPortfolioPublishers);
            Console.WriteLine(BrokerList);

            // Create the container for all the actors
            var actorSystem = ActorSystem.Create("csl-arch-poc", config);

            // Create the Kafka Producer object for use by the actual actors
            var kafkaConfig = new Dictionary<string, object>
            {
                ["bootstrap.servers"] = BrokerList,
            //                ["retries"] = 20,
            //                ["retry.backoff.ms"] = 1000,
                ["client.id"] = "akks-arch-demo",
            //                ["socket.nagle.disable"] = true,
                ["default.topic.config"] = new Dictionary<string, object>
                {
                    ["acks"] = -1,
                    ["message.timeout.ms"] = 60000
                }
            };

            // Create the Kafka Producer
            var producer = new Producer<string, string>(kafkaConfig, new StringSerializer(Encoding.UTF8),
                new StringSerializer(Encoding.UTF8));

            // Subscribe to error, log and statistics
            producer.OnError += (obj, error) =>
            {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt") + $"- Error: {error} Obj: {obj}");
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt") + $"- Obj Type: {obj.GetType()}");

                if (obj.GetType().Equals(producer))
                {
                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt") + $"- Type matches produucer");
                    var temp = (Producer<string, string>) obj;
                }
            };

            producer.OnLog += (obj, error) =>
            {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt") + $"- Log: {error}");
            };

            producer.OnStatistics += (obj, error) =>
            {
                Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt") + $"- Statistics: {error}");
            };

            // Schedule the flush actor so we flush the producer on a regular basis
            var publisherFlushProps = Props.Create(() => new KafkaPublisherFlushActor(producer));

            var flushActor = actorSystem.ActorOf(publisherFlushProps, "publisherFlushActor");

            actorSystem.Scheduler.ScheduleTellRepeatedly(TimeSpan.FromSeconds(0),
                TimeSpan.FromSeconds(5), flushActor, new Flush(), ActorRefs.NoSender);

            // Create the publisher actors for the AccountState
            var actorName = "accountStatePublisherActor";

            var accountStatePublisherProps = Props
                .Create(() => new KafkaPublisherActor(AccountStateTopicName, producer, actorName))
                .WithRouter(new RoundRobinPool(NumAccountPublishers));

            var accountStatePublisherActor = actorSystem.ActorOf(accountStatePublisherProps, actorName);

            // Create the publisher actors for the PortfolioState
            /*
            actorName = "portfolioStatePublisherActor";
            Props portfolioStatePublisherProps = Props.Create(() => new KafkaPublisherActor(PortfolioStateTopicName, producer, actorName))
                .WithRouter(new RoundRobinPool(NumPortfolioPublishers));
            IActorRef portfolioStatePublisherActor = actorSystem.ActorOf(portfolioStatePublisherProps, actorName);
            */

            // Create some AccountState events and send them to kafka
            for (var index = 0; index < 1200000; index++)
            {
                var key = "key" + index;
                var msgToSend = new SimpleClass(key, index, 10);
                accountStatePublisherActor.Tell(new Publish(key, msgToSend));
            }

            Console.WriteLine("Sent topic1");

            // Wait for the messages to be sent
            while (true)
            {
                var ret = producer.Flush(5000);
                Console.WriteLine("Flushing ret=" + ret);
                DogStatsd.Gauge("QueueOfMsgsToSend", ret);

                if (ret == 0)
                {
                    stopWatch.Stop();

                    // Get the elapsed time as a TimeSpan value.
                    var ts = stopWatch.Elapsed;

                    // Format and display the TimeSpan value.
                    var elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                        ts.Hours, ts.Minutes, ts.Seconds,
                        ts.Milliseconds / 10);
                    Console.WriteLine("RunTime " + elapsedTime);
                }

                Thread.Sleep(5000);
            }
        }
Beispiel #48
0
        public CallRequestContainer()
        {
#if PLAYFAB_REQUEST_TIMING
            Stopwatch = System.Diagnostics.Stopwatch.StartNew();
#endif
        }
/**
 * Stupidly, Unity in 2D mode uses co-ords incompatible with Unity in 3D mode (xy instead of xz).
 *
 * So we have to provide a boolean to switch between the two modes!
 */
        public static VoronoiDiagram CreateDiagramFromVoronoiOutput(Voronoi voronoiGenerator, bool useUnity2DCoordsNot3D)
        {
            GameObject go           = new GameObject("New VoronoiMap");
            GameObject goCellHolder = new GameObject(_cellHolderName);

            goCellHolder.transform.parent = go.transform;
            GameObject goEdgeHolder = new GameObject(_edgeHolderName);

            goEdgeHolder.transform.parent = go.transform;
            GameObject goVertexHolder = new GameObject(_vertexHolderName);

            goVertexHolder.transform.parent = go.transform;

            VoronoiDiagram map = go.AddComponent <VoronoiDiagram>();

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Reset();
            watch.Start();

            Dictionary <Site, VoronoiCell>          generatedCells    = new Dictionary <Site, VoronoiCell>();
            Dictionary <Vector2, VoronoiCellVertex> generatedVertices = new Dictionary <Vector2, VoronoiCellVertex>();

            int numEdgesCreated = 0;

            foreach (Edge edge in voronoiGenerator.Edges())
            {
                GameObject goEdge = new GameObject("Edge-#" + (numEdgesCreated++));
                goEdge.transform.parent = goEdgeHolder.transform;

                VoronoiCellEdge vEdge = goEdge.AddComponent <VoronoiCellEdge>();
                Debug.Log("Processing edge = " + edge + " with clippedEnds = " + (edge.clippedEnds == null?"null":"" + edge.clippedEnds.Count));
                if (!edge.visible)
                {
                    Debug.Log("...Voronoi algorithm generated a non-existent edge, skipping it...");
                    continue;
                }
                Vector2 clippedEndLeft  = (Vector2)edge.clippedEnds [Side.LEFT];
                Vector2 clippedEndRight = (Vector2)edge.clippedEnds [Side.RIGHT];
                vEdge.AddVertex(FetchVertexOrAddToObject(clippedEndLeft, generatedVertices, goVertexHolder, useUnity2DCoordsNot3D));
                vEdge.AddVertex(FetchVertexOrAddToObject(clippedEndRight, generatedVertices, goVertexHolder, useUnity2DCoordsNot3D));
                goEdge.transform.localPosition = (vEdge.edgeVertexA.transform.localPosition + vEdge.edgeVertexB.transform.localPosition) / 2.0f;

                Site[] bothSites = new Site[] { edge.leftSite, edge.rightSite };
                foreach (Site site in bothSites)
                {
                    /** Re-use or create the Cell */
                    VoronoiCell newCell = null; // C# is rubbish. Crashes if Dictionary lacks the key. Very bad design.
                    if (generatedCells.ContainsKey(site))
                    {
                        newCell = generatedCells [site];
                    }
                    GameObject goCell;

                    if (newCell == null)
                    {
                        goCell = new GameObject("Cell-#" + generatedCells.Count);
                        goCell.transform.parent        = goCellHolder.transform;
                        goCell.transform.localPosition = new Vector3(site.Coord.x, useUnity2DCoordsNot3D? site.Coord.y : 0, useUnity2DCoordsNot3D? 0 : site.Coord.y);
                        newCell = goCell.AddComponent <VoronoiCell>();
                        generatedCells.Add(site, newCell);
                    }
                    else
                    {
                        goCell = newCell.gameObject;
                    }

                    /** Now that cell is created, attach it to BOTH Vertex's on the new Edge
                     *        (so that later its easy for us to to find Cells-for-this-Vertex, and also:
                     *        for a Cell to "trace" around its edges, picking "next edge" from each Vertex
                     *        by looking at which edges from the vertex border this cell (by checking
                     *        that BOTH Vertex-ends of the edge are attached to this cell)
                     *
                     *        Also add the edge itself to the cell, and the cell to the edge.
                     */
                    vEdge.AddCellWithSideEffects(newCell);
                }
            }
            watch.Stop();

            return(map);
        }
Beispiel #50
0
        private static IEnumerator FindIllegalShadersEnumerator(GameObject target, string[] whitelist, System.Action <Shader> onFound, bool useWatch = false)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            if (useWatch)
            {
                watch.Start();
            }

            List <Material>    materialCache = new List <Material>();
            Queue <GameObject> children      = new Queue <GameObject>();

            children.Enqueue(target.gameObject);
            while (children.Count > 0)
            {
                GameObject child = children.Dequeue();
                if (child == null)
                {
                    continue;
                }

                for (int idx = 0; idx < child.transform.childCount; ++idx)
                {
                    children.Enqueue(child.transform.GetChild(idx).gameObject);
                }

                foreach (Renderer childRenderers in child.transform.GetComponents <Renderer>())
                {
                    if (childRenderers == null)
                    {
                        continue;
                    }

                    foreach (Material sharedMaterial in childRenderers.sharedMaterials)
                    {
                        if (materialCache.Any(cacheMtl => sharedMaterial == cacheMtl)) // did we already look at this one?
                        {
                            continue;
                        }

                        // Skip empty material slots, or materials without shaders.
                        // Both will end up using the magenta error shader.
                        if (sharedMaterial == null || sharedMaterial.shader == null)
                        {
                            continue;
                        }

                        if (whitelist.All(okayShaderName => sharedMaterial.shader.name != okayShaderName))
                        {
                            onFound(sharedMaterial.shader);
                            yield return(null);
                        }

                        materialCache.Add(sharedMaterial);
                    }

                    if (!useWatch || watch.ElapsedMilliseconds <= 1)
                    {
                        continue;
                    }

                    yield return(null);

                    watch.Reset();
                }
            }
        }
Beispiel #51
0
        /// <summary>
        /// 195/195 cases passed (104 ms)
        /// Your runtime beats 89.9 % of csharp submissions
        /// Your memory usage beats 95.45 % of csharp submissions(24.5 MB)
        /// </summary>
        /// <param name="sw"></param>
        /// <returns></returns>
        public override bool Test(System.Diagnostics.Stopwatch sw)
        {
            bool   isSuccess = true;
            string s         = "barfoothefoobarman";

            int[] nums;
            int   target;
            int   result, checkResult;

            nums        = new int[] { 1, 3, 5 };
            target      = 0;
            result      = Search(nums, target);
            checkResult = -1;

            isSuccess &= result == checkResult;
            Print("isSuccess = {0} result = {1} | checkResult = {2}", isSuccess, (result), (checkResult));

            nums        = new int[] { 3, 5, 1 };
            target      = 5;
            result      = Search(nums, target);
            checkResult = 1;

            isSuccess &= result == checkResult;
            Print("isSuccess = {0} result = {1} | checkResult = {2}", isSuccess, (result), (checkResult));


            nums        = new int[] { 4, 5, 6, 7, 0, 1, 2 };
            target      = 0;
            result      = Search(nums, target);
            checkResult = 4;

            isSuccess &= result == checkResult;
            Print("isSuccess = {0} result = {1} | checkResult = {2}", isSuccess, (result), (checkResult));

            nums        = new int[] { 4, 5, 6, 7, 0, 1, 2 };
            target      = 3;
            result      = Search(nums, target);
            checkResult = -1;

            isSuccess &= result == checkResult;
            Print("isSuccess = {0} result = {1} | checkResult = {2}", isSuccess, (result), (checkResult));

            nums        = new int[] { 4, 5, 6, 7, 0, 1, 2 };
            target      = 6;
            result      = Search(nums, target);
            checkResult = 2;

            isSuccess &= result == checkResult;
            Print("isSuccess = {0} result = {1} | checkResult = {2}", isSuccess, (result), (checkResult));

            nums        = new int[] { 4, 5, 6, 7, 0, 1, 2 };
            target      = 1;
            result      = Search(nums, target);
            checkResult = 5;

            isSuccess &= result == checkResult;
            Print("isSuccess = {0} result = {1} | checkResult = {2}", isSuccess, (result), (checkResult));


            nums        = new int[] { 1 };
            target      = 0;
            result      = Search(nums, target);
            checkResult = -1;

            isSuccess &= result == checkResult;
            Print("isSuccess = {0} result = {1} | checkResult = {2}", isSuccess, (result), (checkResult));

            return(isSuccess);
        }
        /// <summary>
        /// Performs a fully standalone in-place location layout.
        /// This method is used only by editor layouts, not by streaming world.
        /// </summary>
        private void LayoutLocation(ref DFLocation location)
        {
#if SHOW_LAYOUT_TIMES
            // Start timing
            System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
            long startTime = stopwatch.ElapsedMilliseconds;
#endif

            // Get city dimensions
            int width  = location.Exterior.ExteriorData.Width;
            int height = location.Exterior.ExteriorData.Height;

            // Create billboard batch game objects for this location
            //TextureAtlasBuilder miscBillboardAtlas = null;
            summary.NatureBillboardBatch = null;
            DaggerfallBillboardBatch lightsBillboardBatch  = null;
            DaggerfallBillboardBatch animalsBillboardBatch = null;
            //DaggerfallBillboardBatch miscBillboardBatch = null;
            if (dfUnity.Option_BatchBillboards)
            {
                //miscBillboardAtlas = dfUnity.MaterialReader.MiscBillboardAtlas;
                int natureArchive = ClimateSwaps.GetNatureArchive(CurrentNatureSet, CurrentSeason);
                summary.NatureBillboardBatch = GameObjectHelper.CreateBillboardBatchGameObject(natureArchive, transform);
                lightsBillboardBatch         = GameObjectHelper.CreateBillboardBatchGameObject(TextureReader.LightsTextureArchive, transform);
                animalsBillboardBatch        = GameObjectHelper.CreateBillboardBatchGameObject(TextureReader.AnimalsTextureArchive, transform);
                //miscBillboardBatch = GameObjectHelper.CreateBillboardBatchGameObject(miscBillboardAtlas.AtlasMaterial, transform);
            }

            // Import blocks
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    if (dfUnity.Option_BatchBillboards)
                    {
                        // Set block origin for billboard batches
                        // This causes next additions to be offset by this position
                        Vector3 blockOrigin = new Vector3((x * RMBLayout.RMBSide), 0, (y * RMBLayout.RMBSide));
                        summary.NatureBillboardBatch.BlockOrigin = blockOrigin;
                        lightsBillboardBatch.BlockOrigin         = blockOrigin;
                        animalsBillboardBatch.BlockOrigin        = blockOrigin;
                        //miscBillboardBatch.BlockOrigin = blockOrigin;
                    }

                    string     blockName = dfUnity.ContentReader.BlockFileReader.CheckName(dfUnity.ContentReader.MapFileReader.GetRmbBlockName(ref location, x, y));
                    GameObject go        = GameObjectHelper.CreateRMBBlockGameObject(
                        blockName,
                        x,
                        y,
                        dfUnity.Option_RMBGroundPlane,
                        dfUnity.Option_CityBlockPrefab,
                        summary.NatureBillboardBatch,
                        lightsBillboardBatch,
                        animalsBillboardBatch,
                        null, //miscBillboardAtlas,
                        null, //miscBillboardBatch,
                        CurrentNatureSet,
                        CurrentSeason);
                    go.transform.parent   = this.transform;
                    go.transform.position = new Vector3((x * RMBLayout.RMBSide), 0, (y * RMBLayout.RMBSide));
                }
            }

            // Apply batches
            if (summary.NatureBillboardBatch)
            {
                summary.NatureBillboardBatch.Apply();
            }
            if (lightsBillboardBatch)
            {
                lightsBillboardBatch.Apply();
            }
            if (animalsBillboardBatch)
            {
                animalsBillboardBatch.Apply();
            }
            //if (miscBillboardBatch) miscBillboardBatch.Apply();

            // Enumerate start marker game objects
            EnumerateStartMarkers();

#if SHOW_LAYOUT_TIMES
            // Show timer
            long totalTime = stopwatch.ElapsedMilliseconds - startTime;
            DaggerfallUnity.LogMessage(string.Format("Time to layout location: {0}ms", totalTime), true);
#endif
        }
Beispiel #53
0
        private static async Task <int> Main(string[] args)
        {
            bool mode = false;

            Pi.Init <BootstrapWiringPi>();//初始化通信接口,分配内存空间等
            var Count = 0;
            var Exit  = false;

            _ = Task.Factory.StartNew(() =>
            {
                var clkPin      = Pi.Gpio[BcmPin.Gpio23];  //引用16接口
                var dataPin     = Pi.Gpio[BcmPin.Gpio24];  //引用18接口
                clkPin.PinMode  = GpioPinDriveMode.Output; //设置16接口模式为输出
                dataPin.PinMode = GpioPinDriveMode.Output; //设置18接口模式为输出
                init:
                {
                    Show(0xC0, 0x40);
                    Show(0xC1, 0x40);
                    Show(0xC2, 0x40);
                    Show(0xC3, 0x40);
                }
                Console.CancelKeyPress += delegate
                {
                    startDisp();
                    writeByte(0x80);
                    stopDisp();
                };
                void startDisp()
                {
                    //数据输入开始
                    clkPin.Write(GpioPinValue.High);  //CLK拉为高电平
                    dataPin.Write(GpioPinValue.High); //DIO拉为高电平
                    dataPin.Write(GpioPinValue.Low);  //和上面那句指令一起就是DIO由高变低
                    clkPin.Write(GpioPinValue.Low);   //然后CLK上的时钟信号拉低,DIO接口的数据允许改变,代表开始写入数据
                }
                void stopDisp()
                {
                    //结束条件是CLK为高时,DIO由低电平变为高电平
                    clkPin.Write(GpioPinValue.Low);   //先拉低CLK,代表允许DIO改变数据
                    dataPin.Write(GpioPinValue.Low);  //拉低DIO
                    clkPin.Write(GpioPinValue.High);  //CLK拉高,满足结束条件前半部分
                    dataPin.Write(GpioPinValue.High); //DIO由低变高,代表数据输入结束
                }
                void writeByte(byte input)
                {
                    //开始写入数据
                    for (int i = 0; i < 8; i++)         //每次写入一个byte,一共8bit
                    {
                        clkPin.Write(GpioPinValue.Low); //确保无误输入前再拉低一次时钟 ,代表开始写入数据
                        if ((input & 0x01) == 1)        //判断每一位的高低电平
                        {
                            dataPin.Write(GpioPinValue.High);
                        }
                        else
                        {
                            dataPin.Write(GpioPinValue.Low);
                        }
                        input >>= 1;                     //每写入完毕一次,移动一位
                        clkPin.Write(GpioPinValue.High); //每次输入完一位,就拉高一次时钟
                    }
                    //应答信号ACK,这里本来是用来判断DIO脚是否被自动拉低,代表上面写入的数据TM1637已经接受到了,
                    //但是我们这里闲麻烦,直接将CLK信号低高低的拉,让芯片直接执行下一步操作
                    clkPin.Write(GpioPinValue.Low);  //先拉低
                    clkPin.Write(GpioPinValue.High); //需要判断D是否为低电平此期间C一直拉高
                    clkPin.Write(GpioPinValue.Low);  //应答完毕以后拉低C
                }
                void Show(byte address, byte show)
                {
                    //Start transmission
                    startDisp();     //开始写入指令 C高D高D低
                    writeByte(0x44); //40H模式地址自动+1,44H模式固定地址
                    stopDisp();      //结束写入指令 C低D低C高D高
                                     //上述完成数据指令设置

                    //设置光标位置为11000000,光标位置每次输入+1
                    startDisp();
                    writeByte(address);  //设置首地址
                                         //Write text
                                         //数据从01000000写到01111111
                                         //
                                         //      A
                                         //     ---
                                         //  F |   | B
                                         //     -G-
                                         //  E |   | C
                                         //     ---
                                         //      D

                    /*
                     * XGFEDCBA
                     * 10000000
                     * 00111111,    // 0
                     * 00000110,    // 1
                     * 01011011,    // 2
                     * 01001111,    // 3
                     * 01100110,    // 4
                     * 01101101,    // 5
                     * 01111101,    // 6
                     * 00000111,    // 7
                     * 01111111,    // 8
                     * 01101111,    // 9
                     * 01110111,    // A
                     * 01111100,    // b
                     * 00111001,    // C
                     * 01011110,    // d
                     * 01111001,    // E
                     * 01110001     // F
                     */
                    //写入字符

                    writeByte(show);
                    //停止写入
                    startDisp();
                    //开始写入亮度
                    startDisp();                  //开始写入指令
                    writeByte(0x8f);              //最大亮度
                    stopDisp();                   //停止写入
                }
                clkPin.Write(GpioPinValue.High);  //初始化电平为低,可不加
                dataPin.Write(GpioPinValue.High); //初始化电平为低,可不加
                var ShowCount = false;
                while (true)
                {
                    if (mode)
                    {
                        var Date = DateTime.Now.ToString("HHmm").ToCharArray();
                        Show(0xC3, numbers[Date[Date.Length - 1] - 48]);
                        if (Date.Length > 1)
                        {
                            Show(0xC2, numbers[Date[Date.Length - 2] - 48]);
                        }
                        else
                        {
                            Show(0xC2, 0x40);
                        }
                        if (Date.Length > 2)
                        {
                            if (ShowCount)
                            {
                                ShowCount = false;
                                Show(0xC1, (byte)(numbers[Date[Date.Length - 3] - 48] | 0x80));
                            }
                            else
                            {
                                ShowCount = true;

                                Show(0xC1, numbers[Date[Date.Length - 3] - 48]);
                            }
                        }
                        else
                        {
                            Show(0xC1, 0x40);
                        }
                        if (Date.Length > 3)
                        {
                            Show(0xC0, numbers[Date[Date.Length - 4] - 48]);
                        }
                        else
                        {
                            Show(0xC0, 0x40);
                        }
                        //Interlocked.Increment(ref Count);
                        if (Exit)
                        {
                            startDisp();
                            writeByte(0x80);
                            stopDisp();
                            break;
                        }
                        Thread.Sleep(250);
                    }
                    else
                    {
                        var Date = Count.ToString().ToCharArray();
                        Show(0xC3, numbers[Date[Date.Length - 1] - 48]);
                        if (Date.Length > 1)
                        {
                            Show(0xC2, numbers[Date[Date.Length - 2] - 48]);
                        }
                        else
                        {
                            Show(0xC2, 0x40);
                        }
                        if (Date.Length > 2)
                        {
                            Show(0xC1, numbers[Date[Date.Length - 3] - 48]);
                        }
                        else
                        {
                            Show(0xC1, 0x40);
                        }
                        if (Date.Length > 3)
                        {
                            Show(0xC0, numbers[Date[Date.Length - 4] - 48]);
                        }
                        else
                        {
                            Show(0xC0, 0x40);
                        }
                        //Interlocked.Increment(ref Count);
                        if (Count == 10000)
                        {
                            Count = 0;
                        }
                        if (Exit)
                        {
                            startDisp();
                            writeByte(0x80);
                            stopDisp();
                            break;
                        }
                        Thread.Sleep(100);
                    }
                }
            });
            _ = Task.Factory.StartNew(() =>
            {
                var Shock     = Pi.Gpio[BcmPin.Gpio22];
                Shock.PinMode = GpioPinDriveMode.Input;
                System.Diagnostics.Stopwatch StartWatch = new System.Diagnostics.Stopwatch();
                System.Diagnostics.Stopwatch KeepWatch  = new System.Diagnostics.Stopwatch();
                var KeyCount = 0;

                while (true)
                {
                    Thread.Sleep(50);
                    if (!Shock.Read() && !KeepWatch.IsRunning)//按下按钮,计时未开始
                    {
                        KeepWatch.Restart();
                    }
                    else if (Shock.Read() && KeepWatch.IsRunning)//松开按钮,计时开始中,松开按钮计时
                    {
                        KeepWatch.Stop();
                        StartWatch.Restart();
                        KeyCount++;
                    }
                    else if (!Shock.Read() && KeepWatch.IsRunning && KeepWatch.ElapsedMilliseconds > 1000)//按下按钮,计时开始中
                    {
                        if (KeepWatch.ElapsedMilliseconds > 1000)
                        {
                            Count = 0;
                        }
                        else if (KeepWatch.ElapsedMilliseconds > 5000)
                        {
                            Exit = true;
                            Thread.Sleep(100);
                            ShutdownResetEvent.SetResult(0);
                        }
                    }
                    else if (Shock.Read() && KeepWatch.IsRunning && StartWatch.ElapsedMilliseconds > 200)
                    {
                        StartWatch.Restart();
                        KeyCount++;
                    }

                    if (KeyCount != 0 && StartWatch.ElapsedMilliseconds > 500)
                    {
                        switch (KeyCount)
                        {
                        case 1:
                            {
                                if (Count > 0 && !mode)
                                {
                                    Interlocked.Decrement(ref Count);
                                }
                            }
                            break;

                        case 2:
                            {
                                if (!mode)
                                {
                                    Interlocked.Increment(ref Count);
                                }
                            }
                            break;

                        default:
                            {
                                if (KeyCount > 6)
                                {
                                    mode = mode ? false : true;
                                }
                            }
                            break;
                        }
                        KeepWatch.Stop();
                        StartWatch.Stop();
                        KeyCount = 0;
                    }

                    /* if (!Shock.Read() && !KeepWatch.IsRunning)
                     * {
                     *   KeepWatch.Restart();
                     * }
                     * else if (Shock.Read() && KeepWatch.IsRunning)
                     * {
                     *   if(KeepWatch.ElapsedMilliseconds < 1000&& Count > 0&& !mode)
                     *       Interlocked.Decrement(ref Count);
                     *   KeepWatch.Stop();
                     * }
                     * else if (KeepWatch.IsRunning && KeepWatch.ElapsedMilliseconds > 5000)
                     * {
                     *   //Exit = true;
                     *   Thread.Sleep(100);
                     *   mode = mode ? false : true;
                     *  // ShutdownResetEvent.SetResult(0);
                     * }
                     * else if (KeepWatch.IsRunning && KeepWatch.ElapsedMilliseconds > 1000)
                     * {
                     *   Count = 0;
                     * }
                     * else if (KeepWatch.IsRunning&&KeepWatch.ElapsedMilliseconds > 6000)
                     * {
                     *   KeepWatch.Stop();
                     * }*/

                    /*if (!Shock.Read() && !KeySign)
                     * {
                     *  KeySign = true;
                     *  if(Count>0)
                     *  Interlocked.Decrement(ref Count);
                     * }
                     * if (Shock.Read() && KeySign)
                     * {
                     *  KeySign = false;
                     * }*/
                }
            });
            _ = Task.Factory.StartNew(() =>
            {
                var Tilt     = Pi.Gpio[BcmPin.Gpio04];
                Tilt.PinMode = GpioPinDriveMode.Input;
                var KeySign  = false;
                System.Diagnostics.Stopwatch KeepWatch = new System.Diagnostics.Stopwatch();

                while (true)
                {
                    Thread.Sleep(50);

                    /*  if (Tilt.Read() && !KeySign)
                     * {
                     *     KeySign = true;
                     *     if (!KeepWatch.IsRunning)
                     *         Interlocked.Increment(ref Count);
                     *     KeepWatch.Restart();
                     * }else if (!Tilt.Read() && KeySign)
                     * {
                     *     KeySign = false;
                     * }
                     * if (KeepWatch.ElapsedMilliseconds > 4000) KeepWatch.Stop();*/

                    if (!Tilt.Read() && !KeySign)
                    {
                        KeySign = true;
                        if (!KeepWatch.IsRunning)
                        {
                            Interlocked.Increment(ref Count);
                        }
                        KeepWatch.Restart();
                    }
                    else if (Tilt.Read() && KeySign)
                    {
                        KeySign = false;
                    }
                    if (KeepWatch.ElapsedMilliseconds > 4000)
                    {
                        KeepWatch.Stop();
                    }
                }
            });
            return(await ShutdownResetEvent.Task.ConfigureAwait(false));
        }
Beispiel #54
0
        public void Equip(int _equipId)
        {
            if (Transform == null)
            {
                return;
            }
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();

            if (!ItemEquipmentData.dataMap.ContainsKey(_equipId))
            {
                LoggerHelper.Error("can not find equip:" + _equipId);
                return;
            }
            ItemEquipmentData equip = ItemEquipmentData.dataMap[_equipId];

            if (equip.mode > 0)
            {
                if (Actor == null)
                {
                    return;
                }
                Actor.m_isChangingWeapon = true;
                Actor.Equip(equip.mode);
                if (equip.type == (int)EquipType.Weapon)
                {
                    ControllerOfWeaponData    controllerData = ControllerOfWeaponData.dataMap[equip.subtype];
                    RuntimeAnimatorController controller;
                    if (animator == null)
                    {
                        return;
                    }
                    string controllerName = (MogoWorld.inCity ? controllerData.controllerInCity : controllerData.controller);
                    if (animator.runtimeAnimatorController != null)
                    {
                        if (animator.runtimeAnimatorController.name == controllerName)
                        {
                            return;
                        }
                        AssetCacheMgr.ReleaseResource(animator.runtimeAnimatorController);
                    }

                    AssetCacheMgr.GetResource(controllerName,
                                              (obj) =>
                    {
                        controller = obj as RuntimeAnimatorController;
                        if (animator == null)
                        {
                            return;
                        }
                        animator.runtimeAnimatorController = controller;
                        if (this is EntityMyself)
                        {
                            (this as EntityMyself).UpdateSkillToManager();
                            EventDispatcher.TriggerEvent <int, int>(InventoryEvent.OnChangeEquip, equip.type, equip.subtype);
                        }
                        if (this is EntityPlayer)
                        {
                            if (MogoWorld.inCity)
                            {
                                animator.SetInteger("Action", -1);
                            }
                            else
                            {
                                animator.SetInteger("Action", 0);
                            }
                            if (MogoWorld.isReConnect)
                            {
                                ulong s   = stateFlag;
                                stateFlag = 0;
                                stateFlag = s;
                            }
                        }
                    });
                }

                stopWatch.Stop();

                //if (!isCreatingModel)
                //{
                //    SetPosition();
                //    stopWatch.Start();
                //    //AssetCacheMgr.ReleaseInstance(GameObject);
                //    CreateActualModel();
                //    stopWatch.Stop();
                //    Mogo.Util.LoggerHelper.Debug("CreateModel:" + stopWatch.Elapsed.Milliseconds);

                //}
            }
        }
        public void Compile()
        {
            Profiler.BeginSample("UdonSharp Compile");

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

            int totalErrorCount = 0;
            int moduleCounter   = 0;

            try
            {
                List <ClassDefinition> classDefinitions = BuildClassDefinitions();
                if (classDefinitions == null)
                {
                    totalErrorCount++;
                }

                if (totalErrorCount == 0)
                {
                    foreach (CompilationModule module in modules)
                    {
                        EditorUtility.DisplayProgressBar("UdonSharp Compile",
                                                         $"Compiling {AssetDatabase.GetAssetPath(module.programAsset.sourceCsScript)}...",
                                                         Mathf.Clamp01((moduleCounter++ / (float)modules.Length) + Random.Range(0.01f, 1f / modules.Length))); // Make it look like we're doing work :D

                        int moduleErrorCount = module.Compile(classDefinitions);
                        totalErrorCount += moduleErrorCount;
                    }

                    if (totalErrorCount == 0)
                    {
                        EditorUtility.DisplayProgressBar("UdonSharp Compile", "Assigning constants...", 1f);
                        int initializerErrorCount = AssignHeapConstants();
                        totalErrorCount += initializerErrorCount;

                        if (initializerErrorCount == 0)
                        {
                            foreach (CompilationModule module in modules)
                            {
                                module.programAsset.ApplyProgram();
                            }
                        }
                    }
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }

            compileTimer.Stop();

            EditorUtility.ClearProgressBar();

            if (totalErrorCount == 0)
            {
                if (modules.Length > 5)
                {
                    Debug.Log($"[UdonSharp] Compile of {modules.Length} scripts finished in {compileTimer.Elapsed.ToString("mm\\:ss\\.fff")}");
                }
                else
                {
                    Debug.Log($"[UdonSharp] Compile of script{(modules.Length > 1 ? "s" : "")} {string.Join(", ", modules.Select(e => Path.GetFileName(AssetDatabase.GetAssetPath(e.programAsset.sourceCsScript))))} finished in {compileTimer.Elapsed.ToString("mm\\:ss\\.fff")}");
                }
            }

            Profiler.EndSample();
        }
Beispiel #56
0
        public override void Run()
        {
            #region Create renderers

            // Note: the renderers take care of creating their own
            // device resources and listen for DeviceManager.OnInitialize

            // Create a axis-grid renderer
            var axisGrid = ToDispose(new AxisGridRenderer());
            axisGrid.Initialize(this);

            var triangle = new TriangleRenderer();
            triangle.Initialize(this);

            var quad = new QuadRenderer();
            quad.Initialize(this);

            var bezier = new BezierPatchRenderer();
            bezier.Initialize(this);

            var parametric = new ParametricRenderer();
            parametric.Initialize(this);
            parametric.Show = false;

            // Create and initialize a Direct2D FPS text renderer
            var fps = ToDispose(new Common.FpsRenderer("Calibri", Color.CornflowerBlue, new Point(8, 8), 16));
            fps.Initialize(this);

            // Create and initialize a general purpose Direct2D text renderer
            // This will display some instructions and the current view and rotation offsets
            var textRenderer = ToDispose(new Common.TextRenderer("Calibri", Color.CornflowerBlue, new Point(8, 40), 12));
            textRenderer.Initialize(this);

            #endregion

            // Initialize the world matrix
            var worldMatrix = Matrix.Identity;

            // Set the camera position
            var cameraPosition = new Vector3(0, 0, 2);
            var cameraTarget   = Vector3.Zero;  // Looking at the origin 0,0,0
            var cameraUp       = Vector3.UnitY; // Y+ is Up

            // Prepare matrices
            // Create the view matrix from our camera position, look target and up direction
            var viewMatrix = Matrix.LookAtRH(cameraPosition, cameraTarget, cameraUp);
            viewMatrix.TranslationVector += new Vector3(0, -0.98f, 0);

            // Create the projection matrix
            /* FoV 60degrees = Pi/3 radians */
            // Aspect ratio (based on window size), Near clip, Far clip
            var projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.5f, 100f);

            // Maintain the correct aspect ratio on resize
            Window.Resize += (s, e) =>
            {
                projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.5f, 100f);
            };

            #region Rotation and window event handlers

            // Create a rotation vector to keep track of the rotation
            // around each of the axes
            var rotation              = new Vector3(0.0f, 0.0f, 0.0f);
            var tessellationFactor    = 1f;
            var tessellationPartition = "Integer";
            // We will call this action to update text
            // for the text renderer
            Action updateText = () =>
            {
                textRenderer.Text =
                    String.Format("Tessellation Factor: {0:#0.0} (+/- to change)"
                                  + "\nPartitioning: {1} (F1,F2,F3,F4 to change)"
                                  + "\nPress F to toggle wireframe"
                                  + "\nPress 1,2,3,4,5,6,7,8 to switch shaders",
                                  tessellationFactor,
                                  tessellationPartition,
                                  DeviceManager.Direct3DDevice.NativePointer);
            };

            Dictionary <Keys, bool> keyToggles = new Dictionary <Keys, bool>();
            keyToggles[Keys.Z] = false;
            keyToggles[Keys.F] = false;

            // Support keyboard/mouse input to rotate or move camera view
            var moveFactor                  = 0.02f; // how much to change on each keypress
            var shiftKey                    = false;
            var ctrlKey                     = false;
            var background                  = Color.White;
            var activeTriTessellator        = tessellateTriIntegerShader;
            var activeQuadTessellator       = tessellateQuadIntegerShader;
            var activeBezierTessellator     = tessellateBezierIntegerShader;
            var activeParametricTessellator = tessellateParametricIntegerShader;
            var showNormals                 = false;
            Window.KeyDown += (s, e) =>
            {
                var context = DeviceManager.Direct3DContext;

                shiftKey = e.Shift;
                ctrlKey  = e.Control;

                switch (e.KeyCode)
                {
                // WASD -> pans view
                case Keys.A:
                    viewMatrix.TranslationVector += new Vector3(moveFactor * 2, 0f, 0f);
                    break;

                case Keys.D:
                    viewMatrix.TranslationVector -= new Vector3(moveFactor * 2, 0f, 0f);
                    break;

                case Keys.S:
                    if (shiftKey)
                    {
                        viewMatrix.TranslationVector += new Vector3(0f, moveFactor * 2, 0f);
                    }
                    else
                    {
                        viewMatrix.TranslationVector -= new Vector3(0f, 0f, 1) * moveFactor * 2;
                    }
                    break;

                case Keys.W:
                    if (shiftKey)
                    {
                        viewMatrix.TranslationVector -= new Vector3(0f, moveFactor * 2, 0f);
                    }
                    else
                    {
                        viewMatrix.TranslationVector += new Vector3(0f, 0f, 1) * moveFactor * 2;
                    }
                    break;

                // Up/Down and Left/Right - rotates around X / Y respectively
                // (Mouse wheel rotates around Z)
                case Keys.Down:
                    worldMatrix *= Matrix.RotationX(moveFactor);
                    rotation    += new Vector3(moveFactor, 0f, 0f);
                    break;

                case Keys.Up:
                    worldMatrix *= Matrix.RotationX(-moveFactor);
                    rotation    -= new Vector3(moveFactor, 0f, 0f);
                    break;

                case Keys.Left:
                    worldMatrix *= Matrix.RotationY(moveFactor);
                    rotation    += new Vector3(0f, moveFactor, 0f);
                    break;

                case Keys.Right:
                    worldMatrix *= Matrix.RotationY(-moveFactor);
                    rotation    -= new Vector3(0f, moveFactor, 0f);
                    break;

                case Keys.T:
                    fps.Show          = !fps.Show;
                    textRenderer.Show = !textRenderer.Show;
                    break;

                case Keys.B:
                    if (background == Color.White)
                    {
                        background = new Color(30, 30, 34);
                    }
                    else
                    {
                        background = Color.White;
                    }
                    break;

                case Keys.G:
                    axisGrid.Show = !axisGrid.Show;
                    break;

                case Keys.P:
                    //    // Pause or resume mesh animation
                    //    meshes.ForEach(m => {
                    //        if (m.Clock.IsRunning)
                    //            m.Clock.Stop();
                    //        else
                    //            m.Clock.Start();
                    //    });
                    var p = Matrix.OrthoRH(3 * (Width / (float)Height), 3, 0.1f, 100f);
                    if (projectionMatrix != p)
                    {
                        projectionMatrix = p;
                    }
                    else
                    {
                        projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.5f, 100f);
                    }
                    break;

                case Keys.X:
                    // To test for correct resource recreation
                    // Simulate device reset or lost.
                    System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                    DeviceManager.Initialize(DeviceManager.Dpi);
                    System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                    break;

                case Keys.Z:
                    keyToggles[Keys.Z] = !keyToggles[Keys.Z];
                    if (keyToggles[Keys.Z])
                    {
                        context.PixelShader.Set(depthPixelShader);
                    }
                    else
                    {
                        context.PixelShader.Set(pixelShader);
                    }
                    break;

                case Keys.F:
                    keyToggles[Keys.F] = !keyToggles[Keys.F];
                    RasterizerStateDescription rasterDesc;
                    if (context.Rasterizer.State != null)
                    {
                        rasterDesc = context.Rasterizer.State.Description;
                    }
                    else
                    {
                        rasterDesc = new RasterizerStateDescription()
                        {
                            CullMode = CullMode.Back,
                            FillMode = FillMode.Solid
                        }
                    };
                    if (keyToggles[Keys.F])
                    {
                        rasterDesc.FillMode      = FillMode.Wireframe;
                        context.Rasterizer.State = ToDispose(new RasterizerState(context.Device, rasterDesc));
                    }
                    else
                    {
                        rasterDesc.FillMode      = FillMode.Solid;
                        context.Rasterizer.State = ToDispose(new RasterizerState(context.Device, rasterDesc));
                    }
                    break;

                case Keys.N:
                    showNormals = !showNormals;
                    break;

                case Keys.D1:
                    context.PixelShader.Set(pixelShader);
                    break;

                case Keys.D2:
                    context.PixelShader.Set(lambertShader);
                    break;

                case Keys.D3:
                    context.PixelShader.Set(phongShader);
                    break;

                case Keys.D4:
                    context.PixelShader.Set(blinnPhongShader);
                    break;

                case Keys.Add:
                    tessellationFactor += 0.2f;
                    tessellationFactor  = Math.Min(tessellationFactor, 64);
                    break;

                case Keys.Subtract:
                    tessellationFactor -= 0.2f;
                    tessellationFactor  = Math.Max(tessellationFactor, 1);
                    break;

                case Keys.F1:
                    tessellationPartition       = "Integer";
                    activeTriTessellator        = tessellateTriIntegerShader;
                    activeQuadTessellator       = tessellateQuadIntegerShader;
                    activeBezierTessellator     = tessellateBezierIntegerShader;
                    activeParametricTessellator = tessellateParametricIntegerShader;
                    break;

                case Keys.F2:
                    tessellationPartition       = "Pow2";
                    activeTriTessellator        = tessellateTriPow2Shader;
                    activeQuadTessellator       = tessellateQuadPow2Shader;
                    activeBezierTessellator     = tessellateBezierPow2Shader;
                    activeParametricTessellator = tessellateParametricPow2Shader;
                    break;

                case Keys.F3:
                    tessellationPartition       = "Fractional Even";
                    activeTriTessellator        = tessellateTriFractionalEvenShader;
                    activeQuadTessellator       = tessellateQuadFractionalEvenShader;
                    activeBezierTessellator     = tessellateBezierFractionalEvenShader;
                    activeParametricTessellator = tessellateParametricFractionalEvenShader;
                    break;

                case Keys.F4:
                    tessellationPartition       = "Fractional Odd";
                    activeTriTessellator        = tessellateTriFractionalOddShader;
                    activeQuadTessellator       = tessellateQuadFractionalOddShader;
                    activeBezierTessellator     = tessellateBezierFractionalOddShader;
                    activeParametricTessellator = tessellateParametricFractionalOddShader;
                    break;

                case Keys.Back:
                    if (triangle.Show && quad.Show && bezier.Show)
                    {
                        triangle.Show   = true;
                        quad.Show       = false;
                        bezier.Show     = false;
                        parametric.Show = false;
                    }
                    else if (triangle.Show && quad.Show)
                    {
                        triangle.Show = false;
                        quad.Show     = false;
                        bezier.Show   = true;
                    }
                    else if (triangle.Show)
                    {
                        quad.Show = true;
                    }
                    else if (bezier.Show)
                    {
                        parametric.Show = true;
                        bezier.Show     = false;
                    }
                    else if (parametric.Show)
                    {
                        triangle.Show = true;
                        quad.Show     = true;
                        bezier.Show   = true;
                    }
                    break;
                }

                updateText();
            };
            Window.KeyUp += (s, e) =>
            {
                // Clear the shift/ctrl keys so they aren't sticky
                if (e.KeyCode == Keys.ShiftKey)
                {
                    shiftKey = false;
                }
                if (e.KeyCode == Keys.ControlKey)
                {
                    ctrlKey = false;
                }
            };
            Window.MouseWheel += (s, e) =>
            {
                if (shiftKey)
                {
                    // Zoom in/out
                    viewMatrix.TranslationVector += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor * 2);
                }
                else
                {
                    // rotate around Z-axis
                    viewMatrix *= Matrix.RotationZ((e.Delta / 120f) * moveFactor);
                    rotation   += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor);
                }
                updateText();
            };

            var lastX = 0;
            var lastY = 0;

            Window.MouseDown += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    lastX = e.X;
                    lastY = e.Y;
                }
            };

            Window.MouseMove += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    var yRotate = lastX - e.X;
                    var xRotate = lastY - e.Y;
                    lastY = e.Y;
                    lastX = e.X;

                    // Mouse move changes
                    // Rotate view (i.e. camera)
                    //viewMatrix *= Matrix.RotationX(xRotate * moveFactor);
                    //viewMatrix *= Matrix.RotationY(yRotate * moveFactor);

                    // Rotate around origin
                    var backup = viewMatrix.TranslationVector;
                    viewMatrix.TranslationVector = Vector3.Zero;
                    viewMatrix *= Matrix.RotationX(xRotate * moveFactor);
                    viewMatrix.TranslationVector = backup;
                    worldMatrix *= Matrix.RotationY(yRotate * moveFactor);

                    updateText();
                }
            };

            // Display instructions with initial values
            updateText();

            #endregion

            var clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            #region Render loop

            // Create and run the render loop
            RenderLoop.Run(Window, () =>
            {
                // Start of frame:

                // Retrieve immediate context
                var context = DeviceManager.Direct3DContext;

                // Clear depth stencil view
                context.ClearDepthStencilView(DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
                // Clear render target view
                context.ClearRenderTargetView(RenderTargetView, background);

                // Create viewProjection matrix
                var viewProjection = Matrix.Multiply(viewMatrix, projectionMatrix);

                // Extract camera position from view
                var camPosition = Matrix.Transpose(Matrix.Invert(viewMatrix)).Column4;
                cameraPosition  = new Vector3(camPosition.X, camPosition.Y, camPosition.Z);

                // If Keys.CtrlKey is down, auto rotate viewProjection based on time
                var time = clock.ElapsedMilliseconds / 1000.0f;

                var perFrame                = new ConstantBuffers.PerFrame();
                perFrame.Light.Color        = new Color(0.8f, 0.8f, 0.8f, 1.0f);
                var lightDir                = Vector3.Transform(new Vector3(1f, -1f, -1f), worldMatrix);
                perFrame.Light.Direction    = new Vector3(lightDir.X, lightDir.Y, lightDir.Z);// new Vector3(Vector3.Transform(new Vector3(1f, -1f, 1f), worldMatrix * worldRotation).ToArray().Take(3).ToArray());
                perFrame.CameraPosition     = cameraPosition;
                perFrame.TessellationFactor = tessellationFactor;
                context.UpdateSubresource(ref perFrame, perFrameBuffer);

                // Render each object

                var perMaterial           = new ConstantBuffers.PerMaterial();
                perMaterial.Ambient       = new Color4(0.2f);
                perMaterial.Diffuse       = Color.White;
                perMaterial.Emissive      = new Color4(0);
                perMaterial.Specular      = Color.White;
                perMaterial.SpecularPower = 20f;
                perMaterial.HasTexture    = 1;
                perMaterial.UVTransform   = Matrix.Identity;
                context.UpdateSubresource(ref perMaterial, perMaterialBuffer);

                if (showNormals)
                {
                    context.GeometryShader.Set(debugNormals);
                }

                var perObject = new ConstantBuffers.PerObject();

                // MESH
                perObject.World = worldMatrix;
                perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                perObject.WorldViewProjection   = perObject.World * viewProjection;
                perObject.ViewProjection        = viewProjection;
                perObject.Transpose();
                context.UpdateSubresource(ref perObject, perObjectBuffer);

                // TRIANGLE
                context.VertexShader.Set(tessellateVertexShader);
                context.HullShader.Set(activeTriTessellator);
                context.DomainShader.Set(tessellateTriDomainShader);
                triangle.Render();

                // QUAD
                context.VertexShader.Set(tessellateVertexShader);
                context.HullShader.Set(activeQuadTessellator);
                context.DomainShader.Set(tessellateQuadDomainShader);
                quad.Render();

                // BEZIER
                context.VertexShader.Set(tessellateVertexShader);
                context.HullShader.Set(activeBezierTessellator);
                context.DomainShader.Set(tessellateBezierDomainShader);
                bezier.Render();

                // PARAMETRIC
                context.VertexShader.Set(tessellateVertexShader);
                context.HullShader.Set(activeParametricTessellator);
                context.DomainShader.Set(tessellateParametricDomainShader);
                parametric.Render();

                // AXIS GRID
                context.VertexShader.Set(vertexShader);
                context.HullShader.Set(null);
                context.DomainShader.Set(null);
                context.GeometryShader.Set(null);

                using (var prevPixelShader = context.PixelShader.Get())
                {
                    perMaterial.HasTexture  = 0;
                    perMaterial.UVTransform = Matrix.Identity;
                    context.UpdateSubresource(ref perMaterial, perMaterialBuffer);
                    context.PixelShader.Set(pixelShader);
                    perObject       = new ConstantBuffers.PerObject();
                    perObject.World = worldMatrix;
                    perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                    perObject.WorldViewProjection   = perObject.World * viewProjection;
                    perObject.ViewProjection        = viewProjection;
                    perObject.Transpose();
                    context.UpdateSubresource(ref perObject, perObjectBuffer);
                    axisGrid.Render();
                    context.PixelShader.Set(prevPixelShader);
                }

                // Render FPS
                fps.Render();

                // Render instructions + position changes
                textRenderer.Render();

                // Present the frame
                Present();
            });
            #endregion
        }
Beispiel #57
0
        public void greedy()
        {
            // start our timer
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();

            // get cost from nearest neighbor
            Random        rand          = new Random();
            double        totalCost     = double.PositiveInfinity;
            int           start         = 0;
            HashSet <int> visitedCities = new HashSet <int>()
            {
                start
            };
            ArrayList path = new ArrayList();

            while (double.IsInfinity(totalCost) || double.IsNaN(totalCost))
            {
                totalCost     = 0;
                start         = rand.Next(Cities.Length);
                visitedCities = new HashSet <int>()
                {
                    start
                };
                path = new ArrayList()
                {
                    Cities[start]
                };

                int current = start;
                do
                {
                    int    bestCity = -1;
                    double bestCost = Double.PositiveInfinity;
                    for (int i = 0; i < Cities.Length; i++)
                    {
                        if (!visitedCities.Contains(i))
                        {
                            double cost = Cities[current].costToGetTo(Cities[i]);
                            if (cost < bestCost)
                            {
                                bestCity = i;
                                bestCost = cost;
                            }
                        }
                    }

                    totalCost += bestCost;
                    visitedCities.Add(bestCity);
                    path.Add(Cities[bestCity]);
                    current = bestCity;
                } while (visitedCities.Count != Cities.Length);
                totalCost += Cities[current].costToGetTo(Cities[start]);
            }

            bssf = new TSPSolution(path);

            timer.Stop();

            Program.MainForm.tbCostOfTour.Text  = "" + bssf.costOfRoute();
            Program.MainForm.tbElapsedTime.Text = Convert.ToString(timer.Elapsed);
        }
Beispiel #58
0
        private void Acquire(TimeSpan timeout)
        {
            logger.Trace($"Trying to acquire lock for {resource} within {timeout.TotalSeconds} seconds");

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

            string id  = $"{resource}:{DocumentTypes.Lock}".GenerateHash();
            Uri    uri = UriFactory.CreateDocumentUri(storage.Options.DatabaseName, storage.Options.CollectionName, id);

            while (string.IsNullOrEmpty(resourceId))
            {
                // default ttl for lock document
                TimeSpan ttl = DateTime.UtcNow.Add(timeout).AddMinutes(1).TimeOfDay;

                try
                {
                    Task <DocumentResponse <Lock> > readTask = storage.Client.ReadDocumentWithRetriesAsync <Lock>(uri);
                    readTask.Wait();

                    if (readTask.Result.Document != null)
                    {
                        Lock @lock = readTask.Result.Document;
                        @lock.ExpireOn   = DateTime.UtcNow.Add(timeout);
                        @lock.TimeToLive = (int)ttl.TotalSeconds;

                        Task <ResourceResponse <Document> > updateTask = storage.Client.UpsertDocumentWithRetriesAsync(storage.CollectionUri, @lock);
                        updateTask.Wait();

                        if (updateTask.Result.StatusCode == HttpStatusCode.OK)
                        {
                            resourceId = id;
                            break;
                        }
                    }
                }
                catch (AggregateException ex) when(ex.InnerException is DocumentClientException clientException && clientException.StatusCode == HttpStatusCode.NotFound)
                {
                    Lock @lock = new Lock
                    {
                        Id         = id,
                        Name       = resource,
                        ExpireOn   = DateTime.UtcNow.Add(timeout),
                        TimeToLive = (int)ttl.TotalSeconds
                    };

                    Task <ResourceResponse <Document> > createTask = storage.Client.UpsertDocumentWithRetriesAsync(storage.CollectionUri, @lock);

                    createTask.Wait();

                    if (createTask.Result.StatusCode == HttpStatusCode.OK || createTask.Result.StatusCode == HttpStatusCode.Created)
                    {
                        resourceId = id;
                        break;
                    }
                }

                // check the timeout
                if (acquireStart.ElapsedMilliseconds > timeout.TotalMilliseconds)
                {
                    throw new DocumentDbDistributedLockException($"Could not place a lock on the resource '{resource}': Lock timeout.");
                }

                // sleep for 2000 millisecond
                logger.Trace($"Unable to acquire lock for {resource}. Will check try after 2 seconds");
                System.Threading.Thread.Sleep(2000);
            }

            logger.Trace($"Acquired lock for {resource} in {acquireStart.Elapsed.TotalMilliseconds:#.##} ms");
        }
    }
Beispiel #59
0
        public override bool Test(System.Diagnostics.Stopwatch sw)
        {
            bool isSuccess = true;

            return(isSuccess);
        }
Beispiel #60
0
        public void branchAndBound()
        {
            // start our timer
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();

            int solNumber          = 0;
            int statesCreated      = 0;
            int branchesConsidered = 0;
            int statesStored       = 0;
            int statesPruned       = 0;

            // generate bssf
            initBSSF();
            double bsf     = costOfBssf();
            double initial = bsf;

            // generate initial cost matrix
            state s = new state(Cities.Length);

            for (int i = 0; i < Cities.Length; i++)
            {
                for (int j = 0; j < Cities.Length; j++)
                {
                    if (i == j)
                    {
                        s.costMatrix[i, j] = double.PositiveInfinity;
                    }
                    else
                    {
                        s.costMatrix[i, j] = Cities[i].costToGetTo(Cities[j]);
                    }
                }
            }
            reduce(s);

            // create priority queue and init with initial state
            PriorityQueue <state> pq = new PriorityQueue <state>();

            pq.Enqueue(s, 0);

            // loop - while !empty and cost < bssf{
            while (pq.Count > 0)
            {
                state cur = pq.Dequeue();
                if (cur.cost > bsf)
                {
                    statesPruned++;
                    continue;
                }

                state  nextInc = cur;
                state  nextEx;
                int    cityOut     = -1;
                int    cityIn      = -1;
                double improvement = double.NegativeInfinity;

                // for all edges
                for (int i = 0; i < cur.numEdges; i++)
                {
                    for (int j = 0; j < cur.numEdges; j++)
                    {
                        // if edge is 0
                        if (cur.costMatrix[i, j] == 0)
                        {
                            // calculate best if included
                            state tmp = includeEdge(cur, i, j);
                            branchesConsidered++;

                            // and improvement over exclude
                            double tmpImprov = worstCase(cur, i, j) - tmp.cost;

                            // and if keep if best improvement so far
                            if (improvement < tmpImprov)
                            {
                                nextInc     = tmp;
                                cityOut     = i;
                                cityIn      = j;
                                improvement = tmpImprov;
                            }
                        }
                    }
                }

                if (nextInc.cost < bsf)
                {
                    // is this state a complete solution?
                    if (nextInc.numAddedEdges == nextInc.numEdges)
                    {
                        // transform into bssf
                        ArrayList route = new ArrayList();
                        int       city  = 0;
                        do
                        {
                            route.Add(Cities[city]);
                            city = nextInc.outEdges[city];
                        } while (city != 0);

                        // update
                        bssf = new TSPSolution(route);
                        bsf  = costOfBssf();
                        solNumber++;
                    }
                    else
                    {
                        // we've found the state with the best improvement
                        // so calculate create the exclude state;
                        nextEx = new state(cur);
                        nextEx.costMatrix[cityOut, cityIn] = double.PositiveInfinity;
                        reduce(nextEx);

                        // enqueue both of the new states
                        pq.Enqueue(nextInc, Convert.ToInt32(nextInc.cost / (nextInc.numAddedEdges + 1)));
                        statesCreated += 2;

                        // enqueue if not infinite
                        if (nextEx.cost < bsf)
                        {
                            pq.Enqueue(nextEx, Convert.ToInt32(nextEx.cost / (nextInc.numAddedEdges + 1)));
                        }
                        else
                        {
                            statesPruned++;
                        }

                        // die with soemthing if we never actually expanded the state
                        if (nextInc == cur)
                        {
                            throw new NotSupportedException();
                        }
                    }
                    if (pq.Count > statesStored)
                    {
                        statesStored = pq.Count;
                    }
                }
            } // end while loop

            timer.Stop();

            Program.MainForm.tbCostOfTour.Text  = " " + bssf.costOfRoute();
            Program.MainForm.tbElapsedTime.Text = Convert.ToString(timer.Elapsed);
            Program.MainForm.tbStateInfo.Text   = Convert.ToString(statesCreated) + "-" + Convert.ToString(statesStored) + "-" + Convert.ToString(statesPruned);
            Program.MainForm.tbInitialBSF.Text  = Convert.ToString(initial);
            Program.MainForm.tbSolutionNum.Text = Convert.ToString(solNumber);
            // do a refresh.
            Program.MainForm.Invalidate();
        } // end function