/// <summary>
        ///
        /// </summary>
        private void MigratingKey()
        {
            ConsoleWriter.PrintTitle();
            ConsoleWriter.PrintMenuHeader("Setup Pangaea Node - Placing keys");
            Console.WriteLine(string.Empty);
            Console.WriteLine("You should receive a key, please unzip them and copy them to the data/pangaea/ folder");
            Console.WriteLine("1. Place the ECDSA account address key in the data/pangaea/ folder, its the file starting with 'UTC.'");
            Console.WriteLine(string.Empty);
            var spinner = new ConsoleSpiner();

            while (!Directory.EnumerateFiles("/harmony/data/pangaea/", "UTC*").Any())
            {
                spinner.Turn("Waiting for ECDSA account address key to be present in the data/pangaea/ folder");
                Thread.Sleep(TimeSpan.FromMilliseconds(250));
            }

            Console.WriteLine("2. Place the BLS key in the data/pangaea/ folder, its the one which ends with '.key'");
            while (!Directory.EnumerateFiles("/harmony/data/pangaea/", "*.key").Any())
            {
                spinner.Turn("Waiting for BLS key to be present in the data/pangaea/ folder");
                Thread.Sleep(TimeSpan.FromMilliseconds(250));
            }

            Console.WriteLine("Hurray, found the pangaea keys");
        }
Exemple #2
0
        static void Main(string[] args)
        {
            ConsoleSpiner spin = new ConsoleSpiner();

            Console.WindowWidth   = 40;
            Console.WindowHeight  = 10;
            Console.CursorVisible = false;
            Console.WriteLine("Press ESC to stop");
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("Im Working....");
            int i     = 600;
            int count = 0;

            do
            {
                while (!Console.KeyAvailable)
                {
                    SetCursorPos(i, 500);
                    Thread.Sleep(300);
                    spin.Turn();
                    i = i == 600 && count % 10 == 0 ? 500 : 600;
                    count++;
                }
            } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
        }
Exemple #3
0
        private static async Task Parse(ConsoleSpiner spin, CancellationToken token)
        {
            try
            {
                spin.Turn();

                var result = await httpClient.SendAsync(QueryFactory.GetNewOffers(), token).ConfigureAwait(false);

                result.EnsureSuccessStatusCode();

                var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

                var cars = JsonConvert.DeserializeObject <List <Car> >(content);

                if (cars != null)
                {
                    foreach (var car in cars.Where(c => c.CarStatus() != Status.Bad))
                    {
                        CarFileSaver.Save(car);
                        MailSender.Send(car);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Exemple #4
0
        /// <summary>
        ///
        /// </summary>
        private void MigratingKey()
        {
            ConsoleWriter.PrintTitle();
            ConsoleWriter.PrintMenuHeader("Setup Foundation Node - Migrating keys");
            Console.WriteLine(string.Empty);
            Console.WriteLine("Since you already got the keys, please copy them to the data/mainnet/ folder");
            Console.WriteLine("1. Place the ECDSA account address key in the data/mainnet/ folder, its the file starting with 'UTC.'");
            Console.WriteLine(string.Empty);
            var spinner = new ConsoleSpiner();

            while (!Directory.EnumerateFiles("/harmony/data/mainnet/", "UTC*").Any())
            {
                spinner.Turn("Waiting for ECDSA account address key to be present in the data/mainnet/ folder");
                Thread.Sleep(TimeSpan.FromMilliseconds(250));
            }

            Console.WriteLine("2. Place the BLS key in the data/mainnet/ folder, its the one which ends with '.key'");
            while (!Directory.EnumerateFiles("/harmony/data/mainnet/", "*.key").Any())
            {
                spinner.Turn("Waiting for BLS key to be present in the data/mainnet/ folder");
                Thread.Sleep(TimeSpan.FromMilliseconds(250));
            }

            Console.WriteLine("Found the keys");
        }
Exemple #5
0
        static void Main(string[] args)
        {
            Initialize();
            ITextSource    textSource    = null;
            IResultWriter  resultWriter  = null;
            ITextProcessor textProcessor = null;

#if version1
            //Проверяем наличие модулей
            if (sourses.Length == 0)
            {
                System.Diagnostics.Trace.WriteLine("Not found any SourceModule");
                return;
            }

            if (writers.Length == 0)
            {
                System.Diagnostics.Trace.WriteLine("Not found any SourceModule");
                return;
            }

            if (processors.Length == 0)
            {
                System.Diagnostics.Trace.WriteLine("Not found any SourceModule");
                return;
            }
#endif
            //Получаем название модулей и загружаем
            var textSourceName    = SelectModuleName("Select a source of text", sourses);
            var resultWriterName  = SelectModuleName("Select method of write result", writers);
            var textProcessorName = SelectModuleName("Select method of word processing", processors);

#if version2
            textSourceModule.SetNecessaryType(textSourceName);
            resultWriterModule.SetNecessaryType(resultWriterName);
            textProcessorModule.SetNecessaryType(textProcessorName);

            kernel = new StandardKernel(new NinjectModule[] { textSourceModule, resultWriterModule, textProcessorModule });
#endif

            textSource    = kernel.Get <ITextSource>(textSourceName);
            resultWriter  = kernel.Get <IResultWriter>(resultWriterName);
            textProcessor = kernel.Get <ITextProcessor>(textProcessorName);

            //Запускаем обработку текста
            var spinner = new ConsoleSpiner();
            spinner.Start("Processing");

            IWorker worker = new SimpleWorker(textSource, resultWriter, textProcessor);
            var     d      = worker.ExecuteAsync().Result;

            spinner.Stop();
            Console.WriteLine();
            Console.Write("All done. Press any key...");
            Console.ReadKey();
        }
Exemple #6
0
        static void Main(string[] args)
        {
            ConsoleSpiner spin = new ConsoleSpiner();

            Console.Write("Working....");
            while (true)
            {
                spin.Turn();
            }
        }
Exemple #7
0
        private static void Main(string[] args)
        {
            var timer = new Timer(5000);
            var spin  = new ConsoleSpiner();
            var cts   = new CancellationTokenSource();
            var token = cts.Token;

            timer.Elapsed += async(sender, e) => await Parse(spin, token).ConfigureAwait(false);

            timer.Start();

            Console.CancelKeyPress += (sender, e) => CancelHandler(cts, timer);
            Console.ReadKey();
        }
Exemple #8
0
 static void Main(string[] args)
 {
     try
     {
         ConsoleSpiner.StartLoading();
         _cli.OnExecute(() => _cli.ShowHelp());
         _cli.Execute(args);
     }
     catch (Exception e)
     {
         ConsoleSpiner.StopLoading();
         Console.WriteLine(e.Message);
     }
     ConsoleSpiner.StopLoading();
 }
Exemple #9
0
        private static void Play(string prefix, int numberOfPlayers, int numberOfMarbels)
        {
            var currentPlayer = 0;
            var score         = new long[numberOfPlayers + 1];
            var gamefield     = new LinkedList <int>();
            LinkedListNode <int> currentNode = gamefield.AddFirst(0);
            var consoleSpinner = new ConsoleSpiner();

            for (var i = 1; i <= numberOfMarbels; i++)
            {
                currentPlayer = Math.Max(1, ++currentPlayer % (numberOfPlayers + 1));

                if (i % 23 == 0)
                {
                    score[currentPlayer] += i;
                    var moveLeft = 7;

                    while (moveLeft > 0)
                    {
                        moveLeft--;
                        currentNode = currentNode.Previous ?? gamefield.Last;
                    }

                    score[currentPlayer] += currentNode.Value;

                    LinkedListNode <int> next = currentNode.Next ?? gamefield.First;

                    gamefield.Remove(currentNode);
                    currentNode = next;
                }
                else
                {
                    currentNode = gamefield.AddAfter(currentNode.Next ?? gamefield.First, i);
                }

                if (i % 1000 == 0)
                {
                    consoleSpinner.Spin();
                }
            }

            consoleSpinner.Done();
            Console.WriteLine($"{prefix}: The winning elfs score is \"{score.Max()}\"");
        }
Exemple #10
0
        protected override void Loop()
        {
            if (!ProcessMemory.IsRunProcess())
            {
                ConsoleSpiner consoleSpiner = new ConsoleSpiner();
                Console.Write("Wait process ");
                while (!ProcessMemory.OpenProcess(Config.Game.Process))
                {
                    consoleSpiner.Turn();
                    Thread.Sleep(100);
                }
                Console.WriteLine("...");
                Console.WriteLine($"Found process: ID:{ProcessMemory.Process.Id}");
            }

            while (true)
            {
                Render2D.WindowRenderTarget.Resize(new Size2(RenderSurface.Size.Width, RenderSurface.Height));

                WriteMemory();
                ReadMemory();

                Render2D.BeginDraw();
                Render2D.Clear();

                Render2D.BrushColor = Color.Green;
                Render2D.DrawRectangle(new SharpDX.RectangleF(0, 0, 1920, 1080));
                Render2D.DrawLine(new Vector2(0, 0), new Vector2(1920, 1080));
                Render2D.DrawLine(new Vector2(1920, 0), new Vector2(0, 1080));

                Draw();

                Render2D.EndDraw();

                if (!ProcessMemory.IsRunProcess())
                {
                    break;
                }
            }
        }
Exemple #11
0
        //Main Async Task -------------------------------------------------------------------------------------------------
        static async Task MainAsync()
        {
            /* **************************************************************************************
             * Make Sure Docker Desktop is running
             * (Requirement 4.3.1)
             */
            Process[] processes = Process.GetProcessesByName(_DockerProcess);

            while (processes.Length == 0)
            {
                Console.WriteLine(_DockerError);
                Console.ReadLine();
                processes = Process.GetProcessesByName(_DockerProcess);
            }

            Console.WriteLine("[Docker] Desktop Started");

            /*
             * While Docker Desktop is not responsive, show a spinner
             * (Requirement 4.3.2)
             */
            if (!IsDockerResponsive())
            {
                ConsoleSpiner spin = new ConsoleSpiner();
                Console.Write("[Docker] Waiting for Docker Desktop Response....");
                while (!IsDockerResponsive())
                {
                    spin.Turn();
                }
                ;
                Console.WriteLine("\n[Docker] Desktop Responsive");
            }

            /*
             * Run Docker Containers
             * execute (Requirement 4.3.3)
             */
            await RunContainers();
        }
Exemple #12
0
        public static double SpeedAcrossEthernet()
        {
            NetworkInterface[] networks = NetworkInterface.GetAllNetworkInterfaces();

            NetworkInterface ethernetNetwork = networks.FirstOrDefault(x => x.Name.ToLower() == "wifi" && x.OperationalStatus == OperationalStatus.Up);

            ReadRequest GetRequest = new ReadRequest();

            Console.WriteLine("Measurement in progress");
            Task downloadTask = GetRequest.init(new Uri("http://ipv4.download.thinkbroadband.com/10MB.zip"));

            ICollection <long> times = new Collection <long>();

            while (!downloadTask.IsCompleted)
            {
                times.Add(ethernetNetwork.Speed);
                Thread.Sleep(500);
                ConsoleSpiner.Spin();
            }

            double normalisedSpeed = times.Average() / 10000000;

            return(normalisedSpeed);
        }
Exemple #13
0
        async static Task Initialize()
        {
            System.Console.WriteLine("Getting all Contacts from the database... ");
            ConsoleSpiner spin = new ConsoleSpiner();

            MinistryPlatformDataContext dataContext = new MinistryPlatformDataContext();

            Task<IEnumerable<Contact>> dataTask = new Task<IEnumerable<Contact>>(
                () =>
            {
                var data = dataContext.ExecuteStoredProcedure<Contact>("api_Example_GetAllContacts");
                return data;
            });

            Task spinTask = new Task(() => spin.StartTurning());

            spinTask.Start();
            dataTask.Start();
            IEnumerable<Contact> table = await dataTask;

            spin.StopTurning();

            foreach (var row in table)
            {
                System.Console.WriteLine("Display Name: " + row.Display_Name);
                System.Console.WriteLine("\tEmail Address: " + row.Email_Address);
                System.Console.WriteLine("\tDate of Birth: " + row.Date_of_Birth);
                System.Console.WriteLine();
            }

            //this section tests the update method that tracks changes in a single object
            System.Console.WriteLine("\nEnter the ID of the contact whose web page field will be updated.");

            int contactID = 0;
            if (Int32.TryParse(System.Console.ReadLine(), out contactID))
            {
                System.Console.WriteLine("\nGetting the contact record...");

                Task<Contact> dataTask2 = new Task<Contact>(
               () =>
               {
                   var data = dataContext.ExecuteStoredProcedure<Contact>("api_Example_GetSingleContact", new { ContactID = contactID });
                   return data.SingleOrDefault();
               });

                Task spinTask2 = new Task(() => spin.StartTurning());

                spinTask2.Start();
                dataTask2.Start();
                Contact record = await dataTask2;
                spin.StopTurning();

                record.Web_Page = "http://google.com/" + ToUnixTime(DateTime.Now);

                try
                {
                    dataContext.Update<Contact>(record);

                    System.Console.WriteLine("\nRecord Updated sucessfully!");         
                }
                catch (Exception e)
                {
                    System.Console.WriteLine("\n " + e.Message);
                }  
            }
            else
                System.Console.WriteLine("\nInvalid integer value. You'll have to restart the application.");

            System.Console.WriteLine("\nPress Enter to Exit.");
            System.Console.ReadLine();
        }
Exemple #14
0
        private static async void SendDeviceToCloudMessagesAsync()
        {
            var random = new Random();
            var spin   = new ConsoleSpiner();

            while (true)
            {
                spin.Turn();

                try
                {
                    var deviceReading = new DeviceMessage();
                    var index         = random.Next(0, _devices.list.Count - 1);

                    // randomly select a device from the registry
                    var device = _devices.list[index];

                    // lookup the participant associated with this device
                    var participant = _profiles.Find(p => p.id == device.participantid);

                    // create an IoT Hub client for this device if necessary
                    if (DeviceClients[index] == null)
                    {
                        // connect to the IoT Hub using unique device registration settings (deviceid, devicekey)
                        var deviceid = device.model + "-" + device.id;
                        DeviceClients[index] = DeviceClient.Create(
                            ConfigurationManager.AppSettings["IoTHubUri"],
                            new DeviceAuthenticationWithRegistrySymmetricKey(deviceid, device.key));
                    }

                    // begin to create the simulated device message
                    deviceReading.deviceid           = device.id;
                    deviceReading.participantid      = participant.id;
                    deviceReading.location.latitude  = participant.location.latitude;
                    deviceReading.location.longitude = participant.location.longitude;

                    // generate simulated sensor reaings
                    var glucose = new SensorReading
                    {
                        type  = SensorType.Glucose,
                        value = random.Next(70, 210)
                    };

                    var heartrate = new SensorReading
                    {
                        type  = SensorType.Heartrate,
                        value = random.Next(60, 180)
                    };

                    var temperature = new SensorReading
                    {
                        type  = SensorType.Temperature,
                        value = random.Next(98, 105) + (.1 * random.Next(0, 9))
                    };

                    var bloodoxygen = new SensorReading
                    {
                        type  = SensorType.Bloodoxygen,
                        value = random.Next(80, 100)
                    };

                    deviceReading.sensors.Add(glucose);
                    deviceReading.sensors.Add(heartrate);
                    deviceReading.sensors.Add(temperature);
                    deviceReading.sensors.Add(bloodoxygen);

                    deviceReading.reading = DateTime.Now;

                    // serialize the message to JSON
                    var json = ModelManager.ModelToJson <DeviceMessage>(deviceReading);

                    // send the message to EventHub
                    DeviceClients[index].SendEventAsync(new Message(Encoding.ASCII.GetBytes(json))).Wait();
                }
                catch (Exception exception)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message);
                    Console.ResetColor();
                }

                Thread.Sleep(1000);
            }
        }
Exemple #15
0
        private static bool ImportarArquivo(List <BufferTmp> listbuffer)
        {
            DateTime tempoini;
            DateTime tempofim;

            Console.WriteLine("Digite o diretorio do arquivo para importação, e pressione Enter");
            arquivo = Convert.ToString(Console.ReadLine());

            //Passo 1 - Carregar o total de linhas
            try
            {
                var fileStream = File.OpenRead(arquivo);

                Console.WriteLine("\r\n");
                Console.WriteLine("\r\n");

                Console.WriteLine("▓███████████████████████████████████████████████████████████████▓");
                Console.WriteLine("▒              Iniciando contagem de linhas                     ▓");
                Console.WriteLine("▓███████████████████████████████████████████████████████████████▓");

                tempoini = DateTime.Now;

                Thread        th = new Thread(RunTaskAsync);
                ConsoleSpiner sp = new ConsoleSpiner();
                inwork = true;
                th.Start();
                while (inwork)
                {
                    sp.Turn();
                }

                tempofim = DateTime.Now;

                posInicioBuffer = 0;
                posFimBuffer    = 0;
                posIniLinha     = 0;
                posFimLinha     = 10;

                CarregarBuffer(listbuffer, 0, 100);
                Console.WriteLine("\r\n");
                Console.WriteLine("▓███████████████████████████████████████████████████████████████▓");
                Console.WriteLine("▒Nome arquivo: {0}                       ▒", arquivo);
                Console.WriteLine("▒        Quantidade Linhas: {0}                            ▓", totalinhas);
                Console.WriteLine("▒        Tempo Total: {0}                          ▓", (tempofim - tempoini));
                Console.WriteLine("▓███████████████████████████████████████████████████████████████▓");


                Console.WriteLine("\r\n");
                Console.WriteLine("\r\n");
                return(true);
            }
            catch (Exception)
            {
                Console.WriteLine("\r\n");
                Console.WriteLine("▓███████████████████████████████████████████████████████████████▓");
                Console.WriteLine("▒                   Arquivo Inválido                            ▓");
                Console.WriteLine("▓███████████████████████████████████████████████████████████████▓");
                Console.WriteLine("\r\n");
                Console.WriteLine("\r\n");
                return(true);
            }
        }
        private static async void SendDeviceToCloudMessagesAsync()
        {
            var random = new Random();
            var spin = new ConsoleSpiner();

            while (true)
            {
                spin.Turn();

                try
                {
                    var deviceReading = new DeviceMessage();
                    var index = random.Next(0, _devices.list.Count - 1);

                    // randomly select a device from the registry
                    var device = _devices.list[index];

                    // lookup the participant associated with this device
                    var participant = _profiles.Find(p => p.id == device.participantid);

                    // create an IoT Hub client for this device if necessary
                    if (DeviceClients[index] == null)
                    {
                        // connect to the IoT Hub using unique device registration settings (deviceid, devicekey)
                        var deviceid = device.model + "-" + device.id;
                        DeviceClients[index] = DeviceClient.Create(
                            ConfigurationManager.AppSettings["IoTHubUri"], 
                            new DeviceAuthenticationWithRegistrySymmetricKey(deviceid, device.key));
                    }

                    // begin to create the simulated device message
                    deviceReading.deviceid = device.id;
                    deviceReading.participantid = participant.id;
                    deviceReading.location.latitude = participant.location.latitude;
                    deviceReading.location.longitude = participant.location.longitude;

                    // generate simulated sensor reaings
                    var glucose = new SensorReading
                    {
                        type = SensorType.Glucose,
                        value = random.Next(70, 210)
                    };

                    var heartrate = new SensorReading
                    {
                        type = SensorType.Heartrate,
                        value = random.Next(60, 180)
                    };

                    var temperature = new SensorReading
                    {
                        type = SensorType.Temperature,
                        value = random.Next(98, 105) + (.1 * random.Next(0, 9))
                    };

                    var bloodoxygen = new SensorReading
                    {
                        type = SensorType.Bloodoxygen,
                        value = random.Next(80, 100)
                    };

                    deviceReading.sensors.Add(glucose);
                    deviceReading.sensors.Add(heartrate);
                    deviceReading.sensors.Add(temperature);
                    deviceReading.sensors.Add(bloodoxygen);

                    deviceReading.reading = DateTime.Now;

                    // serialize the message to JSON
                    var json = ModelManager.ModelToJson<DeviceMessage>(deviceReading);

                    // send the message to EventHub
                    DeviceClients[index].SendEventAsync(new Message(Encoding.ASCII.GetBytes(json))).Wait();
                }
                catch (Exception exception)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message);
                    Console.ResetColor();
                }

                Thread.Sleep(1000);
            }
        }
Exemple #17
0
        private static void Run(string host, Range range)
        {
            Console.Clear();
            Console.ResetColor();

            var spin = new ConsoleSpiner {
                Background = ConsoleColor.Gray, Foreground = ConsoleColor.Black
            };
            string msg = $"Searching {host} through ports {range.Min} to {range.Max}";

            #region Sanity Checks

            if (range.Min == 0)
            {
                ConsoleUtils.Report("Minimum port value can't be 0", ReportType.ERROR);
                return;
            }

            if (range.Max > 65534)
            {
                ConsoleUtils.Report("Maximum port value can't be greater than 65534", ReportType.ERROR);
                return;
            }

            if (range.Max < range.Min)
            {
                ConsoleUtils.Report("Maximum port value can't be less than minimum port value", ReportType.ERROR);
                return;
            }

            if (!host.Contains("."))
            {
                ConsoleUtils.Report("Can't determine hostname type", ReportType.ERROR);
                return;
            }

            #endregion

            ConsoleUtils.WriteWholeLineWithBackground(0, "[-] PortFinder\n",
                                                      ConsoleColor.Gray, ConsoleColor.Black);
            ConsoleUtils.WriteWithBackground(0, Console.BufferWidth - msg.Length, msg, ConsoleColor.Gray,
                                             ConsoleColor.Black);

            var finder = new PortFinderManager(host, range);
            finder.PortSearched += delegate(int index, bool open)
            {
                ConsoleUtils.Report($"Port {index} is {(open ? "open" : "closed")}",
                                    open ? ReportType.OK : ReportType.WARN);

                spin.Turn();
            };

            finder.Completed += sucess =>
            {
                var fileName = $"Export-{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.txt";

                if (sucess)
                {
                    ConsoleUtils.Report($"Search completed. Found {finder.OpenPortsDictionary.Count} open ports.", ReportType.INFO);
                }
                else
                {
                    ConsoleUtils.Report("Search could not complete sucessfully.", ReportType.ERROR);
                }

                ConsoleUtils.Report($"Exporting results to {fileName}.", ReportType.INFO);
                Export(fileName, finder);
            };

            finder.FindOpenPorts();
        }
Exemple #18
0
        static void Main(string[] args)
        {
            string demonArt = @"                               ,-.
          ___,---.__          /'|`\          __,---,___
       ,-'    \`    `-.____,-'  |  `-.____,-'    //    `-.
     ,'        |           ~'\     /`~           |        `.
    /      ___//              `. ,'          ,  , \___      \
   |    ,-'   `-.__   _         |        ,    __,-'   `-.    |
   |   /          /\_  `   .    |    ,      _/\          \   |
   \  |           \ \`-.___ \   |   / ___,-'/ /           |  /
    \  \           | `._   `\\  |  //'   _,' |           /  /
     `-.\         /'  _ `---'' , . ``---' _  `\         /,-'
        ``       /     \    ,='/ \`=.    /     \       ''
                |__   /|\_,--.,-.--,--._/|\   __|
                /  `./  \\`\ |  |  | /,//' \,'  \
               /   /     ||--+--|--+-/-|     \   \
              |   |     /'\_\_\ | /_/_/`\     |   |
               \   \__, \_     `~'     _/ .__/   /
                `-._,-'   `-._______,-'   `-._,-'
";

            string welcomeMessage = @"
          ████████▄     ▄████████   ▄▄▄▄███▄▄▄▄    ▄██████▄  ▀█████████▄   ▄██████▄      ███     
          ███   ▀███   ███    ███ ▄██▀▀▀███▀▀▀██▄ ███    ███   ███    ███ ███    ███ ▀█████████▄ 
          ███    ███   ███    █▀  ███   ███   ███ ███    ███   ███    ███ ███    ███    ▀███▀▀██ 
          ███    ███  ▄███▄▄▄     ███   ███   ███ ███    ███  ▄███▄▄▄██▀  ███    ███     ███   ▀ 
          ███    ███ ▀▀███▀▀▀     ███   ███   ███ ███    ███ ▀▀███▀▀▀██▄  ███    ███     ███     
          ███    ███   ███    █▄  ███   ███   ███ ███    ███   ███    ██▄ ███    ███     ███     
          ███   ▄███   ███    ███ ███   ███   ███ ███    ███   ███    ███ ███    ███     ███     
          ████████▀    ██████████  ▀█   ███   █▀   ▀██████▀  ▄█████████▀   ▀██████▀     ▄████▀   
                                                                                                 
";

            string pickdemon_Label = @"
╔═╗┌─┐┌─┐┬─┐┌─┐┬ ┬┬┌┐┌┌─┐  ┬ ┬┌─┐┬  ┬        
╚═╗├┤ ├─┤├┬┘│  ├─┤│││││ ┬  ├─┤├┤ │  │        
╚═╝└─┘┴ ┴┴└─└─┘┴ ┴┴┘└┘└─┘  ┴ ┴└─┘┴─┘┴─┘      
┌─┐┌─┐┬─┐  ┌─┐┌┐┌  ┌─┐┬  ┬┌─┐┬┬  ┌─┐┌┐ ┬  ┌─┐
├┤ │ │├┬┘  ├─┤│││  ├─┤└┐┌┘├─┤││  ├─┤├┴┐│  ├┤ 
└  └─┘┴└─  ┴ ┴┘└┘  ┴ ┴ └┘ ┴ ┴┴┴─┘┴ ┴└─┘┴─┘└─┘
┌┬┐┌─┐┌┬┐┌─┐┌┐┌           ┬                  
 ││├┤ ││││ ││││           │                  
─┴┘└─┘┴ ┴└─┘┘└┘  o  o  o  o                  
";
            string questionLabel   = @"
╔═╗┌─┐┬┌─  ┌─┐  ┌─┐ ┬ ┬┌─┐┌─┐┌┬┐┬┌─┐┌┐┌        ┬
╠═╣└─┐├┴┐  ├─┤  │─┼┐│ │├┤ └─┐ │ ││ ││││        │
╩ ╩└─┘┴ ┴  ┴ ┴  └─┘└└─┘└─┘└─┘ ┴ ┴└─┘┘└┘  o  o  o
";

            Hashtable answerList = new Hashtable();

            answerList.Add(1, "Don't feel like answering that..");
            answerList.Add(2, "I don't know.... and I don't care");
            answerList.Add(3, "Don't push it...! You don't know who you're messing with");
            answerList.Add(4, "You already know the answer..");
            answerList.Add(5, "I'm coming for you tonight....");
            answerList.Add(6, "You're stupid....");
            answerList.Add(7, "Not sure if I want to talk to you anymore...");
            answerList.Add(8, "You're making me angry... probably not a good thing...");
            answerList.Add(9, "Really? You gotta be kidding me....");
            answerList.Add(10, "You're full of bullshit...");

            Hashtable demonList = new Hashtable();

            demonList.Add(1, "Magmaz");
            demonList.Add(2, "Baggannok");
            demonList.Add(3, "Sangroth");
            demonList.Add(4, "Ragezar");
            demonList.Add(5, "Mannakath");
            demonList.Add(6, "Agmen");
            demonList.Add(7, "Urgrith");
            demonList.Add(8, "Gostrath");
            demonList.Add(9, "Al'guran");
            demonList.Add(10, "Ar'gonnath");

            string questionString = "I would like to know";


            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine();
            Console.WriteLine(welcomeMessage);
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("\t Play at your own risk..!");

            Console.Write("\t Press Enter to continue.....");
            Console.ReadLine();
            Console.ResetColor();
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(pickdemon_Label);
            Console.WriteLine();

            Random rnd    = new Random();
            int    rndKey = rnd.Next(1, 10);

            /*
             * foreach (DictionaryEntry demon in demonList)
             * {
             *  Console.WriteLine("{0} - {1}", demon.Key, demon.Value);
             * }
             */
            ConsoleSpiner spin = new ConsoleSpiner();

            Console.ResetColor();
            Console.Write("Searching....");
            int i = 0;

            while (i < 40)
            {
                spin.Turn();
                i++;
                Thread.Sleep(100);
            }
            Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("{0}", demonList[rndKey]);
            Console.ResetColor();
            Console.Write(" is available to talk..");
            Console.WriteLine();
            Console.Write("Press Enter to continue.....");
            Console.ResetColor();

            Console.ReadLine();
            Console.Clear();

            while (true)
            {
                StringBuilder input = new StringBuilder();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(demonArt);
                Console.WriteLine(questionLabel);
                Console.ResetColor();
                Console.Write("Question: ");
                var startKey = Console.ReadKey(true);

                if (startKey.Key == ConsoleKey.OemPeriod)
                {
                    foreach (char c in questionString)
                    {
                        var stopKey = Console.ReadKey(true);
                        if (stopKey.Key == ConsoleKey.OemPeriod)
                        {
                            break;
                        }
                        //if (stopKey.Key == ConsoleKey.Backspace && input.Length > 0) Console.Write("\b");//input.Remove(input.Length - 1, 1);
                        //else if (key.Key != ConsoleKey.Backspace)
                        input.Append(stopKey.KeyChar);

                        Console.Write(c);
                    }
                    Console.ReadLine();
                    Console.BackgroundColor = ConsoleColor.DarkRed;
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write("{0}", demonList[rndKey]);
                    Console.ResetColor();
                    Console.Write(" says: ");
                    int j = 0;
                    while (j < 40)
                    {
                        spin.Turn();
                        j++;
                        Thread.Sleep(100);
                    }
                    Console.Write("{0}", input.ToString());
                    Console.ReadLine();
                    Console.Clear();
                }
                else
                {
                    Console.Write(startKey.KeyChar);

                    Console.ReadLine();
                    Console.BackgroundColor = ConsoleColor.DarkRed;
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write("{0}", demonList[rndKey]);
                    Console.ResetColor();
                    Console.Write(" says: ");
                    int k = 0;
                    while (k < 40)
                    {
                        spin.Turn();
                        k++;
                        Thread.Sleep(100);
                    }
                    Random rndSeed   = new Random();
                    int    rndAnswer = rndSeed.Next(1, 10);
                    Console.Write("{0}", answerList[rndAnswer]);
                    Console.ReadLine();
                    Console.Clear();
                }
            }
        }
        internal static void Run()
        {
            Console.WriteLine("\nPlease enter the sudoku puzzle you wish to solve.");
            Console.WriteLine("You will be entering the nine values for each row.");
            Console.WriteLine("Just enter the values with no spaces, for unknown");
            Console.WriteLine("values enter 0.  Once you're done the solver will");
            Console.WriteLine("produce an answer.  The solver will notify you if");
            Console.WriteLine("the sodoku puzzle cannot be solved.\n");
            Console.WriteLine("Press enter to continue!");

            Console.ReadLine();

            var continueLoop = true;

            do
            {
                var response = new StringBuilder();

                Console.Write("Enter the first row:   ");

                response.Append(Console.ReadLine());

                Console.Write("Enter the second row:  ");

                response.Append(Console.ReadLine());

                Console.Write("Enter the third row:   ");

                response.Append(Console.ReadLine());

                Console.Write("Enter the fourth row:  ");

                response.Append(Console.ReadLine());

                Console.Write("Enter the fifth row:   ");

                response.Append(Console.ReadLine());

                Console.Write("Enter the sixth row:   ");

                response.Append(Console.ReadLine());

                Console.Write("Enter the seventh row: ");

                response.Append(Console.ReadLine());

                Console.Write("Enter the eighth row:  ");

                response.Append(Console.ReadLine());

                Console.Write("Enter the ninth row:   ");

                response.Append(Console.ReadLine());

                Console.Write("\nPress enter to continue... ");

                Console.ReadLine();

                Console.WriteLine();

                var matrix = new SudokuMatrix(response.ToString());

                Task solver = matrix.Solve();

                ConsoleSpiner spin = new ConsoleSpiner();

                while (!solver.IsCompleted)
                {
                    spin.Turn();
                }

                Console.WriteLine();

                Console.Beep();

                if (matrix.IsValid())
                {
                    var displayMatrix = new SudokuMatrix(matrix.ToIntList());

                    displayMatrix.SetDifficulty(
                        new Difficulty {
                        Name            = "Test",
                        DifficultyLevel = DifficultyLevel.TEST
                    });

                    DisplayScreens.DisplayMatix(displayMatrix);

                    // Format and display the TimeSpan value.
                    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                       matrix.Stopwatch.Elapsed.Hours,
                                                       matrix.Stopwatch.Elapsed.Minutes,
                                                       matrix.Stopwatch.Elapsed.Seconds,
                                                       matrix.Stopwatch.Elapsed.Milliseconds / 10);

                    Console.Write("\n\nTime to generate solution: " + elapsedTime + "\n\n");
                }
                else
                {
                    Console.WriteLine("\nNeed more values in order to deduce a solution.\n");
                }

                Console.Write("Would you like to solve another solution (yes/no): ");

                var result = Console.ReadLine();

                if (result.ToLower().Equals("no") || result.ToLower().Equals("n"))
                {
                    continueLoop = false;
                }
                else
                {
                    Console.WriteLine();
                }
            } while (continueLoop);
        }
        private static void Main(string[] args)
        {
            ManualResetEvent ctrlC = GetExitEvent();
            var recipes            = new LinkedList <Recipe>();
            var elves           = new[] { new Elf(), new Elf() };
            var sequence        = "030121";
            int numberOfRecipes = int.Parse(sequence);

            elves[0].CurrentRecipe = recipes.AddFirst(new Recipe(GetNextReceipeIndex(), 3));
            elves[1].CurrentRecipe = recipes.AddLast(new Recipe(GetNextReceipeIndex(), 7));

            var consoleSpinner = new ConsoleSpiner();

            for (var i = 0; i < numberOfRecipes + 10; i++)
            {
                if (i % 1000 == 0)
                {
                    consoleSpinner.Spin();
                }

                GenerateRecipes(recipes, elves);
            }

            consoleSpinner.Done();

            LinkedListNode <Recipe> next = recipes.First;

            for (var i = 0; i < numberOfRecipes; i++)
            {
                next = next.Next;
            }

            var sb = new StringBuilder();

            for (var j = 0; j < 10; j++)
            {
                sb.Append(next.Value.Score);
                next = next.Next;
            }

            Console.WriteLine($"Day 14: The score of the next then recipes after the first \"{numberOfRecipes}\" is \"{sb}\"");

            next = recipes.First;
            var predicate = new int[sequence.Length];
            var k         = 0;

            while (true)
            {
                k++;

                if (k % 100000 == 0)
                {
                    consoleSpinner.Spin();
                }

                Array.Copy(predicate, 1, predicate, 0, predicate.Length - 1);
                predicate[predicate.Length - 1] = next.Value.Score;

                if (string.Join("", predicate) == sequence)
                {
                    break;
                }

                if (next.Next == null)
                {
                    GenerateRecipes(recipes, elves);
                }

                next = next.Next;
            }

            consoleSpinner.Done();
            Console.WriteLine($"Part Two: \"{next.Previous.Value.Index + 1 - sequence.Length}\" recipies appear on the scoreboard to the left.");

            ctrlC.WaitOne();
        }