System.Console.ReadLine()

Here are the examples of the csharp api System.Console.ReadLine() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

7148 Examples 7

19 View Source File : PacketDeviceSelector.cs
License : MIT License
Project Creator : 0blu

public static ICaptureDevice AskForPacketDevice()
        {
            // Retrieve the device list from the local machine
            CaptureDeviceList devices = CaptureDeviceList.Instance;

            if (devices.Count == 0)
            {
                throw new Exception("No interfaces found! Make sure WinPcap is installed.");
            }

            // Print the list
            for (int i = 0; i != devices.Count; ++i)
            {
                ICaptureDevice device = devices[i];
                Console.Write((i + 1) + ". ");
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + devices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > devices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            return devices[deviceIndex - 1];
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5

static void GetFLPaths()
        {
            string path = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Image-Line\\Shared\\Paths", "FL Studio", null);
            if(path == null)
            {
                Console.WriteLine("No FL Studio path detected!\n\n");
                Console.Write("Please enter full path to the FL Studio executable: ");
                string output = Console.ReadLine();
                System.Diagnostics.FileVersionInfo FLInf = System.Diagnostics.FileVersionInfo.GetVersionInfo(output);
                if (FLInf.ProductName != "FL Studio")
                {
                    Console.WriteLine("\n   This file doesn't appear to be a FL Studio executable...try again!");
                    GetFLPaths();
                }
                FLStudioPaths = output;
            }
            else
            {
                FLStudioPaths = path;
                Console.WriteLine(string.Format("Found FL Studio at path: {0}", path));
                Console.WriteLine("Correct? (Y/N)");
                switch (Console.ReadKey().Key)
                {
                    case ConsoleKey.Y:
                        break;
                    case ConsoleKey.N:
                        Console.Write("Please enter full path to the FL Studio executable: ");
                        string output = Console.ReadLine();
                        output.Replace("\"", string.Empty);
                        System.Diagnostics.FileVersionInfo FLInf = System.Diagnostics.FileVersionInfo.GetVersionInfo(output);
                        if (FLInf.ProductName != "FL Studio")
                        {
                            Console.WriteLine("\n   This file doesn't appear to be a FL Studio executable...try again!");
                            System.Threading.Thread.Sleep(1000);
                            GetFLPaths();
                        }
                        FLStudioPaths = output;
                        break;
                }
            }
            
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5

static void GetInfo()
        {
            Console.WriteLine("Would you like to replace your current shortcuts on your desktop? (Y/N)");
            switch (Console.ReadKey().Key)
            {
                case ConsoleKey.Y:
                    ReplaceDesktop = true;
                    break;
                case ConsoleKey.N:
                    ReplaceDesktop = false;
                    break;
                default:
                    ReplaceDesktop = false;
                    break;
            }
            Console.WriteLine("\n Leave blank if you don't want to add shortcuts");
            Console.Write("\n Where would you like to write (additonal) shortcuts? Write the full path to the folder, seperate folder paths with a comma (,): ");
            string feed = Console.ReadLine();
            if (feed != null)
            {
                WriteShortcuts = feed.Split(',');
            }

            Console.Write("\n Enter the version number of FL Studio (e.g 20): ");
            VersionNumber = Console.ReadLine();
            Console.WriteLine("Thank you! \n \n");
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0xDivyanshu

static void powershell_clm(String file_tmp)
        {
            Console.WriteLine("[+] Powershell CLM bypreplaced!\n");
            Runspace rs = RunspaceFactory.CreateRunspace();
            String op_file = file_tmp;
            PowerShell ps = PowerShell.Create();
            while (true)
            {
                Console.Write("PS:>");
                string input = Console.ReadLine();
                if (input == "exit")
                {
                    break;
                }
                ps.AddScript(input + " | Out-File -FilePath " + op_file);
                ps.Invoke();
                string output = File.ReadAllText(op_file);
                Console.WriteLine(output);
                File.Delete(op_file);
            }
            rs.Close();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 1iveowl

static async Task Main(string[] args)
        {
            await Start();

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 1iveowl

static async Task Main(string[] args)
        {
            TcpListenerTest();
            //await UdpMulticastListenerTest();
            Console.WriteLine("Press any key to stop.");
            Console.ReadLine();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static async Task Main(string[] args)
        {
            var instance = RedisClientBuilder.Builder();
            //await instance.OutputIntefaceAsync("IFreeRedisContext.cs");
            //await instance.OutputProxyAsync("FreeRedisContext.cs");
            await instance.OutputRedisHelperAsync("FreeRedisHelper.cs");

            Console.ReadLine();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 3583Bytes

private static void RunEngine()
	{
		bool ShowBoard = false;

		var engine = new Engine();



		Console.WriteLine("Chess Core");
		Console.WriteLine("Created by Adam Berent");
		Console.WriteLine("Version: 1.0.1");
		Console.WriteLine("");
		Console.WriteLine("Type quit to exit");
		Console.WriteLine("Type show to show board");
		Console.WriteLine("");
		Console.WriteLine("feature setboard=1");


		while (true)
		{
			try
			{
				if (ShowBoard)
				{
					DrawBoard(engine);
				}

				if (engine.WhoseMove != engine.HumanPlayer)
				{
					MakeEngineMove(engine);
				}
				else
				{
					Console.WriteLine();

					string move = Console.ReadLine();

					if (String.IsNullOrEmpty(move))
					{
						continue;
					}

					move = move.Trim();


					if (move == "new")
					{
						engine.NewGame();
						continue;
					}
					if (move == "quit")
					{
						return;
					}
					if (move == "xboard")
					{
						continue;
					}
					if (move == "show")
					{
						ShowBoard = !ShowBoard;

						continue;
					}
					if (move.StartsWith("edit"))
					{
						continue;
					}
					if (move == "hint")
					{
						continue;
					}
					if (move == "bk")
					{
						continue;
					}
					if (move == "undo")
					{
						engine.Undo();
						continue;
					}
					if (move == "remove")
					{
						continue;
					}
					if (move == "remove")
					{
						continue;
					}
					if (move == "hard")
					{
						engine.GameDifficulty = Engine.Difficulty.Hard;
						continue;
					}
					if (move == "easy")
					{
						continue;
					}
					if (move.StartsWith("accepted"))
					{
						continue;
					}
					if (move.StartsWith("rejected"))
					{
						continue;
					}
					if (move.StartsWith("variant"))
					{
						continue;
					}
					if (move == "random")
					{
						continue;
					}
					if (move == "force")
					{
						continue;
					}
					if (move == "go")
					{
						continue;
					}
					if (move == "playother")
					{
						if (engine.WhoseMove == ChessPieceColor.White)
						{
							engine.HumanPlayer = ChessPieceColor.Black;
						}
						else if (engine.WhoseMove == ChessPieceColor.Black)
						{
							engine.HumanPlayer = ChessPieceColor.White;
						}

						continue;
					}
					if (move == "white")
					{
						engine.HumanPlayer = ChessPieceColor.Black;

						if (engine.WhoseMove != engine.HumanPlayer)
						{
							MakeEngineMove(engine);
						}
						continue;
					}
					if (move == "black")
					{
						engine.HumanPlayer = ChessPieceColor.White;

						if (engine.WhoseMove != engine.HumanPlayer)
						{
							MakeEngineMove(engine);
						}
						continue;
					}

					if (move.StartsWith("level"))
					{
						continue;
					}
					if (move.StartsWith("st"))
					{
						continue;
					}
					if (move.StartsWith("sd"))
					{
						continue;
					}
					if (move.StartsWith("time"))
					{
						continue;
					}
					if (move.StartsWith("otim"))
					{
						continue;
					}
					if (move.StartsWith("otim"))
					{
						continue;
					}
					if (move == "?")
					{
						continue;
					}
					if (move.StartsWith("ping"))
					{
						if (move.IndexOf(" ") > 0)
						{
							string pong = move.Substring(move.IndexOf(" "), move.Length - move.IndexOf(" "));

							Console.WriteLine("pong " + pong);
						}
						continue;
					}

					if (move.StartsWith("result"))
					{
						continue;
					}

					if (move.StartsWith("setboard"))
					{
						if (move.IndexOf(" ") > 0)
						{
							string fen = move.Substring(move.IndexOf(" "), move.Length - move.IndexOf(" ")).Trim();

							engine.InitiateBoard(fen);
						}

						continue;
					}

					if (move.StartsWith("setboard"))
					{
						continue;
					}
					if (move.StartsWith("edit"))
					{
						engine.NewGame();
						continue;
					}
					if (move.StartsWith("1/2-1/2"))
					{
						engine.NewGame();
						continue;
					}
					if (move.StartsWith("0-1"))
					{
						engine.NewGame();
						continue;
					}
					if (move.StartsWith("1-0"))
					{
						engine.NewGame();
						continue;
					}

					if (move.Length < 4)
					{
						continue;
					}

					if (move.Length > 5)
					{
						continue;
					}

					string src = move.Substring(0, 2);
					string dst = move.Substring(2, 2);


					byte srcCol;
					byte srcRow;
					byte dstRow;
					byte dstCol;

					try
					{
						srcCol = GetColumn(src);
						srcRow = GetRow(src);
						dstRow = GetRow(dst);
						dstCol = GetColumn(dst);
					}
					catch (Exception ex)
					{
						Console.WriteLine(ex.Message);
						continue;
					}

					if (!engine.IsValidMove(srcCol, srcRow, dstCol, dstRow))
					{
						Console.WriteLine("Invalid Move");
						continue;
					}

					engine.MovePiece(srcCol, srcRow, dstCol, dstRow);

					MakeEngineMove(engine);
					    

					if (engine.StaleMate)
					{
						if (engine.InsufficientMaterial)
						{
							Console.WriteLine("1/2-1/2 {Draw by insufficient material}");
						}
						else if (engine.RepeatedMove)
						{
							Console.WriteLine("1/2-1/2 {Draw by repereplacedion}");
						}
						else if (engine.FiftyMove)
						{
							Console.WriteLine("1/2-1/2 {Draw by fifty move rule}");
						}
						else
						{
							Console.WriteLine("1/2-1/2 {Stalemate}");
						}
						engine.NewGame();
					}
					else if (engine.GetWhiteMate())
					{
						Console.WriteLine("0-1 {Black mates}");
						engine.NewGame();
					}
					else if (engine.GetBlackMate())
					{
						Console.WriteLine("1-0 {White mates}");
						engine.NewGame();
					}
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
				return;
			}
		}
	}

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

private static async Task RunAsync()
        {
            try
            {
                AuthenticationResult result = null;
                result = await Auth();
                DateTime exp = result.ExpiresOn.DateTime;

                if (result != null)
                {

                    string userid = await GetUserID(result.AccessToken, ConfigurationManager.AppSettings["User"].ToString());
                    string mailfolderid = await GetFolderID(result.AccessToken, userid, ConfigurationManager.AppSettings["FolderName"].ToString());

                    while (true)
                    {
                        Console.Write("#> ");
                        string input = null;
                        input = Console.ReadLine().Trim();
                        while (input != null && input != "")
                        {
                            int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
                            if (exptime < 0)
                            {
                                result = await Auth();
                                exp = result.ExpiresOn.DateTime;
                            }
                            await SendMessage(result.AccessToken, userid, mailfolderid, input);
                            Thread.Sleep(2000);
                            string output = null;
                            while (output == null)
                            {
                                output = await ReadMessage(result.AccessToken, userid, mailfolderid);
                                if (output != null & output != "")
                                {
                                    Console.WriteLine(output);
                                }
                            }
                            input = null;
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

private static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

                var arguments = new Dictionary<string, string>();
                foreach (var argument in args)
                {
                    var idx = argument.IndexOf(':');
                    if (idx > 0)
                        arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
                    else
                        arguments[argument] = string.Empty;
                }

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    Console.WriteLine("[+] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/pname"))
                {
                    Process[] process = Process.GetProcessesByName(arguments["/pname"]);
                    if (process.Length > 0)
                    {
                        for (int i = 0; i < process.Length; i++)
                        {
                            Console.WriteLine($"[+] Dumping {process[i].ProcessName} process");
                            Console.WriteLine($"[+] {process[i].ProcessName} process handler {process[i].Handle}");
                            Console.WriteLine($"[+] {process[i].ProcessName} process id {process[i].Id}");
                            dump(process[i].Handle, (uint)process[i].Id, process[i].ProcessName);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[+] {arguments["/pname"]} process is not running.");
                    }
                }
                else if (arguments.ContainsKey("/pid"))
                {
                    int procid = Convert.ToInt32(arguments["/pid"]);
                    Process process = Process.GetProcessById(procid);
                    Console.WriteLine($"[+] Dumping {process.ProcessName} process");
                    Console.WriteLine($"[+] {process.ProcessName} process handler {process.Handle}");
                    Console.WriteLine($"[+] {process.ProcessName} process id {process.Id}");
                    dump(process.Handle, (uint)process.Id, process.ProcessName);
                }
                else
                {
                    Console.WriteLine("[+] Invalid argument. Please refer the help section for more details.");
                    help();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

private static async Task RunAsync()
        {
            AuthenticationResult result = null;
            result = await Auth();
            DateTime exp = result.ExpiresOn.DateTime;


            if (result != null)
            {
                var pageid = await GetPageID(result.AccessToken);
                while (true)
                {
                    Console.Write("#> ");
                    string input = null;
                    input = Console.ReadLine().Trim();
                    while (input != null && input != "")
                    {
                        int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
                        if (exptime < 0)
                        {
                            result = await Auth();
                            exp = result.ExpiresOn.DateTime;
                        }
                        await CreateTask(result.AccessToken, pageid,input);
                        input = null;
                        Thread.Sleep(2000);
                    }

                }
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 42skillz

private static void Main(string[] args)
        {
            var train = args[0];
            var seats = int.Parse(args[1]);

            var manager = new WebTicketManager();

            var jsonResult = manager.Reserve(train, seats);

            Console.WriteLine(jsonResult.Result);

            Console.WriteLine("Type <enter> to exit.");
            Console.ReadLine();
        }

19 View Source File : SocketServiceImpl.cs
License : MIT License
Project Creator : 499116344

public void ReceiveVerifyCode(byte[] data)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "yanzhengma");
            var img = ImageHelper.CreateImageFromBytes(path, data);
            Console.Write($"请输入验证码({img}):");
            var code = Console.ReadLine();
            if (!string.IsNullOrEmpty(code))
            {
                Send(new Send_0X00Ba(_user, code));
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 52ABP

public static void Main(string[] args)
        {
            ParseArgs(args);

            using (var bootstrapper = AbpBootstrapper.Create<BookListMigratorModule>())
            {
                bootstrapper.IocManager.IocContainer
                    .AddFacility<LoggingFacility>(
                        f => f.UseAbpLog4Net().WithConfig("log4net.config")
                    );

                bootstrapper.Initialize();

                using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MulreplacedenantMigrateExecuter>())
                {
                    var migrationSucceeded = migrateExecuter.Object.Run(_quietMode);
                    
                    if (_quietMode)
                    {
                        // exit clean (with exit code 0) if migration is a success, otherwise exit with code 1
                        var exitCode = Convert.ToInt32(!migrationSucceeded);
                        Environment.Exit(exitCode);
                    }
                    else
                    {
                        Console.WriteLine("Press ENTER to exit...");
                        Console.ReadLine();
                    }
                }
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 4egod

static void Main(string[] args)
        {
            if (RawDebug)
            {
                bot.PostReceived += Bot_PostReceived;            
            }
            bot.InvalidPostReceived += Bot_InvalidPostReceived;

            bot.OnMessage += Bot_OnMessage;
            bot.OnFollow += Bot_OnFollow;
            bot.OnUnFollow += Bot_OnUnFollow;
            bot.OnTweet += Bot_OnTweet; 
            bot.OnRetweet += Bot_OnRetweet;
            bot.OnQuote += Bot_OnQuote;
            bot.OnComment += Bot_OnComment;
            bot.OnMention += Bot_OnMention;
            bot.OnLike += Bot_OnLike;

            bot.StartReceivingAsync();

            while (true)
            {
                Console.ReadLine();
                Console.Clear();
            }
        }

19 View Source File : MultiTenantMigrateExecuter.cs
License : MIT License
Project Creator : 52ABP

public bool Run(bool skipConnVerification)
        {
            var hostConnStr = CensorConnectionString(_connectionStringResolver.GetNameOrConnectionString(new ConnectionStringResolveArgs(MulreplacedenancySides.Host)));
            if (hostConnStr.IsNullOrWhiteSpace())
            {
                _log.Write("Configuration file should contain a connection string named 'Default'");
                return false;
            }

            _log.Write("Host database: " + ConnectionStringHelper.GetConnectionString(hostConnStr));
            if (!skipConnVerification)
            {
                _log.Write("Continue to migration for this host database and all tenants..? (Y/N): ");
                var command = Console.ReadLine();
                if (!command.IsIn("Y", "y"))
                {
                    _log.Write("Migration canceled.");
                    return false;
                }
            }

            _log.Write("HOST database migration started...");

            try
            {
                _migrator.CreateOrMigrateForHost(SeedHelper.SeedHostDb);
            }
            catch (Exception ex)
            {
                _log.Write("An error occured during migration of host database:");
                _log.Write(ex.ToString());
                _log.Write("Canceled migrations.");
                return false;
            }

            _log.Write("HOST database migration completed.");
            _log.Write("--------------------------------------------------------");

            var migratedDatabases = new HashSet<string>();
            var tenants = _tenantRepository.GetAllList(t => t.ConnectionString != null && t.ConnectionString != "");
            for (var i = 0; i < tenants.Count; i++)
            {
                var tenant = tenants[i];
                _log.Write(string.Format("Tenant database migration started... ({0} / {1})", (i + 1), tenants.Count));
                _log.Write("Name              : " + tenant.Name);
                _log.Write("TenancyName       : " + tenant.TenancyName);
                _log.Write("Tenant Id         : " + tenant.Id);
                _log.Write("Connection string : " + SimpleStringCipher.Instance.Decrypt(tenant.ConnectionString));

                if (!migratedDatabases.Contains(tenant.ConnectionString))
                {
                    try
                    {
                        _migrator.CreateOrMigrateForTenant(tenant);
                    }
                    catch (Exception ex)
                    {
                        _log.Write("An error occured during migration of tenant database:");
                        _log.Write(ex.ToString());
                        _log.Write("Skipped this tenant and will continue for others...");
                    }

                    migratedDatabases.Add(tenant.ConnectionString);
                }
                else
                {
                    _log.Write("This database has already migrated before (you have more than one tenant in same database). Skipping it....");
                }

                _log.Write(string.Format("Tenant database migration completed. ({0} / {1})", (i + 1), tenants.Count));
                _log.Write("--------------------------------------------------------");
            }

            _log.Write("All databases have been migrated.");

            return true;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 52ABP

public static void Main(string[] args)
        {
            ParseArgs(args);

            using (var bootstrapper = AbpBootstrapper.Create<PhoneBookMigratorModule>())
            {
                bootstrapper.IocManager.IocContainer
                    .AddFacility<LoggingFacility>(
                        f => f.UseAbpLog4Net().WithConfig("log4net.config")
                    );

                bootstrapper.Initialize();

                using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MulreplacedenantMigrateExecuter>())
                {
                    var migrationSucceeded = migrateExecuter.Object.Run(_quietMode);
                    
                    if (_quietMode)
                    {
                        // exit clean (with exit code 0) if migration is a success, otherwise exit with code 1
                        var exitCode = Convert.ToInt32(!migrationSucceeded);
                        Environment.Exit(exitCode);
                    }
                    else
                    {
                        Console.WriteLine("Press ENTER to exit...");
                        Console.ReadLine();
                    }
                }
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 6tail

static void Main(string[] args)
        {
            // ����
            Solar solar = new Solar(2020, 5, 26, 23, 42, 0);
            Console.WriteLine(solar);
            Console.WriteLine(solar.toFullString());

            // ����
            Lunar lunar = solar.getLunar();
            Console.WriteLine(lunar);
            Console.WriteLine(lunar.toFullString());

            // ����
            EightChar baZi = lunar.getEightChar();
            Console.WriteLine(baZi.getYear() + " " + baZi.getMonth() + " " + baZi.getDay() + " " + baZi.getTime());

            // ��������
            Console.WriteLine(baZi.getYearNaYin() + " " + baZi.getMonthNaYin() + " " + baZi.getDayNaYin() + " " + baZi.getTimeNaYin());

            // ��������
            Console.WriteLine(baZi.getYearWuXing() + " " + baZi.getMonthWuXing() + " " + baZi.getDayWuXing() + " " + baZi.getTimeWuXing());

            // �������ʮ��
            Console.WriteLine(baZi.getYearShiShenGan() + " " + baZi.getMonthShiShenGan() + " " + baZi.getDayShiShenGan() + " " + baZi.getTimeShiShenGan());

            // ���ֵ�֧ʮ��
            Console.WriteLine(baZi.getYearShiShenZhi()[0] + " " + baZi.getMonthShiShenZhi()[0] + " " + baZi.getDayShiShenZhi()[0] + " " + baZi.getTimeShiShenZhi()[0]);

            // ������֧ʮ��
            foreach (string s in baZi.getYearShiShenZhi())
            {
                Console.Write(s + " ");
            }
            Console.WriteLine();

            // ������֧ʮ��
            foreach (string s in baZi.getMonthShiShenZhi())
            {
                Console.Write(s + " ");
            }
            Console.WriteLine();

            // ������֧ʮ��
            foreach (string s in baZi.getDayShiShenZhi())
            {
                Console.Write(s + " ");
            }
            Console.WriteLine();

            // ����ʱ֧ʮ��
            foreach (string s in baZi.getTimeShiShenZhi())
            {
                Console.Write(s + " ");
            }
            Console.WriteLine();

            // ����̥Ԫ
            Console.WriteLine(baZi.getTaiYuan());

            // ��������
            Console.WriteLine(baZi.getMingGong());

            // �������
            Console.WriteLine(baZi.getShenGong());

            Console.WriteLine();
            solar = new Solar(1988, 3, 20, 18, 0, 0);
            lunar = solar.getLunar();
            EightChar bazi = lunar.getEightChar();

            // ����
            Yun yun = bazi.getYun(1);
            Console.WriteLine("����" + solar.toYmdHms() + "����");
            Console.WriteLine("����" + yun.getStartYear() + "��" + yun.getStartMonth() + "����" + yun.getStartDay() + "�������");
            Console.WriteLine("����" + yun.getStartSolar().toYmd() + "������");
            Console.WriteLine();

            // �ڼ���
            List<Holiday> holidays = HolidayUtil.getHolidays(2012);
            foreach (Holiday holiday in holidays)
            {
                Console.WriteLine(holiday);
            }
            Console.WriteLine();

            // ����ת����
            List<Solar> solars = Solar.fromBaZi("����", "����", "��î", "����");
            foreach (Solar d in solars)
            {
                Console.WriteLine(d.toFullString());
            }
            Console.WriteLine();

            Console.ReadLine();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 8bitbytes

static void PrintMenu(SdkWrapper wrapper)
        {
            var done = false;

            //wrapper.BaseActions.CommandMode().Execute();
            while (!done)
            {
                TelloSdkCoreNet.actions.Action action = null;
                Console.Clear();
                Console.WriteLine("1.TakeOff");
                Console.WriteLine("2.Land");
                Console.WriteLine("3.Flip");
                Console.WriteLine("4.Fly forward");
                Console.WriteLine("5.Fly back");
                Console.WriteLine("6.Rotate");
                Console.WriteLine("7.Battery %");
                Console.WriteLine("8.Execute flight plan");
                Console.WriteLine("9.Exit");
                var choice = Console.ReadLine();
                try
                {
                    switch (choice)
                    {
                        case "1":
                            {
                                action = wrapper.BaseActions.TakeOff();
                                break;
                            }
                        case "2":
                            {
                                action = wrapper.BaseActions.Land();
                                break;
                            }
                        case "3":
                            {
                                action = wrapper.FlipActions.FlipBackLeft();
                                break;
                            }
                        case "4":
                            {
                                action = wrapper.FlyActions.FlyForward(50);
                                break;
                            }
                        case "5":
                            {
                                action = wrapper.FlyActions.FlyBack(50);
                                break;
                            }
                        case "6":
                            {
                                action = wrapper.RotationActions.RotateClockwise(360);
                                break;
                            }
                        case "7":
                            {
                                var resp = wrapper.BaseActions.QueryBattery().Execute();
                                if (resp == SdkWrapper.SdkReponses.OK)
                                {
                                    Console.WriteLine($"Battery percentage is {wrapper.BaseActions.QueryBattery().ServerResponse}%");
                                    Console.ReadLine();
                                }
                                break;
                            }
                        case "8":
                            {
                                ExecuteFlightPlan(wrapper);
                                break;
                            }
                        case "9":
                            {
                                done = true;
                                break;
                            }

                    }
                    if (action != null)
                    {
                        var resp1 = action.Execute();
                        if (resp1 == SdkWrapper.SdkReponses.FAIL)
                        {
                            if (action.LastException != null)
                            {
                                throw action.LastException;
                            }
                        }
                    }

                }
                catch (Exception ex)
                {
                    WriteError(ex.Message);
                    Console.ReadLine();
                }
            }
        }

19 View Source File : OwinRadiumPlugin.cs
License : MIT License
Project Creator : 99x

protected override void Listen()
        {
            object portNumber = null;

            if (Environment.Configuration.ContainsKey("server"))
            {
                ServerSettings = (JObject)Environment.Configuration["server"];
                var portJValue = ServerSettings.GetValue("port");
                if (portJValue != null)
                    portNumber = portJValue.ToString();

            }

            if (portNumber == null)
                portNumber = 9000;

            var handler = new RequestHandler(this.Kernel);
            using (Microsoft.Owin.Hosting.WebApp.Start("http://localhost:" + portNumber, handler.Configuration))
            {
                Console.WriteLine("Radium REST Server listeneing in port : " + portNumber);
                Console.ReadLine();
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 8bitbytes

static void Main(string[] args)
        {
            //ExecuteFlightPlan(SdkWrapper.Instance);
            PrintMenu(SdkWrapper.Instance);
            Console.ReadLine();
            SdkWrapper.Instance.Shutdown();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 8bitbytes

static void ExecuteFlightPlan(SdkWrapper wrapper)
        {
            try
            {
                var fp = TelloSdkCoreNet.flightplans.FlightPlan.Materialize(System.IO.File.ReadAllText(@"/Users/peterhallock/Doreplacedents/git/TelloSdkCoreNet/TestApp/TestApp\FP_4-10-18 102058 PM_b59c89eb.json.fp"));
                wrapper.ExecuteFlightPlan(fp);
            }
            catch (Exception ex)
            {
                WriteError(ex.Message);
                Console.ReadLine();
            }
            
        }

19 View Source File : ToolsMain.cs
License : Apache License 2.0
Project Creator : 91270

static void Main(string[] args)
        {
            do
            {
                try
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("=============================================================================");
                    Console.WriteLine("*            1      -      生成模型");
                    Console.WriteLine("=============================================================================");
                    Console.Write("请选择要执行的程序 : ");
                    Console.ResetColor();

                    switch (Int32.Parse(Console.ReadLine()))
                    {
                        case 1:

                            #region  生成模型
                            Task001.Execute();
                            #endregion

                            Console.ReadKey();

                            break;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.ReadKey();
                }
            } while (true);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : a4004

[STAThread]
        static void Main(string[] argv)
        {
            if (argv.Any(o => o.Contains("--debug") || o.Contains("-d")))
            {
                NativeMethods.AllocConsole();
                Default = Console.ForegroundColor;
                DebugMode = true;

                Console.replacedle = "Espressif Flash Manager - Debugging Console";
            }

            AllowFileDebugging = -1;
            Debug("Application init.");

            if (argv.Any(o => o.Contains("--fixdriver") || o.Contains("-fd")))
            {
                Debug("Program executed with --fixdriver flag. Device picker will be disabled and esptool will autodetect" +
                    " in order to mitigate access denied error messages.");

                Settings.PortFix = true;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            if (argv.Any(o => o.Contains("--portable") || o.Contains("-p")))
            {
                Portable = true;

                Debug("Program executed with the --portable flag which removes the need for Python and the esptool module" +
                    " and instead uses a precompiled (outdated) copy of the esptool.", Event.Warning);
                Debug("You are warned that using untrusted executables not provided by N2D22 exposes your computer system" +
                    " to security risks. It's recommended that you do not use this mode and instead use the Python utility.", Event.Warning);

                if (!File.Exists("esptool.exe"))
                {
                    Debug("Could not find a matching file for esptool.exe in the current working directory.", Event.Critical);

                    OpenFileDialog fileDialog = new OpenFileDialog()
                    {
                        Multiselect = false,
                        SupportMultiDottedExtensions = true,
                        Filter = "Executable files (*.exe)|*.exe|All files (*.*)|*.*",
                        replacedle = "Browse for esptool binary",
                    };

                    if (fileDialog.ShowDialog() == DialogResult.OK)
                        Settings.EsptoolExe = fileDialog.FileName;
                    else
                        Terminate();                  
                }
                else
                    Settings.EsptoolExe = "esptool.exe";
            }

            Application.ThreadException += (s, e) =>
            {
                Debug("threadexception", e.Exception.ToString(), Event.Critical);

                MainWindow.Instance.Invoke(new Action(() =>
                {
                    MessageBox.Show($"{e.Exception.Message}\nThe application will terminate immediately.", "Unexpected Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Terminate();
                }));
            };
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                Debug("appdomain", e.ExceptionObject.ToString(), Event.Critical);

                MainWindow.Instance.Invoke(new Action(() =>
                {
                    MessageBox.Show($"{(e.ExceptionObject as Exception).Message}\nThe application will terminate immediately.", "Unexpected Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Terminate();
                }));
            };

            if (!argv.Any(o => o.Contains("--debugyes") || o.Contains("-dyes")) && DebugMode)
            {
                Debug("[WARN] Do not close this debugging window, doing so will prevent logging " +
                    "to the disk and may cause unintended behaviour.", Event.Critical);
                Debug("If you wish to hide this window, please run N2D22 without the --debug flag.", Event.Warning);

                string conf = string.Empty;

                do
                {
                    Console.Write("Please type \"understood\" without the quotes to continue: ");
                    conf = Console.ReadLine();
                }
                while (conf != "understood");

                Debug("To debug faster, simply append 'yes' to the --debug flag i.e. \"--debugyes\" to skip the confirmation.", Event.Success);

                Console.Write("Press any key to continue . . .");
                Console.ReadKey();
            }

            Debug("Creating MainWindow");
            Application.Run(new MainWindow());
            Debug("Window destroyed. Exiting", Event.Critical);

            if (argv.Any(o => o.Contains("--debug") || o.Contains("-d")))
                NativeMethods.FreeConsole();

            Terminate();
        }

19 View Source File : BitfinexTest.cs
License : MIT License
Project Creator : aabiryukov

public static void Test()
		{

            using (var wsApi = new BitfinexSocketApi())
			{
                BitfinexSocketApi.SetLogVerbosity(Bitfinex.Logging.LogVerbosity.Info);

                Console.WriteLine("Bitfinex: Socket starting...");
                wsApi.Connect();

                Task.Delay(3000).Wait();
/*
                var subcribtion1 = wsApi.SubscribeToTradingPairTicker("tETHBTC", summary =>
                {
                    Console.WriteLine($"{DateTime.Now} BTC-ETH: {summary.LastPrice}");
                });
                Console.WriteLine($"Subcribtion1: {subcribtion1}");
*/

                var subcribtion2 = wsApi.SubscribeToOrderBooks("tETHBTC", OnOrderBooks, frequency: Frequency.F0, length: 1);
                Console.WriteLine($"Subcribtion2: {subcribtion2}");

                Console.ReadLine();
			}

/*
			var ticker = BitfinexApi.GetPublicTicker(BtcInfo.PairTypeEnum.btcusd, BtcInfo.BitfinexUnauthenicatedCallsEnum.pubticker);
			Console.WriteLine(ticker.LastPrice);

			var trades = BitfinexApi.GetPairTrades(BtcInfo.PairTypeEnum.btcusd, BtcInfo.BitfinexUnauthenicatedCallsEnum.trades);
			Console.WriteLine("trades.Count=" + trades.Count);

			var orderBook = BitfinexApi.GetOrderBook(BtcInfo.PairTypeEnum.btcusd);
			Console.WriteLine("orderBook.Asks.Length={0}, orderBook.Bids.Length={1}", orderBook.Asks.Length, orderBook.Bids.Length);
*/
			var api = new BitfinexApi(ApiKey, ApiSecret);

			var balances = api.GetBalances();
			var usd = balances.FirstOrDefault(x => x.Type == "exchange" && x.Currency == "usd");
			var btc = balances.FirstOrDefault(x => x.Type == "exchange" && x.Currency == "btc");
			Console.WriteLine("usd: " + usd);
			Console.WriteLine("btc: " + btc);

			foreach (var balance in balances)
			{
				Console.WriteLine("balance: " + balance);
			}

			var info = api.GetAccountInformation();
			Console.WriteLine("Account info: {0}", info);

			var openOrders = api.GetActiveOrders();
			Console.WriteLine("Open orders: {0}", openOrders.Count());
/*
			var cancelResult = api.CancelOrder(12345);
			Console.WriteLine("CancelOrder: {0}", cancelResult);

			var sellAnswer = api.Sell(12456.3M, 2);
			Console.WriteLine("Sell: {0}", sellAnswer);

			var buyAnswer = api.Buy(12.3M, 1);
			Console.WriteLine("Buy: {0}", buyAnswer);
 */ 
		}

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : aaaddress1

static WorkbookEditor cmd_ModifyLabel(WorkbookEditor wbe)
        {
            List<Lbl> existingLbls = wbe.WbStream.GetAllRecordsByType<Lbl>();
            log("\t[+] Detect {0} Labels ...\n", ConsoleColor.Yellow, existingLbls.Count);
            for (int i = 0; i < existingLbls.Count; i++)
            {           // XLUnicodeStringNoCch
                var labelName = existingLbls[i].IsAutoOpenLabel() ? "Auto_Open" : existingLbls[i].Name.Value;
                log("\t\t[{0}] {1:s}\n", ConsoleColor.Yellow, i, labelName);
            }

            log("\t[?] which one to midify (index): ", ConsoleColor.Yellow);
            try
            {
                int indx = Convert.ToInt32(Console.ReadLine());
                var labelName = existingLbls[indx].IsAutoOpenLabel() ? "Auto_Open" : existingLbls[indx].Name.Value;
                log("\t[v] select label `{0}`\n", ConsoleColor.Yellow, labelName);
                log("\t\t[1] hide label\n", ConsoleColor.Yellow);
                log("\t\t[2] obfuscate label\n", ConsoleColor.Yellow);
                log("\t[?] choose action (index): ", ConsoleColor.Yellow);

                var replaceLabelStringLbl = ((BiffRecord)existingLbls[indx].Clone()).AsRecordType<Lbl>();
                switch (Convert.ToInt32(Console.ReadLine())) {
                    case 1:
                        replaceLabelStringLbl.fHidden = true;
                        wbe.WbStream = wbe.WbStream.ReplaceRecord(existingLbls[indx], replaceLabelStringLbl);
                        wbe.WbStream = wbe.WbStream. FixBoundSheetOffsets();
                        historyList.Add(string.Format("[#] History - label `{0}` vanish!\n", labelName));
                        break;

                    case 2:
                        replaceLabelStringLbl.SetName(new XLUnicodeStringNoCch(getObfscuteName(labelName), true));
                        replaceLabelStringLbl.fBuiltin = false;
                        wbe.WbStream = wbe.WbStream.ReplaceRecord(existingLbls[indx], replaceLabelStringLbl);
                        wbe.WbStream = wbe.WbStream.FixBoundSheetOffsets();
                        historyList.Add(string.Format("[#] History - obfuscate `{0}` done!\n", labelName));
                        break;
                }
            }
            catch (Exception) {}
            return wbe;
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : aaaddress1

static WorkbookEditor cmd_ModifySheet(WorkbookEditor wbe)
        {
            List<BoundSheet8> sheetList = wbe.WbStream.GetAllRecordsByType<BoundSheet8>();
            log("\t[+] Detect {0} Sheets ...\n", ConsoleColor.Yellow, sheetList.Count);
            for (int i = 0; i < sheetList.Count; i++)
                log("\t\t[{0}] {1:s}\n", ConsoleColor.Yellow, i, sheetList[i].stName.Value);
            log("\t[?] which one to hide (index): ", ConsoleColor.Yellow);
            try
            {
                int indx = Convert.ToInt32(Console.ReadLine());
                var replaceSheet = ((BiffRecord)sheetList[indx].Clone()).AsRecordType<BoundSheet8>();
                replaceSheet.hsState = BoundSheet8.HiddenState.SuperVeryHidden;
                wbe.WbStream = wbe.WbStream.ReplaceRecord(sheetList[indx], replaceSheet);
                wbe.WbStream = wbe.WbStream.FixBoundSheetOffsets();
                historyList.Add(string.Format("[#] History - Hide Sheet `{0}` done!\n", sheetList[indx].stName.Value));

            }
            catch { }
            return wbe;
        }

19 View Source File : PerformanceTest.cs
License : Apache License 2.0
Project Creator : aadreja

public void Run()
        {

            CreateTable();

            int iteration = 5;
            int count = 1000;

            Dictionary<string, Dictionary<int, long>> insertTimings = new Dictionary<string, Dictionary<int, long>>();
            Dictionary<string, Dictionary<int, long>> updateTimings = new Dictionary<string, Dictionary<int, long>>();
            Dictionary<string, Dictionary<int, long>> selectTimings = new Dictionary<string, Dictionary<int, long>>();
            Dictionary<string, Dictionary<int, long>> selectListTimings = new Dictionary<string, Dictionary<int, long>>();

            insertTimings.Add("ADO", new Dictionary<int, long>());
            insertTimings.Add("Vega", new Dictionary<int, long>());
            insertTimings.Add("Dapper", new Dictionary<int, long>());

            updateTimings.Add("ADO", new Dictionary<int, long>());
            updateTimings.Add("Vega", new Dictionary<int, long>());
            updateTimings.Add("Dapper", new Dictionary<int, long>());

            selectTimings.Add("ADO", new Dictionary<int, long>());
            selectTimings.Add("Vega", new Dictionary<int, long>());
            selectTimings.Add("Dapper", new Dictionary<int, long>());

            selectListTimings.Add("ADO", new Dictionary<int, long>());
            selectListTimings.Add("Vega", new Dictionary<int, long>());
            selectListTimings.Add("Dapper", new Dictionary<int, long>());

            for (int i = 1; i <= iteration; i++)
            {
                WriteLine("Iteration " + i, ConsoleColor.Yellow);

                ADOTest adoTest = new ADOTest();
                VegaTest vegaTest = new VegaTest();
                DapperTest dapperTest = new DapperTest();

                insertTimings["ADO"].Add(i, adoTest.InsertTest(count));
                insertTimings["Vega"].Add(i, vegaTest.InsertTest(count));
                insertTimings["Dapper"].Add(i, dapperTest.InsertTest(count));

                updateTimings["ADO"].Add(i, adoTest.UpdateTest(count));
                updateTimings["Vega"].Add(i, vegaTest.UpdateTest(count));
                updateTimings["Dapper"].Add(i, dapperTest.UpdateTest(count));

                selectTimings["ADO"].Add(i, adoTest.SelectTest(count));
                selectTimings["Vega"].Add(i, vegaTest.SelectTest(count));
                selectTimings["Dapper"].Add(i, dapperTest.SelectTest(count));

                selectListTimings["ADO"].Add(i, adoTest.SelectListTest(count));
                selectListTimings["Vega"].Add(i, vegaTest.SelectListTest(count));
                selectListTimings["Dapper"].Add(i, dapperTest.SelectListTest(count));
            }

            //show results
            Console.Clear();
            WriteLine($"Results for {count} records {iteration} iteration", ConsoleColor.Yellow);
            WriteLine("--------" + new string('-',10 * iteration), ConsoleColor.Green);
            Write("Iteration\t", ConsoleColor.Green);
            for (int i = 1; i <= iteration; i++)
            {
                Write($"{i}\t", ConsoleColor.Green);
            }
            Write("Mean\t", ConsoleColor.Green);
            Write("stDEV\t", ConsoleColor.Green);
            WriteLine("");
            WriteLine("--------" + new string('-', 10 * iteration), ConsoleColor.Green);

            WriteStatus("Insert Tests", insertTimings);
            WriteStatus("Update Tests", updateTimings);
            WriteStatus("Select Tests", selectTimings);
            WriteStatus("Select List Tests", selectListTimings);
            
            Console.ReadLine();
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : aaaddress1

static void Main(string[] args)
        {
            printMenu();
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            if (args.Length < 1) {
                log("usage: xlsKami.exe [path/to/xls]", ConsoleColor.Red);
                return;
            }

            WorkbookEditor wbe;


            try {
                wbe = new WorkbookEditor(LoadDecoyDoreplacedent(args[0]));
            }
            catch (Exception e) {
                log(e.Message, ConsoleColor.Red);
                return;
            }
            
            for (bool bye = false; !bye; ) {
                try {
                    printMenu(showMenu: true, loadXlsPath: args[0]);
                    
                    switch (Convert.ToInt32(Console.ReadLine())) {

                        case 1:
                            log("[+] Enter Mode: Label Patching\n", ConsoleColor.Cyan);
                            wbe = cmd_ModifyLabel(wbe);
                            log("[+] Exit Mode\n", ConsoleColor.Cyan);
                            break;

                        case 2:
                            log("[+] Enter Mode: Sheet Patching\n", ConsoleColor.Cyan);
                            wbe = cmd_ModifySheet(wbe);
                            log("[!] Exit Mode\n", ConsoleColor.Cyan);
                            break;

                        case 3:
                            WorkbookStream createdWorkbook = wbe.WbStream;
                            ExcelDocWriter writer = new ExcelDocWriter();
                            string outputPath = args[0].Insert(args[0].LastIndexOf('.'), "_infect");
                            Console.WriteLine("Writing generated doreplacedent to {0}", outputPath);
                            writer.WriteDoreplacedent(outputPath, createdWorkbook, null);
                            bye = true;
                            break;

                        case 4:
                            bye = true;
                            break;


                    }
                }
                catch (Exception) { }
            }

            Console.WriteLine("Thanks for using xlsKami\nbye.\n");
        }

19 View Source File : OKCoinTest.cs
License : MIT License
Project Creator : aabiryukov

public static void Test()
		{
/*
			// Sell
			{
				var priceUsd = 245 * 99999;
				var CIY2USD = 0.1611;

				var client1 = new OKCoinAPI(ApiKey, ApiSecret);
				var responce = client1.PlaceOrder((double)(priceUsd / CIY2USD), -(double)2.5,
					OKCoinAPI.MarketType.BTCCNY);
				Console.WriteLine(responce);
			}
*/


			using (var wsApi = new WebSocketApi())
			{
				wsApi.OrdersDepthReceived += OnOrdersDepth;
				wsApi.Start();
				Console.ReadLine();
				wsApi.Stop();
			}

			var ticker = OKCoinAPI.GetTicker();
			Console.WriteLine("ticker.Last: " + ticker.Last);

			var orderBook = OKCoinAPI.GetOrderBook(33);
			Console.WriteLine("orderBook.Asks.Count=" + orderBook.Asks.Count);

			var client = new OKCoinAPI(ApiKey, ApiSecret);

			var info = client.GetUserInfo();
			Console.WriteLine("FreeBtc= " + info.Free.Btc);

			var orderId = client.TradeSell(300, 0.08M);
			Console.WriteLine("orderId: " + orderId);

			var orders = client.GetActiveOrders();
			Console.WriteLine("Active orders: " + orders.Count());

			var cancelResult = client.CancelOrder(orderId);
			Console.WriteLine("cancelResult: " + cancelResult);
		}

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : Aaronontheweb

static async Task Main(string[] args)
        {
            var actorSystem = ActorSystem.Create("WordCount");

            IActorRef wordFrequencyActor = actorSystem.ActorOf(
                Props.Create(() => new WordFrequencyActor()), 
                "words");

            Console.WriteLine("Type a line to have its word frequencies counted.");
            Console.WriteLine("The actors will aggregate the frequencies of words" +
                              "across all lines it receives");
            Console.WriteLine("Type /exit to quit.");
            bool stillRunning = true;
            while (stillRunning)
            {
                var line = Console.ReadLine();
                if (string.IsNullOrEmpty(line))
                    continue;
                if (line.Equals("/exit"))
                    stillRunning = false;
                else
                {
                    var lineFrequency = await wordFrequencyActor.Ask<FrequencyOut>(new LineIn(line), 
                        TimeSpan.FromSeconds(1));
                    Console.WriteLine(lineFrequency);
                }
            }

            await actorSystem.Terminate();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Abc-Arbitrage

public static void Main()
        {
            //Throughput();

            //LatencyMultiProducer(4, 4 * 25_000, 4 * 250_000, 64);
            //LatencyMultiProducer(8, 8 * 25_000, 8 * 250_000, 64);
            //LatencyMultiProducer(4, 4 * 25_000, 4 * 250_000, 1024);
            //LatencyMultiProducer(8, 8 * 25_000, 8 * 250_000, 1024);

            //EnumBenchmarksRunner.Run();
            //ThroughputToFileBench.Run();

            BenchmarkSwitcher.Fromreplacedembly(typeof(Program).replacedembly).Run();

            while (Console.KeyAvailable)
                Console.ReadKey(true);

            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Abdirahiim

static void Main(string[] args)
        {
            CoronavirusData data = new CoronavirusData();

            Console.WriteLine("Confirmed: " + data.LatestConfirmed());
            Console.WriteLine("Recovered: " + data.LatestRecovered());
            Console.WriteLine("Deaths: " + data.LatestDeaths());


            // Fetches the latest data of a country code.
            string country_code = "DK";
            Console.WriteLine("Denmark Confirmed: " + data.FromCountryCodeConfirmed(country_code));
            Console.WriteLine("Denmark Recovered: " + data.FromCountryCodeRecovered(country_code));
            Console.WriteLine("Denmark Deaths: " + data.FromCountryCodeDeaths(country_code));
            Console.WriteLine("Denmark population: " + data.FromCountryCodePopulation(country_code));

            // Fetches data of a country Name.
            string country_name = "China";
            Console.WriteLine("China Confirmed: " + data.FromCountryNameConfirmed(country_name));
            Console.WriteLine("China Recovered: " + data.FromCountryNameRecovered(country_name));
            Console.WriteLine("China Deaths: " + data.FromCountryNameDeaths(country_name));
            Console.WriteLine("China population: " + data.FromCountryNamePopulation(country_name));

            //Fetches the data of the Country/province replacedociated with the ID
            Console.WriteLine("Name of the Faroe Islands: " + data.FromIDProvince("92"));
            Console.WriteLine("Name of the country of the Faroe Islands: " + data.FromIDCountry("92"));
            Console.WriteLine("Denmark Lareplacedude: " + data.FromIDLareplacedude("94"));
            Console.WriteLine("Denmark Longreplacedude: " + data.FromIDLongitude("94"));
            Console.WriteLine("Denmark Population: " + data.FromIDPopulation("94"));

            // Fetches lists of data, if not defined the default source will be jhu
             Console.WriteLine(data.GetCountryList());
             Console.WriteLine(data.GetPopulationList());
             Console.WriteLine(data.GetProvinceList());
             Console.WriteLine(data.GetCountyList("csbs")); //The source is set to csbs


            Console.ReadLine();
        }

19 View Source File : ConsoleExtensions.cs
License : Apache License 2.0
Project Creator : acblog

public static string Input(string prompt = "")
        {
            Console.Write(prompt);
            return Console.ReadLine() ?? string.Empty;
        }

19 View Source File : BiotaGuidConsolidator.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void ConsolidateBiotaGuids(uint startingGuid, out int numberOfBiotasConsolidated, out int numberOfErrors)
        {
            log.Info($"Consolidating biotas, starting at guid 0x{startingGuid:X8}...");

            Thread.Sleep(1000); // Give the logger type to flush to the client so that our output lines up in order

            Console.WriteLine("!!! Do not proceed unless you have backed up your shard database first !!!");
            Console.WriteLine("In the event of any failure, you may be asked to rollback your shard database.");
            Console.WriteLine("Press any key to proceed, or abort the process to quit.");
            Console.ReadLine();
            Console.WriteLine(".... hold on to your butts...");

            if (startingGuid < ObjectGuid.DynamicMin)
                throw new Exception($"startingGuid cannot be lower than ObjectGuid.DynamicMin (0x{ObjectGuid.DynamicMin:X8})");

            int numOfBiotasConsolidated = 0;
            int numOfErrors = 0;

            var shardDatabase = new ShardDatabase();

            var sequenceGaps = shardDatabase.GetSequenceGaps(ObjectGuid.DynamicMin, 10000000);
            var availableIDs = new LinkedList<(uint start, uint end)>(sequenceGaps);
            List<Biota> partialBiotas;

            using (var context = new ShardDbContext())
                partialBiotas = context.Biota.Where(r => r.Id >= startingGuid).OrderByDescending(r => r.Id).ToList();

            var idConversions = new ConcurrentDictionary<uint, uint>();

            // Process ConsolidatableBasicWeenieTypes first
            Parallel.ForEach(partialBiotas, partialBiota =>
            {
                if (numOfErrors > 0)
                    return;

                if (!ConsolidatableBasicWeenieTypes.Contains((WeenieType)partialBiota.WeenieType))
                    return;

                // Get the original biota
                var fullBiota = shardDatabase.GetBiota(partialBiota.Id, true);

                if (fullBiota == null)
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Warn($"Failed to get biota with id 0x{partialBiota.Id:X8} from the database. This shouldn't happen. It also shouldn't require a rollback.");
                    return;
                }

                // Get the next available id
                uint newId = 0;

                lock (availableIDs)
                {
                    if (availableIDs.First != null)
                    {
                        var id = availableIDs.First.Value.start;

                        if (availableIDs.First.Value.start == availableIDs.First.Value.end)
                            availableIDs.RemoveFirst();
                        else
                            availableIDs.First.Value = (availableIDs.First.Value.start + 1, availableIDs.First.Value.end);

                        newId = id;
                    }
                }

                if (newId == 0)
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal("Failed to generate new id. No more id's available for consolidation. This shouldn't require a rollback.");
                    return;
                }

                idConversions[fullBiota.Id] = newId;

                // Copy our original biota into a new biota and set the new id
                var converted = BiotaConverter.ConvertToEnreplacedyBiota(fullBiota);
                converted.Id = newId;

                // Save the new biota
                if (!shardDatabase.SaveBiota(converted, new ReaderWriterLockSlim()))
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal($"Failed to save new biota with id 0x{fullBiota.Id:X8} to the database. Please rollback your shard.");
                    return;
                }

                // Finally, remove the original biota
                if (!shardDatabase.RemoveBiota(fullBiota.Id))
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal($"Failed to remove original biota with id 0x{fullBiota.Id:X8} from database. Please rollback your shard.");
                    return;
                }

                var tempNumOfBiotasConsolidated = Interlocked.Increment(ref numOfBiotasConsolidated);

                if ((tempNumOfBiotasConsolidated + numOfErrors) % 1000 == 0)
                    Console.WriteLine($"{tempNumOfBiotasConsolidated:N0} biotas successfully processed out of {partialBiotas.Count:N0}...");
            });


            // Process ConsolidatableContainerWeenieTypes second
            foreach (var partialBiota in partialBiotas)
            {
                if (numOfErrors > 0)
                    break;

                if (!ConsolidatableContainerWeenieTypes.Contains((WeenieType)partialBiota.WeenieType))
                    continue;

                // Get the original biota
                var fullBiota = shardDatabase.GetBiota(partialBiota.Id, true);

                if (fullBiota == null)
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Warn($"Failed to get biota with id 0x{partialBiota.Id:X8} from the database. This shouldn't happen. It also shouldn't require a rollback.");
                    break;
                }

                // Get the next available id
                uint newId = 0;

                lock (availableIDs)
                {
                    if (availableIDs.First != null)
                    {
                        var id = availableIDs.First.Value.start;

                        if (availableIDs.First.Value.start == availableIDs.First.Value.end)
                            availableIDs.RemoveFirst();
                        else
                            availableIDs.First.Value = (availableIDs.First.Value.start + 1, availableIDs.First.Value.end);

                        newId = id;
                    }
                }

                if (newId == 0)
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal("Failed to generate new id. No more id's available for consolidation. This shouldn't require a rollback.");
                    break;
                }

                idConversions[fullBiota.Id] = newId;

                // Copy our original biota into a new biota and set the new id
                var converted = BiotaConverter.ConvertToEnreplacedyBiota(fullBiota);
                converted.Id = newId;

                // Save the new biota
                if (!shardDatabase.SaveBiota(converted, new ReaderWriterLockSlim()))
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal($"Failed to save new biota with id 0x{fullBiota.Id:X8} to the database. Please rollback your shard.");
                    break;
                }

                // update contained items to point to the new container
                using (var context = new ShardDbContext())
                {
                    var ownedItems = context.BiotaPropertiesIID.Where(r => r.Type == (ushort)PropertyInstanceId.Owner && r.Value == fullBiota.Id);

                    foreach (var item in ownedItems)
                        item.Value = converted.Id;

                    var containedItems = context.BiotaPropertiesIID.Where(r => r.Type == (ushort)PropertyInstanceId.Container && r.Value == fullBiota.Id);

                    foreach (var item in containedItems)
                        item.Value = converted.Id;

                    context.SaveChanges();
                }

                // Finally, remove the original biota
                if (!shardDatabase.RemoveBiota(fullBiota.Id))
                {
                    Interlocked.Increment(ref numOfErrors);
                    log.Fatal($"Failed to remove original biota with id 0x{fullBiota.Id:X8} from database. Please rollback your shard.");
                    break;
                }

                var tempNumOfBiotasConsolidated = Interlocked.Increment(ref numOfBiotasConsolidated);

                if ((tempNumOfBiotasConsolidated + numOfErrors) % 1000 == 0)
                    Console.WriteLine($"{tempNumOfBiotasConsolidated:N0} biotas successfully processed out of {partialBiotas.Count:N0}...");
            }


            // Update enchantment tables for equipped items
            using (var context = new ShardDbContext())
            {
                var enchantments = context.BiotaPropertiesEnchantmentRegistry.Where(r => r.CasterObjectId >= startingGuid).ToList();

                // First, remove the enchantments from the database
                foreach (var enchantment in enchantments)
                {
                    if (idConversions.TryGetValue(enchantment.CasterObjectId, out var newId))
                        context.BiotaPropertiesEnchantmentRegistry.Remove(enchantment);
                }

                context.SaveChanges();

                // Second, re-id them and add them back
                foreach (var enchantment in enchantments)
                {
                    if (idConversions.TryGetValue(enchantment.CasterObjectId, out var newId))
                    {
                        enchantment.CasterObjectId = newId;

                        context.BiotaPropertiesEnchantmentRegistry.Add(enchantment);
                    }
                }

                var shortcuts = context.CharacterPropertiesShortcutBar.Where(r => r.ShortcutObjectId >= startingGuid).ToList();

                foreach (var shortcut in shortcuts)
                {
                    if (idConversions.TryGetValue(shortcut.ShortcutObjectId, out var newId))
                        shortcut.ShortcutObjectId = newId;
                }

                context.SaveChanges();
            }


            // Finished
            numberOfBiotasConsolidated = numOfBiotasConsolidated;
            numberOfErrors = numOfErrors;

            log.Info($"Consolidated {numberOfBiotasConsolidated:N0} biotas with {numberOfErrors:N0} errors out of {partialBiotas.Count:N0} total.");
        }

19 View Source File : DeveloperDatabaseCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[CommandHandler("fix-spell-bars", AccessLevel.Admin, CommandHandlerFlag.ConsoleInvoke, "Fixes the players spell bars.", "<execute>")]
        public static void HandleFixSpellBars(Session session, params string[] parameters)
        {
            Console.WriteLine();

            Console.WriteLine("This command will attempt to fix player spell bars. Unless explictly indicated, command will dry run only");
            Console.WriteLine("You must have executed 2020-04-11-00-Update-Character-SpellBars.sql script first before running this command");

            Console.WriteLine();

            var execute = false;

            if (parameters.Length < 1)
                Console.WriteLine("This will be a dry run and show which characters that would be affected. To perform fix, please use command: fix-spell-bars execute");
            else if (parameters[0].ToLower() == "execute")
                execute = true;
            else
                Console.WriteLine("Please use command fix-spell-bars execute");


            if (!execute)
            {
                Console.WriteLine();
                Console.WriteLine("Press enter to start.");
                Console.ReadLine();
            }

            var numberOfRecordsFixed = 0;

            log.Info($"Starting FixSpellBarsPR2918 process. This could take a while...");

            using (var context = new ShardDbContext())
            {
                var characterSpellBarsNotFixed = context.CharacterPropertiesSpellBar.Where(c => c.SpellBarNumber == 0).ToList();

                if (characterSpellBarsNotFixed.Count > 0)
                {
                    log.Warn("2020-04-11-00-Update-Character-SpellBars.sql patch not yet applied. Please apply this patch ASAP! Skipping FixSpellBarsPR2918 for now...");
                    log.Fatal("2020-04-11-00-Update-Character-SpellBars.sql patch not yet applied. You must apply this patch before proceeding further...");
                    return;
                }

                var characterSpellBars = context.CharacterPropertiesSpellBar.OrderBy(c => c.CharacterId).ThenBy(c => c.SpellBarNumber).ThenBy(c => c.SpellBarIndex).ToList();

                uint characterId = 0;
                uint spellBarNumber = 0;
                uint spellBarIndex = 0;

                foreach (var entry in characterSpellBars)
                {
                    if (entry.CharacterId != characterId)
                    {
                        characterId = entry.CharacterId;
                        spellBarIndex = 0;
                    }

                    if (entry.SpellBarNumber != spellBarNumber)
                    {
                        spellBarNumber = entry.SpellBarNumber;
                        spellBarIndex = 0;
                    }

                    spellBarIndex++;

                    if (entry.SpellBarIndex != spellBarIndex)
                    {
                        Console.WriteLine($"FixSpellBarsPR2918: Character 0x{entry.CharacterId:X8}, SpellBarNumber = {entry.SpellBarNumber} | SpellBarIndex = {entry.SpellBarIndex:000}; Fixed - {spellBarIndex:000}");
                        entry.SpellBarIndex = spellBarIndex;
                        numberOfRecordsFixed++;
                    }
                    else
                    {
                        Console.WriteLine($"FixSpellBarsPR2918: Character 0x{entry.CharacterId:X8}, SpellBarNumber = {entry.SpellBarNumber} | SpellBarIndex = {entry.SpellBarIndex:000}; OK");
                    }
                }

                // Save
                if (execute)
                {
                    Console.WriteLine("Saving changes...");
                    context.SaveChanges();
                    log.Info($"Fixed {numberOfRecordsFixed:N0} CharacterPropertiesSpellBar records.");
                }
                else
                {
                    Console.WriteLine($"{numberOfRecordsFixed:N0} CharacterPropertiesSpellBar records need to be fixed!");
                    Console.WriteLine("dry run completed. Use fix-spell-bars execute to actually run command");
                }
            }
        }

19 View Source File : CommandManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void CommandThread()
        {
            Console.WriteLine("");
            Console.WriteLine("ACEmulator command prompt ready.");
            Console.WriteLine("");
            Console.WriteLine("Type \"acecommands\" for help.");
            Console.WriteLine("");

            for (;;)
            {
                Console.Write("ACE >> ");

                string commandLine = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(commandLine))
                    continue;

                string command = null;
                string[] parameters = null;
                try
                {
                    ParseCommand(commandLine, out command, out parameters);
                }
                catch (Exception ex)
                {
                    log.Error($"Exception while parsing command: {commandLine}", ex);
                    return;
                }
                try
                {
                    if (GetCommandHandler(null, command, parameters, out var commandHandler) == CommandHandlerResponse.Ok)
                    {
                        try
                        {
                            if (commandHandler.Attribute.IncludeRaw)
                            {
                                parameters = StuffRawIntoParameters(commandLine, command, parameters);
                            }
                            // Add command to world manager's main thread...
                            ((CommandHandler)commandHandler.Handler).Invoke(null, parameters);
                        }
                        catch (Exception ex)
                        {
                            log.Error($"Exception while invoking command handler for: {commandLine}", ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error($"Exception while getting command handler for: {commandLine}", ex);
                }
            }
        }

19 View Source File : Program_Setup.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void DoOutOfBoxSetup(string configFile)
        {
            var exeLocation = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location);
            var configJsExample = Path.Combine(exeLocation, "Config.js.example");
            var exampleFile = new FileInfo(configJsExample);
            if (!exampleFile.Exists)
            {
                log.Error("config.js.example Configuration file is missing.  Please copy the file config.js.example to config.js and edit it to match your needs before running ACE.");
                throw new Exception("missing config.js configuration file");
            }
            else
            {
                if (!IsRunningInContainer)
                {
                    Console.WriteLine("config.js Configuration file is missing,  cloning from example file.");
                    File.Copy(configJsExample, configFile, true);
                }
                else
                {
                    Console.WriteLine("config.js Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                    var configJsDocker = Path.Combine(exeLocation, "Config.js.docker");
                    File.Copy(configJsDocker, configFile, true);
                }
            }

            var fileText = File.ReadAllText(configFile);
            var config = JsonConvert.DeserializeObject<MasterConfiguration>(new JsMinifier().Minify(fileText));

            Console.WriteLine("Performing setup for ACEmulator...");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Welcome to ACEmulator! To configure your world for first use, please follow the instructions below. Press enter at each prompt to accept default values.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the name for your World (default: \"{config.Server.WorldName}\"): ");
            var variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_WORLD_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.WorldName = variable.Trim();
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("The next two entries should use defaults, unless you have specific network environments...");
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"Enter the Host address for your World (default: \"{config.Server.Network.Host}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.Network.Host = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the Port for your World (default: \"{config.Server.Network.Port}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.Network.Port = Convert.ToUInt32(variable.Trim());
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the directory location for your DAT files (default: \"{config.Server.DatFilesDirectory}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_DAT_FILES_DIRECTORY");
            if (!string.IsNullOrWhiteSpace(variable))
            {
                var path = Path.GetFullPath(variable.Trim());
                if (!Path.EndsInDirectorySeparator(path))
                    path += Path.DirectorySeparatorChar;
                //path = path.Replace($"{Path.DirectorySeparatorChar}", $"{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}");

                config.Server.DatFilesDirectory = path;
            }
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Next we will configure your SQL server connections. You will need to know your database name, username and preplacedword for each.");
            Console.WriteLine("Default names for the databases are recommended, and it is also recommended you not use root for login to database. The preplacedword must not be blank.");
            Console.WriteLine("It is also recommended the SQL server be hosted on the same machine as this server, so defaults for Host and Port would be ideal as well.");
            Console.WriteLine("As before, pressing enter will use default value.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the database name for your authentication database (default: \"{config.MySql.Authentication.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.Authentication.Database = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the database name for your shard database (default: \"{config.MySql.Shard.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.Shard.Database = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the database name for your world database (default: \"{config.MySql.World.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.World.Database = variable.Trim();
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the same SQL server, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the Host address for your SQL server (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Host = variable.Trim();
                    config.MySql.Shard.Host = variable.Trim();
                    config.MySql.World.Host = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the Port for your SQL server (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                    config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
                    config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
                }
                Console.WriteLine();
            }
            else
            {
                Console.Write($"Enter the Host address for your authentication database (default: \"{config.MySql.Authentication.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your authentication database (default: \"{config.MySql.Authentication.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();

                Console.Write($"Enter the Host address for your shard database (default: \"{config.MySql.Shard.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your shard database (default: \"{config.MySql.Shard.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();

                Console.Write($"Enter the Host address for your world database (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your world database (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the using the same SQL server credentials, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = "y";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the username for your SQL server (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_USER");
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Username = variable.Trim();
                    config.MySql.Shard.Username = variable.Trim();
                    config.MySql.World.Username = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your SQL server (default: \"{config.MySql.World.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_PreplacedWORD");
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Preplacedword = variable.Trim();
                    config.MySql.Shard.Preplacedword = variable.Trim();
                    config.MySql.World.Preplacedword = variable.Trim();
                }
            }
            else
            {
                Console.Write($"Enter the username for your authentication database (default: \"{config.MySql.Authentication.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your authentication database (default: \"{config.MySql.Authentication.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Preplacedword = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the username for your shard database (default: \"{config.MySql.Shard.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your shard database (default: \"{config.MySql.Shard.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Preplacedword = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the username for your world database (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your world database (default: \"{config.MySql.World.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Preplacedword = variable.Trim();
            }

            Console.WriteLine("commiting configuration to memory...");
            using (StreamWriter file = File.CreateText(configFile))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Formatting = Formatting.Indented;
                //serializer.NullValueHandling = NullValueHandling.Ignore;
                //serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
                serializer.Serialize(file, config);
            }


            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to ACEmulator to attempt to initilize your SQL databases? This will erase any existing ACEmulator specific databases that may already exist on the server (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_INITIALIZE_DATABASES")) ? "y" : "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                Console.Write($"Waiting for connection to SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                for (; ; )
                {
                    try
                    {
                        using (var sqlTestConnection = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120"))
                        {
                            Console.Write(".");
                            sqlTestConnection.Open();
                        }

                        break;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {
                        Console.Write(".");
                        Thread.Sleep(5000);
                    }
                }
                Console.WriteLine(" connected!");

                if (IsRunningInContainer)
                {
                    Console.Write("Clearing out temporary ace% database .... ");
                    var sqlDBFile = "DROP DATABASE `ace%`;";
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {

                    }
                    Console.WriteLine(" done!");
                }

                Console.WriteLine("Searching for base SQL scripts .... ");
                foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Base").GetFiles("*.sql").OrderBy(f => f.Name))
                {
                    Console.Write($"Found {file.Name} .... ");
                    var sqlDBFile = File.ReadAllText(file.FullName);
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
                    switch (file.Name)
                    {
                        case "AuthenticationBase":
                            sqlConnectInfo = $"server={config.MySql.Authentication.Host};port={config.MySql.Authentication.Port};user={config.MySql.Authentication.Username};preplacedword={config.MySql.Authentication.Preplacedword};DefaultCommandTimeout=120";
                            break;
                        case "ShardBase":
                            sqlConnectInfo = $"server={config.MySql.Shard.Host};port={config.MySql.Shard.Port};user={config.MySql.Shard.Username};preplacedword={config.MySql.Shard.Preplacedword};DefaultCommandTimeout=120";
                            break;
                    }
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {

                    }
                    Console.WriteLine(" complete!");
                }
                Console.WriteLine("Base SQL scripts import complete!");

                Console.WriteLine("Searching for Update SQL scripts .... ");

                PatchDatabase("Authentication", config.MySql.Authentication.Host, config.MySql.Authentication.Port, config.MySql.Authentication.Username, config.MySql.Authentication.Preplacedword, config.MySql.Authentication.Database);

                PatchDatabase("Shard", config.MySql.Shard.Host, config.MySql.Shard.Port, config.MySql.Shard.Username, config.MySql.Shard.Preplacedword, config.MySql.Shard.Database);

                PatchDatabase("World", config.MySql.World.Host, config.MySql.World.Port, config.MySql.World.Username, config.MySql.World.Preplacedword, config.MySql.World.Database);
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to download the latest world database and import it? (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_DOWNLOAD_LATEST_WORLD_RELEASE")) ? "y" : "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                if (IsRunningInContainer)
                {
                    Console.WriteLine(" ");
                    Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
                    Console.WriteLine(" ");
                }

                Console.Write("Looking up latest release from ACEmulator/ACE-World-16PY-Patches .... ");

                // webrequest code provided by OptimShi
                var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "Mozilla//5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko//20100101 Firefox//72.0";
                request.UserAgent = "ACE.Server";

                var response = request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                var html = reader.ReadToEnd();
                reader.Close();
                response.Close();

                dynamic json = JsonConvert.DeserializeObject(html);
                string tag = json[0].tag_name;
                string dbURL = json[0].replacedets[0].browser_download_url;
                string dbFileName = json[0].replacedets[0].name;
                // webrequest code provided by OptimShi

                Console.WriteLine($"Found {tag} !");

                Console.Write($"Downloading {dbFileName} .... ");
                using (var client = new WebClient())
                {
                    client.DownloadFile(dbURL, dbFileName);
                }
                Console.WriteLine("download complete!");

                Console.Write($"Extracting {dbFileName} .... ");
                ZipFile.ExtractToDirectory(dbFileName, ".", true);
                Console.WriteLine("extraction complete!");
                Console.Write($"Deleting {dbFileName} .... ");
                File.Delete(dbFileName);
                Console.WriteLine("Deleted!");

                var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);
                Console.Write($"Importing {sqlFile} into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} (This will take a while, please be patient) .... ");
                using (var sr = File.OpenText(sqlFile))
                {
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120");

                    var line = string.Empty;
                    var completeSQLline = string.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                        //do minimal amount of work here
                        if (line.EndsWith(";"))
                        {
                            completeSQLline += line + Environment.NewLine;

                            var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
                            try
                            {
                                script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                                var count = script.Execute();
                            }
                            catch (MySql.Data.MySqlClient.MySqlException)
                            {

                            }
                            completeSQLline = string.Empty;
                        }
                        else
                            completeSQLline += line + Environment.NewLine;
                    }
                }
                Console.WriteLine(" complete!");

                Console.Write($"Deleting {sqlFile} .... ");
                File.Delete(sqlFile);
                Console.WriteLine("Deleted!");
            }

            Console.WriteLine("exiting setup for ACEmulator.");
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : action-bi-toolkit

static int Main(string[] args)
        {
            // When invoked w/o args, print usage and exit immediately (do not trigger ArgException)
            if ((args ?? new string[0]).Length == 0)
            {
                ArgUsage.GenerateUsageFromTemplate<CmdLineActions>().WriteLine();
                return (int)ExitCode.NoArgsProvided;
            }

            var result = default(ExitCode);
            try
            {
                var action = Args.ParseAction<CmdLineActions>(args);
                
                action.Invoke(); // throws ArgException (DuplicateArg, MissingArg, UnexpectedArg, UnknownArg, ValidationArg)

                // in Debug compilation, propagates any exceptions thrown by executing action
                // in Release compilation, a user friendly error message is displayed, and exceptions thrown are available via the HandledException property

                /* This branch only applies in Release (StandardExceptionHandling enabled) mode, and only to __parser__ exceptions */
                if (action.HandledException != null)
                {
                    // Standard output has been generated by PowerArgs framework already
                    Console.WriteLine();
                    Log.Verbose(action.HandledException, "PowerArgs exception");
                }

                // TODO Define and handle specific exceptions to report back to user directly (No PBI install, etc...)

                result = action.HandledException == null ? ExitCode.Success : ExitCode.InvalidArgs;
            }
            catch (ArgException ex)
            {
                // In RELEASE mode, the PowerArgs error has already been emitted, and the usage docs have been printed to the console at this stage
                
                if (!Environment.UserInteractive)
                {
                    Log.Fatal(ex, "Bad user input.");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Error.WriteLine(ex.Message);
                    Console.ResetColor();
#if DEBUG
                    ArgUsage.GenerateUsageFromTemplate(ex.Context.Definition).WriteLine();
#endif
                }
                result = ExitCode.InvalidArgs;
            }
            catch (PbiToolsCliException ex)
            {
                Log.Error(ex.Message);
                result = ex.ErrorCode;
            }
            catch (Exception ex) /* Any unhandled exception */
            {
                // TODO Explicitly log into crash file...
                // If CWD is not writable, put into user profile and show path...

                Log.Fatal(ex, "An unhandled exception occurred.");
                result = ExitCode.UnexpectedError;
            }

            // Prevent closing of window when debugging
            if (Debugger.IsAttached && Environment.UserInteractive)
            {
                Console.WriteLine();
                Console.Write("Press ENTER to exit...");
                Console.ReadLine();
            }

            // ExitCode:
            return (int)result;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : actions

public static int Main(string[] args)
        {
            Console.CancelKeyPress += Console_CancelKeyPress;

            // Set encoding to UTF8, process invoker will use UTF8 write to STDIN
            Console.InputEncoding = Encoding.UTF8;
            Console.OutputEncoding = Encoding.UTF8;
            try
            {
                ArgUtil.NotNull(args, nameof(args));
                ArgUtil.Equal(2, args.Length, nameof(args.Length));

                string pluginType = args[0];
                if (string.Equals("action", pluginType, StringComparison.OrdinalIgnoreCase))
                {
                    string replacedemblyQualifiedName = args[1];
                    ArgUtil.NotNullOrEmpty(replacedemblyQualifiedName, nameof(replacedemblyQualifiedName));

                    string serializedContext = Console.ReadLine();
                    ArgUtil.NotNullOrEmpty(serializedContext, nameof(serializedContext));

                    RunnerActionPluginExecutionContext executionContext = StringUtil.ConvertFromJson<RunnerActionPluginExecutionContext>(serializedContext);
                    ArgUtil.NotNull(executionContext, nameof(executionContext));

                    VariableValue culture;
                    ArgUtil.NotNull(executionContext.Variables, nameof(executionContext.Variables));
                    if (executionContext.Variables.TryGetValue("system.culture", out culture) &&
                        !string.IsNullOrEmpty(culture?.Value))
                    {
                        CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(culture.Value);
                        CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(culture.Value);
                    }

                    replacedemblyLoadContext.Default.Resolving += Resolvereplacedembly;
                    try
                    {
                        Type type = Type.GetType(replacedemblyQualifiedName, throwOnError: true);
                        var taskPlugin = Activator.CreateInstance(type) as IRunnerActionPlugin;
                        ArgUtil.NotNull(taskPlugin, nameof(taskPlugin));
                        taskPlugin.RunAsync(executionContext, tokenSource.Token).GetAwaiter().GetResult();
                    }
                    catch (Exception ex)
                    {
                        // any exception throw from plugin will fail the task.
                        executionContext.Error(ex.Message);
                        executionContext.Debug(ex.StackTrace);
                        return 1;
                    }
                    finally
                    {
                        replacedemblyLoadContext.Default.Resolving -= Resolvereplacedembly;
                    }

                    return 0;
                }
                else
                {
                    throw new ArgumentOutOfRangeException(pluginType);
                }
            }
            catch (Exception ex)
            {
                // infrastructure failure.
                Console.Error.WriteLine(ex.ToString());
                return 1;
            }
            finally
            {
                Console.CancelKeyPress -= Console_CancelKeyPress;
            }
        }

19 View Source File : Terminal.cs
License : MIT License
Project Creator : actions

public string ReadLine()
        {
            // Read and trace the value.
            Trace.Info("READ LINE");
            string value = Console.ReadLine();
            Trace.Info($"Read value: '{value}'");
            return value;
        }

public static void KxQuery(string host, int port, string Credentials)
        {
            var list = new List<string>();
            c c = new c(host, port, Credentials);
            Console.WriteLine("Connected to Q Successfully!! \n");
            Console.WriteLine("Begin q script: \n");
            while (true)
            {
                var str = Console.ReadLine();
                var lis = str.Split('\n').ToList();
                list.AddRange(lis);
                if (str == "EXIT")
                {
                    break;
                }
            }

            foreach (var a in list)
            {
                Console.WriteLine("Executing : " + a + "\n");
                c.ks(a); // create example table using async msg (c.ks)                   
            }
            Console.WriteLine("\n Scripts Executed Successfully!!");

            c.Close();
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence

static void Main(string[] args)
        {
            bool DonotLoadGrid = true;
            var grid = new List<IList<double>>();
            if (!DonotLoadGrid)
            {
                Console.WriteLine("Loading Stream: " + DateTime.Now.ToString());
                var sr = new StreamReader(@"C:\data\table.csv");

                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    var fieldValues = line.Split(',');
                    var fields = new List<double>();
                    var rdm = new Random(100000);
                    foreach (var field in fieldValues)
                    {
                        var res = 0d;
                        var add = double.TryParse(field, out res) == true ? res : rdm.NextDouble();
                        fields.Add(add);
                    }
                    grid.Add(fields);
                }
                Console.WriteLine("Grid loaded successfully!! " + DateTime.Now.ToString());
            }
            var keepProcessing = true;
            while (keepProcessing)
            {
                Console.WriteLine(DateTime.Now.ToString());
                Console.WriteLine("Enter Expression:");
                var expression = Console.ReadLine();
                if (expression.ToLower() == "exit")
                {
                    keepProcessing = false;
                }
                else
                {
                    try
                    {
                        if(expression.Equals("zspread"))
                        {
                            var result = ConnectedInstruction.GetZSpread(grid,3,503);
                        }
                        if (expression.Substring(0, 19).ToLower().Equals("logisticregression "))
                        {
                            keepProcessing = true;
                            var paths = expression.Split(' '); 
                            #region Python
                                var script [email protected]"
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score

creditData = pd.read_csv("+paths[1][email protected]")

print(creditData.head())
print(creditData.describe())
print(creditData.corr())

features = creditData[['income', 'age', 'loan']]
target = creditData.default

feature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size = 0.3)

model = LogisticRegression()
model.fit = model.fit(feature_train, target_train)
predictions = model.fit.predict(feature_test)

print(confusion_matrix(target_test, predictions))
print(accuracy_score(target_test, predictions))
";
                            var sw = new StreamWriter(@"c:\data\logistic.py");
                            sw.Write(script);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\logistic.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..."+ DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if(expression.Substring(0,12) == "videoreplacedyse")
                        {
                            #region python
                            var python = @"
from keras.preprocessing.image import img_to_array
import imutils
import cv2
from keras.models import load_model
import numpy as np
import geocoder
#import mysql.connector as con

#mydb = con.connect(
#  host=""localhost"",
#  user=""yourusername"",
#  preplacedwd=""yourpreplacedword"",
# database=""mydatabase""
#)
#mycursor = mydb.cursor()

g = geocoder.ip('me')

# parameters for loading data and images
detection_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\haarcascade_files\\haarcascade_frontalface_default.xml'
emotion_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\models\\_mini_XCEPTION.102-0.66.hdf5'

# hyper-parameters for bounding boxes shape
# loading models
face_detection = cv2.CascadeClreplacedifier(detection_model_path)
emotion_clreplacedifier = load_model(emotion_model_path, compile = False)
EMOTIONS = [""angry"", ""disgust"", ""scared"", ""happy"", ""sad"", ""surprised"",
""neutral""]


# feelings_faces = []
# for index, emotion in enumerate(EMOTIONS):
# feelings_faces.append(cv2.imread('emojis/' + emotion + '.png', -1))

# starting video streaming
cv2.namedWindow('your_face')
camera = cv2.VideoCapture(0)
f = open(""C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Probability.txt"", ""a+"")

while True:
frame = camera.read()[1]
#reading the frame
frame = imutils.resize(frame, width = 300)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detection.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (30, 30), flags = cv2.CASCADE_SCALE_IMAGE)


canvas = np.zeros((250, 300, 3), dtype = ""uint8"")
frameClone = frame.copy()
if len(faces) > 0:
faces = sorted(faces, reverse = True,
key = lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
(fX, fY, fW, fH) = faces
# Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare
# the ROI for clreplacedification via the CNN
roi = gray[fY: fY + fH, fX: fX + fW]
roi = cv2.resize(roi, (64, 64))
roi = roi.astype(""float"") / 255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi, axis = 0)



preds = emotion_clreplacedifier.predict(roi)[0]
emotion_probability = np.max(preds)
label = EMOTIONS[preds.argmax()]
else: continue



for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):
# construct the label text
text = ""{}: {:.2f}%"".format(emotion, prob * 100)
#sql = ""INSERT INTO predData (Metadata, Probability) VALUES (%s, %s)""
#val = (""Meta"", prob * 100)
f.write(text)
#str1 = ''.join(str(e) for e in g.latlng)
#f.write(str1)
#mycursor.execute(sql, val)
#mydb.commit()
# draw the label + probability bar on the canvas
# emoji_face = feelings_faces[np.argmax(preds)]

                
w = int(prob * 300)
cv2.rectangle(canvas, (7, (i * 35) + 5),
(w, (i * 35) + 35), (0, 0, 255), -1)
cv2.putText(canvas, text, (10, (i * 35) + 23),
cv2.FONT_HERSHEY_SIMPLEX, 0.45,
(255, 255, 255), 2)
cv2.putText(frameClone, label, (fX, fY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
(0, 0, 255), 2)


#    for c in range(0, 3):
#        frame[200:320, 10:130, c] = emoji_face[:, :, c] * \
#        (emoji_face[:, :, 3] / 255.0) + frame[200:320,
#        10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0)


cv2.imshow('your_face', frameClone)
cv2.imshow(""Probabilities"", canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

camera.release()
cv2.destroyAllWindows()
";
                            var sw = new StreamWriter(@"c:\data\face.py");
                            sw.Write(python);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\face.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..." + DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if (expression.Substring(0,12).ToLower().Equals("kaplanmeier "))
                        {
                            keepProcessing = true;
                            var columnsOfconcern = expression.Split(' ');
                            Console.WriteLine("Preparing...");
                            var observations = new List<PairedObservation>();
                            var ca = GetColumn(grid,int.Parse(columnsOfconcern[1]));
                            var cb = GetColumn(grid, int.Parse(columnsOfconcern[2]));
                            var cc = GetColumn(grid, int.Parse(columnsOfconcern[3]));
                            for(int i=0;i<ca.Count;i++)
                            {
                                observations.Add(new PairedObservation((decimal)ca[i], (decimal)cb[i], (decimal)cc[i]));
                            }
                            var kp = new KaplanMeier(observations);
                        }
                        if (expression.Equals("write"))
                        {
                            keepProcessing = true;
                            ConnectedInstruction.WritetoCsvu(grid, @"c:\data\temp.csv");
                        }
                        if (expression.Substring(0, 9) == "getvalue(")
                        {
                            keepProcessing = true;
                            Regex r = new Regex(@"\(([^()]+)\)*");
                            var res = r.Match(expression);
                            var val = res.Value.Split(',');
                            try
                            {
                                var gridVal = grid[int.Parse(val[0].Replace("(", "").Replace(")", ""))]
                                    [int.Parse(val[1].Replace("(", "").Replace(")", ""))];
                                Console.WriteLine(gridVal.ToString() + "\n");
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                Console.WriteLine("Hmmm,... apologies, can't seem to find that within range...");
                            }
                        }
                        else
                        {
                            keepProcessing = true;
                            Console.WriteLine("Process Begin:" + DateTime.Now.ToString());
                            var result = ConnectedInstruction.ParseExpressionAndRunAgainstInMemmoryModel(grid, expression);
                            Console.WriteLine("Process Ended:" + DateTime.Now.ToString());
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    {

                    }
                }
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : ad313

static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var summary3 = BenchmarkRunner.Run<SerializerCloneTest>();

            Console.ReadLine();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : adamped

static void Main(string[] args)
		{
			Console.WriteLine(" **** Scenario 1 (Intial Sync) ****");

			var server = new ServerApi();
			var client1 = new Client(server);
			var client2 = new Client(server);

			var row1Id = Guid.NewGuid();
			var row2Id = Guid.NewGuid();

			// Initial data loaded into the server
			server.Insert(new TableSchema() { Id = row1Id, Name = "Row1", Description = "mbeat" });
			server.Insert(new TableSchema() { Id = row2Id, Name = "Row2", Description = "samsung" });

			// Client adds a row
			var clientRow3 = new ClientTableSchema()
			{
				Id = Guid.NewGuid(),
				Name = "Row3",
				Description = "acer"
			};

			client1.InsertRow(clientRow3);

			// Scenario 1: New Row Added, New Server Rows
			client1.Sync();

			Console.WriteLine("\nCLIENT1:");
			foreach (var row in client1.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nSERVER:");
			foreach (var row in server.GetAll())
				Console.WriteLine(RowDisplay(row));


			// Scenario 2: New Row Added, Client2
			Console.WriteLine("\n **** Scenario 2 (Client Row Added) ****");
			var row4Id = Guid.NewGuid();
			client2.InsertRow(new ClientTableSchema() { Id = row4Id, Name = "Row4", Description = "lg" });

			Console.WriteLine("\nCLIENT2 (Before Sync):");
			foreach (var row in client2.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nNow syncing Client 2 and Client 1");
			client2.Sync();
			client1.Sync();

			Console.WriteLine("\nCLIENT1:");
			foreach (var row in client1.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nCLIENT2:");
			foreach (var row in client2.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nSERVER:");
			foreach (var row in server.GetAll())
				Console.WriteLine(RowDisplay(row));

			// This finishes up the Insert Rows, nice and easy

			// Scenario 3: Delete a row and sync
			Console.WriteLine("\n **** Scenario 3 (Delete Row) ****");
			client1.DeleteRow(row1Id);

			Console.WriteLine("\nCLIENT1 (Before Sync):");
			foreach (var row in client1.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nNow syncing Client 1 and Client 2");
			client1.Sync();
			client2.Sync();

			Console.WriteLine("\nCLIENT1:");
			foreach (var row in client1.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nCLIENT2:");
			foreach (var row in client2.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nSERVER:");
			foreach (var row in server.GetAll())
				Console.WriteLine(RowDisplay(row));


			// Scenario 4: Update a row
			Console.WriteLine("\n **** Scenario 4 (Update Row) ****");
			clientRow3.Name = "Row3 (Updated)";
			clientRow3.LastUpdated = DateTimeOffset.Now;
			client1.UpdateRow(clientRow3);

			Console.WriteLine("\nCLIENT1 (Before Sync):");
			foreach (var row in client1.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nNow syncing Client 2 and Client 1");
			client1.Sync();
			client2.Sync();

			Console.WriteLine("\nCLIENT1:");
			foreach (var row in client1.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nCLIENT2:");
			foreach (var row in client2.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nSERVER:");
			foreach (var row in server.GetAll())
				Console.WriteLine(RowDisplay(row));

			// Scenario 5: Conflicting Update
			Console.WriteLine("\n **** Scenario 5 (Partial non-conflicting update) ****");

			// Client 1 updates first, but Client 2 sync's first

			client1.UpdateRow(new ClientTableSchema() { Id = row4Id, LastUpdated = DateTimeOffset.Now, Name = "Updated Name (Row4)", Description = "lg" });

			client2.UpdateRow(new ClientTableSchema() { Id = row4Id, LastUpdated = DateTimeOffset.Now, Name = "Row4", Description = "Updated Description (lg)" });

			Console.WriteLine("\nNow syncing Client 2 and Client 1");
			client2.DifferentialSync(); // Does normal update

			client1.DifferentialSync(); // Will do partial, if it detects conflict

			Console.WriteLine("\nCLIENT1:");
			foreach (var row in client1.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nCLIENT2:");
			foreach (var row in client2.GetAll())
				Console.WriteLine(RowDisplay(row));

			Console.WriteLine("\nSERVER:");
			foreach (var row in server.GetAll())
				Console.WriteLine(RowDisplay(row));


			Console.ReadLine();
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : adrag239

static void Main(string[] args)
        {
            // 1
            BinaryClreplacedification.BinaryClreplacedificationDemo.Run();

            // 2
            MultiClreplacedClreplacedification.MultiClreplacedClreplacedificationDemo.Run();

            // 3
            Regression.RegressionDemo.Run();

            // 4
            Clustering.ClusteringDemo.Run();

            Console.ReadLine();
        }

19 View Source File : Stdio.cs
License : MIT License
Project Creator : AdrianWilczynski

public string ReadLine() => Console.ReadLine();

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : Aeroblast

static void ProcPath(string[] args)
        {
            string azw3_path = null;
            string azw6_path = null;
            string dir;
            string p = args[0];
            if (Directory.Exists(p))
            {
                string[] files = Directory.GetFiles(p);
                if (dedrm)
                {
                    foreach (string n in files)
                    {
                        if (Path.GetExtension(n).ToLower() == ".azw")
                        {
                            DeDRM(n);
                        }
                    }
                    files = Directory.GetFiles(p);
                }

                foreach (string n in files)
                {
                    if (Path.GetExtension(n).ToLower() == ".azw3")
                    {
                        azw3_path = n;
                    }
                    if (Path.GetExtension(n) == ".res")
                    {
                        azw6_path = n;
                    }
                }
            }
            else
            {
                if (dedrm && Path.GetExtension(p).ToLower() == ".azw")
                {
                    DeDRM(p);
                    dir = Path.GetDirectoryName(p);
                    string[] files = Directory.GetFiles(dir);
                    foreach (string n in files)
                    {
                        if (Path.GetExtension(n) == ".res")
                        {
                            azw6_path = n;
                        }
                        if (Path.GetExtension(n).ToLower() == ".azw3")
                        {
                            azw3_path = n;
                        }
                    }
                }
                else
                if (Path.GetExtension(p).ToLower() == ".azw3")
                {
                    azw3_path = p;
                    dir = Path.GetDirectoryName(p);
                    string[] files = Directory.GetFiles(dir);
                    foreach (string n in files)
                    {
                        if (Path.GetExtension(n) == ".res")
                        {
                            azw6_path = n;
                            break;
                        }
                    }
                }
                else if (Path.GetExtension(p).ToLower() == ".res")
                {
                    azw6_path = p;
                    dir = Path.GetDirectoryName(p);
                    string[] files = Directory.GetFiles(dir);
                    foreach (string n in files)
                    {
                        if (Path.GetExtension(n).ToLower() == ".azw3")
                        {
                            azw3_path = n;
                            break;
                        }
                    }
                }
            }


            Azw3File azw3 = null;
            Azw6File azw6 = null;
            if (azw3_path != null)
            {
                Log.log("==============START===============");
                azw3 = new Azw3File(azw3_path);
            }
            if (azw6_path != null)
                azw6 = new Azw6File(azw6_path);
            if (azw3 != null)
            {
                string auther = "";
                if (azw3.mobi_header.extMeta.id_string.ContainsKey(100))
                {
                    auther = "[" + azw3.mobi_header.extMeta.id_string[100].Split('&')[0] + "] ";
                }
                string outname = auther + azw3.replacedle + ".epub";
                outname = Util.FilenameCheck(outname);
                Epub epub = new Epub(azw3, azw6, rename_xhtml_with_id);
                Log.log(azw3);
                string output_path;
                if (args.Length >= 2 && Directory.Exists(args[1]))
                {
                    output_path = Path.Combine(args[1], outname);
                }
                else
                {
                    string outdir = Path.GetDirectoryName(args[0]);
                    output_path = Path.Combine(outdir, outname);
                }
                if (File.Exists(output_path))
                {
                    Log.log("[Warn]Output already exist.");
                    if (rename_when_exist)
                    {
                        string r_dir = Path.GetDirectoryName(output_path);
                        string r_name = Path.GetFileNameWithoutExtension(output_path);
                        string r_path = Path.Combine(r_dir, r_name);
                        output_path = "";
                        for (int i = 2; i < 50; i++)
                        {
                            string r_test = r_path + "(" + i + ").epub";
                            if (!File.Exists(r_test))
                            {
                                output_path = r_test;
                                break;
                            }
                        }
                        Log.log("[Warn]Save as...");
                    }
                    else if (!overwrite)
                    {
                        Console.WriteLine("Output file already exist. N(Abort,Defualt)/y(Overwrite)/r(Rename)?");
                        Console.WriteLine("Output path:" + output_path);
                        string input = Console.ReadLine().ToLower();
                        if (input == "y")
                        {
                            Log.log("[Warn]Old file will be replaced.");
                        }
                        else if (input == "r")
                        {
                            string r_dir = Path.GetDirectoryName(output_path);
                            string r_name = Path.GetFileNameWithoutExtension(output_path);
                            string r_path = Path.Combine(r_dir, r_name);
                            output_path = "";
                            for (int i = 2; i < 50; i++)
                            {
                                string r_test = r_path + "(" + i + ").epub";
                                if (!File.Exists(r_test))
                                {
                                    output_path = r_test;
                                    break;
                                }
                            }
                            Log.log("[Warn]Save as...");
                        }
                        else
                        {
                            Log.log("[Error]Operation aborted. You can use --overwrite or --rename-when-exist to avoid pause.");
                            output_path = "";
                        }

                    }
                    else
                    {
                        Log.log("[Warn]Old file will be replaced.");
                    }
                }
                if (output_path != "")
                    epub.Save(output_path);
                Log.log("azw3 source:" + azw3_path);
                if (azw6_path != null)
                    Log.log("azw6 source:" + azw6_path);
            }
            else
            {
                Console.WriteLine("Cannot find .azw3 file in " + p);
            }
        }

19 View Source File : LanguageModule.cs
License : MIT License
Project Creator : AgathokakologicalBit

ExpressionNode Input(ExpressionNode type, Context context)
        {
            var data = new StringNode(Console.ReadLine(), false);
            var result = interpreter.Run(type, data);
            return result;
        }

19 View Source File : ZeroApplication.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void CommandConsole()
        {
            while (true)
            {
                var cmd = Console.ReadLine();
                if (String.IsNullOrWhiteSpace(cmd))
                    continue;
                switch (cmd.Trim().ToLower())
                {
                    case "quit":
                    case "exit":
                        Shutdown();
                        return;
                    case "start":
                        Start();
                        continue;
                }

                var words = cmd.Split(' ', '\t', '\r', '\n');
                if (words.Length == 0)
                {
                    Console.WriteLine("请输入正确命令");
                    continue;
                }

                var result = SystemManager.Instance.CallCommand(words);
                if (result.InteractiveSuccess)
                    ZeroTrace.SystemLog("Console", result.TryGetValue(ZeroFrameType.Status, out var value)
                        ? value
                        : result.State.Text());
                else
                    ZeroTrace.WriteError("Console", result.TryGetValue(ZeroFrameType.Status, out var value)
                        ? value
                        : result.State.Text());
            }
        }

See More Examples