コード例 #1
0
ファイル: Program.cs プロジェクト: parrottsquawk/School
        public static void Main(string[] args)
        {
            // Command Line Control
              //-----------------------------------------------------------------
              try {
            CommandInterpreter ci = new CommandInterpreter(args);

            Console.WriteLine();
            if (ci.Encoding == Encoding.ASCII) {
              AsciiFileReader reader = new AsciiFileReader(ci);
              RunAsciiTestOnce(reader.Data, ci.QueryString, ci.NumOfRuns);
            }
            else {
              BinaryFileReader reader = new BinaryFileReader(ci);
              RunBinaryTestOnce(reader.Data, MakeBitArray(ci.QueryString), ci.NumOfRuns);
            }
              }
              catch (ArgumentException ex) {
            Console.WriteLine(ex.Message);
              }
              //-----------------------------------------------------------------

              // Or Create the Test Input Files and Run the Tests
              //-----------------------------------------------------------------
              //CreateTestFiles();
              //RunAsciiTestFiles();
              //RunBinaryTestFiles();
              //-----------------------------------------------------------------

              // Or Run an Ad-Hoc Test
              //-----------------------------------------------------------------
              //RunAsciiTestOnce("abracadabra", "abra");
              //RunBinaryTestOnce(MakeBitArray("111001101"), MakeBitArray("01"));
              //-----------------------------------------------------------------
        }
コード例 #2
0
ファイル: SimulationManager.cs プロジェクト: cccarmo/tccgame
    void Start()
    {
        GameObject panel = GameObject.FindWithTag ("DropPanel");
        interpreter = panel.GetComponent<CommandInterpreter>();

        running = false;
    }
コード例 #3
0
ファイル: Server.cs プロジェクト: theradeonxt/yoloth
 private void ServerService()
 {
     _tcpListener.Start();
     Socket = _tcpListener.AcceptSocket();
     try
     {
         Stream = new NetworkStream(Socket);
         var buffer = new byte[1024];
         var commandInterpreter = new CommandInterpreter();
         while (true)
         {
             if (!Stream.DataAvailable) continue;
             var bytesRead = Stream.Read(buffer, 0, buffer.Length);
             var receivedMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
             if (commandInterpreter.ExecuteCommand(receivedMessage))
             {
                 MessageBox.Show("Remote Client Disconnected");
                 break;
             }
         }
         Stream.Close();
         _tcpListener.Stop();
     }
     catch (Exception e)
     {
         MessageBox.Show("Something went wrong with the connection " + e.Message);
     }
 }
コード例 #4
0
ファイル: CommandsDisplayer.cs プロジェクト: cccarmo/tccgame
    void Start()
    {
        displayer = GetComponentInChildren<Text>();
        standardColor = displayer.color;

        GameObject panel = GameObject.FindWithTag("DropPanel");
        interpreter = panel.GetComponent<CommandInterpreter>();
    }
コード例 #5
0
        public void EvalArgless()
        {
            var interp = new CommandInterpreter();
            int ran = 0;
            interp.AddCommand("run", new Action(() => ran++));

            interp.Eval("run");
            Assert.AreEqual(1, ran);
        }
コード例 #6
0
        public void EvalAsyncArgless()
        {
            var io = new StringWriter();
            var interp = new CommandInterpreter(io, io);
            var obj = new CommandObj();
            interp.AddCommand("say", new Action<TextWriter>(obj.AsyncArgless));

            interp.Eval("say");
            Assert.AreEqual("hi", io.ToString());
        }
コード例 #7
0
        public void Eval()
        {
            var io = new StringWriter();
            var interp = new CommandInterpreter(io, io);
            var args = new CommandArg() { Type = typeof(int) }.And(new CommandArg() { Type = typeof(int) });
            interp.AddCommand("plus", args, (o, e, c) => o.WriteLine(c["0"].ConvertTo<int>() + c["1"].ConvertTo<int>()));

            interp.Eval("plus 2 2");
            Assert.AreEqual("4\r\n", io.ToString());
        }
コード例 #8
0
        public void EvalFromMethodInfo()
        {
            var io = new StringWriter();
            var interp = new CommandInterpreter(io, io);
            var obj = new CommandObj();
            interp.AddCommand("Plus", obj);

            interp.Eval("Plus 2 2");
            Assert.AreEqual("4\r\n", io.ToString());
        }
コード例 #9
0
        public void EvalFromAction()
        {
            var io = new StringWriter();
            var interp = new CommandInterpreter(io, io);
            var obj = new CommandObj();
            interp.AddCommand("plus", new Action<TextWriter, int, int>(obj.AsyncPlus));

            interp.Eval("plus 2 2");
            Assert.AreEqual("4", io.ToString());
        }
コード例 #10
0
ファイル: Karuta.cs プロジェクト: TheDarkVoid/Karuta
        //Initialize
        static Karuta()
        {
            //Init Vars
            _threads = new Dictionary<string, Thread>();
            _timers = new Dictionary<string, Timer>();
            _interpretor = new CommandInterpreter<Command>();
            logger = new Logger();
            random = new Random();
            //Prepare Console
            try
            {
                Console.Title = "Karuta";
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Clear();
            }catch(Exception e)
            {
                Write(e.StackTrace);
            }
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Write("Preparing Karuta...");
            //Init Event Manager
            eventManager = new EventManager();
            eventManager.Init();
            //Init Registry
            Write("Loading Registry...");
            if(File.Exists(dataDir + "/karuta.data"))
            {
                registry = DataSerializer.deserializeData<Registry>(File.ReadAllBytes(dataDir + "/karuta.data"));
            }else
            {
                registry = new Registry();
                registry.Init();
                registry.SetValue("user", "user");
            }

            try
            {
                //Register Commands
                RegisterCommands();
                //Initalize commands
                Write("Initializing processes...");
                _interpretor.Init();
            }catch(Exception e)
            {
                Write($"An error occured while initializing commands: {e.Message}");
                Write(e.StackTrace);
            }
            sw.Stop();
            long elapsedT = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L));

            Write($"Karuta is ready. Finished in {elapsedT}ms");
            logger.Log($"Karuta started in {elapsedT}ms", "Karuta");
        }
コード例 #11
0
        public void Lexer_WithMultipleCommands_LineSeparated_Unsuccessful()
        {
            // Arrange
            const string s = "PLACE 1,2,EAST\r\nMOVE,1\r\nREPORT";

            // Act
            var lexerResult = CommandInterpreter.Lexer(s);

            // Assert
            Assert.Null(lexerResult);
        }
コード例 #12
0
        public static void RunMain()
        {
            //using (BillsPaymentSystemContext context = new BillsPaymentSystemContext())
            //{
            //    DbInitializer.Seed(context);
            //}
            ICommandInterpreter commandInterpreter = new CommandInterpreter();
            IEngine             engine             = new Engine();

            engine.Run();
        }
コード例 #13
0
        public void ShouldNotInterpretInValidPlaceCommand(string commandStr)
        {
            // Setup
            var interpreter = new CommandInterpreter();

            // Execute
            var result = interpreter.Interpret(commandStr);

            // Validate
            result.ShouldBe(null);
        }
コード例 #14
0
        private static bool ProcessCliCommands(string[] args)
        {
            var daemon        = new Daemon(Global, TerminateService);
            var interpreter   = new CommandInterpreter(Console.Out, Console.Error);
            var executionTask = interpreter.ExecuteCommandsAsync(
                args,
                new MixerCommand(daemon),
                new PasswordFinderCommand(Global.WalletManager));

            return(executionTask.GetAwaiter().GetResult());
        }
コード例 #15
0
        public void HtmlHelp(ICommandInterpreter _ci)
        {
            CommandInterpreter ci   = ((CommandInterpreter)_ci);
            HtmlLightDocument  doc  = new HtmlLightDocument(ci.GetHtmlHelp("help"));
            XmlLightElement    e    = doc.SelectRequiredNode("/html/body/h1[2]");
            XmlLightElement    body = e.Parent;
            int i = body.Children.IndexOf(e);

            body.Children.RemoveRange(i, body.Children.Count - i);

            StringWriter sw = new StringWriter();

            // Command index
            sw.WriteLine("<html><body>");
            sw.WriteLine("<h1>All Commands:</h1>");
            sw.WriteLine("<blockquote><ul>");
            ILookup <string, ICommand> categories = ci.Commands.Where(c => c.Visible).ToLookup(c => c.Category ?? "Unk");

            foreach (IGrouping <string, ICommand> group in categories.OrderBy(g => g.Key))
            {
                sw.WriteLine("<li><a href=\"#{0}\">{0}</a></li>", group.Key);
                sw.WriteLine("<ul>");
                foreach (ICommand cmd in group)
                {
                    sw.WriteLine("<li><a href=\"#{0}\">{0}</a> - {1}</li>", cmd.DisplayName, HttpUtility.HtmlEncode(cmd.Description));
                }
                sw.WriteLine("</ul>");
            }
            sw.WriteLine("</ul></blockquote>");

            // Command Help
            foreach (IGrouping <string, ICommand> group in categories.OrderBy(g => g.Key))
            {
                sw.WriteLine("<h2><a name=\"{0}\"></a>{0} Commands:</h2>", group.Key);
                sw.WriteLine("<blockquote>");
                foreach (ICommand cmd in group)
                {
                    e = new HtmlLightDocument(ci.GetHtmlHelp(cmd.DisplayName)).SelectRequiredNode("/html/body/h3");
                    sw.WriteLine("<a name=\"{0}\"></a>", cmd.DisplayName);
                    sw.WriteLine(e.InnerXml);
                    sw.WriteLine(e.NextSibling.NextSibling.InnerXml);
                }
                sw.WriteLine("</blockquote>");
            }

            e = new HtmlLightDocument(sw.ToString()).SelectRequiredNode("/html/body");
            body.Children.AddRange(e.Children);

            string html = body.Parent.InnerXml;
            string path = Path.Combine(Path.GetTempPath(), "HttpClone.Help.html");

            File.WriteAllText(path, html);
            System.Diagnostics.Process.Start(path);
        }
コード例 #16
0
        static void Main()
        {
            IReader             reader             = new ConsoleReader();
            IWriter             writer             = new ConsoleWriter();
            ICommandInterpreter commandInterpreter = new CommandInterpreter();
            IController         controller         = new Controller();

            IEngine engine = new Engine(reader, writer, commandInterpreter, controller);

            engine.Run();
        }
コード例 #17
0
    public static void Main(string[] args)
    {
        IReader            consoleReader      = new ConsoleReader();
        IWriter            consoleWriter      = new ConsoleWriter();
        IServiceProvider   serviceProvider    = ConfigureServices();
        CommandInterpreter commandInterpreter = new CommandInterpreter(serviceProvider);

        Engine engine = new Engine(commandInterpreter, consoleReader, consoleWriter);

        engine.Run();
    }
コード例 #18
0
    static void Main(string[] args)
    {
        var repository    = new WeaponRepository();
        var interpreter   = new CommandInterpreter();
        var weaponFactory = new WeaponFactory();
        var gemFactory    = new GemFactory();

        IRunnable engine = new Engine(gemFactory, weaponFactory, repository, interpreter);

        engine.Run();
    }
コード例 #19
0
        public static void Main()
        {
            var input = Console.ReadLine();
            var commandInterpreter = new CommandInterpreter();

            while (input != "END")
            {
                commandInterpreter.ProcessCommand(input);
                input = Console.ReadLine();
            }
        }
コード例 #20
0
        static void Main(string[] args)
        {
            IServiceProvider serviceProvider = ConfigureServices();

            IRepository         repository         = new UnitRepository();
            IUnitFactory        unitFactory        = new UnitFactory();
            ICommandInterpreter commandInterpreter = new CommandInterpreter(repository, unitFactory);
            IRunnable           engine             = new Engine(commandInterpreter);

            engine.Run();
        }
コード例 #21
0
        static void Main(string[] args)
        {
            IRepository         repository  = new UnitRepository();
            IUnitFactory        unitFactory = new UnitFactory();
            ICommandInterpreter commandInterpreter
                = new CommandInterpreter(repository, unitFactory);

            IRunnable engine = new Engine(commandInterpreter);

            engine.Run();
        }
コード例 #22
0
ファイル: BashSoftProgram.cs プロジェクト: nayots/SoftUni
        private static void Main(string[] args)
        {
            Tester             tester    = new Tester();
            IOManager          ioManager = new IOManager();
            StudentsRepository repo      = new StudentsRepository(new RepositorySorter(), new RepositoryFilter());

            CommandInterpreter currentInterpreter = new CommandInterpreter(tester, repo, ioManager);
            InputReader        reader             = new InputReader(currentInterpreter);

            reader.StartReadingCommands();
        }
コード例 #23
0
        public static void Main()
        {
            var tester    = new Tester();
            var ioManager = new IOManager();
            var repo      = new StudentsRepository(new RepositoryFilter(), new RepositorySorter());

            var currentInterpreter = new CommandInterpreter(tester, repo, ioManager);
            var reader             = new InputReader(currentInterpreter);

            reader.StartReadingCommands();
        }
コード例 #24
0
        public static void Main()
        {
            IRepository           repository         = new Repository();
            IBehaviourFactory     behaviourFactory   = new BehaviorFactory();
            IAttackFactory        attackFactory      = new AttackFactory();
            ICommandInterpretable commandInterpreter =
                new CommandInterpreter(repository, behaviourFactory, attackFactory);
            IRunable engine = new Engine(commandInterpreter);

            engine.Run();
        }
コード例 #25
0
        static void Main(string[] args)
        {
            IServiceProvider provider = ConfigureServices();

            ICommandInterpreter commandInterpreter =
                new CommandInterpreter(provider);

            IRunnable engine = new Engine(commandInterpreter);

            engine.Run();
        }
コード例 #26
0
        public void Lexer_BadParams_OK()
        {
            // Arrange
            const string s = "MOVE +1";

            // Act
            var lexerResult = CommandInterpreter.Lexer(s);

            // Assert
            Assert.Null(lexerResult);
        }
コード例 #27
0
ファイル: StartUp.cs プロジェクト: mariko33/OOP-Advanced
        static void Main()
        {
            IContentComparer  tester    = new Tester();
            IDirectoryManager ioManager = new IOManager();
            IDatabase         repo      = new StudentsRepository(new RepositoryFilter(), new RepositorySorter());

            IInterpreter currentInterpreter = new CommandInterpreter(tester, repo, ioManager);
            IReader      reader             = new InputReader(currentInterpreter);

            reader.StartReadingCommands();
        }
コード例 #28
0
        public void Lexer_BadCommand_Unsuccessful()
        {
            // Arrange
            const string s = "LE+FT";

            // Act
            var lexerResult = CommandInterpreter.Lexer(s);

            // Assert
            Assert.Null(lexerResult);
        }
コード例 #29
0
        public static void Main()
        {
            IMachinesManager machinesManager = new MachinesManager();

            ICommandInterpreter commandInterpreter = new CommandInterpreter(machinesManager);
            IWriter             writer             = new Writer();

            IEngine engine = new Engine(commandInterpreter, writer);

            engine.Run();
        }
コード例 #30
0
        private static bool ShouldRunGui(string[] args)
        {
            var daemon        = new Daemon(Global);
            var interpreter   = new CommandInterpreter(Console.Out, Console.Error);
            var executionTask = interpreter.ExecuteCommandsAsync(
                args,
                new MixerCommand(daemon),
                new PasswordFinderCommand(Global.WalletManager),
                new CrashReportCommand(Global.CrashReporter));

            return(executionTask.GetAwaiter().GetResult());
        }
コード例 #31
0
    public static void Main()
    {
        IInputReader        reader      = new ConsoleReader();
        IOutputWriter       writer      = new ConsoleWriter();
        ItemFactory         itemFactory = new ItemFactory();
        IHeroManager        heroManager = new HeroManager(itemFactory);
        ICommandInterpreter interpreter = new CommandInterpreter(heroManager);

        Engine engine = new Engine(reader, writer, interpreter);

        engine.Run();
    }
コード例 #32
0
        public static void Main()
        {
            IReader             reader             = new ConsoleReader();
            IWriter             writer             = new ConsoleWriter();
            IBattleOperator     battleOperator     = new TankBattleOperator();
            IManager            manager            = new TankManager(battleOperator);
            ICommandInterpreter commandInterpreter = new CommandInterpreter(manager);

            IEngine engine = new Engine(reader, writer, commandInterpreter);

            engine.Run();
        }
コード例 #33
0
        /// Warning! In Avalonia applications Main must not be async. Otherwise application may not run on OSX.
        /// see https://github.com/AvaloniaUI/Avalonia/wiki/Unresolved-platform-support-issues
        private static void Main(string[] args)
        {
            bool runGui = false;

            try
            {
                Global = new Global();

                Locator.CurrentMutable.RegisterConstant(Global);

                Platform.BaseDirectory = Path.Combine(Global.DataDir, "Gui");
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                TaskScheduler.UnobservedTaskException      += TaskScheduler_UnobservedTaskException;

                runGui = CommandInterpreter.ExecuteCommandsAsync(Global, args).GetAwaiter().GetResult();

                if (!runGui)
                {
                    return;
                }

                if (Global.InitializeUiConfigAsync().GetAwaiter().GetResult())
                {
                    Logger.LogInfo($"{nameof(Global.UiConfig)} is successfully initialized.");
                }
                else
                {
                    Logger.LogError($"Failed to initialize {nameof(Global.UiConfig)}.");
                    return;
                }

                Logger.LogSoftwareStarted("Wasabi GUI");

                BuildAvaloniaApp().StartShellApp("Wasabi Wallet", AppMainAsync, args);
            }
            catch (Exception ex)
            {
                Logger.LogCritical(ex);
                throw;
            }
            finally
            {
                MainWindowViewModel.Instance?.Dispose();
                Global.DisposeAsync().GetAwaiter().GetResult();
                AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException;
                TaskScheduler.UnobservedTaskException      -= TaskScheduler_UnobservedTaskException;

                if (runGui)
                {
                    Logger.LogSoftwareStopped("Wasabi GUI");
                }
            }
        }
コード例 #34
0
        public static void Main(string[] args)
        {
            IWriter writer = new ConsoleWriter();
            IReader reader = new ConsoleReader();

            DungeonMaster       dungeonMaster      = new DungeonMaster();
            ICommandInterpreter commandInterpreter = new CommandInterpreter(dungeonMaster);

            Engine engine = new Engine(writer, reader, dungeonMaster, commandInterpreter);

            engine.Run();
        }
コード例 #35
0
    public static void Main()
    {
        string             input      = Console.ReadLine();
        CommandInterpreter intrerpret = new CommandInterpreter();

        while (input != "END")
        {
            intrerpret.Interpret(input);
            input = Console.ReadLine();
        }
        intrerpret.Interpret(input);
    }
コード例 #36
0
    public static void Main()
    {
        IReader              reader              = new ConsoleReader();
        IWriter              writer              = new ConsoleWriter();
        IEnergyRepository    energyRepository    = new EnergyRepository();
        IHarvesterController harvesterController = new HarvesterController(energyRepository);
        IProviderController  providerController  = new ProviderController(energyRepository);
        ICommandInterpreter  commandInterpreter  = new CommandInterpreter(harvesterController, providerController);
        var engine = new Engine(reader, writer, harvesterController, providerController, commandInterpreter);

        engine.Run();
    }
コード例 #37
0
    public static void Main()
    {
        IInterpreter interpreter = new CommandInterpreter();

        string input = Console.ReadLine();

        while (input != "END")
        {
            interpreter.InterpretCommand(input);
            input = Console.ReadLine();
        }
    }
コード例 #38
0
        public void ConvertPlaceInStructuredData()
        {
            IInterpreter interpreter = new CommandInterpreter();

            var convert = interpreter.Convert("PLACE 0,0,NORTH");

            convert.Should().Be(new Action
            {
                ActionType = ActionType.Place,
                Position   = (0, 0),
                Facing     = new North()
            });
コード例 #39
0
        public static void Main()
        {
            // Create database and seed data on first strat.
            // ConfigureDatabaase();

            IServiceProvider serviceProvider = ConfigureServices();

            ICommandInterpreter commandInterpreter = new CommandInterpreter(serviceProvider);
            IEngine             engine             = new Engine(commandInterpreter);

            engine.Run();
        }
コード例 #40
0
 public string execute(CommandInterpreter commandInterpreter, string[] array)
 {
     if (array.Length != 1)
     {
         commandInterpreter.putResponse("Usage: statsReset");
     }
     else
     {
         this.this_0.recognizer.resetMonitors();
     }
     return("");
 }
コード例 #41
0
ファイル: CommandCreator.cs プロジェクト: cccarmo/tccgame
    void Start()
    {
        GameObject panel = GameObject.FindWithTag ("DropPanel");
        interpreter = panel.GetComponent<CommandInterpreter>();

        actions = new Dictionary<string, newCommandClosure>();
        comparisons = new Dictionary<string, newComparisonClosure>();

        // Creating Command Generators
        newCommandClosure newShootCommand = () => new ShootCommand(this);
        newCommandClosure newShieldCommand = () => new ShieldCommand(this);
        newCommandClosure newFowardCommand = () => new MoveForwardCommand(this);
        newCommandClosure newBackwardCommand = () => new MoveBackwardCommand(this);
        newCommandClosure neweLeftwardCommand = () => new MoveLeftwardsCommand(this);
        newCommandClosure newRightwardCommand = () => new MoveRightwardsCommand(this);
        newCommandClosure newClockwiseCommand = () => new TurnClockwiseCommand(this);
        newCommandClosure newCounterclockwiseCommand = () => new TurnCounterclockwiseCommand(this);

        newCommandClosure newForCommand = () => new FlowCommand(interpreter.semanticInterpreter.ForCommand, "Scoped Repetition", availableBoxes[7], 1, true);
        newCommandClosure newEndForCommand = () => new FlowCommand(interpreter.semanticInterpreter.EndForCommand, "Scoped Repetition End", availableBoxes[8], -1, false);
        newCommandClosure newForComparisonCommand = () => new FlowCommand(interpreter.semanticInterpreter.ForCommand, "Scoped Repetition", availableBoxes[9], 1, true);
        newCommandClosure newIfCommand = () => new FlowCommand(interpreter.semanticInterpreter.ForCommand, "Scoped Repetition", availableBoxes[11], 1, false);

        newComparisonClosure newComparison = () => new Comparison(availableBoxes[10]);
        newComparisonClosure newComparisonB = () => new Comparison(availableBoxes[13]);
        newComparisonClosure newComparisonF = () => new Comparison(availableBoxes[14]);

        // Adding Ship Commands to dictionary
        actions.Add("Shoot", newShootCommand);
        actions.Add("Shield", newShieldCommand);
        actions.Add("Move Forward", newFowardCommand);
        actions.Add("Move Backward", newBackwardCommand);
        actions.Add("Move Leftwards", neweLeftwardCommand);
        actions.Add("Move Rightwards", newRightwardCommand);
        actions.Add("Turn Clockwise", newClockwiseCommand);
        actions.Add("Turn Counterclockwise", newCounterclockwiseCommand);

        // Adding Flow Commands to dictionary
        actions.Add("Scoped Repetition", newForCommand);
        actions.Add("Scoped Repetition End", newEndForCommand);
        actions.Add("Scoped Repetition Comparison", newForComparisonCommand);

        // Adding If Command to dictionary
        actions.Add("Scoped Repetition If", newIfCommand);

        // Adding Comparisons to dictionary
        comparisons.Add("AsteroidsComparisonBox", newComparison);
        comparisons.Add("BatteryComparisonBox", newComparisonB);
        comparisons.Add("ForceFieldComparisonBox", newComparisonF);
    }
コード例 #42
0
ファイル: Startup.cs プロジェクト: AlexanderKrustev/SoftUni
        static void Main()
        {
            string input = Console.ReadLine();
            Data data=new Data();
            CommandInterpreter commandHandler=new CommandInterpreter();
            HardwareFactory hardwareFactory=new HardwareFactory();
            SoftwareFactory softwareFactory= new SoftwareFactory();

            while (true)
            {
                string[] inputParameters = input.Split(new[] {'(', ')', ','}, StringSplitOptions.RemoveEmptyEntries);

                Command c=commandHandler.ParseCommand(data, inputParameters, hardwareFactory, softwareFactory);
                c.Execute();

                if (inputParameters[0].Equals("System Split"))
                {
                    break;
                }
                input = Console.ReadLine();
            }
        }
コード例 #43
0
ファイル: Client.cs プロジェクト: theradeonxt/yoloth
 private void ClientService()
 {
     try
     {
         Stream = _tcpClient.GetStream();
         var buffer = new byte[1024];
         var commandInterpreter = new CommandInterpreter();
         while (true)
         {
             if (!Stream.DataAvailable) continue;
             var bytesRead = Stream.Read(buffer, 0, buffer.Length);
             var receivedMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
             commandInterpreter.ExecuteCommand(receivedMessage);
         }
     }
     catch (Exception e)
     {
         MessageBox.Show("Something went wrong with the client connection:" + e.Message);
     }
     finally
     {
         _tcpClient.Close();
     }
 }
コード例 #44
0
ファイル: Server.cs プロジェクト: Vivendus/yoloth
        private void ServerService()
        {
            try
            {
                _tcpListener.Start();
                _tcpClient = _tcpListener.AcceptTcpClient();
                Stream = _tcpClient.GetStream();
                var commandInterpreter = new CommandInterpreter();
                var connectValidation = true;
                while (true)
                {
                    if (connectValidation)
                    {
                        Common.GameBoardController.ConnectionEstablished();
                        connectValidation = false;
                        _isConnected = true;
                    }

                    var streamReader = new StreamReader(Stream);
                    var receivedMessage = streamReader.ReadLine();

                    if (commandInterpreter.ExecuteCommand(receivedMessage))
                    {
                        _isConnected = false;
                        MessageBox.Show(@"Oponent bailed!");
                        break;
                    }
                }
                Stream.Close();
                _tcpListener.Stop();
            }
            catch (Exception exception)
            {
                MessageBox.Show(@"Connection Error: " + exception.Message);
            }
        }
コード例 #45
0
 public SemanticInterpreter(CommandInterpreter commandInterpreter)
 {
     setCommandInterpreter(commandInterpreter);
 }
コード例 #46
0
 public void EvalWithStringListArg()
 {
     var io = new StringWriter();
     var interp = new CommandInterpreter(io, io, new CommandParser(), new CommandObj());
     interp.Eval("ListArg 1 2 --c test,more-text");
     Assert.AreEqual("(test,more-text)\r\n", io.ToString());
 }
コード例 #47
0
 public void EvalWithQuotedCommandName()
 {
     var io = new StringWriter();
     var interp = new CommandInterpreter(io, io, new CommandParser(), new CommandObj());
     interp.Eval("\"Plus\" 1 2");
     Assert.AreEqual("3\r\n", io.ToString());
 }
コード例 #48
0
    static int Main(string[] args)
    {
        int result = -1;

        string temp;
        var wait = ArgumentList.Remove(ref args, "wait", out temp);
        var nologo = ArgumentList.Remove(ref args, "nologo", out temp);
       
        try
        {
            // Display logo/header information
            var entryAssembly = Assembly.GetEntryAssembly();
            if (entryAssembly != null && nologo == false)
            {
                Console.WriteLine("{0}", entryAssembly.GetName());
                foreach (AssemblyCopyrightAttribute a in entryAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false))
                    Console.WriteLine("{0}", a.Copyright);
                Console.WriteLine();
            }

            // If verbose output was specified, attach a trace listener
            if (ArgumentList.Remove(ref args, "verbose", out temp) || ArgumentList.Remove(ref args, "verbosity", out temp))
            {
                SourceLevels traceLevel;
                try { traceLevel = (SourceLevels)Enum.Parse(typeof(SourceLevels), temp); }
                catch { traceLevel = SourceLevels.All; }

                Trace.Listeners.Add(new ConsoleTraceListener()
                {
                    Filter = new EventTypeFilter(traceLevel),
                    IndentLevel = 0,
                    TraceOutputOptions = TraceOptions.None
                });
            }

            // Construct the CommandInterpreter and initialize
            ICommandInterpreter ci = new CommandInterpreter(
                DefaultCommands.Help |
                // Allows a simple ECHO command to output text to std::out
                DefaultCommands.Echo |
                // Allows getting/setting properties, like prompt and errorlevel below
                DefaultCommands.Get | DefaultCommands.Set |
                DefaultCommands.Prompt |
                DefaultCommands.ErrorLevel |
                // uncomment to allow cmd > C:\output.txt or cmd < C:\input.txt
                //DefaultCommands.IORedirect |
                // uncomment to use aaa | bbb | FIND "abc" | MORE
                //DefaultCommands.PipeCommands | DefaultCommands.Find | DefaultCommands.More |
                0,
                // Add the types to use static members
                typeof(Filters), 
                // Add classes to use instance members
                new Commands()
            );

            // If you want to hide some options/commands at runtime you can:
            foreach (var name in new[] {"prompt", "errorlevel"})
            {
                IOption opt;
                if (ci.TryGetOption(name, out opt))
                    opt.Visible = false;
            }
            foreach (var name in new[] {"echo", "set", "get"})
            {
                ICommand opt;
                if (ci.TryGetCommand(name, out opt))
                    opt.Visible = false;
            }

            // Apply all DefaultValue values to properties
            ci.SetDefaults();

            // If we have arguments, just run with those arguments...
            if (args.Length > 0)
                ci.Run(args);
            else
            {
                //When run without arguments you can either display help:
                //ci.Help(null);
                //... or run the interpreter:
                ci.Run(Console.In);
            }

            result = ci.ErrorLevel;
        }
        catch (OperationCanceledException)
        { result = 3; }
        catch (ApplicationException ex)
        {
            Trace.TraceError("{0}", ex);
            Console.Error.WriteLine(ex.Message);
            result = 1;
        }
        catch (Exception ex)
        {
            Trace.TraceError("{0}", ex);
            Console.Error.WriteLine(ex.ToString());
            result = 2;
        }
        finally
        {
            if (wait)
            {
                Console.WriteLine("Exited with result = {0}, Press Enter to quit.", result);
                Console.ReadLine();
            }
        }

        return Environment.ExitCode = result;
    }
コード例 #49
0
        public void EvalFromSignature()
        {
            var io = new StringWriter();
            var interp = new CommandInterpreter(io, io);
            interp.AddCommand<int, int, int>("plus", (i, j) => i + j);

            interp.Eval("plus 2 2");
            Assert.AreEqual("4\r\n", io.ToString());
        }
コード例 #50
0
        public void EvalWithFlag()
        {
            var io = new StringWriter();
            var interp = new CommandInterpreter(io, io);
            var obj = new CommandObj();
            interp.AddCommand("plus", obj, "PlusFlag");

            interp.Eval("plus 2 2");
            Assert.AreEqual("4\r\n", io.ToString());

            interp.Output = new StringWriter();
            interp.Eval("plus 2 2 --invert");
            Assert.AreEqual("-4\r\n", interp.Output.ToString());
        }
コード例 #51
0
        public void EvalWithSwitch()
        {
            var interp = new CommandInterpreter(new StringWriter(), new StringWriter());
            var obj = new CommandObj();
            interp.AddCommand("plus", obj, "PlusSwitch");

            interp.Eval("plus 2 2");
            Assert.AreEqual("5\r\n", interp.Output.ToString());

            interp.Output = new StringWriter();
            interp.Eval("plus 2 2 -c 2");
            Assert.AreEqual("6\r\n", interp.Output.ToString());
        }
コード例 #52
0
 public void setCommandInterpreter(CommandInterpreter commandInterpreter)
 {
     this.commandInterpreter = commandInterpreter;
 }
コード例 #53
0
ファイル: RobotTests.cs プロジェクト: richinoz/Orchard1.6
 public void All_instruction_strings_will_be_less_than_100_characters_in_length()
 {
     var commandInterpreter = new CommandInterpreter(new List<Command>());
     commandInterpreter.Interpret(new string('L', 100));            
 }      
コード例 #54
0
        public void EvalWithNullDefaults()
        {
            var io = new StringWriter();
            var interp = new CommandInterpreter(io, io);
            var commandObj = new CommandObj();
            interp.AddCommand("join", commandObj, "Join");

            interp.Eval("join");
            Assert.AreEqual("ab\r\n", io.ToString());
        }
コード例 #55
0
ファイル: PlayerController.cs プロジェクト: cccarmo/tccgame
    void Start()
    {
        dX = (xMax - xMin) / 9f;
        dY = (yMax - yMin) / 11f;
        animate = false;
        interpretCommands = true;
        body = GetComponent<Rigidbody2D>();
        shootSound = GetComponents<AudioSource>()[0];
        failSound = GetComponents<AudioSource>()[1];
        landingSound = GetComponents<AudioSource>()[2];
        shieldSound = GetComponents<AudioSource>()[3];
        nextFire = 0.0f;
        ticks = 0;
        GameScreen = GameObject.FindWithTag("GameScreen");
        initRotationDirection();

        GameObject panel = GameObject.FindWithTag("DropPanel");
        interpreter = panel.GetComponent<CommandInterpreter>();

        GameObject missilesDisplayer = GameObject.FindWithTag("MissilesDisplayer");
        missilesLabel = missilesDisplayer.GetComponentInChildren<Text>();
        missilesLabel.text = laserMissiles.ToString();

        animator = GetComponent<Animator>();
    }
コード例 #56
0
ファイル: Program.cs プロジェクト: parrottsquawk/School
        public static void RunAsciiTestFiles()
        {
            const string DirectoryString = @"..\..";
              var gen = new Random();
              var files = Directory.EnumerateFiles(DirectoryString + @"\GenFiles\", "*").Where(u => !u.Contains(@"GenFiles\B_"));
              StringBuilder output = new StringBuilder();
              int fileNum = 0;
              foreach (var file in files) {
            var ob = new StatObj { FileName = file };
            var commandLineInterpreter = new CommandInterpreter() { Encoding = Encoding.ASCII, Path = ob.FileName };
            var fileReader = new AsciiFileReader(commandLineInterpreter);
            var sa = new SuffixArrayAsc(fileReader.Data);
            var bwt = new BurrowsWheelerTransformAsc(sa);
            for (var i = 1; i < Math.Min(20, ob.FileSize / 2); i++) {
              ob.PatternSize = i;
              commandLineInterpreter.QueryString = fileReader.Data.Substring(
              (int)(
                  (ob.FileSize - ob.PatternSize) * gen.NextDouble()
                  ), ob.PatternSize
              );

              // Settings and timers
              //===============================================================
              int times = 1000;
              Stopwatch sw;
              //===============================================================

              // BWT
              //===============================================================
              StatObj bwtStat = ob;
              bwtStat.EndTimeTicks = 0;
              bwtStat.Results = 0;
              bwtStat.RuntimeTicks = 0;
              bwtStat.StartTimeTicks = 0;

              sw = Stopwatch.StartNew();
              for (int t = 0; t < times; t++) {
            bwtStat.Results = bwt.CountOccurrences(commandLineInterpreter.QueryString);
              }
              sw.Stop();

              bwtStat.RuntimeTicks = sw.ElapsedMilliseconds;
              //===============================================================

              // BF
              //===============================================================
              StatObj bfStat = ob;
              bfStat.EndTimeTicks = 0;
              bfStat.Results = 0;
              bfStat.RuntimeTicks = 0;
              bfStat.StartTimeTicks = 0;

              sw = Stopwatch.StartNew();
              for (int t = 0; t < times; t++) {
            bfStat.Results = BruteForce.Run(fileReader.Data, commandLineInterpreter.QueryString);
              }
              sw.Stop();

              bfStat.RuntimeTicks = sw.ElapsedMilliseconds;
              //===============================================================

              // Print Results
              //===============================================================
              int m = ob.PatternSize;
              int n = ob.FileSize;
              int ep = ob.AlphabetSize;

              output.AppendLine(String.Format("BWT,{0},{1},{2},{3},{4},{5}", bwtStat.RuntimeTicks, m, n, ep, bwtStat.Results, Encoding.ASCII));
              output.AppendLine(String.Format("BruteForce,{0},{1},{2},{3},{4},{5}", bfStat.RuntimeTicks, m, n, ep, bfStat.Results, Encoding.ASCII));
              //===============================================================
            }
            fileNum++;
            Console.WriteLine(((((double)fileNum) / files.ToArray<string>().Length) * 100).ToString() + " %");
              }
              using (StreamWriter writer = new StreamWriter(DirectoryString + @"\GenFiles\AsciiResults.csv")) {
            writer.Write(output.ToString());
              }
        }
コード例 #57
0
ファイル: DestroyByContact.cs プロジェクト: cccarmo/tccgame
 void Start()
 {
     gameScreen = GameObject.FindWithTag("GameScreen");
     GameObject panel = GameObject.FindWithTag("DropPanel");
     commandInterpreter = panel.GetComponent<CommandInterpreter>();
 }
コード例 #58
0
        public void ParseErrors()
        {
            var interp = new CommandInterpreter(new StringWriter(), new StringWriter());
            interp.AddCommand<int, int, int>("plus", (i, j) => i + j);

            Assert.Throws<ParseException>(() => interp.Eval("plus 2 abc"));
        }