示例#1
0
    // Use this for initialization
    void Start()
    {
        if (SVGFile != null) {
          Stopwatch w = new Stopwatch();

          w.Reset();
          w.Start();
          ISVGDevice device;
          if(useFastButBloatedRenderer)
        device = new SVGDeviceFast();
          else
        device = new SVGDeviceSmall();
          m_implement = new Implement(this.SVGFile, device);
          w.Stop();
          long c = w.ElapsedMilliseconds;

          w.Reset();
          w.Start();
          m_implement.StartProcess();
          w.Stop();
          long p = w.ElapsedMilliseconds;

          w.Reset();
          w.Start();
          renderer.material.mainTexture = m_implement.GetTexture();
          w.Stop();
          long r = w.ElapsedMilliseconds;
          UnityEngine.Debug.Log("Construction: " + Format(c) + ", Processing: " + Format(p) + ", Rendering: " + Format(r));

          Vector2 ts = renderer.material.mainTextureScale;
          ts.x *= -1;
          renderer.material.mainTextureScale = ts;
          renderer.material.mainTexture.filterMode = FilterMode.Trilinear;
        }
    }
示例#2
0
 public void ActivateUI(NavigationController.directions d)
 {
     if (CategoryUI.activeInHierarchy)
     {
         SleepTimer?.Reset();
         SleepTimer?.Start();
         StartCoroutine(MoveVidToTop());
         StartCoroutine(UnfadeCategories());
     }
 }
示例#3
0
    public static void Main(string[] args)
    {
        Stopwatch sw = new Stopwatch();
        int status;

        // Generate input data
        sw.Start();
        const int SIZE = 384;

        List<int> firstVector = new List<int>();
        List<int> secondVector = new List<int>();

        const int Scalar = 3;

        Random random = new Random();
        for (int i = 0; i < SIZE; i++)
        {
                firstVector.Add(random.Next(0, 100));
                secondVector.Add(random.Next(0, 100));
        }

        sw.Stop();
        Console.WriteLine("Generating input data:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);

        // DFE Output
        sw.Reset();
        sw.Start();
        List<int> dataOutDFE = VectorAdditionDfe(SIZE, firstVector, secondVector, Scalar);
        sw.Stop();
        Console.WriteLine("DFE vector addition total time:\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);

        // CPU Output
        sw.Reset();
        sw.Start();
        List<int> dataOutCPU = VectorAdditionCpu(SIZE, firstVector, secondVector, Scalar);
        sw.Stop();
        Console.WriteLine("CPU vector addition time:\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);

        // Checking results
        sw.Reset();
        sw.Start();
        status = Check(dataOutDFE, dataOutCPU, SIZE);
        sw.Stop();
        Console.WriteLine("Checking results:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);

        if (status > 0)
        {
            Console.WriteLine("Test failed {0} times! ", status);
            Environment.Exit(-1);
        }
        else
        {
            Console.WriteLine("Test passed!");
        }
    }
示例#4
0
    /// <summary> Calculates simpleDfe and simpleCpu and
    /// checks if they return the same value. 
    /// </summary>
    /// <param name = "args"> Command line arguments </param>
    public static void Main(string[] args)
    {
        Stopwatch sw = new Stopwatch();
        int status;

        sw.Start();
        const int SIZE = 1024;
        List<double> dataIn = new List<double>();

        for (int i = 0; i < SIZE; i++)
        {
            dataIn.Add(i + 1);
        }

        sw.Stop();
        Console.WriteLine("Generating input data:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);

        // DFE Output
        sw.Reset();
        sw.Start();
        List<double> dataOutDFE = SimpleDFE(SIZE, dataIn);
        sw.Stop();
        Console.WriteLine("DFE simple total time:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);

        // CPU Output
        sw.Reset();
        sw.Start();
        List<double> dataOutCPU = SimpleCPU(SIZE, dataIn);
        sw.Stop();
        Console.WriteLine("CPU simple total time:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);

        // Checking results
        sw.Reset();
        sw.Start();
        status = Check(dataOutDFE, dataOutCPU, SIZE);
        sw.Stop();
        Console.WriteLine("Checking results:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);

        if (status > 0)
        {
            Console.WriteLine("Test failed {0} times! ", status);
            Environment.Exit(-1);
        }
        else
        {
            Console.WriteLine("Test passed!");
        }
    }
示例#5
0
    public static void Main()
    {
        Stopwatch watch = new Stopwatch();
        Random rand = new Random();
        watch.Start();
        for (int i = 0; i < iterations; i++)
            DayOfYear1(rand.Next(1, 13), rand.Next(1, 29));
        watch.Stop();
        Console.WriteLine("Local array: " + watch.Elapsed);
        watch.Reset();
        watch.Start();
        for (int i = 0; i < iterations; i++)
            DayOfYear2(rand.Next(1, 13), rand.Next(1, 29));
        watch.Stop();
        Console.WriteLine("Static array: " + watch.Elapsed);

        // trying to modify static int []
        daysCumulativeDays[0] = 18;
        foreach (int days in daysCumulativeDays)
        {
            Console.Write("{0}, ", days);
        }
        Console.WriteLine("");

        // MY_STR_CONST = "NOT CONST";
    }
示例#6
0
    void Start()
    {
        Stopwatch timer = new Stopwatch();
        timer.Start();
        worldTree = new WorldTree(8);
        //worldTree.ExpandNode(3);

        TestWTI2(30);

        timer.Stop();
           // DumpToFile("WorldTreeDump2.txt");

        DebugOutput.Shout("timer says: " + timer.ElapsedMilliseconds.ToString());

        DebugOutput.Shout("there is " + worldTree.GetIndiceCount().ToString() + " nodes");
        timer.Reset();
        timer.Start();

        TestWTI2(10);
        //DumpToFile("WorldTreeDump.txt");

        //TestWTI2();
        //TestWTI(new Vector3(14, 14,14));

        timer.Stop();
        wti = new WorldTreeInterface(worldTree, transform.position);

        DebugOutput.Shout("timer says: " + timer.ElapsedMilliseconds.ToString());
        DebugOutput.Shout("there is " + worldTree.GetIndiceCount().ToString() + " nodes");

        DumpToFile("WorldTreeDump.txt");
        wti.DumpAllToFile("WTIDump.txt");
    }
示例#7
0
 static void Main()
 {
     Database db = new Database();
     using (db)
     {
         var employees = db.Employees;
         Stopwatch sw = new Stopwatch();
         Console.WriteLine("EmployeeName | EmployeeDepartment | EmployeeTown");
         sw.Start();
         foreach (var item in employees)
         {
             Console.WriteLine("{0} | {1} | {2}", item.FirstName, item.Department.Name, item.Address.Town.Name);
         }
         sw.Stop();
         Console.WriteLine();
         Console.WriteLine("Time with problem N+1: {0}", sw.Elapsed);
         Console.WriteLine("338 queryes with proffiler");
         Console.WriteLine("------------------------------------------------------------");
         sw.Reset();
         sw.Start();
         foreach (var item in employees.Include("Department").Include("Address.Town"))
         {
             Console.WriteLine("{0} | {1} | {2}", item.FirstName, item.Department.Name, item.Address.Town.Name);
         }
         sw.Stop();
         Console.WriteLine("Time withouth problem N+1: {0}", sw.Elapsed);
         Console.WriteLine("1 queryes with proffiler");
     }
     
 }
示例#8
0
 private void ResetRecords()
 {
     clcStopwatch?.Reset();
     relStopwatch?.Reset();
     wrtStopwatch?.Reset();
     glbStopwatch?.Reset();
 }
    private static void Main()
    {
        Stopwatch timer = new Stopwatch();
        timer.Start();
        Console.WriteLine("Creating products data.....");
        OrderedMultiDictionary<double, string> products = GenerateProducts();
        timer.Stop();
        Console.WriteLine("Time needed: "+timer.Elapsed);
        timer.Reset();
        double lowestPrice = randomNumberGenerator.NextDouble() * (MaxPrice/2 - MinPrice) + MinPrice;
        double highestPrice = randomNumberGenerator.NextDouble() * (MaxPrice - lowestPrice) + lowestPrice;
        bool isFirstSearch = true;
        timer.Start();

        for (int i = 0; i < CountSearches; i++)
        {
            IEnumerable<KeyValuePair<double, ICollection<string>>> extract = products.Range(lowestPrice, true, highestPrice, true).Take(CountResults);
            if (isFirstSearch)
            {
                timer.Stop();
                Console.WriteLine("First search result");
                Console.WriteLine("Price range from {0:F2} to {1:F2}:", lowestPrice, highestPrice);
                PrintSearchResults(extract);
                isFirstSearch = false;
                Console.WriteLine("Time needed: {0}\n {1} more to go......", timer.Elapsed, CountSearches - 1);
                timer.Start();
            }
        }
        timer.Stop();
        Console.WriteLine("Total search time: "+timer.Elapsed);
    }
示例#10
0
 public static void playGame(Game.Client client)
 {
     GameInit gameInit = client.ready();
     GameInfo gameInfo = gameInit.GameInfo;
     Solution solution = new Solution(gameInit);
     Stopwatch stopwatch = new Stopwatch();
     stopwatch.Start();
     while (true) {
         stopwatch.Stop();
         synchronize(gameInfo.NextWorldModelTimeEstimateMs - stopwatch.Elapsed.Milliseconds);
         gameInfo = client.getGameInfo();
         stopwatch.Reset();
         stopwatch.Start ();
         if (gameInfo.GameStatus == GameStatus.FINISHED)
         {
             solution.EndOfGame(gameInfo.GameResult);
             break;
         }
         if (gameInfo.IsMyTurn)
         {
             Command command = solution.playTurn(gameInfo.WorldModel, gameInfo.Cycle);
             client.sendCommand(command);
         }
     }
 }
        private void Initialize()
        {
            SM = new StateMachine <States, Signals>();

            // Get the active state object to subscribe to OnStateEnter and OnStateLeave events.
            IState activeState = SM.CreateState(States.Active);

            // We want to only subscribe to OnStateEnter event of Stopped state. We can write an anonymous function such as:
            SM.CreateState(States.Stopped, States.Active).OnStateEnter += () => { stopwatch?.Stop(); Console.WriteLine("Elapsed time: " + stopwatch?.ElapsedMilliseconds.ToString()); };
            // We also only want to listen OnStateEnter event of Running state.
            SM.CreateState(States.Running, States.Active).OnStateEnter += () => { stopwatch?.Start(); };

            // Subscribe to activeState's event with anonymous functions.
            activeState.OnStateEnter += () => { stopwatch = stopwatch ?? new Stopwatch(); };
            activeState.OnStateLeave += () => { stopwatch?.Reset(); };

            // We do not need to get the signal objects if we don't want to. We can emit the signal with the Signals enum.
            SM.ConnectSignal(Signals.Reset, States.Active, States.Active, out ISignal resetSignal);
            SM.ConnectSignal(Signals.StartStop, States.Stopped, States.Running, out ISignal startStopSignal);
            SM.ConnectSignal(Signals.StartStop, States.Running, States.Stopped);

            SM.SetInitialState(States.Active);
            SM.SetInitialState(States.Stopped, States.Active);

            SM.OnStateChanged += SM_OnStateChanged;
        }
示例#12
0
        public KinectPlayer(Vector3 platformData)
        {
            JumpLeft = false;
            progressBarBackground = new Sprite();
            progressBarBackground.Rectangle = new Rectangle(0,0,GameConstants.HorizontalGameResolution,GameConstants.VerticalGameResolution/80);
            progressBarFrame = new Sprite();
            progressBarFrame.Rectangle = new Rectangle(0,0,GameConstants.HorizontalGameResolution,GameConstants.VerticalGameResolution/80);
            newGameCounter = new Stopwatch();
            newGameCounter.Reset();

            nyanSprite = new Sprite();
            nyanSprite.Rectangle = new Rectangle(-(int)GameConstants.nyanDimensions.X, (int)GameConstants.VerticalGameResolution/25, (int)GameConstants.nyanDimensions.X, (int)GameConstants.nyanDimensions.Y);

            progressBarRectangle=new Rectangle(0,0,GameConstants.HorizontalGameResolution,GameConstants.VerticalGameResolution/80);
            progressBarTextures = new Texture2D[3];
            modelPosition = new Hero(new ObjectData3D
                                      {
                                          Scale = new Vector3(GameConstants.HeroScale),
                                          Rotation = new Vector3(0.0f)
                                      });

            currentStance = GameConstants.PlayerStance.GameSettingsSetup;
            lastStance = GameConstants.PlayerStance.GameSettingsSetup;
            isMotionCheckEnabled = true;
            modelGroundLevel = platformData.Y+GameConstants.PlayerModelHeight;
            modelPosition.objectArrangement.Position = new Vector3(platformData.X,modelGroundLevel,platformData.Z);
            modelPosition.oldArrangement = modelPosition.objectArrangement;
            currentModel = modelUp;
        }
示例#13
0
        public override async Task OnKeyUp(StreamDeckEventPayload args)
        {
            var elapsedSeconds = _ButtonHoldTimer != null ? _ButtonHoldTimer.Elapsed.TotalSeconds : 0;

            _ButtonHoldTimer?.Reset();

            // Cheer 142 cpayette 12/3/19
            // Cheer 142 roberttables 12/3/19

            if (elapsedSeconds > 2)
            {
                await StopTestsAsync();

                return;
            }
            else if (SettingsModel.State == UnitTestButtonState.NoTestsRunning)
            {
                await StartTests(args);

                return;
            }

            // TODO:  Figure out what to do in each of the other states...
            // NOTE: If tests have completed, perhaps open a report of those tests
        }
    //Float operations
    public static TimeSpan MesureFloatOperationsPerformance(float num, string operation, Stopwatch stopwatch)
    {
        stopwatch.Reset();
        switch (operation)
        {
            case "square root":
                {
                    stopwatch.Start();
                    Math.Sqrt(num);
                    stopwatch.Stop();

                    return stopwatch.Elapsed;
                }
            case "natural logarithm":
                {
                    stopwatch.Start();
                    Math.Log(num);
                    stopwatch.Stop();

                    return stopwatch.Elapsed;
                }
            case "sinus":
                {
                    stopwatch.Start();
                    Math.Sin(num);
                    stopwatch.Stop();

                    return stopwatch.Elapsed;
                }
            default:
                throw new ArgumentException("Invalid operations");
        }
    }
示例#15
0
    // Use this for initialization
    void Start()
    {
        file = new System.IO.StreamWriter("K:\\Logs\\ArrayTest.txt");
        array1 = new GameObject[cycles];
        array2 = new GameObject[cycles];
        stopWatch = new Stopwatch();
        GameObject test = Instantiate(memCell, Vector3.zero, Quaternion.identity) as GameObject;
        for (int i = 0; i< cycles; i++){
            array1[i] = Instantiate(memCell, new Vector3(i,0f,0f), Quaternion.identity) as GameObject;
            array1[i].SetActive(false);
        }

        for (int i=0; i<cycles; i++){
            stopWatch.Reset ();
            stopWatch.Start();

            //write(array1[i], i);
            write(i);

            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            file.WriteLine(ts.TotalMilliseconds + "\t");

        }
    }
示例#16
0
        static void Main()
        {
            var list = new List<int>();
            list.AddRange(Enumerable.Range(1, short.MaxValue/2));

            var watch = new Stopwatch();

            watch.Start();
            var result1 = Method1(list);
            watch.Stop();

            Console.WriteLine("Elapsed Ticks for Method1: {0}, with result: {1}", watch.ElapsedTicks, result1);
            var watch1Ticks = watch.ElapsedTicks;

            watch.Reset();
            watch.Start();
            var result2 = Method2(list);
            watch.Stop();

            Console.WriteLine("Elapsed Ticks for Method2: {0}, with result: {1}", watch.ElapsedTicks, result2);
            var watch2Ticks = watch.ElapsedTicks;
            double result = (double) watch1Ticks / watch2Ticks - 1.0; 
            Console.WriteLine("Method2 is faster that Method1 in {0:P}", result);

            Console.ReadKey();
        }
示例#17
0
 public void ActivateUI(NavigationController.directions d)
 {
     if (mediaController.IntermissionPlayer.isActiveAndEnabled)
     {
         return;
     }
     else
     {
         StartCoroutine(MoveVidToTop());
         SleepTimer?.Reset();
         SleepTimer?.Start();
         if (CategoryUI.activeInHierarchy)
         {
             StartCoroutine(UnfadeCategories());
         }
     }
 }
示例#18
0
        public Civilian(Vector2 origin, Texture2D texture)
            : base(origin, texture)
        {
            lifeTime = new Stopwatch();
            lifeTime.Reset();

            this.Heading = new Vector2(0, 1);
            shot = false;
        }
        /// <summary>
        /// Call to stop recording to FileStream.
        /// </summary>
        public void StopRecording()
        {
            MMALLog.Logger.LogInformation("Stop recording.");

            _recordToFileStream = false;
            _receivedIFrame     = false;
            _recordingElapsed?.Stop();
            _recordingElapsed?.Reset();
        }
    public void Should_be_fast()
    {
        var stopWatch = new Stopwatch();
        stopWatch.Start();
        for (var i = 0; i < 10000; i++)
            SaveFocusSession(i.ToString());

        Assert.That(stopWatch.Elapsed.TotalSeconds, Is.LessThan(10));
        stopWatch.Reset();

        var allSessions = LoadAllSessions.Run();
        Assert.That(stopWatch.Elapsed.Milliseconds, Is.LessThan(300));
        Assert.That(allSessions.Count, Is.EqualTo(10000));

        stopWatch.Reset();
        Console.WriteLine(allSessions.Sum(x => x.Minutes));
        Console.WriteLine(stopWatch.Elapsed);
    }
示例#21
0
        protected virtual void Dry(CancellationTokenPair pair)
        {
            byte unitsToRemove;
            {
                using var lls = LaundryFlags.SpinLock(TimeSpan.FromSeconds(2));
                unitsToRemove = lls.LoadedLaundryItem != LaundryItems.InvalidItem
                    ? lls.LoadedLaundryItem.Dampness
                    : throw new StateLogicErrorException(
                                          "It should not be possible to lack laundry during the wash cycle.");
            }
            byte     unitsToDeduct = unitsToRemove;
            TimeSpan timeRequired  = TimeToDecrementDampnessPerUnit * unitsToRemove;
            double   randomFactor  = RandomNumberSource.Next(1, 11) / 100.0; //introduce randomness factor of 10%, either direction

            Debug.Assert(randomFactor >= 0.0 && randomFactor <= 0.11);
            TimeSpan randomTimeToAddOrSub = timeRequired * randomFactor;

            Debug.Assert(randomTimeToAddOrSub <= timeRequired);
            bool negate = RandomNumberSource.Next(1, 3) == 1;

            randomTimeToAddOrSub = negate ? -randomTimeToAddOrSub : +randomTimeToAddOrSub;
            timeRequired        += randomTimeToAddOrSub;

            Stopwatch sw = null;

            try
            {
                sw = HighPrecisionTimer;
                sw.Restart();
                SimulateWait(pair, timeRequired);
            }
            catch (OperationCanceledException)
            {
                if (sw == null)
                {
                    string log = "For some reason the stopwatch is null.";
                    TerminationHelper.TerminateApplication(log);
                    return;
                }

                TimeSpan elapsed    = sw.Elapsed;
                double   percentage = elapsed >= timeRequired ? 1.0 : elapsed / timeRequired;
                unitsToDeduct = Convert.ToByte(Math.Floor(unitsToRemove * percentage));
                throw;
            }
            finally
            {
                sw?.Reset();
                byte newSetting = (byte)(unitsToRemove - unitsToDeduct);
                Debug.Assert(newSetting <= unitsToRemove);
                using var lls = LaundryFlags.SpinLock(TimeSpan.FromSeconds(2));
                lls.SetDampFactor(newSetting);
                Debug.Assert(lls.LoadedLaundryItem.Dampness <= unitsToRemove);
            }
        }
示例#22
0
    /* 3 Write a program that finds a set of words (e.g. 1000 words)
     * in a large text (e.g. 100 MB text file). Print how many times
     * each word occurs in the text.
     * Hint: you may find a C# trie in Internet.
     * */
    static void Main(string[] args)
    {
        var dict = new Dictionary<string, int>();
        var knownCount = new Dictionary<string, int>
        {
            {"foo", 10*1000},
            {"bar", 20*1000},
            {"quux",30*1000},
            {"frob",40*1000},
            {"asdf",50*1000}
        };
        var trie = new Trie<int>();

        var sw = new Stopwatch();

        sw.Start();

        // obviously, I couldn't zip the 100 MB file
        // use "bin\debug\generator.cs" to generate it if you want

        using (var reader = new StreamReader("text.txt"))
            foreach (var word in Words(reader))
                dict[word] = 1 + dict.GetOrDefault(word, 0);

        sw.Stop();
        /*
        foreach (var kvp in knownCount)
            Debug.Assert(dict[kvp.Key] == kvp.Value);
        */

        Console.WriteLine("Using hashtable: " + sw.Elapsed.TotalMilliseconds);

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

        using (var reader = new StreamReader("text.txt"))
            foreach (var word in Words(reader))
                trie.Add(word, 1 + trie.GetOrDefault(word, 0));

        sw.Stop();

        foreach (var kvp in dict)
            Debug.Assert(trie.Find(kvp.Key) == kvp.Value);

        // the trie would probably do much better compared to a hashtable when used on
        // natural text with large amount of repetition and low average word length
        // it is however extremely space inefficient

        // at any rate, I'd be surprised if this implementation could beat .NET's build-in
        // hashtable

        Console.WriteLine("Using trie: " + sw.Elapsed.TotalMilliseconds);
    }
示例#23
0
 internal void LoadEntryPoints()
 {
   int num = 0;
   FieldInfo[] fields = this.DelegatesClass.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
   if (fields == null)
     throw new InvalidOperationException("The specified type does not have any loadable extensions.");
   Stopwatch stopwatch = new Stopwatch();
   stopwatch.Reset();
   stopwatch.Start();
   foreach (FieldInfo fieldInfo in fields)
   {
     Delegate @delegate = this.LoadDelegate(fieldInfo.Name, fieldInfo.FieldType);
     if (@delegate != null)
       ++num;
     lock (this.SyncRoot)
       fieldInfo.SetValue((object) null, (object) @delegate);
   }
   this.rebuildExtensionList = true;
   stopwatch.Stop();
   stopwatch.Reset();
 }
示例#24
0
 private static void stringConcat(String[] ss, int n)
 {
     // This is *very* slow for large n
     Stopwatch t = new Stopwatch();
     t.Reset();
     t.Start();
     String res = "";
     for (int i=0; i<n; i++)
       res += ss[i];
     t.Stop();
     Console.WriteLine("Result length:{0,7};    time:{1,8:F3} sec\n" ,
           res.Length, t.ElapsedMilliseconds/1000.0);
 }
    public int Receive(out string s)
    {
        s = "";

        try
        {
            if (tc.Connected == false) return 1;

            tc.ReceiveTimeout = to;
            Stream st = tc.GetStream();

            st.ReadTimeout = to;

            int len;

            do
            {
                len = st.ReadByte();
            } while (len == 0);

            Stopwatch sw = new Stopwatch();
            sw.Reset();
            //sw.Start();

            for (int i = 0; i < len && sw.ElapsedMilliseconds < to * len; i++)
            {
                int b;
                do
                {
                    b = st.ReadByte();
                }
                while (b == -1 && sw.ElapsedMilliseconds < to * len);

                s += (char)b;
            }

            sw.Stop();
            if (sw.ElapsedMilliseconds < to * len)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }
        catch (Exception e)
        {
            return 1;
        }
    }
示例#26
0
        //TODO: Handle age-restricted and country-restricted videos
        public async Task <DumpResult> DumpAsync(string videoId)
        {
            sw_parsing?.Reset();
            sw_parsing?.Reset();

            sw?.Start();
            var buffer  = _pool.Rent(60000);
            var content = await GetJsonAsync($"https://www.youtube.com/watch?v={videoId}" +
                                             $"&gl={_config.Geolocation}" +
                                             $"&hl={_config.Language}" +    //Set the language
                                             $"&has_verified=1" +
                                             $"&bpctr=9999999999", buffer); //For videos that 'may be inappropriate or offensive for some users'

            sw_parsing?.Start();

            var config = ParseConfig(content);

            _pool.Return(buffer);
            var video = config.Video;

            var player_url = "https://www.youtube.com/" + config.PlayerUrl;

            var data = (config.RawAdaptiveStreams + "," +
                        config.RawMixedStream).Split(',');

            video.MediaStreams = await ParseMediaStreamsAsync(data, player_url);

            sw_parsing?.Stop();
            sw?.Stop();

            return(new DumpResult
            {
                ElapsedTime = sw.Elapsed,
                ElapsedParsingTime = sw_parsing.Elapsed,
                Video = video
            });
        }
示例#27
0
	public int Run()
	{
		Stopwatch sw = new Stopwatch();		
		AutoResetEvent are = new AutoResetEvent(false);
		sw.Start();
		bool ret = are.WaitOne(1000);//,false);
		sw.Stop();
		//We should never get signaled
		if(ret)
		{
			Console.WriteLine("AutoResetEvent should never be signalled.");
			return -1;
		}

		if(sw.ElapsedMilliseconds < 900)
		{
			Console.WriteLine("It should take at least 900 milliseconds to call bool ret = are.WaitOne(1000,false);.");
			Console.WriteLine("sw.ElapsedMilliseconds = " + sw.ElapsedMilliseconds);			
			return -2;
		}
		
		are.Set();
		if(!are.WaitOne(0))//,false))
		{
			Console.WriteLine("Signalled event should always return true on call to !are.WaitOne(0,false).");
			return -3;
		}
		
		sw.Reset();		
		sw.Start();
		ret = are.WaitOne(1000);//,false);
		sw.Stop();
		//We should never get signaled
		if(ret)
		{
			Console.WriteLine("AutoResetEvent should never be signalled after is is AutoReset.");
			return -4;
		}

		if(sw.ElapsedMilliseconds < 900)
		{
			Console.WriteLine("It should take at least 900 milliseconds to call bool ret = are.WaitOne(1000,false);.");
			Console.WriteLine("sw.ElapsedMilliseconds = " + sw.ElapsedMilliseconds);			
			return -5;
		}
		
		return 100;
		
	}
示例#28
0
    static void Main()
    {
        string fileLocation = "@../../text.txt";
        StreamReader reader = new StreamReader(fileLocation);
        string text;

        using(reader)
        {
            text = reader.ReadToEnd();
        }

        char[] separators = new char[] { '.', ',', ' ', '?', '!', '-', '(', ')' };

        string[] words = text.Split(separators, StringSplitOptions.RemoveEmptyEntries);

        WordsTree tree = new WordsTree();
        Dictionary<string, int> dict = new Dictionary<string, int>();

        Stopwatch watch = new Stopwatch();
        watch.Start();

        foreach (var word in words)
        {
            tree.Add(word);
        }

        Console.WriteLine(tree.SearchOccurences("sit"));
        watch.Stop();
        Console.WriteLine("Time elapsed trie structure: {0}", watch.Elapsed);

        watch.Reset();
        watch.Start();

        foreach (var word in words)
        {
            if (dict.ContainsKey(word))
            {
                dict[word]++;
            }
            else
            {
                dict.Add(word, 1);
            }
        }

        Console.WriteLine(dict["sit"]);
        watch.Stop();
        Console.WriteLine("Time elapsed dictionary: {0}", watch.Elapsed);
    }
示例#29
0
 private static void stringBuilder(String[] ss, int n)
 {
     // This is fast for all n
     Stopwatch t = new Stopwatch();
     t.Reset();
     t.Start();
     String res = null;
     StringBuilder buf = new StringBuilder();
     for (int i=0; i<n; i++)
       buf.Append(ss[i]);
     res = buf.ToString();
     t.Stop();
     Console.WriteLine("Result length:{0,7};    time:{1,8:F3} sec\n" ,
           res.Length, t.ElapsedMilliseconds/1000);
 }
示例#30
0
文件: Invoke.cs 项目: MrJoy/UnitySVG
    private void Start()
    {
        //yield return new WaitForSeconds(0.1f);
        if(SVGFile != null) {
          Stopwatch w = new Stopwatch();

          w.Reset();
          w.Start();
          ISVGDevice device;
          if(fastRenderer)
        device = new SVGDeviceFast();
          else
        device = new SVGDeviceSmall();
          var implement = new Implement(SVGFile, device);
          w.Stop();
          long c = w.ElapsedMilliseconds;

          w.Reset();
          w.Start();
          implement.StartProcess();
          w.Stop();
          long p = w.ElapsedMilliseconds;

          w.Reset();
          w.Start();
          var myRenderer = GetComponent<Renderer>();
          var result = implement.GetTexture();
          result.wrapMode   = wrapMode;
          result.filterMode = filterMode;
          result.anisoLevel = anisoLevel;
          myRenderer.material.mainTexture = result;
          w.Stop();
          long r = w.ElapsedMilliseconds;
          UnityEngine.Debug.LogFormat("Construction: {0} ms, Processing: {1} ms, Rendering: {2} ms", c, p, r);
        }
    }
示例#31
0
        protected virtual void Soak(CancellationTokenPair token)
        {
            Stopwatch sw = null;

            try
            {
                Debug.WriteLine("Beginning Cleanse Soak");
                byte oldDampness;
                byte newDampness;
                sw = HighPrecisionTimer;
                sw.Reset();
                sw.Start();
                {
                    using LockedLaundryStatus lls =
                              LaundryFlags.SpinLock(token.IndividualToken, TimeSpan.FromSeconds(2));
                    var res = lls.SoakLaundry() ??
                              throw new StateLogicErrorException(
                                        "It is supposed to be impossible to start the machine without laundry in it.");
                    oldDampness = res.OldDampness;
                    newDampness = res.NewDampness;
                }

                Debug.Assert(newDampness >= oldDampness);
                int      dampnessUnitsIncrease = newDampness - oldDampness;
                TimeSpan totalTimeRequired     = TimeToIncrementDampnessPerUnit * dampnessUnitsIncrease;
                TimeSpan timeRemaining         = totalTimeRequired - sw.Elapsed;
                if (timeRemaining > TimeSpan.Zero)
                {
                    SimulateWait(token, timeRemaining, "Beginning soak wait", "Ending soak wait");
                }
            }
            catch (StateLogicErrorException ex)
            {
                Console.Error.WriteLineAsync(ex.ToString());
                Environment.Exit(-1);
            }
            catch (TimeoutException)
            {
                Console.Error.WriteAsync(
                    $"Unable to obtain lock in {nameof(Soak)} method of {nameof(WashTask)} task.");
                throw;
            }
            finally
            {
                sw?.Reset();
                Debug.WriteLine("Ending soak.");
            }
        }
        public Mediator_Player_Controls(Controls c_, H_Player p_)
        {
            p_avatar = p_;
            c_input = c_;
            shooter = Shoot_State.CHILL;
            jumper = Jump_State.ON_GROUND;
            AirTime = new Stopwatch();
            AirTime.Reset();
            AirTime.Stop();

            cur_structure = 0;
            structure_wheel.Add(Structure_Type_e.HEALING_POOL);
            structure_wheel.Add(Structure_Type_e.SNOW_FACTORY);
            structure_wheel.Add(Structure_Type_e.FORT);
            structure_wheel.Add(Structure_Type_e.SNOWMAN);
        }
示例#33
0
	static void Main()
	{
		var stopwatch = new Stopwatch(); // создаем таймер
		stopwatch.Reset();               // так делается сброс таймера
		stopwatch.Start();               // запускаем таймер
		
		double id, i = 100;                         // функции, время выполнения...
		for (id = 0;id<i;id++) Console.WriteLine(id); // ...которых мы хотим измерить
		
		stopwatch.Stop(); // остановка таймера
		Console.WriteLine(); // далее вывод результатов...
		Console.WriteLine("Тактов:\t{0:###,###,###}", stopwatch.ElapsedTicks       );
		Console.WriteLine("Мс:    \t{0:###,###}"    , stopwatch.ElapsedMilliseconds);
		
		Console.ReadKey();
	}
示例#34
0
    public static void Main()
    {
        List<long> times = new List<long>();
        var stopwatch = new Stopwatch();
        for (int i = 0; i < 5; i++)
        {
            stopwatch.Start();
            List<int> result = PrimesUnder(3000000);
            stopwatch.Stop();

            times.Add(stopwatch.ElapsedMilliseconds);
            stopwatch.Reset();
        }

        foreach (var time in times)
            Console.WriteLine(time);
    }
示例#35
0
        protected virtual void Cleanse(CancellationTokenPair token)
        {
            byte unitsToRemove;
            {
                using var lls = LaundryFlags.SpinLock(TimeSpan.FromSeconds(2));
                unitsToRemove = lls.LoadedLaundryItem != LaundryItems.InvalidItem
                    ? lls.LoadedLaundryItem.SoiledFactor
                    : throw new StateLogicErrorException(
                                          "It should not be possible to lack laundry during the wash cycle.");
            }
            byte      unitsToDeduct = unitsToRemove;
            TimeSpan  timeRequired  = TimeToRemoveOneUnitOfSoil * unitsToRemove;
            Stopwatch sw            = null;

            try
            {
                sw = HighPrecisionTimer;
                sw.Restart();
                if (timeRequired > TimeSpan.Zero)
                {
                    SimulateWait(token, timeRequired, "Beginning cleanse wait.");
                }
            }
            catch (IndividualOperationCancelledException)
            {
                if (sw == null)
                {
                    string log = "For some reason the stopwatch is null.";
                    TerminationHelper.TerminateApplication(log);
                    return;
                }
                TimeSpan elapsed    = sw.Elapsed;
                double   percentage = elapsed >= timeRequired ? 1.0 : elapsed / timeRequired;
                unitsToDeduct = Convert.ToByte(Math.Floor(unitsToRemove * percentage));
                throw;
            }
            finally
            {
                sw?.Reset();
                byte newSetting = (byte)(unitsToRemove - unitsToDeduct);
                Debug.Assert(newSetting <= unitsToRemove);
                using var lls = LaundryFlags.SpinLock(TimeSpan.FromSeconds(2));
                lls.SetSoilFactor(newSetting);
                Debug.Assert(lls.LoadedLaundryItem.SoiledFactor <= unitsToRemove);
            }
        }
    //Decimal operations
    private static TimeSpan MesurePerformanceOfDecimalOperations(decimal numOne, decimal numTwo, string sign, Stopwatch stoplatch)
    {
        stoplatch.Reset();
        decimal sum = 0;

        switch (sign)
        {
            case "+":
                {
                    stoplatch.Start();
                    sum = numOne + numTwo;
                    stoplatch.Stop();
                    return stoplatch.Elapsed;
                }
            case "-":
                {
                    stoplatch.Start();
                    sum = numOne - numTwo;
                    stoplatch.Stop();
                    return stoplatch.Elapsed;
                }
            case "++":
                {
                    stoplatch.Start();
                    numOne++;
                    stoplatch.Stop();
                    return stoplatch.Elapsed;
                }
            case "*":
                {
                    stoplatch.Start();
                    sum = numOne * numTwo * 555555555;
                    stoplatch.Stop();
                    return stoplatch.Elapsed;
                }
            case "/":
                {
                    stoplatch.Start();
                    sum = numOne / numTwo;
                    stoplatch.Stop();
                    return stoplatch.Elapsed;
                }
            default:
                throw new ArgumentException("This is not a valid sign");
        }
    }
示例#37
0
    /* Task 2:
     * Write a program to read a large collection of products (name + price) I love 
     * and efficiently find the first 20 products in the price range [a…b]. Test for 
     * 500 000 products and 10 000 price searches.
     * Hint: you may use OrderedBag<T> and sub-ranges.
     */

    static void Main(string[] args)
    {
        Random randomGenerator = new Random();
        Stopwatch stopWatch = new Stopwatch();

        string[] product = { "bread", "butter", "meat", "eggs", "flower", "oil", "soda", "candy" };
        var productLenght = product.Length;
        var orderedDictionary = new OrderedDictionary<int, string>();

        stopWatch.Start();
        while (orderedDictionary.Count < 500000)
        {
            var key = randomGenerator.Next(1, 1000000);
            var value = product[randomGenerator.Next(0, productLenght)];
            if (!orderedDictionary.ContainsKey(key))
            {
                orderedDictionary.Add(key, value);
            }
        }

        stopWatch.Stop();

        Console.WriteLine("Time for creating the elements is: {0}", stopWatch.Elapsed);

        stopWatch.Reset();

        stopWatch.Start();
        for (int i = 0; i < 10000; i++)
        {
            var min = randomGenerator.Next(0, 500000);
            var max = randomGenerator.Next(500000, 1000000);
            var products = orderedDictionary.Range(min, true, max, true);
        }
        stopWatch.Stop();

        Console.WriteLine("Time for performing 10k range searches: {0}", stopWatch.Elapsed);

        var range = orderedDictionary.Range(1000, true, 100000, true);

        for (int i = 0; i < 20; i++)
        {
            Console.WriteLine(range.ElementAt(i));
        }
    }
示例#38
0
	static void Main(string[] args){
		int n = 1;
		int count = 0;
		Random rnd = new Random (42);
		Stopwatch st = new Stopwatch ();
		if (args.Length > 0) n = Int32.Parse(args[0]);

		int[] v = new int [n];
		for (int i = 0; i < n; i++)
			v [i] = i;

		/* Shuffle */
		for (int i = n - 1; i > 0; i--) {
			int t, pos;
			pos = rnd.Next () % i;
			t = v [i];
			v [i] = v [pos];
			v [pos] = t;
		}

		Hashtable table = new Hashtable (n); 

		st.Start ();
		for (int i = 0; i < n; i++) 
			table.Add (v [i], v [i]);
		for (int i = 0; i < n; i++) 
			table.Remove (v [i]);
		for (int i = n - 1; i >= 0; i--) 
			table.Add (v [i], v [i]);
		st.Stop ();  
		Console.WriteLine ("Addition {0}", st.ElapsedMilliseconds);

		st.Reset ();
		st.Start ();
		for (int j = 0; j < 8; j++) {
			for (int i = 0; i < n; i++) {
				if (table.ContainsKey (v [i]))
					count++;
			}	
		}
		st.Stop ();
		Console.WriteLine ("Lookup {0} - Count {1}", st.ElapsedMilliseconds, count);

	}
示例#39
0
 // Use this for initialization
 void Start()
 {
     var watch = new Stopwatch();
     watch.Start();
     for(var i = 0; i < 10000; i ++)
     {
     //			var t = transform.position;
     }
     watch.Stop();
     UnityEngine.Debug.Log(watch.ElapsedTicks/10000000f);
     watch.Reset();
     watch.Start();
     for(var i = 0; i < 10000; i ++)
     {
     //		var t = transform.localPosition;
     }
     watch.Stop();
     UnityEngine.Debug.Log(watch.ElapsedTicks/10000000f);
 }
        public void Start()
        {
            finished = false;
            STOP     = false;

            Report("Execute", 0, 0, messagesPerMinute);
            intervalStopWatch?.Reset();
            executionStopWatch?.Reset();
            sourceLogger.Info($"Scheduling Start of Rate Source Controller: {name}");
            CancellationTokenSource source = new CancellationTokenSource();

            if (lineInUse)
            {
                Task.Run(async delegate {
                    await Task.Delay(TimeSpan.FromSeconds(deferredStart), source.Token);
                    logger.Info($"Starting Rate Source Controller: {name}");
                    messagesSent  = 0;
                    intervalCount = 0;
                    PrepareProfileThreads();  //Set up the threads which modify the rate profile/interval
                    executionStopWatch.Start();
                    intervalStopWatch.Start();

                    sourceLogger.Info($"Starting timer with interval {interval}");
                    sendTimer = new System.Timers.Timer(interval)
                    {
                        Enabled   = true,
                        AutoReset = false
                    };
                    sendTimer.Elapsed += FireEvent;
                });
            }
            else
            {
                sourceLogger.Warn($"No Destination configured to use Rate Source Controller: {name}");
            }
        }
示例#41
0
 public void Stop()
 {
     sw.Stop();
     sw.Reset();
 }
示例#42
0
        } // PVM.InBounds

        public static void Emulator(int initPC, int codeLen, int initSP,
                                    InFile data, OutFile results, bool tracing,
                                    bool traceStack, bool traceHeap)
        {
            // Emulates action of the codeLen instructions stored in mem[0 .. codeLen-1], with
            // program counter initialized to initPC, stack pointer initialized to initSP.
            // data and results are used for I/O.  Tracing at the code level may be requested

            int pcNow;            // current program counter
            int loop;             // internal loops
            int tos, sos;         // values popped from stack
            int adr;              // effective address for memory accesses
            int target;           // destination for branches

            stackBase = initSP;
            heapBase  = codeLen;  // initialize boundaries
            cpu.hp    = heapBase; // initialize registers
            cpu.sp    = stackBase;
            cpu.gp    = stackBase;
            cpu.mp    = stackBase;
            cpu.fp    = stackBase;
            cpu.pc    = initPC;   // initialize program counter
            for (int i = heapBase; i < stackBase; i++)
            {
                mem[i] = 0;       // set entire memory to null or 0
            }
            ps = running;         // prepare to execute
            int ops = 0;

            timer.Start();
            do
            {
                ops++;
                pcNow = cpu.pc;   // retain for tracing/postmortem
                if (cpu.pc < 0 || cpu.pc >= codeLen)
                {
                    ps = badAdr;
                    break;
                }
                cpu.ir = Next();  // fetch
                if (tracing)
                {
                    Trace(results, pcNow, traceStack, traceHeap);
                }
                switch (cpu.ir)   // execute
                {
                case PVM.nop:     // no operation
                    break;

                case PVM.dsp:     // decrement stack pointer (allocate space for variables)
                    int localSpace = Next();
                    cpu.sp -= localSpace;
                    if (InBounds(cpu.sp)) // initialize all local variables to zero/null
                    {
                        for (loop = 0; loop < localSpace; loop++)
                        {
                            mem[cpu.sp + loop] = 0;
                        }
                    }
                    break;

                case PVM.ldc:     // push constant value
                    Push(Next());
                    break;

                case PVM.ldc_m1:  // push constant -1
                    Push(-1);
                    break;

                case PVM.ldc_0:   // push constant 0
                    Push(0);
                    break;

                case PVM.ldc_1:   // push constant 1
                    Push(1);
                    break;

                case PVM.ldc_2:   // push constant 2
                    Push(2);
                    break;

                case PVM.ldc_3:   // push constant 3
                    Push(3);
                    break;

                case PVM.ldc_4:   // push constant 4
                    Push(4);
                    break;

                case PVM.ldc_5:   // push constant 5
                    Push(5);
                    break;

                case PVM.lda:     // push local address
                    adr = cpu.fp - 1 - Next();
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.lda_0:   // push local address 0
                    adr = cpu.fp - 1;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.lda_1:   // push local address 1
                    adr = cpu.fp - 2;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.lda_2:   // push local address 2
                    adr = cpu.fp - 3;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.lda_3:   // push local address 3
                    adr = cpu.fp - 4;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.lda_4:   // push local address 4
                    adr = cpu.fp - 5;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.lda_5:   // push local address 5
                    adr = cpu.fp - 6;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.ldga:  // push global address
                    adr = cpu.gp - 1 - Next();
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.ldg_0:   // push local address 0
                    adr = cpu.gp - 1;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.ldg_1:   // push local address 1
                    adr = cpu.gp - 2;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.ldg_2:   // push local address 2
                    adr = cpu.gp - 3;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.ldg_3:   // push local address 3
                    adr = cpu.gp - 4;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.ldg_4:   // push local address 4
                    adr = cpu.gp - 5;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.ldg_5:   // push local address 5
                    adr = cpu.gp - 6;
                    if (InBounds(adr))
                    {
                        Push(adr);
                    }
                    break;

                case PVM.ldl:     // push local value
                    adr = cpu.fp - 1 - Next();
                    if (InBounds(adr))
                    {
                        Push(mem[adr]);
                    }
                    break;

                case PVM.ldl_0:   // push value of local variable 0
                    adr = cpu.fp - 1;
                    if (InBounds(adr))
                    {
                        Push(mem[adr]);
                    }
                    break;

                case PVM.ldl_1:   // push value of local variable 1
                    adr = cpu.fp - 2;
                    if (InBounds(adr))
                    {
                        Push(mem[adr]);
                    }
                    break;

                case PVM.ldl_2:   // push value of local variable 2
                    adr = cpu.fp - 3;
                    if (InBounds(adr))
                    {
                        Push(mem[adr]);
                    }
                    break;

                case PVM.ldl_3:   // push value of local variable 3
                    adr = cpu.fp - 4;
                    if (InBounds(adr))
                    {
                        Push(mem[adr]);
                    }
                    break;

                case PVM.ldl_4:   // push value of local variable 4
                    adr = cpu.fp - 5;
                    if (InBounds(adr))
                    {
                        Push(mem[adr]);
                    }
                    break;

                case PVM.ldl_5:   // push value of local variable 5
                    adr = cpu.fp - 6;
                    if (InBounds(adr))
                    {
                        Push(mem[adr]);
                    }
                    break;

                case PVM.stl:     // store local value
                    adr = cpu.fp - 1 - Next();
                    if (InBounds(adr))
                    {
                        mem[adr] = Pop();
                    }
                    break;

                case PVM.stlc:    // character checked pop to local variable
                    tos = Pop(); adr = cpu.fp - 1 - Next();
                    if (InBounds(adr))
                    {
                        if (tos >= 0 && tos <= maxChar)
                        {
                            mem[adr] = tos;
                        }
                        else
                        {
                            ps = badVal;
                        }
                    }
                    break;

                case PVM.stl_0:   // pop to local variable 0
                    adr = cpu.fp - 1;
                    if (InBounds(adr))
                    {
                        mem[adr] = Pop();
                    }
                    break;

                case PVM.stl_1:   // pop to local variable 1
                    adr = cpu.fp - 2;
                    if (InBounds(adr))
                    {
                        mem[adr] = Pop();
                    }
                    break;

                case PVM.stl_2:   // pop to local variable 2
                    adr = cpu.fp - 3;
                    if (InBounds(adr))
                    {
                        mem[adr] = Pop();
                    }
                    break;

                case PVM.stl_3:   // pop to local variable 3
                    adr = cpu.fp - 4;
                    if (InBounds(adr))
                    {
                        mem[adr] = Pop();
                    }
                    break;

                case PVM.stl_4:   // pop to local variable 4
                    adr = cpu.fp - 5;
                    if (InBounds(adr))
                    {
                        mem[adr] = Pop();
                    }
                    break;

                case PVM.stl_5:   // pop to local variable 5
                    adr = cpu.fp - 6;
                    if (InBounds(adr))
                    {
                        mem[adr] = Pop();
                    }
                    break;

                case PVM.ldv:     // dereference
                    adr = Pop();
                    if (InBounds(adr))
                    {
                        Push(mem[adr]);
                    }
                    break;

                case PVM.sto:     // store
                    tos = Pop(); adr = Pop();
                    if (InBounds(adr))
                    {
                        mem[adr] = tos;
                    }
                    break;

                case PVM.stoc:    // character checked store
                    tos = Pop(); adr = Pop();
                    if (InBounds(adr))
                    {
                        if (tos >= 0 && tos <= maxChar)
                        {
                            mem[adr] = tos;
                        }
                        else
                        {
                            ps = badVal;
                        }
                    }
                    break;

                case PVM.ldxa:    // heap array indexing
                    adr = Pop();
                    int heapPtr = Pop();
                    if (heapPtr == 0)
                    {
                        ps = nullRef;
                    }
                    else if (heapPtr < heapBase || heapPtr >= cpu.hp)
                    {
                        ps = badMem;
                    }
                    else if (adr < 0 || adr >= mem[heapPtr])
                    {
                        ps = badInd;
                    }
                    else
                    {
                        Push(heapPtr + adr + 1);
                    }
                    break;

                case PVM.inpi:    // integer input
                    adr = Pop();
                    if (InBounds(adr))
                    {
                        mem[adr] = data.ReadInt();
                        if (data.Error())
                        {
                            ps = badData;
                        }
                    }
                    break;

                case PVM.inpb:    // boolean input
                    adr = Pop();
                    if (InBounds(adr))
                    {
                        mem[adr] = data.ReadBool() ? 1 : 0;
                        if (data.Error())
                        {
                            ps = badData;
                        }
                    }
                    break;

                case PVM.inpc:    // character input
                    adr = Pop();
                    if (InBounds(adr))
                    {
                        mem[adr] = data.ReadChar();
                        if (data.Error())
                        {
                            ps = badData;
                        }
                    }
                    break;

                case PVM.inpl:    // skip to end of input line
                    data.ReadLine();
                    break;

                case PVM.i2c:     // check convert character to integer
                    if (mem[cpu.sp] < 0 || mem[cpu.sp] > maxChar)
                    {
                        ps = badVal;
                    }
                    break;

                case PVM.prni:    // integer output
                    if (tracing)
                    {
                        results.Write(padding);
                    }
                    results.Write(Pop(), 0);
                    if (tracing)
                    {
                        results.WriteLine();
                    }
                    break;

                case PVM.prnb:    // boolean output
                    if (tracing)
                    {
                        results.Write(padding);
                    }
                    if (Pop() != 0)
                    {
                        results.Write(" true  ");
                    }
                    else
                    {
                        results.Write(" false ");
                    }
                    if (tracing)
                    {
                        results.WriteLine();
                    }
                    break;

                case PVM.prnc:    // character output
                    if (tracing)
                    {
                        results.Write(padding);
                    }
                    results.Write((char)(Math.Abs(Pop()) % (maxChar + 1)), 1);
                    if (tracing)
                    {
                        results.WriteLine();
                    }
                    break;

                case PVM.prns:    // string output
                    if (tracing)
                    {
                        results.Write(padding);
                    }
                    loop = Next();
                    while (ps == running && mem[loop] != 0)
                    {
                        results.Write((char)mem[loop]); loop--;
                        if (loop < stackBase)
                        {
                            ps = badMem;
                        }
                    }
                    if (tracing)
                    {
                        results.WriteLine();
                    }
                    break;

                case PVM.prnl:    // newline
                    results.WriteLine();
                    break;

                case PVM.neg:     // integer negation
                    Push(-Pop());
                    break;

                case PVM.add:     // integer addition
                    tos = Pop(); Push(Pop() + tos);
                    break;

                case PVM.sub:     // integer subtraction
                    tos = Pop(); Push(Pop() - tos);
                    break;

                case PVM.mul:     // integer multiplication
                    tos = Pop();
                    sos = Pop();
                    if (tos != 0 && Math.Abs(sos) > maxInt / Math.Abs(tos))
                    {
                        ps = badVal;
                    }
                    else
                    {
                        Push(sos * tos);
                    }
                    break;

                case PVM.div:     // integer division (quotient)
                    tos = Pop();
                    if (tos == 0)
                    {
                        ps = divZero;
                    }
                    else
                    {
                        Push(Pop() / tos);
                    }
                    break;

                case PVM.rem:     // integer division (remainder)
                    tos = Pop();
                    if (tos == 0)
                    {
                        ps = divZero;
                    }
                    else
                    {
                        Push(Pop() % tos);
                    }
                    break;

                case PVM.not:     // logical negation
                    Push(Pop() == 0 ? 1 : 0);
                    break;

                case PVM.and:     // logical and
                    tos = Pop(); Push(Pop() & tos);
                    break;

                case PVM.or:      // logical or
                    tos = Pop(); Push(Pop() | tos);
                    break;

                case PVM.ceq:     // logical equality
                    tos = Pop(); Push(Pop() == tos ? 1 : 0);
                    break;

                case PVM.cne:     // logical inequality
                    tos = Pop(); Push(Pop() != tos ? 1 : 0);
                    break;

                case PVM.clt:     // logical less
                    tos = Pop(); Push(Pop() < tos ? 1 : 0);
                    break;

                case PVM.cle:     // logical less or equal
                    tos = Pop(); Push(Pop() <= tos ? 1 : 0);
                    break;

                case PVM.cgt:     // logical greater
                    tos = Pop(); Push(Pop() > tos ? 1 : 0);
                    break;

                case PVM.cge:     // logical greater or equal
                    tos = Pop(); Push(Pop() >= tos ? 1 : 0);
                    break;

                case PVM.brn:     // unconditional branch
                    cpu.pc = Next();
                    if (cpu.pc < 0 || cpu.pc >= codeLen)
                    {
                        ps = badAdr;
                    }
                    break;

                case PVM.bze:     // pop top of stack, branch if false
                    target = Next();
                    if (Pop() == 0)
                    {
                        cpu.pc = target;
                        if (cpu.pc < 0 || cpu.pc >= codeLen)
                        {
                            ps = badAdr;
                        }
                    }
                    break;

                case PVM.bfalse:  // conditional short circuit "and" branch
                    target = Next();
                    if (mem[cpu.sp] == 0)
                    {
                        cpu.pc = target;
                    }
                    else
                    {
                        cpu.sp++;
                    }
                    break;

                case PVM.btrue:   // conditional short circuit "or" branch
                    target = Next();
                    if (mem[cpu.sp] == 1)
                    {
                        cpu.pc = target;
                    }
                    else
                    {
                        cpu.sp++;
                    }
                    break;

                case PVM.anew:    // heap array allocation
                    int size = Pop();
                    if (size <= 0 || size + 1 > cpu.sp - cpu.hp - 2)
                    {
                        ps = badAll;
                    }
                    else
                    {
                        mem[cpu.hp] = size; // first element stores size for bounds checking
                        Push(cpu.hp);
                        cpu.hp += size + 1; // bump heap pointer
                                            // elements are already initialized to 0 / null (why?)
                    }
                    break;

                case PVM.halt:    // halt
                    ps = finished;
                    break;

                case PVM.inc:     // integer ++
                    adr = Pop();
                    if (InBounds(adr))
                    {
                        mem[adr]++;
                    }
                    break;

                case PVM.dec:     // integer --
                    adr = Pop();
                    if (InBounds(adr))
                    {
                        mem[adr]--;
                    }
                    break;

                case PVM.incc:    // ++ characters
                    adr = Pop();
                    if (InBounds(adr))
                    {
                        if (mem[adr] < maxChar)
                        {
                            mem[adr]++;
                        }
                        else
                        {
                            ps = badVal;
                        }
                    }
                    break;

                case PVM.decc:    // -- characters
                    adr = Pop();
                    if (mem[adr] > 0)
                    {
                        mem[adr]--;
                    }
                    else
                    {
                        ps = badVal;
                    }
                    break;

                case PVM.stack:   // stack dump (debugging)
                    StackDump(results, pcNow);
                    break;

                case PVM.heap:    // heap dump (debugging)
                    HeapDump(results, pcNow);
                    break;

                case PVM.fhdr:    // allocate frame header
                    if (InBounds(cpu.sp - headerSize))
                    {
                        mem[cpu.sp - headerSize] = cpu.mp;
                        cpu.mp  = cpu.sp;
                        cpu.sp -= headerSize;
                    }
                    break;

                case PVM.call:    // call function
                    if (mem[cpu.pc] < 0)
                    {
                        ps = badAdr;
                    }
                    else
                    {
                        mem[cpu.mp - 2] = cpu.fp;
                        mem[cpu.mp - 3] = cpu.pc + 1;
                        cpu.fp          = cpu.mp;
                        cpu.pc          = mem[cpu.pc];
                    }
                    break;

                case PVM.retv:    // return from void function
                    cpu.sp = cpu.fp;
                    cpu.mp = mem[cpu.fp - 4];
                    cpu.pc = mem[cpu.fp - 3];
                    cpu.fp = mem[cpu.fp - 2];
                    break;

                case PVM.ret:     // return from non-void function
                    cpu.sp = cpu.fp - 1;
                    cpu.mp = mem[cpu.fp - 4];
                    cpu.pc = mem[cpu.fp - 3];
                    cpu.fp = mem[cpu.fp - 2];
                    break;

                case PVM.trap:    // trap falling off end of function
                    ps = badFun;
                    break;

                case PVM.low:     // toLowerCase
                    Push(Char.ToLower((char)Pop()));
                    break;

                case PVM.cap:     // toUpperCase
                    Push(Char.ToUpper((char)Pop()));
                    break;

                case PVM.islet:   // isLetter
                    tos = Pop();
                    Push(Char.IsLetter((char)tos) ? 1 : 0);
                    break;

                case PVM.pop:     // pop and discard tos
                    tos = Pop();
                    break;

                case PVM.dup:     // duplicate tos
                    tos = Pop();
                    Push(tos); Push(tos);
                    break;

                default:          // unrecognized opcode
                    ps = badOp;
                    break;
                }
            } while (ps == running);
            TimeSpan ts = timer.Elapsed;
            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                               ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

            Console.WriteLine("\n\n" + ops + " operations.  Run Time " + elapsedTime + "\n\n");
            if (ps != finished)
            {
                PostMortem(results, pcNow);
            }
            timer.Reset();
            timer.Stop();
        } // PVM.Emulator
示例#43
0
 internal static void ResetRender()
 {
     _RenderSW.Reset();
 }
示例#44
0
        private void btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                switch (btn.Content.ToString())
                {
                case "1":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += "1";
                    }
                    break;

                case "2":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += "2";
                    }
                    break;

                case "3":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += "3";
                    }
                    break;

                case "4":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += "4";
                    }
                    break;

                case "5":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += "5";
                    }
                    break;

                case "6":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += "6";
                    }
                    break;

                case "7":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += "7";
                    }
                    break;

                case "8":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += "8";
                    }
                    break;

                case "9":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += "9";
                    }
                    break;

                case "0":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += "0";
                    }
                    break;

                case "(":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += "(";
                    }
                    break;

                case ")":
                    if (textBoxExpression.Text != "0")
                    {
                        textBoxExpression.Text += ")";
                    }
                    break;

                case "*":
                    textBoxExpression.Text += "*";
                    break;

                case "/":
                    textBoxExpression.Text += "/";
                    break;

                case "+":
                    textBoxExpression.Text += "+";
                    break;

                case "-":
                    textBoxExpression.Text += "-";
                    break;

                case "mod":
                    textBoxExpression.Text += "mod";
                    break;

                case "C":
                    textBoxExpression.Text = "";
                    textBoxResult.Text     = "";
                    break;

                case "Backspace":
                    if (textBoxExpression.Text.Length > 0)
                    {
                        textBoxExpression.Text = textBoxExpression.Text.Remove(textBoxExpression.Text.Length - 1);
                    }
                    if (textBoxExpression.Text.Length == 0)
                    {
                        textBoxExpression.Text = "0";
                    }
                    break;

                case "MC":
                    Memory = 0;
                    break;

                case "MR":

                    textBoxExpression.Text += Memory.ToString();
                    break;

                case "M+":
                    try
                    {
                        Memory = int.Parse(textBoxResult.Text);
                    }
                    catch
                    {
                        textBoxResult.Text = "Неможливо перетворити до числа";
                    }

                    break;

                case "+/-":
                    if (!_timer.IsRunning)
                    {
                        _timer = Stopwatch.StartNew();
                    }
                    else
                    {
                        _timer.Stop();
                        if (_timer.Elapsed.Seconds > 3)
                        {
                            _timer.Reset();
                            _timer = Stopwatch.StartNew();
                            return;
                        }
                    }
                    if (textBoxExpression.Text[textBoxExpression.Text.Length - 1] == 'm')
                    {
                        textBoxExpression.Text  = textBoxExpression.Text.Remove(textBoxExpression.Text.Length - 1, 1);
                        textBoxExpression.Text += 'p';
                    }
                    else
                    {
                        if (textBoxExpression.Text[textBoxExpression.Text.Length - 1] == 'p')
                        {
                            textBoxExpression.Text  = textBoxExpression.Text.Remove(textBoxExpression.Text.Length - 1, 1);
                            textBoxExpression.Text += 'm';
                        }
                        else
                        {
                            if (textBoxExpression.Text == "0")
                            {
                                textBoxExpression.Text = "m";
                            }
                            else
                            {
                                textBoxExpression.Text += "m";
                            }
                        }
                    }
                    _checkExp = textBoxExpression.Text;
                    break;

                case "=":
                    Analyzer.Expression = textBoxExpression.Text;
                    textBoxResult.Text  = Analyzer.Estimate();
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Sorry for the inconvenience, Unexpected error occured. Details: " +
                                ex.Message);
            }
        }
示例#45
0
        public decimal FindOptimum(ComboBox func_text, TextBox a_text, TextBox b_text,TextBox tol_text,TextBox max_iter_text,TextBox max_time_text, ProgressBar pb)
        {
            decimal a=0,b=0,r = 0;
            decimal x1 = 0, x2 = 0;
            decimal F1 = 0, F2 = 0;
            int max_iter, max_iter2;
            int max_time, max_time2;
            int iter = 0;
            int cond = 0;

            decimal tol = Decimal.Parse(tol_text.Text, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint);
            a = Convert.ToDecimal(a_text.Text);
            b = Convert.ToDecimal(b_text.Text);
            func = func_text.Text;
            Stopwatch stopwatch = new Stopwatch();
            max_iter2 = max_iter = Convert.ToInt32(max_iter_text.Text);
            max_time2 = max_time = Convert.ToInt32(max_time_text.Text);

            pb.Value = 0;
            stopwatch.Start();
            r = (decimal)((Math.Sqrt(5)-1) / 2);
            x1 = a + (1 - r) * (b - a);
            F1 = f(x1);
            x2 = a + r * (b - a);
            F2 = f(x2);

                while (cond == 0)
                {
                    iter++;
                    if (Math.Abs(b - a) <= tol)
                    {
                        stopwatch.Stop();
                        cond = 3;
                        pb.Value = pb.Maximum;
                    }
                    else
                    {
                        if (F1 > F2)
                        {
                            a = x1;
                            x1 = x2;
                            F1 = F2;
                            x2 = a + r * (b - a);
                            F2 = f(x2);
                            pb.Value = iter;
                        }
                        else
                        {
                            b = x2;
                            x2 = x1;
                            F2 = F1;
                            x1 = a + (1 - r) * (b - a);
                            F1 = f(x1);
                            pb.Value = iter;
                        }
                        if (max_time <= Convert.ToInt16(stopwatch.ElapsedMilliseconds)) //Проверка на время
                        {
                            stopwatch.Stop();
                            pb.Value = pb.Maximum;

                            DialogResult dr = MessageBox.Show("Время вышло. Продолжить вычисление? Будет добавлено " + max_time2 + " миллисекунд", "Продолжить вычисления?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (dr == DialogResult.No)
                            {

                                cond = 1;
                            }
                            else if (dr == DialogResult.Yes)
                            {
                                max_time += max_time2;
                                max_time_text.Text = max_time.ToString();
                                pb.Maximum = max_iter + 1;
                                stopwatch.Start();
                            }
                        }

                        if (iter >= max_iter) //проверка на итерацию
                        {
                            stopwatch.Stop();
                            pb.Value = pb.Maximum;
                            DialogResult dr = MessageBox.Show("Указанная точность за " + iter + " итераций не достигнута.Продолжить вычисление ? Будет добавлено " + max_iter + " итераций.", "Продолжить вычисления ? ", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (dr == DialogResult.No)
                            {
                                cond = 2;
                            }
                            else if (dr == DialogResult.Yes)
                            {
                                max_iter = max_iter + max_iter2;
                                pb.Maximum = max_iter + 1;
                                max_iter_text.Text = (max_iter).ToString();
                                stopwatch.Start();
                            }
                        }
                    }
                }
            
            stopwatch.Stop();
            tol_res = Math.Abs(b - a);
            cond_res = cond;
            iter_res = iter;
            time_res = stopwatch.ElapsedMilliseconds;
            f_res = F2;
            pb.Visible = false;
            stopwatch.Reset();
            return x1;   
        }
示例#46
0
 public static void Stop()
 {
     _stopwatch?.Reset();
 }
示例#47
0
 public static void ResetFrameTime()
 {
     Timing.Accumulator = 0.0f;
     stopwatch?.Reset();
     stopwatch?.Start();
 }
示例#48
0
        public static void Run()
        {
            int           threadCount = 5;
            List <Thread> _pool       = new List <Thread>();

            Stopwatch sw = new Stopwatch();

            Thread.Sleep(1000);

            long creationTicks = 0;

            Process proc = Process.GetCurrentProcess();

            Console.WriteLine(proc.WorkingSet64 + "\n");

            for (int i = 0; i < threadCount; i++)
            {
                sw.Start();

                Thread thread = new Thread(new ThreadStart(WaitThread));
                _pool.Add(thread);

                sw.Stop();
                //Console.WriteLine(sw.ElapsedTicks);
                creationTicks += sw.ElapsedMilliseconds;
                sw.Reset();
            }

            proc = Process.GetCurrentProcess();
            Console.WriteLine(proc.WorkingSet64 + "\n");

            Console.WriteLine($"Total creation time: {creationTicks} ticks");
            Console.WriteLine($"Average creation time: {creationTicks / threadCount} ticks\n");

            long startTicks = 0;

            foreach (Thread t in _pool)
            {
                sw.Start();

                t.Start();

                sw.Stop();
                //Console.WriteLine(sw.ElapsedTicks);
                startTicks += sw.ElapsedMilliseconds;
                sw.Reset();
            }

            proc = Process.GetCurrentProcess();
            Console.WriteLine(proc.WorkingSet64 + "\n");

            Console.WriteLine($"Total start time: {startTicks} ticks");
            Console.WriteLine($"Average start time: {startTicks / threadCount} ticks\n");

            long runTicks = 0;

            foreach (Thread t in _pool)
            {
                sw.Start();

                t.Join();

                sw.Stop();
                //Console.WriteLine(sw.ElapsedTicks);
                runTicks += sw.ElapsedMilliseconds;
                sw.Reset();
            }
            sw.Stop();

            _pool.Clear();

            Console.WriteLine($"Total run time: {runTicks} ticks");
            Console.WriteLine($"Average run time: {runTicks / threadCount} ticks");
            Console.ReadLine();
        }
示例#49
0
        void MCPingCommand(CommandDetails command)
        {
            if (command.Arguments.Count <= 0)
            {
                Chat(command.Channel.Name, command.Pinger + ColorGeneral + "That command is written as: " + ColorHighlightMajor + Prefixes[0] + command.Name + " <Minecraft server IP address>");
                return;
            }
            IRCUser user = new IRCUser(command.Arguments[0]);
            string  IP   = user.Settings.ReadString("general.minecraft_server_ip", null);

            if (IP == null)
            {
                IP = command.Arguments[0];
            }
            ushort port = 0;

            if (IP.Contains(':'))
            {
                string[] dat = IP.Split(new char[] { ':' }, 2);
                IP   = dat[0];
                port = Utilities.StringToUShort(dat[1]);
            }
            if (port == 0)
            {
                try
                {
                    DnsQueryRequest  dqr  = new DnsQueryRequest();
                    DnsQueryResponse resp = dqr.Resolve("_minecraft._tcp." + IP, NsType.SRV, NsClass.ANY, ProtocolType.Tcp);
                    if (resp != null)
                    {
                        for (int i = 0; i < resp.AdditionalRRecords.Count; i++)
                        {
                            if (resp.AdditionalRRecords[i] is SrvRecord)
                            {
                                port = (ushort)((SrvRecord)resp.AdditionalRRecords[i]).Port;
                            }
                        }
                        for (int i = 0; i < resp.Answers.Length; i++)
                        {
                            if (resp.Answers[i] is SrvRecord)
                            {
                                port = (ushort)((SrvRecord)resp.Answers[i]).Port;
                            }
                        }
                    }
                    else
                    {
                        Logger.Output(LogType.DEBUG, "Null SRV record.");
                    }
                    if (port == 0)
                    {
                        port = (ushort)25565;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Output(LogType.ERROR, "Pinging a SRV record for a minecraft server: " + ex.ToString());
                    port = 25565;
                }
            }
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                Stopwatch Timer = new Stopwatch();
                Timer.Reset();
                Timer.Start();
                sock.SendBufferSize    = 8192;
                sock.ReceiveBufferSize = 8192 * 10;
                sock.ReceiveTimeout    = 3000;
                sock.SendTimeout       = 3000;
                IAsyncResult result  = sock.BeginConnect(IP, port, null, null);
                bool         timeout = !result.AsyncWaitHandle.WaitOne(5000, true);
                if (timeout)
                {
                    throw new Exception("Connection timed out");
                }
                if (!sock.Connected)
                {
                    throw new Exception("Failed to connect");
                }
                byte[] address   = UTF8.GetBytes(IP);
                int    packlen   = 1 + 1 + 1 + address.Length + 2 + 1;
                byte[] send      = new byte[1 + packlen + 1 + 1];
                byte[] portbytes = BitConverter.GetBytes(port).Reverse().ToArray();
                send[0] = (byte)packlen;                    // packet length
                send[1] = (byte)0x00;                       // Packet ID
                send[2] = (byte)0x04;                       // Protocol Version
                send[3] = (byte)address.Length;             // Address string length
                address.CopyTo(send, 4);                    // Address string
                portbytes.CopyTo(send, address.Length + 4); // Port
                send[address.Length + 6] = (byte)0x01;      // Next state
                send[address.Length + 7] = (byte)0x01;      // Next packet length
                send[address.Length + 8] = (byte)0x00;      // Empty state request packet ~ packet ID
                sock.Send(send);
                int length = 0;
                // Packet size -> packet ID -> JSON length
                for (int x = 0; x < 2; x++)
                {
                    length = 0;
                    int j = 0;
                    while (true)
                    {
                        byte[] recd = new byte[1];
                        sock.Receive(recd, 1, SocketFlags.None);
                        int k = recd[0];
                        length |= (k & 0x7F) << j++ *7;
                        if (j > 5)
                        {
                            throw new Exception("VarInt too big");
                        }
                        if ((k & 0x80) != 128)
                        {
                            break;
                        }
                        if (Timer.ElapsedMilliseconds > 7000)
                        {
                            throw new Exception("Timeout while reading response");
                        }
                    }
                    if (x == 0)
                    {
                        byte[] resp = new byte[1];
                        sock.Receive(resp, 1, SocketFlags.None);
                    }
                }
                int    gotten   = 0;
                byte[] response = new byte[length];
                while (gotten < length)
                {
                    byte[] gotbit = new byte[length - gotten];
                    int    newgot = sock.Receive(gotbit, length - gotten, SocketFlags.None);
                    gotbit.CopyTo(response, gotten);
                    gotten += newgot;
                    if (Timer.ElapsedMilliseconds > 7000)
                    {
                        throw new Exception("Timeout while reading response");
                    }
                }
                string fullresponse = UTF8.GetString(response);
                int    ind          = fullresponse.IndexOf('{');
                if (ind < 0)
                {
                    throw new Exception("Invalid response packet - is that an actual minecraft server?");
                }
                fullresponse = fullresponse.Substring(ind);
                Dictionary <string, dynamic> dict = new JavaScriptSerializer().Deserialize <Dictionary <string, dynamic> >(fullresponse.Trim());
                string version     = dict["version"]["name"].ToString();
                string versionnum  = dict["version"]["protocol"].ToString();
                string players_on  = dict["players"]["online"].ToString();
                string players_max = dict["players"]["max"].ToString();
                string description;
                if (dict["description"] is Dictionary <String, Object> )
                {
                    description = dict["description"]["text"].ToString();
                }
                else
                {
                    description = dict["description"].ToString();
                }
                Chat(command.Channel.Name, command.Pinger + ColorGeneral + "Server: " + IP + ":" + port.ToString() + ", MOTD: '"
                     + Utilities.mctoirc(description) + ColorGeneral + "', players: " + players_on + "/" + players_max + ", version: " + Utilities.mctoirc(version));
            }
            catch (Exception ex)
            {
                Logger.Output(LogType.DEBUG, "Pinging minecraft server: " + ex.ToString());
                Chat(command.Channel.Name, command.Pinger + ColorGeneral + "Couldn't ping server: internal exception: " + ex.Message);
            }
            finally
            {
                sock.Close();
            }
        }
示例#50
0
        /// <summary>
        /// Event handler for Kinect sensor's SkeletonFrameReady event
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        public void SkeletonMoved(float time, Skeleton skel)
        {
            using (DrawingContext dc = this.drawingGroup.Open())
            {
                // Draw a transparent background to set the render size
                dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, RenderWidth, RenderHeight));
                //RenderClippedEdges(skel, dc);
                
                //rightHand = skel.Joints[JointType.HandRight];
                foreach (Joint joint in skel.Joints)
                {
                    rightHand = skel.Joints[JointType.HandRight].Position;
                    leftHand = skel.Joints[JointType.HandLeft].Position;
                    rightHip = skel.Joints[JointType.HipRight].Position;
                    leftHip = skel.Joints[JointType.HipLeft].Position;
                    rightShoulder = skel.Joints[JointType.ShoulderRight].Position;
                    neck = skel.Joints[JointType.ShoulderCenter].Position;
                    spine = skel.Joints[JointType.Spine].Position;
                    core = skel.Joints[JointType.HipCenter].Position;
                }
                if (rightHand.X != 0 && rightHip.X != 0)
                {
                    rightHipValues = SkeletonPointToScreen(rightHip);
                    leftHipValues = SkeletonPointToScreen(leftHip);
                    rightHandValues = SkeletonPointToScreen(rightHand);
                    leftHandValues = SkeletonPointToScreen(leftHand);
                    rightShoulderValues = SkeletonPointToScreen(rightShoulder);
                    neckValues = SkeletonPointToScreen(neck);
                    spineValues = SkeletonPointToScreen(spine);
                    coreValues = SkeletonPointToScreen(core);
                }
                if (drawHipLine)
                {
                    if (rightHandValues.Y < rightHipValues.Y) { dc.DrawLine(new Pen(Brushes.Green, 4), new Point((leftHipValues.X + rightHipValues.X) / 2, rightHipValues.Y), new Point(1000, rightHipValues.Y)); }
                    else { dc.DrawLine(new Pen(Brushes.Red, 4), new Point((leftHipValues.X + rightHipValues.X) / 2, rightHipValues.Y), new Point(1000, rightHipValues.Y)); }
                    if (leftHandValues.Y < rightHipValues.Y) { dc.DrawLine(new Pen(Brushes.Green, 4), new Point(0, rightHipValues.Y), new Point((leftHipValues.X + rightHipValues.X) / 2, rightHipValues.Y)); }
                    else { dc.DrawLine(new Pen(Brushes.Red, 4), new Point(0, rightHipValues.Y), new Point((leftHipValues.X + rightHipValues.X) / 2, rightHipValues.Y)); }
                }
                if (showStartBox)
                {
                    box2.Location = new Point(neckValues.X, 10);
                    box2.Size = new Size(RenderWidth - neckValues.X - 10, neckValues.Y + Math.Abs(neckValues.Y - rightShoulderValues.Y) * 1.5 );
                    dc.DrawRectangle(null, new Pen(Brushes.Gray, 4), box2);                  
                }
                if (tempoBox)
                {
                    //if (playSong && Gestures.tempo.beat) 
                    //{
                    //    beat++;
                    //    if (beat <= 4) { StartBeat.Content = beat; }
                    //    else { StartBeat.Content = ""; }
                    //}
                    box2.Size = new Size(RenderWidth - 20, RenderHeight - 20);
                    box2.Location = new Point(10, 10);
                    if (Gestures.tempo.beat == true || stopwatch.ElapsedMilliseconds <= 200)
                    {
                        dc.DrawRectangle(null, new Pen(Brushes.Green, 4), box2);
                        if (stopwatch.ElapsedMilliseconds > 200 || stopwatch.ElapsedMilliseconds == 0) { stopwatch.Restart(); }
                    }
                    else { dc.DrawRectangle(null, new Pen(Brushes.Red, 4), box2); }

                }
                if (checkRightHandStill)
                {
                    if (rightHand.X != 0 && rightHip.X != 0)
                    {
                        if (rightHand.Y > rightHip.Y) { aboveHip = true; }
                        else { aboveHip = false; belowHipCounter++; }
                        if (counterRight == 15)
                        {
                            if (checkBothHandsStill) { rightHandStill = true; }
                            else
                            {
                                box1.Location = new Point((spineValues.X + leftHipValues.X) / 2, (spineValues.Y + coreValues.Y) / 2);
                                box1.Size = new Size(Math.Abs(spineValues.Y - rightHipValues.Y) * 1.75, Math.Abs(spineValues.Y - rightHipValues.Y) * 1.75);
                                if (!boxDisappear) { dc.DrawRectangle(null, new Pen(Brushes.Red, 4), box1); }
                                if (showCheckMark && !playSong)
                                {
                                    if (Contains(rightHandValues, box2))
                                    {
                                        Instructions.Text = "Good! See the red box? Your beats must fall in this box. Make a down and up motion roughly like this:";
                                        var newImage3 = new Uri(@"C:\Users\admin\Desktop\VirtualOrchestra\GUI\capture.jpg");
                                        checkMarkImage.Source = new BitmapImage(newImage3);
                                        Instructions.Text += Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + "The box will turn green when this is successfully completed.";
                                    }
                                }
                                if (!Contains(SkeletonPointToScreen(prevOneRight), box1) && Contains(rightHandValues, box1) && SkeletonPointToScreen(prevOneRight).Y < box1.Top && rightHandValues.Y > box1.Top) { down = true; }
                                if (down && Contains(SkeletonPointToScreen(prevOneRight), box1) && !Contains(rightHandValues, box1) && SkeletonPointToScreen(prevOneRight).Y > box1.Top && rightHandValues.Y < box1.Top && rightHandValues.X < box1.Right && rightHandValues.X > box1.Left)
                                {
                                    dc.DrawRectangle(null, new Pen(Brushes.Green, 4), box1);
                                    showStartBox = false;
                                    checkMarkImage.Source = null;
                                    showCheckMark = false;
                                    if (!playSong) { Instructions.Text = "Well done!" + Environment.NewLine + "Now spend a little time practicing!" + Environment.NewLine + "The box around the skeleton will flash green each time a beat is recognized."; }
                                    else
                                    {
                                        checkLeftHandStill = true;
                                        counterRight = 0;
                                    }
                                    //if (playSong) { StartBeat.Content = "1"; }
                                    goBack = true;
                                    if (once) { boxDisappear = true; once = false; }
                                    tempoBox = true;
                                    checkRightHandStill = false;
                                    stopwatch.Start();
                                }
                            }
                        }
                        if (checkBothHandsStill && counterRight < 15 && Math.Abs(prevOneRight.X - rightHand.X) < .08 && Math.Abs(prevOneRight.Y - rightHand.Y) < .08 && Math.Abs(prevTwoRight.X - rightHand.X) < .08 && Math.Abs(prevTwoRight.Y - rightHand.Y) < .08 && aboveHip == true && Contains(leftHandValues, box1) && Contains(rightHandValues, box1)) { counterRight++; }
                        if (counterRight < 15 && Math.Abs(prevOneRight.X - rightHand.X) < .08 && Math.Abs(prevOneRight.Y - rightHand.Y) < .08 && Math.Abs(prevTwoRight.X - rightHand.X) < .08 && Math.Abs(prevTwoRight.Y - rightHand.Y) < .08 && aboveHip == true) { counterRight++; }
                        else if (counterRight < 15) { counterRight = 0; }
                    }
                }
                if (checkLeftHandStill)
                {
                    if (leftHand.X != 0 && leftHip.X != 0)
                    {
                        if (leftHand.Y > leftHip.Y) { aboveHip = true; }
                        else { aboveHip = false; belowHipCounter++; }
                        if (belowHipCounter > 1)
                        {
                            if (counterLeft == 15)
                            {
                                if (checkBothHandsStill) { leftHandStill = true; }
                                else
                                {
                                    if (setLocation) { box1.Location = new Point(leftHandValues.X - Math.Abs(leftHipValues.X - rightHipValues.X) * .875,  10); setLocation = false; }
                                    box1.Size = new Size(Math.Abs(leftHipValues.X - rightHipValues.X) * 1.25, rightHipValues.Y);
                                    if (Contains(leftHandValues, box1) && boxDisappear == false)
                                    {
                                        dc.DrawRectangle(null, new Pen(Brushes.Green, 4), box1); 
                                        if (printText && !playSong) { Instructions.Text += Environment.NewLine + "See the green box? Move your hand up and down in this box to increase and decrease the volume."; }
                                        printText = false;
                                    }
                                    else
                                    {
                                        dc.DrawRectangle(null, new Pen(Brushes.Red, 4), box1);
                                        boxDisappear = true;
                                        stopwatch.Start();
                                    }
                                }
                            }
                            if (checkBothHandsStill && counterLeft < 15 && Math.Abs(prevOneLeft.X - leftHand.X) < .08 && Math.Abs(prevOneLeft.Y - leftHand.Y) < .08 && Math.Abs(prevTwoLeft.X - leftHand.X) < .08 && Math.Abs(prevTwoLeft.Y - leftHand.Y) < .08 && aboveHip == true && Contains(leftHandValues, box1) && Contains(rightHandValues, box1)) { counterLeft++; }
                            else if (!checkBothHandsStill && counterLeft < 15 && Math.Abs(prevOneLeft.X - leftHand.X) < .08 && Math.Abs(prevOneLeft.Y - leftHand.Y) < .08 && Math.Abs(prevTwoLeft.X - leftHand.X) < .08 && Math.Abs(prevTwoLeft.Y - leftHand.Y) < .08 && aboveHip == true) { counterLeft++; }
                            else if (counterLeft < 15) { counterLeft = 0; }
                        }
                    }
                }
                if (checkBothHandsStill)
                {
                    double yValue = neckValues.Y + Math.Abs(rightShoulderValues.Y - neckValues.Y) / 2;
                    box1.Size = new Size(Math.Abs(neckValues.Y - coreValues.Y) * 1.5, yValue - 10);
                    box1.Location = new Point(neckValues.X - Math.Abs(neckValues.Y - coreValues.Y) * .75, 10);
                    if (leftHandStill && rightHandStill && rightHandValues.Y < yValue && leftHandValues.Y < yValue) 
                    { 
                        dc.DrawRectangle(null, new Pen(Brushes.Green, 4), box1);
                    }
                    if (leftHandStill && rightHandStill)
                    {
                        if (Instructions.Text != "You stopped the music! Congratulations!" && musicStopped != true && !playSong) { Instructions.Text = "Awesome! Now, move your hands diagonally downward, into the red boxes."; }
                        box2.Size = new Size(Math.Abs(rightHipValues.X - leftHipValues.X) * 1.25, Math.Abs(rightHipValues.X - leftHipValues.X) * 1.25);
                        box2.Location = new Point(coreValues.X - Math.Abs(neckValues.Y - coreValues.Y) - box2.Size.Width, spineValues.Y);
                        box3.Size = box2.Size;
                        box3.Location = new Point(coreValues.X + Math.Abs(neckValues.Y - coreValues.Y), box2.Location.Y);
                        if (Math.Abs(rightHand.X - prevOneRight.X) < .1 && Math.Abs(leftHand.X - prevOneLeft.X) < .1 && Math.Abs(rightHand.Y - prevOneRight.Y) < .1 && Math.Abs(leftHand.Y - prevOneLeft.Y) < .1 && Contains(rightHandValues, box3) && Contains(leftHandValues, box2))
                        {
                            dc.DrawRectangle(null, new Pen(Brushes.Green, 4), box2);
                            dc.DrawRectangle(null, new Pen(Brushes.Green, 4), box3);
                            if (!playSong) { Instructions.Text = "You stopped the music! Congratulations!"; }
                            musicStopped = true;
                            boxDisappear = true;
                        }
                        else if (boxDisappear == false)
                        {
                            dc.DrawRectangle(null, new Pen(Brushes.Red, 4), box2);
                            dc.DrawRectangle(null, new Pen(Brushes.Red, 4), box3);
                        }
                    }
                    else { dc.DrawRectangle(null, new Pen(Brushes.Gray, 4), box1); }
                }
                if (boxDisappear == true && stopwatch.ElapsedMilliseconds > 800)
                {
                    counterLeft = 0;
                    counterRight = 0;
                    checkRightHandStill = false;
                    boxDisappear = false;
                    stopwatch.Reset();
                    belowHipCounter = 0;
                    showStartBox = false;
                    setLocation = true;
                    if (checkLeftHandStill == true && !playSong)
                    {
                        Instructions.Text = "Your hand was no longer inside the box of allowed values, which is why it disappeared." + Environment.NewLine + "To resume changing the volume, put your left hand below your hip. This resets the volume. You can then put your left hand back above your hip and leave it in the same place for about a second. You will see the green box again.";
                    }
                }

                if (skel.TrackingState == SkeletonTrackingState.Tracked)
                {
                    this.DrawBonesAndJoints(skel, dc);
                }
                else if (skel.TrackingState == SkeletonTrackingState.PositionOnly)
                {
                    dc.DrawEllipse(
                    this.centerPointBrush,
                    null,
                    this.SkeletonPointToScreen(skel.Position),
                    BodyCenterThickness,
                    BodyCenterThickness);
                }
            }
            prevTwoRight = prevOneRight;
            prevOneRight = rightHand;
            prevTwoLeft = prevOneLeft;
            prevOneLeft = leftHand;
            // Prevent drawing outside of our render area
            this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, RenderWidth, RenderHeight));
        }
示例#51
0
        static int Main(string[] args)
        {
            Console.WriteLine("S# Test Execute");
            if (args == null || args.Length == 0 || !Directory.Exists(args[0]))
            {
                TypeLine("Please specify valid path containing test files", ConsoleColor.Red);
                return(1);
            }

            TypeLine("Initializing script engine", ConsoleColor.Yellow);

            Stopwatch totalTime = Stopwatch.StartNew();


            Stopwatch sw = new Stopwatch();

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

            RuntimeHost.Initialize();

            TypeLine("Elapsed time:" + sw.ElapsedMilliseconds, ConsoleColor.White);
            TypeLine("Pass 1: Parsing files", ConsoleColor.Yellow);

            DirectoryInfo dir = new DirectoryInfo(args[0]);

            int parsingErr = 0, execErr = 0, total = 0;

            foreach (var file in dir.GetFiles())
            {
                sw.Reset(); sw.Start();
                try
                {
                    Script s = Script.Compile(File.ReadAllText(file.FullName));
                    TypeLine("Parsing:" + file.Name + " success elapsed time:" + sw.ElapsedMilliseconds, ConsoleColor.Gray);
                }
                catch (ScriptSyntaxErrorException)
                {
                    parsingErr++;
                    TypeLine("Parsing:" + file.Name + " failed elapsed time:" + sw.ElapsedMilliseconds, ConsoleColor.Red);
                }
            }

            TypeLine("Pass 2: Executing", ConsoleColor.Yellow);

            foreach (var file in dir.GetFiles())
            {
                sw.Reset(); sw.Start();
                total++;
                try
                {
                    Script s = Script.Compile(File.ReadAllText(file.FullName));
                    s.Context.SetItem("Console", typeof(Console));
                    s.Context.SetItem("Test", new Test());
                    object rez = s.Execute();
                    //TypeLine("Execute:" + file.Name + " success, result [" + (rez == null ? "Null" : rez.ToString()) + "] elapsed time:" + sw.ElapsedMilliseconds, ConsoleColor.Gray);
                    TypeLine(file.Name + ";success;" + sw.ElapsedMilliseconds, ConsoleColor.Gray);
                }
                catch (Exception e)
                {
                    execErr++;
                    //TypeLine("Execute:" + file.Name + " failed, exception [" + e.Message + "] elapsed time:" + sw.ElapsedMilliseconds, ConsoleColor.Red);
                    TypeLine(file.Name + ";fail;" + e.Message, ConsoleColor.DarkRed);
                }
            }

            if (execErr + parsingErr == 0)
            {
                TypeLine("Done, all " + total + " tests passed, time " + totalTime.ElapsedMilliseconds, ConsoleColor.Green);
                return(0);
            }
            else
            {
                TypeLine(string.Format("Done tests {2} in {3} ms with errors: parsing {0}, execution {1}", parsingErr, execErr, total, totalTime.ElapsedMilliseconds), ConsoleColor.Red);
                return(1);
            }
        }
示例#52
0
        static void Main(string[] args)
        {
            int[]        iters    = { 5, 10, 20, 30, 100, 1000 };
            List <Point> pointsst = init(1000);
            PairPoint    ppst     = brutforce(1000, pointsst);

            Console.WriteLine("Алгоритм грубой силы");
            Console.WriteLine("Время работы алгоритма");
            Console.WriteLine("Первая точка");
            Console.WriteLine("(" + ppst.Point1.X + "," + ppst.Point1.Y + ")");
            Console.WriteLine("Вторая точка");
            Console.WriteLine("(" + ppst.Point2.X + "," + ppst.Point2.Y + ")");
            Console.WriteLine("Расстояние между точками");
            Console.WriteLine(ppst.Distance());
            Console.ReadLine();
            DivideAndConquer dacst = new DivideAndConquer(1000, pointsst);
            PairPoint        pp1st = dacst.MyClosestDivide();

            Console.WriteLine("Алгоритм декомпозиции");
            Console.WriteLine("Время работы алгоритма");
            Console.WriteLine("Первая точка");
            Console.WriteLine("(" + pp1st.Point1.X + "," + pp1st.Point1.Y + ")");
            Console.WriteLine("Вторая точка");
            Console.WriteLine("(" + pp1st.Point2.X + "," + pp1st.Point2.Y + ")");
            Console.WriteLine("Расстояние между точками");
            Console.WriteLine(pp1st.Distance());
            Console.ReadLine();
            foreach (int i in iters)
            {
                for (int j = 0; j < 100; j++)
                {
                    //List<Point> points = new List<Point>();
                    //Point point1 = new Point();
                    //point1.X = 3;
                    //point1.Y = 1;
                    //points.Add(point1);
                    //Point point2 = new Point();
                    //point2.X = 4;
                    //point2.Y = 2;
                    //points.Add(point2);
                    //Point point3 = new Point();
                    //point3.X = 5;
                    //point3.Y = 6;
                    //points.Add(point3);
                    //Point point4 = new Point();
                    //point4.X = 7;
                    //point4.Y = 8;
                    //points.Add(point4);
                    //Point point5 = new Point();
                    //point5.X = 6;
                    //point5.Y = 4;
                    //points.Add(point5);
                    List <Point> points = init(i);
                    Stopwatch    timer  = new Stopwatch();
                    timer.Start();
                    PairPoint pp = brutforce(i, points);
                    timer.Stop();
                    Console.WriteLine("Алгоритм грубой силы");
                    long time = timer.ElapsedMilliseconds;
                    Console.WriteLine("Время работы алгоритма");
                    Console.WriteLine(time);
                    Console.WriteLine("Первая точка");
                    Console.WriteLine("(" + pp.Point1.X + "," + pp.Point1.Y + ")");
                    Console.WriteLine("Вторая точка");
                    Console.WriteLine("(" + pp.Point2.X + "," + pp.Point2.Y + ")");
                    Console.WriteLine("Расстояние между точками");
                    Console.WriteLine(pp.Distance());
                    DivideAndConquer dac = new DivideAndConquer(i, points);
                    timer.Reset();
                    timer.Start();
                    PairPoint pp1 = dac.MyClosestDivide();
                    timer.Stop();
                    long time2 = timer.ElapsedMilliseconds;
                    Console.WriteLine("Алгоритм декомпозиции");
                    Console.WriteLine("Время работы алгоритма");
                    Console.WriteLine(time2);
                    Console.WriteLine("Первая точка");
                    Console.WriteLine("(" + pp1.Point1.X + "," + pp1.Point1.Y + ")");
                    Console.WriteLine("Вторая точка");
                    Console.WriteLine("(" + pp1.Point2.X + "," + pp1.Point2.Y + ")");
                    Console.WriteLine("Расстояние между точками");
                    Console.WriteLine(pp1.Distance());
                }
                Console.ReadLine();
            }
        }
示例#53
0
 public static void LogMessage()
 {
     Log.Message(stringBuilder.ToString());
     stringBuilder.Remove(0, stringBuilder.Length);
     stopWatch.Reset();
 }
示例#54
0
 public void Clear()
 {
     _askToConfirmReset = false;
     confirmTimer.Reset();
 }
示例#55
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the size of array.");
            int size = Convert.ToInt32(Console.ReadLine());

            int[]     arr   = new int[size];
            Stopwatch time1 = new Stopwatch();
            Random    rand  = new Random();

            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = rand.Next(100);
            }
            Console.WriteLine("This is a your random array.");

            PrintArray(arr);

            Console.WriteLine("1.Insertion Sort.");
            Console.WriteLine("2.Bubble Sort.");
            Console.WriteLine("3.Heap Sort.");
            Console.WriteLine("4.Quick Sort.");
            Console.WriteLine("5.Merge Sort.");
            Console.WriteLine("6.All");

            string sortIndexis            = Console.ReadLine();
            Dictionary <int, double> dict = new Dictionary <int, double>();
            DateTime currentTime          = DateTime.Now;
            double   time = 0;

            for (int i = 0; i < sortIndexis.Length; i++)
            {
                if (sortIndexis[i] == ',')
                {
                    continue;
                }
                if (sortIndexis.Length == 1 && sortIndexis[0] == '6')
                {
                    int[] arr1 = CopyArray(arr);
                    time1.Start();
                    Insertion.Sort(arr1);
                    time1.Stop();
                    dict.Add(1, time1.Elapsed.TotalMilliseconds);
                    time1.Reset();

                    arr1 = CopyArray(arr);
                    time1.Start();
                    Bubble.Sort(arr1);
                    time1.Stop();
                    dict.Add(2, time1.Elapsed.TotalMilliseconds);
                    time1.Reset();

                    arr1 = CopyArray(arr);
                    time1.Start();
                    Heap.Sort(arr);
                    time1.Stop();
                    dict.Add(3, time1.Elapsed.TotalMilliseconds);
                    time1.Reset();

                    arr1 = CopyArray(arr);
                    time1.Start();
                    Quick.Sort(arr);
                    time1.Stop();
                    dict.Add(4, time1.Elapsed.TotalMilliseconds);
                    time1.Reset();

                    arr1 = CopyArray(arr);
                    time1.Start();
                    Merge.Sort(arr1);
                    time1.Stop();
                    dict.Add(5, time1.Elapsed.TotalMilliseconds);
                    time1.Reset();
                    break;
                }
                else
                {
                    if (i + 1 < sortIndexis.Length && sortIndexis[i + 1] == '-')
                    {
                        char a = sortIndexis[i];

                        while (a <= sortIndexis[i + 2])
                        {
                            switch (a)
                            {
                            case '1':
                            {
                                int[] arr1 = CopyArray(arr);
                                time1.Start();
                                Insertion.Sort(arr1);
                                time1.Stop();
                                dict.Add(1, time1.Elapsed.TotalMilliseconds);
                                time1.Reset();
                                break;
                            }

                            case '2':
                            {
                                int[] arr1 = CopyArray(arr);
                                time1.Start();
                                Bubble.Sort(arr1);
                                time1.Stop();
                                dict.Add(2, time1.Elapsed.TotalMilliseconds);
                                time1.Reset();
                                break;
                            }

                            case '3':
                            {
                                int[] arr1 = CopyArray(arr);
                                time1.Start();
                                Heap.Sort(arr1);
                                time1.Stop();
                                dict.Add(3, time1.Elapsed.TotalMilliseconds);
                                time1.Reset();
                                break;
                            }

                            case '4':
                            {
                                int[] arr1 = CopyArray(arr);
                                time1.Start();
                                Quick.Sort(arr1);
                                time1.Stop();
                                dict.Add(4, time1.Elapsed.TotalMilliseconds);
                                time1.Reset();
                                break;
                            }

                            case '5':
                            {
                                int[] arr1 = CopyArray(arr);
                                time1.Start();
                                Merge.Sort(arr1);
                                time1.Stop();
                                dict.Add(5, time1.Elapsed.TotalMilliseconds);
                                time1.Reset();
                                break;
                            }
                            }
                            a++;
                        }
                        i += 2;
                    }
                    else
                    {
                        if (sortIndexis[i] == '1' || sortIndexis[i] == '2' || sortIndexis[i] == '3' || sortIndexis[i] == '4' || sortIndexis[i] == '5')
                        {
                            switch (sortIndexis[i])
                            {
                            case '1':
                            {
                                int[] arr1 = CopyArray(arr);
                                time1.Start();
                                Insertion.Sort(arr1);
                                time1.Stop();
                                dict.Add(1, time1.Elapsed.TotalMilliseconds);
                                time1.Reset();
                                break;
                            }

                            case '2':
                            {
                                int[] arr1 = CopyArray(arr);
                                time1.Start();
                                Bubble.Sort(arr1);
                                time1.Stop();
                                dict.Add(2, time1.Elapsed.TotalMilliseconds);
                                time1.Reset();
                                break;
                            }

                            case '3':
                            {
                                int[] arr1 = CopyArray(arr);
                                time1.Start();
                                Heap.Sort(arr1);
                                time1.Stop();
                                dict.Add(3, time1.Elapsed.TotalMilliseconds);

                                time1.Reset(); break;
                            }

                            case '4':
                            {
                                int[] arr1 = CopyArray(arr);
                                time1.Start();
                                Quick.Sort(arr1);
                                time1.Stop();
                                dict.Add(4, time1.Elapsed.TotalMilliseconds);
                                time1.Reset();
                                break;
                            }

                            case '5':
                            {
                                int[] arr1 = CopyArray(arr);
                                time1.Start();
                                Merge.Sort(arr1);
                                time1.Stop();
                                dict.Add(5, time1.Elapsed.TotalMilliseconds);
                                time1.Reset();
                                break;
                            }
                            }
                        }
                        else
                        {
                            Console.WriteLine("Incorrect input");
                            break;
                            Console.Read();
                            return;
                        }
                    }
                }
            }

            time = dict.First().Value;
            int    index = dict.First().Key;
            string fast  = "the fastest";

            if (dict.Count == 1)
            {
                fast = null;
            }
            else
            {
                for (int i = 1; i <= 5; i++)
                {
                    if (dict.ContainsKey(i) == false)
                    {
                        continue;
                    }
                    if (dict[i] < time)
                    {
                        time  = dict[i];
                        index = i;
                    }
                    Console.WriteLine(i);
                    Console.WriteLine(dict[i]);
                }
            }
            Console.ForegroundColor = ConsoleColor.Green;
            switch (index)
            {
            case 1:
            {
                Console.WriteLine("Insertion Sort " + fast);
                Console.Write("Time =");
                Console.WriteLine(time);
                Insertion.Sort(arr);
                Console.WriteLine("Memory:0");
                PrintArray(arr);
                break;
            }

            case 2:
            {
                Console.WriteLine("Bubble Sort " + fast);
                Console.Write("Time =");
                Console.WriteLine(time);
                Bubble.Sort(arr);
                Console.WriteLine("Memory:0");
                PrintArray(arr);
                break;
            }

            case 3:
            {
                Console.WriteLine("Heap Sort " + fast);
                Console.Write("Time =");
                Console.WriteLine(time);
                Heap.Sort(arr);
                Console.WriteLine("Memory:0");
                PrintArray(arr);
                break;
            }

            case 4:
            {
                Console.WriteLine("Quick Sort " + fast);
                Console.Write("Time =");
                Console.WriteLine(time);
                Quick.Sort(arr);
                Console.WriteLine("Memory:0");
                PrintArray(arr);
                break;
            }

            case 5:
            {
                Console.WriteLine("Merge Sort " + fast);
                Console.Write("Time =");
                Console.WriteLine(time);
                Console.Write("Memory:");
                Console.Write(Merge.memory);
                Merge.Sort(arr);
                PrintArray(arr);
                break;
            }
            }


            Console.Read();
        }
示例#56
0
文件: FEITTimer.cs 项目: ellil4/CPT
 public void Reset()
 {
     mTimer.Reset();
 }
示例#57
0
        private void FocusButton_Click(object sender, EventArgs e)
        {
            int desiredMillisecondDelay = controls.timeNeededForChange;
            int arraySize = (desiredMillisecondDelay / 1000) * rate;

            serial.Read();
            rate = serial.getRate();

            double lowConcentration  = 0;
            double highConcentration = 0;

            //first get threshholds
            bool done = false;

            while (!done)
            {
                int     reads    = 0;
                decimal allReads = 0;
                MessageBox.Show("First try to let your mind wander until the next popup appears. Hit OK when ready.", string.Empty, MessageBoxButtons.OK);
                timer.Start();
                while (timer.ElapsedMilliseconds < Globals.threshholdAquisitionTime)
                {
                    decimal currentIn = (decimal)Math.Abs(serial.GetData()[Globals.inputNode]);
                    allReads += currentIn;
                    reads++;
                }

                timer.Reset();
                lowConcentration = (double)(allReads / reads);
                Console.WriteLine("Low concentration was: " + lowConcentration);

                reads    = 0;
                allReads = 0;

                MessageBox.Show("Next try to focus as hard as possible something. Hit OK when ready.", string.Empty, MessageBoxButtons.OK);

                timer.Start();
                while (timer.ElapsedMilliseconds < Globals.threshholdAquisitionTime)
                {
                    decimal currentIn = (decimal)Math.Abs(serial.GetData()[Globals.inputNode]);
                    allReads += currentIn;
                    reads++;
                }
                timer.Reset();

                highConcentration = (double)(allReads / reads);

                Console.WriteLine("High concentration was: " + highConcentration);

                if (highConcentration > lowConcentration)
                {
                    done = true;
                }
            }

            double differenceInConcentrations = highConcentration - lowConcentration;
            double deltaBetweenThreshholds    = differenceInConcentrations / 2;

            //make ranges for this run
            ranges = new List <Threshhold>(2);


            //make sure all reads work for it
            ranges.Add(new Threshhold(Double.MinValue, lowConcentration + (deltaBetweenThreshholds)));

            ranges.Add(new Threshhold(lowConcentration + (deltaBetweenThreshholds), Double.MaxValue));


            MessageBox.Show("Ready to control hand. Press OK when ready.", string.Empty, MessageBoxButtons.OK);
        }
示例#58
0
 public void TeaseVideoOptions()
 {
     NavController.ShowVideoOptions();
     VidOptionsTimer?.Reset();
     VidOptionsTimer?.Start();
 }
示例#59
0
        public void Run()
        {
            Mouse.DefaultMoveTime        = 300;
            Keyboard.DefaultKeyPressTime = 100;
            Delay.SpeedFactor            = 1.0;

            Ranorex.Unknown element = null;

            RanorexRepository   repo              = new RanorexRepository();
            fnWriteToLogFile    WriteToLogFile    = new fnWriteToLogFile();
            fnTimeMinusOverhead TimeMinusOverhead = new fnTimeMinusOverhead();
            fnDumpStatsQ4       DumpStatsQ4       = new fnDumpStatsQ4();
            fnWriteToErrorFile  WriteToErrorFile  = new fnWriteToErrorFile();

            // Create new stopwatch
            Stopwatch MystopwatchTT = new Stopwatch();

            MystopwatchTT.Reset();
            MystopwatchTT.Start();

            Stopwatch MystopwatchTotal = new Stopwatch();

            MystopwatchTotal.Reset();
            MystopwatchTotal.Start();
            Stopwatch MystopwatchQ4          = new Stopwatch();
            Stopwatch MystopwatchModuleTotal = new Stopwatch();
            Stopwatch MystopwatchF1          = new Stopwatch();
            Stopwatch MystopwatchTrade       = new Stopwatch();

            Global.LogFileIndentLevel++;
            Global.LogText = "IN fnCheckout";
            WriteToLogFile.Run();

            MystopwatchModuleTotal.Reset();
            MystopwatchModuleTotal.Start();

            // Click on CheckOut F12 button
            Global.LogText = @"Clicking on F12 Checkout";
            WriteToLogFile.Run();

            MystopwatchQ4.Reset();
            MystopwatchQ4.Start();

            if (Global.DomesticRegister)
            {
//				while(!repo.Retech.ButtonCheckout.Enabled)   // change 1/8/18
//				while( !Host.Local.TryFindSingle(repo.Retech.ButtonCheckoutInfo.AbsolutePath.ToString(), out element) )
                while (!Host.Local.TryFindSingle(repo.Retech.DataContextShowCheckoutViewCommandInfo.AbsolutePath.ToString(), out element))
                {
                    if (Host.Local.TryFindSingle(repo.ContinueButtonCommandInfo.AbsolutePath.ToString(), out element))
                    {
                        repo.ContinueButtonCommand.Click();
                        Global.LogText = @"Clicked on Continue Button - 1 in fnCheckout()";
                        WriteToLogFile.Run();
                    }
                    Thread.Sleep(100);
                }
//				Keyboard.Press("{F12}");
// Try fix 1/31/18
                while (!Host.Local.TryFindSingle(repo.Retech.RequestCashSettlementInfo.AbsolutePath.ToString(), out element))
                {
                    // 07-25-18 check for "Pick Up At Store Requests" pop-up
                    if (!Host.Local.TryFindSingle(repo.PickupAtStorePopupNotifier.PickupAtStoreRequestPopUpInfo.AbsolutePath.ToString(), out element))
                    {
                        Thread.Sleep(10);
                    }
                    else
                    {
                        Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Down item 'PopupNotifierView' at 434;30.", repo.PickupAtStorePopupNotifier.SelfInfo, new RecordItemIndex(0));
                        repo.PickupAtStorePopupNotifier.Self.MoveTo("434;30");
                        Keyboard.Press("{ENTER}");
                        //Mouse.ButtonDown(System.Windows.Forms.MouseButtons.Left);
                        Delay.Milliseconds(200);
                        // repo.PopupNotifierView.Self.Click();
                        Thread.Sleep(100);
                    }

                    if (Host.Local.TryFindSingle(repo.Retech.NotInterestedCommandInfo.AbsolutePath.ToString(), out element))
                    {
                        repo.Retech.NotInterestedCommand.Click();
                        Thread.Sleep(100);
                    }



                    if (repo.Retech.DataContextShowCheckoutViewCommand.Enabled)
                    {
                        repo.Retech.DataContextShowCheckoutViewCommand.Click();
                    }
                    Thread.Sleep(300);
                    if (Host.Local.TryFindSingle(repo.ContinueButtonCommandInfo.AbsolutePath.ToString(), out element))
                    {
                        repo.ContinueButtonCommand.Click();
                        Global.LogText = @"Clicked on Continue Button - 1 in fnCheckout()";
                        WriteToLogFile.Run();
                    }
                    Thread.Sleep(100);
                }
//				repo.Retech.DataContextShowCheckoutViewCommand.Click();
            }
            else
            {
//				while(!repo.IPOS20167172.Self.Enabled)
//					{ Thread.Sleep(100); }
//				repo.IPOS20167172.Self.PressKeys("{F12}");
                if (repo.IPOS34069.F12TotalInfo.Exists(5000))                  // 02-08-18
                {
                }
                repo.IPOS34069.F12Total.PressKeys("{F12}");                  // 02-08-18

                if (Global.CurrentScenario == 47)
                {
                    while (!repo.CustomerLookupPhone_Number.Enabled)
                    {
                        Thread.Sleep(100);
                    }

                    MystopwatchQ4.Start();
                    MystopwatchQ4.Reset();
//					repo.CustomerLookupScreen.EdgePowerUpNumber.PressKeys("6364916031910400011");
                    repo.CustomerLookupPhone_Number.PressKeys("9727651234");
                    repo.CustomerLookupScreen.BtnSearch.Click();
                    while (!repo.CustomerLookupSelectF5.Enabled)
                    {
                        Thread.Sleep(100);
                    }
                    repo.CustomerLookupSelectF5.Click();
                    TimeMinusOverhead.Run((float)MystopwatchQ4.ElapsedMilliseconds);                       // Subtract overhead and store in Global.Q4StatLine
                    Global.CurrentMetricDesciption = @"Search for Customer";
                    Global.Module = "Finalize";
                    DumpStatsQ4.Run();

                    MystopwatchQ4.Reset();
                    MystopwatchQ4.Start();

                    repo.TransactionCustomerInformation.Email.Click("160;2");
                    Delay.Milliseconds(200);

                    repo.TransactionCustomerInformation.Email.PressKeys("301 My Street");
                    Delay.Milliseconds(0);

                    repo.TransactionCustomerInformation.LastName.Click("114;1");
                    Delay.Milliseconds(200);

                    repo.TransactionCustomerInformation.LastName.PressKeys("9727651234");
                    Delay.Milliseconds(0);

                    repo.TransactionCustomerInformation.Address1.Click("41;6");
                    Delay.Milliseconds(200);

                    repo.TransactionCustomerInformation.Address1.PressKeys("My City");
                    Delay.Milliseconds(0);

                    repo.TransactionCustomerInformation.Open.Click();
                    Delay.Milliseconds(200);

                    repo.TransactionCustomerInformation.Open.Click();
                    Delay.Milliseconds(200);

                    repo.ListItemsValues.ListItemAB.Click();
                    Delay.Milliseconds(200);

                    repo.TransactionCustomerInformation.BtnAcceptButton.Click("23;27");
                    Delay.Milliseconds(200);

                    repo.PopUpCustomerLookupUnavailable.OKF5.Click("17;22");
                    Delay.Milliseconds(200);

                    TimeMinusOverhead.Run((float)MystopwatchQ4.ElapsedMilliseconds);                       // Subtract overhead and store in Global.Q4StatLine
                    Global.CurrentMetricDesciption = @"Enter Customer Information";
                    Global.Module = "Finalize";
                    DumpStatsQ4.Run();
                }
            }

            Thread.Sleep(1000);

            // Check for Please select a charity to donate
            if (Host.Local.TryFindSingle(repo.RetechPeripheralHostWindow.PleaseSelectACharityToDonateInfo.AbsolutePath.ToString(), out element))
            {
                repo.RetechPeripheralHostWindow.DeclineDonateNoThanks.Click();
                Thread.Sleep(100);
            }

            if (Global.DomesticRegister)
            {
                Global.LogText = @"Waiting on Time to Check Out - in fnCheckout()";
                WriteToLogFile.Run();
                Thread.Sleep(300);
                while (!Host.Local.TryFindSingle(repo.Retech.TimeToCheckOutInfo.AbsolutePath.ToString(), out element))
                {
                    if (Host.Local.TryFindSingle(repo.ContinueButtonCommandInfo.AbsolutePath.ToString(), out element))
                    {
                        repo.ContinueButtonCommand.Click();
                        Global.LogText = @"Clicked on Continue Button - 2 in fnCheckout()";
                        WriteToLogFile.Run();
                        Thread.Sleep(100);
                    }
                    Thread.Sleep(100);

                    if (Host.Local.TryFindSingle(repo.Retech.AcknowledgeRelatedProductsCommandInfo.AbsolutePath.ToString(), out element))
                    {
                        if (Host.Local.TryFindSingle(repo.Retech.AcknowledgeRelatedProductsCommandInfo.AbsolutePath.ToString(), out element))
                        {
                            if (repo.Retech.AcknowledgeRelatedProductsCommand.Enabled)
                            {
                                Global.LogText = @"Clicking on acknowledge related products before F12";
                                WriteToLogFile.Run();
                                repo.Retech.AcknowledgeRelatedProductsCommand.Click();
                                Thread.Sleep(100);
                            }
                        }
                    }
                    else if (Host.Local.TryFindSingle(repo.Retech.ContinueF5_5_6_0_103Info.AbsolutePath.ToString(), out element))
                    {
                        if (repo.Retech.ContinueF5_5_6_0_103.Enabled)
                        {
                            Global.LogText = @"Clicking on F5 Continue before F12";
                            WriteToLogFile.Run();
                            repo.Retech.ContinueF5_5_6_0_103.Click();
                            Thread.Sleep(100);
                            repo.Retech.ButtonCheckout.Click();
                            Thread.Sleep(100);
                        }
                    }
                }

                TimeMinusOverhead.Run((float)MystopwatchQ4.ElapsedMilliseconds);                   // Subtract overhead and store in Global.Q4StatLine
                Global.CurrentMetricDesciption = @"[F12] wait for payment icons";
                Global.Module = "Finalize";
                DumpStatsQ4.Run();
            }

            MystopwatchQ4.Reset();
            MystopwatchQ4.Start();

            // Click on screen to make sure in focust - .focus not work
            //if(Global.DomesticRegister)    1-22-19
            //	repo.Retech.PaymentView.Click("689;82");

            switch (Global.PayWithMethod)
            {
            case "Cash":
                Global.LogText = @"Waiting on Cash F5";
                WriteToLogFile.Run();
                if (Global.DomesticRegister)
                {
                    repo.Retech.Self.Focus();
                }
                Thread.Sleep(100);

                if (Global.DomesticRegister)
                {
                    while (!repo.Retech.RequestCashSettlement.Enabled)
                    {
                        Thread.Sleep(500);
                    }
                }
                else
                {
                    while (!Host.Local.TryFindSingle(repo.FormPOS1.SelfInfo.AbsolutePath.ToString(), out element))
                    {
                        Thread.Sleep(500);
                    }
                    //while(!repo.EnterSerialNumber.F5Cash.Enabled) {	Thread.Sleep(500); }
                }
                Global.LogText = @"Found Cash F5 Enabled";
                WriteToLogFile.Run();
                break;

            case "Credit":
            case "PURCC":
                Global.LogText = @"Waiting on Manual Card F6";
                WriteToLogFile.Run();
                if (Global.DomesticRegister)
                {
                    repo.Retech.Self.Focus();
                }
                Thread.Sleep(100);

                if (Global.DomesticRegister)
                {
                    while (!repo.Retech.RequestManualCardSettlement.Enabled)
                    {
                        Thread.Sleep(500);
                    }
                }
                else
                {
                    while (!repo.EnterSerialNumber.F5Cash.Enabled)
                    {
                        Thread.Sleep(500);
                    }
                }

                Global.LogText = @"Found Manual Card F6 Enabled";
                WriteToLogFile.Run();
                break;
            }

            // Check for cash back
            if (Global.DomesticRegister &&
                repo.Retech.AmountDue.TextValue.Substring(0, 1) == "(" &&
                (Global.CurrentScenario == 37 || Global.CurrentScenario == 47)
                )
            {
                Global.LogText = @"Clicking on Cash F5 button";
                WriteToLogFile.Run();
                // fix 1//22/18
                while (!Host.Local.TryFindSingle(repo.Retech.RequestCashSettlementInfo.AbsolutePath.ToString(), out element))
                {
                    Thread.Sleep(100);
                }
                // end fix
                repo.Retech.RequestCashSettlement.Click();
                Thread.Sleep(100);
                Global.LogText = @"Waiting on CashPaymentView";
                WriteToLogFile.Run();
                while (!repo.RetechCardPaymentView.CashPaymentView.Enabled)
                {
                    Thread.Sleep(100);
                }
                Keyboard.Press("{Enter}");
            }
            else
            {
                string BalanceDueText      = "";
                string BalTemp             = "";
                float  BalanceDueAmount    = 0.0F;
                string BalanceDueAmountTxt = "";

                // Read Remaining Balance from screen
                if (Global.DomesticRegister)
                {
                    BalanceDueText      = repo.Retech.BalanceDue.TextValue;
                    BalTemp             = BalanceDueText.Substring(1, BalanceDueText.Length - 1);
                    BalanceDueAmount    = float.Parse(BalTemp);
                    BalanceDueAmountTxt = Convert.ToString(BalanceDueAmount);
                }
                else
                {
                    BalanceDueText      = repo.IntListItemAmountDue.ToString();
                    BalanceDueText      = BalanceDueText.Replace("\t", "  ");
                    BalTemp             = BalanceDueText.Substring(35, 8);
                    BalanceDueAmount    = float.Parse(BalTemp);
                    BalanceDueAmountTxt = Convert.ToString(BalanceDueAmount);
                }

                switch (Global.PayWithMethod)
                {
                case "Cash":
                    // Click on Cash F5 button
                    Global.LogText = @"Clicking on Cash F5 button";
                    WriteToLogFile.Run();

                    if (Global.DomesticRegister)
                    {
                        while (!Host.Local.TryFindSingle(repo.Retech.RequestCashSettlementInfo.AbsolutePath.ToString(), out element))
                        {
                            Thread.Sleep(100);
                        }                                                            // change 1/8/17
                        repo.Retech.RequestCashSettlement.Click();
                        while (!Host.Local.TryFindSingle(repo.RetechCardPaymentView.TxtAmountPaidInfo.AbsolutePath.ToString(), out element))
                        {
                            Thread.Sleep(100);
                        }

                        // Enter amount paid
                        repo.RetechCardPaymentView.TxtAmountPaid.TextValue = BalanceDueAmountTxt;
                        repo.RetechCardPaymentView.TxtAmountPaid.PressKeys("{Enter}");
                    }
                    else
                    {
                        repo.EnterSerialNumber.Self.PressKeys("{F5}");

                        // Enter amount paid
                        repo.Amount.Self.PressKeys("{Enter}");
                    }

                    TimeMinusOverhead.Run((float)MystopwatchQ4.ElapsedMilliseconds);                               // Subtract overhead and store in Global.Q4StatLine
                    Global.CurrentMetricDesciption = @"[F5] enter amount press Enter";
                    Global.Module = "Finalize";
                    DumpStatsQ4.Run();

                    break;

                case "Credit":
                    if (Global.DomesticRegister)
                    {
                        // Click on Manual Card F6 button
                        Global.LogText = @"Clicking on Manual Card F6 button";
                        WriteToLogFile.Run();
                        repo.Retech.RequestManualCardSettlement.Click();

                        while (!repo.RetechCardPaymentView.RunAsCreditCard.Enabled)
                        {
                            if (!Host.Local.TryFindSingle(repo.RetechCardPaymentView.RetrySameCardInfo.AbsolutePath.ToString(), out element))
                            {
                                Global.LogText = @"Clicking on Retry same card";
                                WriteToLogFile.Run();
                                Global.TempErrorString = Global.LogText;
                                WriteToErrorFile.Run();
                                repo.RetechCardPaymentView.RetrySameCard.Click();
                                Thread.Sleep(200);
                            }
                            Thread.Sleep(100);
                        }

                        // Click on Run as Credit button
                        Global.LogText = @"Clicking on Run as Credit button";
                        WriteToLogFile.Run();
                        while (!Host.Local.TryFindSingle(repo.RetechCardPaymentView.RunAsCreditCardInfo.AbsolutePath.ToString(), out element))
                        {
                            Thread.Sleep(100);
                        }                                                            // change 1/8/17
                        repo.RetechCardPaymentView.RunAsCreditCard.Click();


                        string RetechVersion = Global.RetechVersion;
                        string Sub           = Global.RetechVersion.Substring(0, 4);
                        //						if(Global.RetechVersion.Substring(0,4) != "5.14")
                        if (Global.RetechVersion.Substring(0, 4) == "5.13")
                        {                                       // ### For Retech 5.13 and below - see else code for Retech 5.14
                            while (!repo.RetechCardPaymentView.TxtCardNumber.Enabled)
                            {
                                if (Host.Local.TryFindSingle(repo.RetechCardPaymentView.RetrySameCardInfo.AbsolutePath.ToString(), out element))
                                {
                                    repo.RetechCardPaymentView.RetrySameCard.Click();
                                    Thread.Sleep(200);
                                }
                                Thread.Sleep(100);
                            }

                            //						Thread.Sleep(500);

                            repo.RetechCardPaymentView.TxtCardNumber.TextValue = Global.CreditCardNumber;
                            string aa = Global.CreditCardMonth + "/" + Global.CreditCardYear;
                            repo.RetechCardPaymentView.TxtExpirationDate.TextValue = Global.CreditCardMonth + "/" + Global.CreditCardYear;
                            repo.RetechCardPaymentView.TxtZipCode.TextValue        = Global.CreditCardZip;

                            repo.RetechCardPaymentView.ProcessCreditCardView.PressKeys("{Enter}");
                            //						Thread.Sleep(100);

                            while (!Global.AbortScenario &&
                                   !Host.Local.TryFindSingle(repo.RetechCardPaymentView.Waiting_for_SignatureInfo.AbsolutePath.ToString(), out element))

                            {
                                Thread.Sleep(100);
                                if (Host.Local.TryFindSingle(repo.RetechCardPaymentView.TryAuthorizingAgainInfo.AbsolutePath.ToString(), out element))
                                {
                                    Global.AbortScenario   = true;
                                    Global.TempErrorString = "Credit Card Unable to Process Payment - transaction voided";
                                    WriteToErrorFile.Run();
                                    Global.LogText = Global.TempErrorString;
                                    WriteToLogFile.Run();
                                    Keyboard.Press("{Escape}");
                                    Thread.Sleep(100);
                                    repo.Retech.DataContextVoidOrderCommand.Click();
                                    Thread.Sleep(100);
                                    repo.GenericDialogView.Yesvoidthistransaction.Click();
                                    Thread.Sleep(100);
                                    while (!repo.RetechAnotherTransaction.Visible)
                                    {
                                        Thread.Sleep(100);
                                    }
                                }
                            }
                        }
                        else
                        {                                       // ### This required for Retech 5.14 and above because Ranorex not see detail of new pinpad
                                                                // 11/6/18 use WPF not UAI
                            repo.RetechPeripheralHostWindow.SomeTabPageList.PinPadAcceptCommand.Click();
                            Thread.Sleep(100);
                            repo.RetechPeripheralHostWindow.SomeTabPageList.PinPadCardNumber.TextValue = Global.CreditCardNumber;
                            repo.RetechPeripheralHostWindow.SomeTabPageList.PinPadOK.Click();
                            repo.RetechPeripheralHostWindow.SomeTabPageList.PinPadMonth.TextValue = Global.CreditCardMonth;
                            repo.RetechPeripheralHostWindow.SomeTabPageList.PinPadYear.TextValue  = Global.CreditCardYear;
                            repo.RetechPeripheralHostWindow.SomeTabPageList.PinPadOK.Click();
                            repo.RetechPeripheralHostWindow.PinPadZipCode.TextValue = Global.CreditCardZip;
                            repo.RetechPeripheralHostWindow.SomeTabPageList.AcceptCommand.Click();

// 11/6/18 replace by above
//					            repo.RetechPeripheralHostWindow.TabControl.Click("189;453");
//					            repo.RetechPeripheralHostWindow.TabControl.Click("31;84");
//					            Keyboard.Press(Global.CreditCardNumber);
//					            repo.RetechPeripheralHostWindow.TabControl.Click("157;472");
//					            repo.RetechPeripheralHostWindow.TabControl.Click("44;115");
//					            Keyboard.Press(Global.CreditCardMonth + "{Tab}" + Global.CreditCardYear);
//					            Thread.Sleep(200);
//					            repo.RetechPeripheralHostWindow.TabControl.Click("93;466");
//					            Thread.Sleep(200);
//					            repo.RetechPeripheralHostWindow.TabControl.Click("40;126");
//					            Thread.Sleep(350);
//					            Keyboard.Press(Global.CreditCardZip);
//					            repo.RetechPeripheralHostWindow.TabControl.Click("155;445");
//					            Thread.Sleep(100);
                        }

                        TimeMinusOverhead.Run((float)MystopwatchQ4.ElapsedMilliseconds);                                   // Subtract overhead and store in Global.Q4StatLine
                        Global.CurrentMetricDesciption = @"[F6] enter Card info";
                        Global.Module = "Finalize";
                        DumpStatsQ4.Run();

                        MystopwatchQ4.Reset();
                        MystopwatchQ4.Start();

                        if (!Global.AbortScenario)
                        {
                            // 11/6/18 use WPF not UAI
                            repo.RetechPeripheralHostWindow.SomeTabPageList.ApplySignatureCommand.Click();
                            repo.RetechPeripheralHostWindow.SomeTabPageList.AcceptCommand.Click();
                            repo.RetechCardPaymentView.AcceptSignature.Click();

// 11/6/18 replace by above
//								while(!Host.Local.TryFindSingle(repo.RetechPeripheralHostWindow.SignOnPinPadInfo.AbsolutePath.ToString(), out element))
//								{ Thread.Sleep(100); }
//								repo.RetechPeripheralHostWindow.SignOnPinPad.Click();
//								Thread.Sleep(200);
//								repo.RetechPeripheralHostWindow.AcceptOnPinPad.Click();
//								Thread.Sleep(200);
//								repo.RetechCardPaymentView.Self.Focus();
//								Thread.Sleep(100);
//								repo.RetechCardPaymentView.SignatureAcceptedCommand.Click();
//								Thread.Sleep(200);

                            TimeMinusOverhead.Run((float)MystopwatchQ4.ElapsedMilliseconds);                                       // Subtract overhead and store in Global.Q4StatLine
                            Global.CurrentMetricDesciption = @"Sign on pin pad";
                            Global.Module = "Finalize";
                            DumpStatsQ4.Run();
                        }
                    }
                    else
                    {
                        MystopwatchQ4.Reset();
                        MystopwatchQ4.Start();
                        repo.EnterSerialNumber.Self.PressKeys("{F9}");                                  // Seclect Credit Card
                        TimeMinusOverhead.Run((float)MystopwatchQ4.ElapsedMilliseconds);                // Subtract overhead and store in Global.Q4StatLine
                        Global.CurrentMetricDesciption = @"[F9] Seclect Credit Card";
                        Global.Module = "Finalize";
                        DumpStatsQ4.Run();

                        MystopwatchQ4.Reset();
                        MystopwatchQ4.Start();
                        repo.Amount.Self.PressKeys("{Enter}");                                  // Enter amount paid
                        TimeMinusOverhead.Run((float)MystopwatchQ4.ElapsedMilliseconds);        // Subtract overhead and store in Global.Q4StatLine
                        Global.CurrentMetricDesciption = @"Enter amount paid";
                        Global.Module = "Finalize";
                        DumpStatsQ4.Run();

                        MystopwatchQ4.Reset();
                        MystopwatchQ4.Start();
                        repo.InternatiuonalCreditCardType.Self.PressKeys("{F1}");                      // F1=Visa F2=MasterCard F3=American Express
                        TimeMinusOverhead.Run((float)MystopwatchQ4.ElapsedMilliseconds);               // Subtract overhead and store in Global.Q4StatLine
                        Global.CurrentMetricDesciption = @"[F1] Seclect F1=Visa";
                        Global.Module = "Finalize";
                        DumpStatsQ4.Run();

                        repo.F1VISA.InternationalLast4OfCreditCard.PressKeys("9474{F5}");                      // Enter last 4 digits of credit card
                    }

                    break;

                case "PURCC":
                    // Click on Manual Card F6 button
                    Global.LogText = @"Clicking on Manual Card F6 button";
                    WriteToLogFile.Run();
                    repo.Retech.RequestManualCardSettlement.Click();
                    while (!repo.RetechCardPaymentView.RunAsPURCCCard.Enabled)
                    {
                        Thread.Sleep(100);
                    }

                    // Click on Run as PURCC button (Run as PowerUp Rewards Cerdit Cart
                    Global.LogText = @"Clicking on run as PURCC";
                    WriteToLogFile.Run();
                    repo.RetechCardPaymentView.RunAsPURCCCard.Click();
                    while (!Host.Local.TryFindSingle(repo.RetechCardPaymentView.TxtCardNumberInfo.AbsolutePath.ToString(), out element))
                    {
                        Thread.Sleep(100);
                    }

                    // Select ID type and Issuer (Drivers Lenense and State)
                    repo.RetechCardPaymentView.PickIdType.SelectedItemText = "Drivers License";
                    repo.RetechCardPaymentView.PickIdIssuer.Click();
                    repo.RetechCardPaymentView.PickIdIssuer.SelectedItemText = "Texas";
                    repo.RetechCardPaymentView.ProcessPrivateLabelCreditCardView.Click();

                    // Fill in PowerUp Rewards Credit Card Manual Entry
                    repo.RetechCardPaymentView.TxtCardNumber.TextValue = "7788400030000272";
                    repo.RetechCardPaymentView.TxtNameFromId.TextValue = "PAL User";
                    repo.RetechCardPaymentView.ProcessPrivateLabelCreditCardView.Click();
                    repo.RetechCardPaymentView.Self.PressKeys("{Enter}");

                    Global.LogText = @"Info entered - watching for Waiting for Signature";
                    WriteToLogFile.Run();

                    while (!Global.AbortScenario &&
                           !Host.Local.TryFindSingle(repo.RetechCardPaymentView.Waiting_for_SignatureInfo.AbsolutePath.ToString(), out element))
                    {
                        Thread.Sleep(100);
                        if (Host.Local.TryFindSingle(repo.RetechCardPaymentView.PaymentCouldNotBeAuthorizedAnUnknInfo.AbsolutePath.ToString(), out element))
                        {
                            Global.AbortScenario   = true;
                            Global.TempErrorString = "PURCC Unable to Process Payment - transaction voided";
                            WriteToErrorFile.Run();
                            Global.LogText = Global.TempErrorString;
                            WriteToLogFile.Run();
                            Keyboard.Press("{Escape}");
                            Thread.Sleep(100);
                            repo.Retech.DataContextVoidOrderCommand.Click();
                            Thread.Sleep(100);
                            repo.GenericDialogView.Yesvoidthistransaction.Click();
                            Thread.Sleep(100);
                            while (!repo.RetechAnotherTransaction.Visible)
                            {
                                Thread.Sleep(100);
                            }
                        }
                    }
                    if (!Global.AbortScenario)
                    {
                        repo.RetechPeripheralHostWindow.SignOnPinPad.Click();
                        Thread.Sleep(200);
                        repo.RetechPeripheralHostWindow.AcceptOnPinPad.Click();
                        Thread.Sleep(200);
                        repo.RetechCardPaymentView.Self.Focus();
                        Thread.Sleep(100);
                        repo.RetechCardPaymentView.SignatureAcceptedCommand.Click();
                        Thread.Sleep(200);
                    }
                    break;
                }


                MystopwatchQ4.Reset();
                MystopwatchQ4.Start();

                if (Global.DomesticRegister)
                {
                    // Wait for Another Transaction pop-up
                    while (!Host.Local.TryFindSingle(repo.RetechAnotherTransactionInfo.AbsolutePath.ToString(), out element))
                    {
                        Thread.Sleep(100);
                        if (Host.Local.TryFindSingle(repo.RetechTillOverageWarningView.CodeF4AlertInfo.AbsolutePath.ToString(), out element)
                            ||
                            Host.Local.TryFindSingle(repo.RetechTillOverageWarningView.CodeF4Alert2Info.AbsolutePath.ToString(), out element)
                            )
                        {
                            GlobalOverhead.Stopwatch.Start();
                            repo.RetechTillOverageWarningView.DropCashCommand.Click();
                            while (!repo.RetechLoginView.TxtPassword.Enabled)
                            {
                                Thread.Sleep(100);
                            }
                            repo.RetechLoginView.TxtPassword.PressKeys("advanced{Return}");
                            while (!repo.RetechTillDepositView.DropBoxAmount.Enabled)
                            {
                                Thread.Sleep(100);
                            }
                            repo.RetechTillDepositView.DropBoxAmount.PressKeys("40000");
                            repo.RetechTillDepositView.AddCashDropButton.Click();
                            Thread.Sleep(1000);
                            repo.RetechTillDepositView.DropBoxAmount.PressKeys("{Escape}");
                            GlobalOverhead.Stopwatch.Stop();
                        }
                    }
                }
                else
                {
                    // Wait for log on screen
                    if (Global.CurrentScenario == 47 ||
                        Global.CurrentScenario == 20 ||
                        Global.CurrentScenario == 16 ||
                        Global.CurrentScenario == 33 ||
                        Global.CurrentScenario == 34
                        )
                    {
                        Thread.Sleep(100);
                        while (!Host.Local.TryFindSingle(repo.IPOSScreen.ChangeDueInfo.AbsolutePath.ToString(), out element) &&
                               !repo.LogOn.LoginID.HasFocus
                               )
                        {
                            InternationalCheckForCodeF4Alert();                                     // 11/1/18
                            Thread.Sleep(200);
                        }
                        while (Host.Local.TryFindSingle(repo.IPOSScreen.ChangeDueInfo.AbsolutePath.ToString(), out element) &&
                               !repo.LogOn.LoginID.HasFocus
                               )
                        {
                            InternationalCheckForCodeF4Alert();                                     // 11/1/18
                            Thread.Sleep(200);
                        }
                    }
                    while (!Host.Local.TryFindSingle(repo.LogOn.LoginIDInfo.AbsolutePath.ToString(), out element))
                    {
                        Thread.Sleep(200);
                    }
                    while (!repo.LogOn.LoginID.Enabled)
                    {
                        Thread.Sleep(200);
                    }
                }
            }


            TimeMinusOverhead.Run((float)MystopwatchQ4.ElapsedMilliseconds);               // Subtract overhead and store in Global.Q4StatLine
            Global.CurrentMetricDesciption = @"Wait for another transaction ESC";
            Global.Module = "Finalize";
            DumpStatsQ4.Run();

            switch (Global.PayWithMethod)
            {
            case "Cash":
                Global.NowPayWithCash = Global.AdjustedTime;
                break;

            case "Credit":
                Global.NowPayWithCredit = Global.AdjustedTime;
                break;

            case "PURCC":
                Global.NowPayWithPURCC = Global.AdjustedTime;
                break;
            }

            MystopwatchQ4.Reset();
            MystopwatchQ4.Start();

            if (Global.DomesticRegister)
            {
                // Press excape key on Another Transaction pop-up
                while (!Host.Local.TryFindSingle(repo.RetechLoginView.TxtPasswordInfo.AbsolutePath.ToString(), out element))
                {
                    Thread.Sleep(100);
                }
                repo.RetechLoginView.TxtPassword.PressKeys("{Escape}");
            }
            else
            {
                // Press escape on log on screen
//				repo.LogOn.Self.PressKeys("{Escape}");
//				repo.LogOn.LogOn.Click("231;6");
//              Delay.Milliseconds(200);
//              Keyboard.Press("{Escape}");
                Thread.Sleep(200);
                while (!repo.LogOn.LogOn.Enabled)
                {
                    Thread.Sleep(200);
                }
                repo.LogOn.LogOn.PressKeys("");
                Delay.Milliseconds(200);
                repo.LogOn.LogOn.PressKeys("{Escape}");
            }

            if (!Global.DomesticRegister) // International Store
            {                             // Catch hanging logon
                Thread.Sleep(100);
                if (Host.Local.TryFindSingle(repo.LogOn.LogOnInfo.AbsolutePath.ToString(), out element))
                {
                    Keyboard.Press("{Escape}");
                }
            }

            TimeMinusOverhead.Run((float)MystopwatchQ4.ElapsedMilliseconds);   // Subtract overhead and store in Global.Q4StatLine
            Global.CurrentMetricDesciption = "Wait for Start a Transaction ESC";
            Global.Module = "Finalize";
            DumpStatsQ4.Run();

            TimeMinusOverhead.Run((float)MystopwatchModuleTotal.ElapsedMilliseconds);   // Subtract overhead and store in Global.Q4StatLine
            Global.CurrentMetricDesciption = "Module Total Time";
            Global.Module = "Finalize";
            DumpStatsQ4.Run();

            Global.LogText = "OUT fnCheckout";
            WriteToLogFile.Run();
            Global.LogFileIndentLevel--;
        }
示例#60
-1
        public void TestCanUpdateCustomer()
        {
            JsonServiceClient client = new JsonServiceClient("http://localhost:2337/");
            //Force cache
            client.Get(new GetCustomer { Id = 1 });
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            var cachedResponse = client.Get(new GetCustomer { Id = 1 });
            stopwatch.Stop();
            var cachedTime = stopwatch.ElapsedTicks;
            stopwatch.Reset();

            client.Put(new UpdateCustomer { Id = 1, Name = "Johno" });

            stopwatch.Start();
            var nonCachedResponse = client.Get(new GetCustomer { Id = 1 });
            stopwatch.Stop();
            var nonCacheTime = stopwatch.ElapsedTicks;

            Assert.That(cachedResponse.Result, Is.Not.Null);
            Assert.That(cachedResponse.Result.Orders.Count, Is.EqualTo(5));

            Assert.That(nonCachedResponse.Result, Is.Not.Null);
            Assert.That(nonCachedResponse.Result.Orders.Count, Is.EqualTo(5));
            Assert.That(nonCachedResponse.Result.Name, Is.EqualTo("Johno"));

            Assert.That(cachedTime, Is.LessThan(nonCacheTime));
        }