Ejemplo n.º 1
1
        public static void Main(string[] args)
        {
            // Change the console window
            Terminal term = new Terminal();
            term.Title = "Terminal Window Title";
            term.DisplayMode = (int)ConsoleDisplayModeForSet.CONSOLE_FULLSCREEN_MODE;

            //Console.WriteLine("Terminal Title: {0}", term.Title);
            term.WriteLine("Terminal Window Title - has been set");
            COORD fontSize = term.FontSize;
            Console.WriteLine("Terminal Font Size: X = {0}, Y = {1}", fontSize.X, fontSize.Y);
            Console.WriteLine("mouse buttons: {0}", term.MouseButtons);

            // Instantiate a machine
            Machine aMachine = new Machine();

            // Print some properties
            Console.WriteLine("Name: {0}", aMachine.ShortName);
            Console.WriteLine("Domain: {0}", aMachine.DomainName);

            Environment environ = new Environment();
            Console.WriteLine("Command Line: {0}", environ.CommandLine);

            // Get the name of the process image that this process is running
            //Process aProc = new Process();
            //PrintProcess(aProc);
            //PrintAllProcesses();

            PrintAllDrives();
            //PrintVolumes();

            Console.ReadLine();
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Demo for a MS Telnet server
 /// </summary>
 private static void DemoMSTelnetServer(string[] args)
 {
     string f = null;
     Terminal tn = new Terminal("giga", 23, 10, 80, 40); // hostname, port, timeout [s], width, height
     tn.Connect(); // physcial connection
     do
     {
         f = tn.WaitForString("Login");
         if (f==null)
             throw new TerminalException("No login possible");
         Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
         tn.SendResponse("telnet", true);	// send username
         f = tn.WaitForString("Password");
         if (f==null)
             throw new TerminalException("No password prompt found");
         Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
         tn.SendResponse("telnet", true);	// send password
         f = tn.WaitForString(">");
         if (f==null)
             throw new TerminalException("No > prompt found");
         tn.SendResponse("dir", true);		// send dir command
         if (tn.WaitForChangedScreen())
             Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
     } while (false);
     tn.Close(); // physically close on TcpClient
     Console.WriteLine("\n\nEnter to continue ...\n");
     Console.ReadLine();
 }
Ejemplo n.º 3
0
 public ActionResult Create()
 {
     Terminal model = new Terminal();
     model.TemMax = model.HumiMax = 9999;
     model.Pm25Max = model.LuminMax = model.UVMax = model.GasMax = 9999;
     return View(model);
 }
Ejemplo n.º 4
0
 public ActionResult Index(int id=1,string terminal="EMMS001")
 {
     Bindddl();
     ViewBag.TerminalID = terminal;
     var result = db.EMdatas.Where(p=>p.TerminalID==terminal).Include(p=>p.Terminal).OrderBy(p=>p.Update);
     var bindColor = (IEnumerable<EMdata>)result;
     EMdata now = new EMdata();
     if (bindColor.LastOrDefault() != null)
     {
         now.Temperature = bindColor.LastOrDefault().Temperature;
         now.Pm25 = bindColor.LastOrDefault().Pm25;
         now.Luminance = bindColor.LastOrDefault().Luminance;
         now.Humidity = bindColor.LastOrDefault().Humidity;
         now.UV = bindColor.LastOrDefault().UV;
         now.GasIntensity = bindColor.LastOrDefault().GasIntensity;
         BindColor(now);
     }
     if (result.Count() == 0)
     {
         EMdata em = new EMdata();
         Terminal term = new Terminal();
         term.TerminalName = "无";
         term.TerminalAddr = "无";
         em.Terminal = term;
         em.UV = em.Pm25 = em.Luminance = em.GasIntensity = -1;
         em.Humidity = em.Temperature = -1;
         List<EMdata> emlst=new List<EMdata>();
         emlst.Add(em);
         return View(emlst);
     }
     return View(result);
 }
Ejemplo n.º 5
0
 private Node and_or_ast(Terminal op, Node nleft, Node nright)
 {
     Node n = null;
     switch (op.TokenType) {
         case TokenType.and:
             var lbljmpzero = newLabel();
             n = new Node(op,
                 nleft,
                 new Node(nilterminal(),
                     new Node(new Terminal(TokenType.jmpzero, lbljmpzero, currenttoken.LN, currenttoken.CP)),
                     new Node(nilterminal(),
                         nright,
                         new Node(new Terminal(TokenType.label, lbljmpzero, currenttoken.LN, currenttoken.CP)))));
             break;
         case TokenType.or:
             var lbljmpnotz = newLabel();
             n = new Node(op,
                 nleft,
                 new Node(nilterminal(),
                     new Node(new Terminal(TokenType.jmpnotz, lbljmpnotz, currenttoken.LN, currenttoken.CP)),
                     new Node(nilterminal(),
                         nright,
                         new Node(new Terminal(TokenType.label, lbljmpnotz, currenttoken.LN, currenttoken.CP)))));
             break;
     }
     return n;
 }
Ejemplo n.º 6
0
 public void TestToString()
 {
     // Create a terminal and call tostring on it
     var terminal = new Terminal<int>("abc", int.Parse) {DebugName = "ABC"};
     var stringValue = terminal.ToString();
     Assert.IsNotNull(stringValue);
 }
 public void ProcessOutput(RegexSurfer Surfer, Terminal Terminal, CancellationToken CancellationToken, SubprocessProgressToken Progress,
                           ProgressControllerFactory ProgressControllerFactory)
 {
     using (IProgressController pc = ProgressControllerFactory.CreateController(Progress))
     {
         pc.SetDescription("Проверка прошивки...");
         pc.SetProgress(0);
         Surfer.SeekForMatches(Terminal, CancellationToken,
                               new DelegateExpectation(
                                   new Regex(@"Complete (?<progress>\d+)%.*0x(?<written>[0-9a-fA-F]+) bytes written by applet",
                                             RegexOptions.Compiled | RegexOptions.Singleline), false,
                                   m => pc.SetProgress(0.01 * int.Parse(m.Groups["progress"].Value))),
                               new DelegateExpectation(
                                   @"Sent file & Memory area content \(address: 0x[0-9a-fA-F]+, size: \d+ bytes\) (?<result>.+) !",
                                   m =>
                                   {
                                       switch (m.Groups["result"].Value)
                                       {
                                           case "match exactly":
                                               return true;
                                           case "do not match":
                                               throw new ComparingFailsSambaException();
                                           default:
                                               throw new ApplicationException("Непонятный вывод:\n\n" + Terminal.Log);
                                       }
                                   }));
     }
 }
Ejemplo n.º 8
0
        public GrammarExL514()
        {
            NonTerminal A = new NonTerminal("A");
              Terminal a = new Terminal("a");

              A.Expression = "(" + A + ")" | a;
              this.Root = A;
        }
Ejemplo n.º 9
0
 public static Wire create(Terminal startTerminal)
 {
     Transform container = Instantiate(Dummy.transform) as Transform;
     currentWire = container.GetComponent(typeof(Wire)) as Wire;
     currentWire.Start();
     currentWire.connection1 = startTerminal;
     return currentWire;
 }
Ejemplo n.º 10
0
        public static byte[] crearA_Logueo(Terminal ter, string[] UltimaCon, System.Net.IPAddress ipLocal)
        {
            #region //variables mensaje A

               // string idBody1 = "N";
            string datos1 = UltimaCon[0];
               // string idBody2 = "P";
            string datos2 = UltimaCon[1];
               // string idBody3 = "T";
            string datos3 = UltimaCon[2];

            //Fecha/Hora real con ceros agregados si fuese necesario
            string dia, mes, anio, hora, min, seg;
            if ((Convert.ToString(ter.FechaHora.Day).Length < 2)) { dia = "0" + Convert.ToString(ter.FechaHora.Day); } else { dia = Convert.ToString(ter.FechaHora.Day); }
            if ((Convert.ToString(ter.FechaHora.Month).Length < 2)) { mes = "0" + Convert.ToString(ter.FechaHora.Month); } else { mes = Convert.ToString(ter.FechaHora.Month); }
            if ((Convert.ToString(ter.FechaHora.Year).Length > 2)) { anio = Convert.ToString(ter.FechaHora.Year).Remove(0, 2); } else { anio = Convert.ToString(ter.FechaHora.Year); }
            if ((Convert.ToString(ter.FechaHora.Hour).Length < 2)) { hora = "0" + Convert.ToString(ter.FechaHora.Hour); } else { hora = Convert.ToString(ter.FechaHora.Hour); }
            if ((Convert.ToString(ter.FechaHora.Minute).Length < 2)) { min = "0" + Convert.ToString(ter.FechaHora.Minute); } else { min = Convert.ToString(ter.FechaHora.Minute); }
            if ((Convert.ToString(ter.FechaHora.Second).Length < 2)) { seg = "0" + Convert.ToString(ter.FechaHora.Second); } else { seg = Convert.ToString(ter.FechaHora.Second); }
            #endregion

            //header
            byte[] pacHead = DataConverter.Pack("^$8SbbII$8$8$8$8$8$8S", "A", 0, (int)TransacManager.ProtoConfig.TIPO_CXN, ter.Tipo, ter.Tarjeta, ter.NumeroTerminal, dia, mes, anio, hora, min, seg, ter.Version);
            byte[] pacSal1 = new byte[1024];

            TARJETA = ter.Tarjeta;

            int lon = pacHead.Length + ter.MacTarjeta.Length;

            Array.Copy(pacHead, pacSal1, pacHead.Length);
            Array.Copy(ter.MacTarjeta, 0, pacSal1, pacHead.Length, ter.MacTarjeta.Length);

            string telefono = UltimaCon[2];
            for (int i = 0; i < 15 - UltimaCon[2].Length; i++)
            {
                telefono = telefono + " ";
            }
            telefono = telefono.Substring(0, 15);
            string user = UltimaCon[0];
            for (int i = 0; i < 10 - UltimaCon[0].Length; i++)
            {
                user = "******" + user; ;
            }
            user = user.Substring(0, 10);

            byte[] pacSal2 = DataConverter.Pack("^$8$8", telefono, user);
            Array.Copy(pacSal2, 0, pacSal1, lon, pacSal2.Length);

            byte[] pacSal3 = DataConverter.Pack("^SS", 512, Convert.ToUInt16(UltimaCon[1]));
            byte[] ipBytes = ipLocal.GetAddressBytes();
            Array.Copy(pacSal3, 0, pacSal1, lon+pacSal2.Length, pacSal3.Length);
            Buffer.BlockCopy(ipBytes, 0, pacSal1, lon + pacSal2.Length + pacSal3.Length, ipBytes.Length);

            lon += pacSal2.Length + pacSal3.Length + ipBytes.Length;

            Array.Resize(ref pacSal1, lon);
            return pacSal1;
        }
Ejemplo n.º 11
0
        public TerminalWidget()
        {
            terminal = new Terminal();
            terminalInputOutputSource = new TerminalIOSource(terminal);
            IO = new DetachableIO(terminalInputOutputSource);
            IO.BeforeWrite += b =>
            {
                // we do not check if previous byte was '\r', because it should not cause any problem to 
                // send it twice
                if(ModifyLineEndings && b == '\n')
                {
                    IO.Write((byte)'\r');
                }
            };

            terminal.InnerMargin = new WidgetSpacing(5, 5, 5, 5);
            terminal.Cursor.Enabled = true;
            terminal.ContextMenu = CreatePopupMenu();

            var fontFile = typeof(TerminalWidget).Assembly.FromResourceToTemporaryFile("RobotoMono-Regular.ttf");
            Xwt.Drawing.Font.RegisterFontFromFile(fontFile);
            terminal.CurrentFont = Xwt.Drawing.Font.FromName("Roboto Mono").WithSize(10);

            var encoder = new TermSharp.Vt100.Encoder(x =>
            {
                terminal.ClearSelection();
                terminal.MoveScrollbarToEnd();
                terminalInputOutputSource.HandleInput(x);
            });

            terminal.KeyPressed += (s, a) =>
            {
                a.Handled = true;

                var modifiers = a.Modifiers;
                if(!Misc.IsOnOsX)
                {
                    modifiers &= ~(ModifierKeys.Command);
                }

                if(modifiers == ModifierKeys.Shift)
                {
                    if(a.Key == Key.PageUp)
                    {
                        terminal.PageUp();
                        return;
                    }
                    if(a.Key == Key.PageDown)
                    {
                        terminal.PageDown();
                        return;
                    }
                }
                encoder.Feed(a.Key, modifiers);
            };
            Content = terminal;
        }
Ejemplo n.º 12
0
        public TerminalPad()
        {
            //FIXME look up most of these in GConf
            term = new Terminal ();
            term.ScrollOnKeystroke = true;
            term.CursorBlinks = true;
            term.MouseAutohide = true;
            term.FontFromString = "monospace 10";
            term.Encoding = "UTF-8";
            term.BackspaceBinding = TerminalEraseBinding.Auto;
            term.DeleteBinding = TerminalEraseBinding.Auto;
            term.Emulation = "xterm";

            Gdk.Color fgcolor = new Gdk.Color (0, 0, 0);
            Gdk.Color bgcolor = new Gdk.Color (0xff, 0xff, 0xff);
            Gdk.Colormap colormap = Gdk.Colormap.System;
            colormap.AllocColor (ref fgcolor, true, true);
            colormap.AllocColor (ref bgcolor, true, true);
            term.SetColors (fgcolor, bgcolor, fgcolor, 16);

            //FIXME: whats a good default here
            //term.SetSize (80, 5);

            // seems to want an array of "variable=value"
                    string[] envv = new string [Environment.GetEnvironmentVariables ().Count];
                    int i = 0;
            foreach (DictionaryEntry e in Environment.GetEnvironmentVariables ())
            {
                if (e.Key == "" || e.Value == "")
                    continue;
                envv[i] = String.Format ("{0}={1}", e.Key, e.Value);
                i ++;
            }

            term.ForkCommand (Environment.GetEnvironmentVariable ("SHELL"), Environment.GetCommandLineArgs (), envv, Environment.GetEnvironmentVariable ("HOME"), false, true, true);

            term.ChildExited += new EventHandler (OnChildExited);

            VScrollbar vscroll = new VScrollbar (term.Adjustment);

            HBox hbox = new HBox ();
            hbox.PackStart (term, true, true, 0);
            hbox.PackStart (vscroll, false, true, 0);

            frame.ShadowType = Gtk.ShadowType.In;
            ScrolledWindow sw = new ScrolledWindow ();
            sw.Add (hbox);
            frame.Add (sw);

            Control.ShowAll ();

            /*			Runtime.TaskService.CompilerOutputChanged += (EventHandler) Runtime.DispatchService.GuiDispatch (new EventHandler (SetOutput));
            projectService.StartBuild += (EventHandler) Runtime.DispatchService.GuiDispatch (new EventHandler (SelectMessageView));
            projectService.CombineClosed += (CombineEventHandler) Runtime.DispatchService.GuiDispatch (new CombineEventHandler (OnCombineClosed));
            projectService.CombineOpened += (CombineEventHandler) Runtime.DispatchService.GuiDispatch (new CombineEventHandler (OnCombineOpen));
            */
        }
Ejemplo n.º 13
0
 public Ball(short x, short y, SMALL_RECT ballArea, Terminal aTerm)
 {
     fPosition.X = x;
     fPosition.Y = y;
     xInc = 1;
     yInc = 1;
     fBallArea = ballArea;
     fTerm = aTerm;
 }
Ejemplo n.º 14
0
 public PatternInstruction(OpCode[] eligibleOpCodes, Terminal terminal = null, Predicate predicate = null) {
     if (eligibleOpCodes == null)
         throw new ArgumentNullException(Name.Of(eligibleOpCodes));
     if (eligibleOpCodes.Length == 0)
         throw new ArgumentException("Array length must be greater than zero", Name.Of(eligibleOpCodes));
     EligibleOpCodes = eligibleOpCodes;
     Terminal = terminal;
     this.predicate = predicate ?? PredicateDummy;
 }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            Terminal term = new Terminal();

            TerminalTester tTester = new TerminalTester();
            tTester.Run(term);
            
            //Pong pongGame = new Pong(term);
            //pongGame.Run();
        }
Ejemplo n.º 16
0
 public void ProcessOutput(RegexSurfer Surfer, Terminal Terminal, CancellationToken CancellationToken, SubprocessProgressToken Progress,
                           ProgressControllerFactory ProgressControllerFactory)
 {
     using (IProgressController pc = ProgressControllerFactory.CreateController(Progress))
     {
         pc.SetDescription("Стирание FLASH...");
         pc.SetProgress(0);
         Surfer.SeekForMatches(Terminal, CancellationToken, new BarrierExpectation(@"GENERIC::EraseAll"));
     }
 }
Ejemplo n.º 17
0
 public static void cancelDragWire()
 {
     Destroy(currentWire);
     if (firstDrop)
     {
         wireHelpText.text = "Try again. Start by dragging wire from any terminal";
     }
     currentSource = null;
     currentWire = null;
     currentLR = null;
 }
Ejemplo n.º 18
0
 Node assignment()
 {
     var s = currenttoken.Value.ToString();
     nexttoken();
     expect(TokenType.assig);
     var op = new Terminal(TokenType.assig, s, currenttoken.LN, currenttoken.CP);
     nexttoken();
     var r = new Node(new Terminal(TokenType.identlocal, s, currenttoken.LN, currenttoken.CP));
     var l = expression_single();
     return new Node(op, l, r);
 }
Ejemplo n.º 19
0
        public void TerminalAskTheFirstQuestion()
        {
            // Arrange
            Terminal term = new Terminal();

            // Act
            string actual_output = term.AskFirstQuestion();
            string expected_output = "What would you like for me to do?";

            // Assert
            Assert.AreEqual(expected_output, actual_output);
        }
Ejemplo n.º 20
0
        public GrammarEx434()
        {
            NonTerminal E = new NonTerminal("E");
              NonTerminal T = new NonTerminal("T");
              NonTerminal F = new NonTerminal("F");
              Terminal id = new Terminal("id");

              E.Expression = E + "+" + T | T;
              T.Expression = T + "*" + F | F;
              F.Expression = "(" + E + ")" | id;
              this.Root = E;
        }
Ejemplo n.º 21
0
 private void AddTerminalToLookupByFirstChar(TerminalLookupTable _lookup, Terminal term, char firstChar)
 {
     TerminalList currentList;
       if (!_lookup.TryGetValue(firstChar, out currentList)) {
     //if list does not exist yet, create it
     currentList = new TerminalList();
     _lookup[firstChar] = currentList;
       }
       //add terminal to the list
       if (!currentList.Contains(term))
     currentList.Add(term);
 }
Ejemplo n.º 22
0
 Node build_list()
 {
     var f = expression_lambda();
     if (currenttoken.TokenType == TokenType.comma) {
         nexttoken();
         return new Node(new Terminal(TokenType.comma, currenttoken.LN, currenttoken.CP), f, build_list());
     } else {
         var empty = new Terminal(TokenType.list, currenttoken.LN, currenttoken.CP);
         var oplist = new Terminal(TokenType.comma, currenttoken.LN, currenttoken.CP);
         return new Node(oplist, f, new Node(empty));
     }
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Demo for a Linux RedHat 7.3 telnet server
        /// </summary>
        private static void DemoRH73TelnetServer(string[] args)
        {
            string f = null;
            Terminal tn = new Terminal("10.235.6.197", 23, 50, 80, 40); // hostname, port, timeout [s], width, height
            tn.Connect(); // physcial connection
            do
            {
                f = tn.WaitForString("login");
                if (f==null)
                    break; // this little clumsy line is better to watch in the debugger
                Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
                tn.SendResponse("lophilo", true);	// send username
                f = tn.WaitForString("Password:"******"lab123", true);	// send password
                f = tn.WaitForString("$");			// bash
                if (f==null)
                    break;
                Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
                tn.SendResponse("~/test/thermal", true);		// send Shell command
                f = tn.WaitForString("Meteroi shell>");			// program
                if (f == null)
                    break;
                Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
                tn.VirtualScreen.CleanScreen();
                tn.SendResponse("x -1000", true);		// send Shell command
                f = tn.WaitForString("Meteroi shell>");			// program
                if (f == null)
                    break;
                Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
                tn.VirtualScreen.CleanScreen();
                tn.SendResponse("y -1000", true);		// send Shell command
                f = tn.WaitForString("Meteroi shell>");			// program
                if (f == null)
                    break;
                Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
                tn.VirtualScreen.CleanScreen();
                tn.SendResponse("y 1000", true);		// send Shell command
                f = tn.WaitForString("Meteroi shell>");			// program
                if (f == null)
                    break;
                Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
                if (tn.WaitForChangedScreen())
                    Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());

            } while (false);
            tn.Close(); // physically close on TcpClient
            Console.WriteLine("\n\nEnter to continue ...\n");
            Console.ReadLine();
        }
Ejemplo n.º 24
0
        public GrammarEx446()
        {
            // A' is augmented root
              NonTerminal S = new NonTerminal("S");
              NonTerminal L = new NonTerminal("L");
              NonTerminal R = new NonTerminal("R");
              Terminal id = new Terminal("id");

              S.Expression = L + "=" + R | R;
              L.Expression = "*" + R | id;
              R.Expression = L;
              this.Root = S;
        }
Ejemplo n.º 25
0
    }//method

    private void AddTermLookupInfo(Terminal term, IList<string> firsts) {
      foreach (var prefix in firsts) {
        var termLkp = new TermLookupInfo() {Terminal = term, Prefix = prefix };
        termLkp.FirstChar = prefix[0];
        termLkp.SecondChar = prefix.Length > 1 ? prefix[1] : '\0';
        List<TermLookupInfo> lkpList;
        if (!TermLookupTable.TryGetValue(termLkp.FirstChar, out lkpList)) {
          lkpList = new List<TermLookupInfo>();
          TermLookupTable.Add(termLkp.FirstChar, lkpList);
        }
        lkpList.Add(termLkp); 
      }//foreach
    }
Ejemplo n.º 26
0
        public void TerminalFirstQuestionBadAnswer()
        {
            // Arrange
            Terminal term = new Terminal();

            // Act
            string user_input = "car";
            string actual_output = term.AcceptFirstAnswer(user_input);
            string expected_output = "Whoops!";

            // Assert
            Assert.AreEqual(expected_output, actual_output);
            Assert.AreEqual(0, term.Progress);
        }
Ejemplo n.º 27
0
 protected ConnectivityNode getOtherNeighbor(Terminal term)
 {
     Conductor parentConductor = term.ParentEquipment as Conductor;
     if (ReferenceEquals(term, parentConductor.Terminal1))
     {
         //return the connected node that does not contain term.
         return parentConductor.Terminal2.ConnectionPoint;
     }
     if (ReferenceEquals(term, parentConductor.Terminal2))
     {
         return parentConductor.Terminal1.ConnectionPoint;
     }
     return null;
 }
Ejemplo n.º 28
0
        private static string Accept(Terminal terminal, ref string subject)
        {
            var regex = terminals[terminal];

            var match = Regex.Match(subject, "^" + regex, RegexOptions.IgnoreCase);
            if (match.Success)
            {
                subject = subject.Substring(match.Length);
                return match.Value;
            }
            else
            {
                return null;
            }
        }
Ejemplo n.º 29
0
        public void TerminalFirstQuestionGoodAnswer()
        {
            // Arrange
            Terminal term = new Terminal();

            // Act
            string user_input = "even";
            string actual_output = term.AcceptFirstAnswer(user_input);
            string expected_output = "How many should I print?";

            // Assert
            Assert.AreEqual(expected_output, actual_output);
            Assert.AreEqual(user_input, term.NumberFamily);
            Assert.AreEqual(1, term.Progress);
        }
Ejemplo n.º 30
0
    FoxTerm(string[] args)
    {
        program = new Program ("FoxTerm", "0.1", Modules.UI, args);
        app = new App ("FoxTerm", "Terminal");
        app.SetDefaultSize (600, 450);
        app.DeleteEvent += new DeleteEventHandler (OnAppDelete);

        GConf.Client gc_client = new GConf.Client();

        app.IconName = "terminal";

        Terminal term = new Terminal ();
        term.EncodingChanged += new EventHandler (OnEncodingChanged);
        term.CursorBlinks = true;
        term.MouseAutohide = true;
        term.ScrollOnKeystroke = true;
        term.ScrollbackLines = int.MaxValue;
        term.DeleteBinding = TerminalEraseBinding.Auto;
        term.BackspaceBinding = TerminalEraseBinding.Auto;
        term.Encoding = "UTF-8";

        term.FontFromString = (string)gc_client.Get("/desktop/gnome/interface/monospace_font_name");
        term.ChildExited += new EventHandler (OnChildExited);
        term.WindowTitleChanged += OnTitleChanged;

        ScrolledWindow scroll = new ScrolledWindow(null,term.Adjustment);
        scroll.Add(term);
        scroll.HscrollbarPolicy = PolicyType.Automatic;
        scroll.HScrollbar.Hide();

        string[] argv = Environment.GetCommandLineArgs ();
        // wants an array of "variable=value"
        string[] envv = new string[Environment.GetEnvironmentVariables ().Count];
        int i = 0;
        foreach (DictionaryEntry e in Environment.GetEnvironmentVariables ()) {
            if ((string)(e.Key) == "" || (string)(e.Value) == "")
                continue;
            string tmp = String.Format ("{0}={1}", e.Key, e.Value);
            envv[i] = tmp;
            i++;
        }

        int pid = term.ForkCommand (Environment.GetEnvironmentVariable ("SHELL"), argv, envv, Environment.CurrentDirectory, false, true, true);

        app.Contents = scroll;
        app.ShowAll ();
        program.Run ();
    }
Ejemplo n.º 31
0
    void showLevelReward()
    {
        switch (level)
        {
        case 1:
            Terminal.WriteLine("Have a Book...");
            Terminal.WriteLine(@"
                _________
               /       //)
              / Book  ///
             /_______/// 
             \_______\/ 
                ");
            break;

        case 2:
            Terminal.WriteLine("cracked the safe...");
            break;

        case 3:
            Terminal.WriteLine("Nuclear Weapons Codes...");
            break;
        }
    }
Ejemplo n.º 32
0
 void ShowMenu() // Primary game interface.
 {
     currentScreen = Screen.Menu;
     Terminal.ClearScreen();
     Terminal.WriteLine("                    GTHDB: Main Menu");
     Terminal.WriteLine("          [access at anytime by entering 'menu']");
     Terminal.WriteLine("");
     Terminal.WriteLine("Earn tokens of appreciation (TOA) as rewards for your");
     //                 |<<<----  ----  -- MAXIMUM COULMN WIDTH --  ----  ---->>>|
     Terminal.WriteLine("success. Please work dilligently however, as failures");
     Terminal.WriteLine("will not be accommodated.");
     Terminal.WriteLine("");
     Terminal.WriteLine("  1) What is your favourite colour?");
     Terminal.WriteLine("  2) What is the name of your first pet?");
     if (levelThree == Access.Locked)
     {
         Terminal.WriteLine("  3) Unlock with " + unlockFee_3 + " TOA.");
     }
     else
     {
         Terminal.WriteLine("  3) Who is your favourite SciFi author?");
     }
     if (levelFour == Access.Locked)
     {
         Terminal.WriteLine("  4) Unlock with " + unlockFee_4 + " TOA.");
     }
     else
     {
         Terminal.WriteLine("  4) What is the name of the street you grew up on?");
     }
     Terminal.WriteLine("");
     Terminal.WriteLine("Please enter '?' any time for help, otherwise, please");
     Terminal.WriteLine("select a security question to descramble their answers.");
     Terminal.WriteLine("");
     Terminal.WriteLine("[TOA: " + tokens + "]");
 }
Ejemplo n.º 33
0
        private Terminal GetTerminalUserInput()
        {
            string terminalName = txtTerminalName.Text;
            string ipAddress    = ipcTerminalIP.Text.Replace(" ", "");

            if (string.IsNullOrEmpty(terminalName))
            {
                MessageBox.Show("Terminal Name must not be empty.");
                return(null);
            }

            if (Util.IsValidIP(ipAddress) == false)
            {
                MessageBox.Show("Invalid IP Addess.");
                return(null);
            }

            Terminal terminal = new Terminal();

            terminal.Name      = terminalName;
            terminal.IPAddress = ipAddress;

            return(terminal);
        }
Ejemplo n.º 34
0
        public TestHostContext(object testClass, [CallerMemberName] string testName = "")
        {
            ArgUtil.NotNull(testClass, nameof(testClass));
            ArgUtil.NotNullOrEmpty(testName, nameof(testName));
            _loadContext            = AssemblyLoadContext.GetLoadContext(typeof(TestHostContext).GetTypeInfo().Assembly);
            _loadContext.Unloading += LoadContext_Unloading;
            _testName = testName;

            // Trim the test assembly's root namespace from the test class's full name.
            _suiteName = testClass.GetType().FullName.Substring(
                startIndex: typeof(Tests.Program).FullName.LastIndexOf(nameof(Program)));
            _suiteName = _suiteName.Replace(".", "_");

            // Setup the trace manager.
            TraceFileName = Path.Combine(
                IOUtil.GetBinPath(),
                $"trace_{_suiteName}_{_testName}.log");
            if (File.Exists(TraceFileName))
            {
                File.Delete(TraceFileName);
            }

            var traceListener = new HostTraceListener(TraceFileName);

            _secretMasker = new SecretMasker();
            _traceManager = new TraceManager(traceListener, _secretMasker);
            _trace        = GetTrace(nameof(TestHostContext));
            SetSingleton <ISecretMasker>(_secretMasker);

            // inject a terminal in silent mode so all console output
            // goes to the test trace file
            _term        = new Terminal();
            _term.Silent = true;
            SetSingleton <ITerminal>(_term);
            EnqueueInstance <ITerminal>(_term);
        }
Ejemplo n.º 35
0
    IEnumerator ShowEasterEgg() // The 'backdoor'. Needed by players with no TOA.
    {
        currentScreen = Screen.Egg;
        Terminal.ClearScreen();
        yield return(new WaitForSeconds(.3f));

        Terminal.WriteLine("LOAD \"*\",8,1");
        yield return(new WaitForSeconds(1.4f));

        Terminal.WriteLine("");
        yield return(new WaitForSeconds(.7f));

        Terminal.WriteLine("SEARCHING FOR *");
        yield return(new WaitForSeconds(.8f));

        Terminal.WriteLine("LOADING");
        yield return(new WaitForSeconds(.6f));

        Terminal.WriteLine(".");
        yield return(new WaitForSeconds(1.4f));

        Terminal.WriteLine(".");
        yield return(new WaitForSeconds(1.4f));

        Terminal.WriteLine(".");
        yield return(new WaitForSeconds(1.4f));

        Terminal.ClearScreen();
        //                 |<<<----  ----  -- MAXIMUM COULMN WIDTH --  ----  ---->>>|
        Terminal.WriteLine("        Distributed Social Hacking Tool v3.95f02");
        Terminal.WriteLine("          [enter 'help' or 'exit' at any time]");
        Terminal.WriteLine("");
        Terminal.WriteLine("");
        Terminal.WriteLine("[TOA: " + tokens + "]");
        Terminal.WriteLine("ENTER COMMAND:");
    }
Ejemplo n.º 36
0
        //------listar----------------------------------
        public List <Terminal> ListarNoBajas()
        {
            List <Terminal> resp = null;
            SqlConnection   cnn  = new SqlConnection(Conexion.CONEXION);
            SqlCommand      cmd  = new SqlCommand("ListarTerminalesNoBajas", cnn);

            cmd.CommandType = CommandType.StoredProcedure;


            try
            {
                cnn.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    resp = new List <Terminal>();
                    Terminal ter = null;
                    while (dr.Read())
                    {
                        string   codigo      = (string)dr[0];
                        string   ciudad      = (string)dr[1];
                        string   pais        = (string)dr[2];
                        string[] facilidades = PersistenciaFacilidadTerminal.CargarFacilidades((string)dr[0]);

                        ter = new Terminal(codigo, ciudad, pais, facilidades);
                        resp.Add(ter);
                    }
                }
                dr.Close();
            }
            catch (Exception ex) { throw ex; }
            finally { cnn.Close(); }


            return(resp);
        }
Ejemplo n.º 37
0
            /// <summary>
            /// Executes the workflow to get the next available number sequence value.
            /// </summary>
            /// <param name="request">The request.</param>
            /// <returns>The response.</returns>
            protected override GetNumberSequenceResponse Process(GetNumberSequenceRequest request)
            {
                ThrowIf.Null(request, "request");

                string terminalId;

                // if terminalId is not provided in the request
                if (string.IsNullOrWhiteSpace(request.TerminalId))
                {
                    // use the terminal associated with the request context
                    Terminal terminal = request.RequestContext.GetTerminal();
                    terminalId = terminal.TerminalId;
                }
                else
                {
                    terminalId = request.TerminalId;
                }

                IEnumerable <NumberSequenceSeedData> seedDataFromHeadquarters = this.GetNumberSequenceFromHeadquarters(terminalId);
                IEnumerable <NumberSequenceSeedData> seedDataFromChannel      = this.GetNumberSequenceFromChannelDatabase(terminalId);
                IEnumerable <NumberSequenceSeedData> mergedSeedData           = this.MergeNumberSequenceSeedData(seedDataFromHeadquarters, seedDataFromChannel);

                return(new GetNumberSequenceResponse(mergedSeedData.AsPagedResult()));
            }
Ejemplo n.º 38
0
        private void btnAceptared_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult respuesta = MessageBox.Show("¿Desea modificar los datos?", "Actualización de Terminal.", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (respuesta == MessageBoxResult.Yes)
            {
                Terminal oTerminal = new Terminal();
                oTerminal.Ter_Codigo = Convert.ToInt32(txtCodTerminal.Text);
                oTerminal.Ciu_Codigo = Convert.ToInt32(cmbCiudadEd.SelectedValue);
                oTerminal.Ter_Nombre = txtTerminaled.Text;


                TrabajarTerminales.actualizarTerminal(oTerminal);

                MessageBox.Show("El registro ha sido actualizado.", "¡Información!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            else
            {
                MessageBox.Show("Complete todos los campos necesarios.", "¡Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            traerTerminales();
            grdEditTerminal.Visibility = Visibility.Hidden;
            grdTerminal.Visibility     = Visibility.Visible;
        }
Ejemplo n.º 39
0
        public static Terminal Init(ColorScheme colorScheme)
        {
            _colorScheme            = colorScheme;
            Console.BackgroundColor = colorScheme.BackgroundColor;
            Console.ForegroundColor = colorScheme.Text;
            _terminal = GetTerminal();
            if (_terminal != Terminal.Powershell)
            {
                Console.ResetColor();
            }

            if (_terminal != Terminal.Cygwin)
            {
                Console.Clear();
            }

            Assembly assembly = typeof(CliConsole).Assembly;
            AssemblyInformationalVersionAttribute versionAttribute = assembly.GetCustomAttributes(false).OfType <AssemblyInformationalVersionAttribute>().FirstOrDefault();
            string version = versionAttribute?.InformationalVersion;

            Console.WriteLine("**********************************************", _colorScheme.Comment);
            Console.WriteLine();
            Console.WriteLine("Nethermind CLI {0}", GetColor(_colorScheme.Good), version);
            Console.WriteLine("  https://github.com/NethermindEth/nethermind", GetColor(_colorScheme.Interesting));
            Console.WriteLine("  https://nethermind.readthedocs.io/en/latest/", GetColor(_colorScheme.Interesting));
            Console.WriteLine();
            Console.WriteLine("powered by:", _colorScheme.Text);
            Console.WriteLine("  https://github.com/sebastienros/jint", GetColor(_colorScheme.Interesting));
            Console.WriteLine("  https://github.com/tomakita/Colorful.Console", GetColor(_colorScheme.Interesting));
            Console.WriteLine("  https://github.com/tonerdo/readline", GetColor(_colorScheme.Interesting));
            Console.WriteLine();
            Console.WriteLine("**********************************************", _colorScheme.Comment);
            Console.WriteLine();

            return(_terminal);
        }
Ejemplo n.º 40
0
    void PickRandomPassword()
    {
        switch (level)
        {
        case 1:
            password = level1Passwords[Random.Range(0, level1Passwords.Length)];
            break;

        case 2:
            password = level2Passwords[Random.Range(0, level2Passwords.Length)];
            break;

        case 3:
            password = level3Passwords[Random.Range(0, level3Passwords.Length)];
            break;

        default:
            Debug.LogError("Invalid level");
            break;
        }
        Terminal.WriteLine("Please enter your password: "******"Hint: " + password.Anagram());
        Terminal.WriteLine(menuHint);
    }
Ejemplo n.º 41
0
        public void ShouldBeHumanReadableWhenIsAxiom()
        {
            LexicalRule rule;
            Sequence    predicate;
            Terminal    item;

            predicate = new Sequence();
            item      = new Terminal('a');
            predicate.Items.Add(item);
            item = new Terminal('b');
            predicate.Items.Add(item);
            item = new Terminal('c');
            predicate.Items.Add(item);
            item = new Terminal('d');
            predicate.Items.Add(item);

            rule = new LexicalRule()
            {
                Name = "A", IsAxiom = true
            };
            rule.Predicate = predicate;

            Assert.AreEqual("A*=(abcd)", rule.ToString());
        }
Ejemplo n.º 42
0
    // Start is called before the first frame update
    private void Start()
    {
        _userTerminal = new Terminal(monitor, keylistener, SendCommand);
        keylistener.AddKey(new List <KeyCode> {
            KeyCode.DownArrow
        }, MoveView);
        keylistener.AddKey(new List <KeyCode> {
            KeyCode.UpArrow
        }, MoveView);
        keylistener.AddKey(new List <KeyCode> {
            KeyCode.Escape
        }, StartHelp);
        keylistener.AddKey(new List <KeyCode> {
            KeyCode.Home
        }, LoadStartMenu);

        _textLayer = monitor.NewLayer();
        _textLayer.view.SetSize(new GridSize(22, Monitor.Size.columns));
        _textLayer.view.StayInBounds(true);

        _myMonitorWriter = LoadChatlog;
        _myMonitorWriter();
        _progressStep = 0;
    }
Ejemplo n.º 43
0
 void OnUserInput(string input)
 {
     if (input == "menu")
     {
         ShowMainMenu();
     }
     else if (input == "quit" || input == "close" || input == "exit")
     {
         Terminal.WriteLine("If on the web close the tab.");
         Application.Quit();
     }
     else if (CurrentScreen == Screen.MainMenu)
     {
         RunMainMenu(input);
     }
     else if (CurrentScreen == Screen.Password)
     {
         CheckPassword(input);
     }
     else
     {
         ShowMainMenu();
     }
 }
Ejemplo n.º 44
0
 void runMenu(string input)
 {
     if (!(input == "a" || input == "b" || input == "c"))
     {
         Terminal.WriteLine("Please enter valid option {a, b, c, menu}");
     }
     else
     {
         level = input;
         if (level == "a")
         {
             password = levelOnePasswords[Random.Range(0, levelOnePasswords.Length)];
         }
         else if (level == "b")
         {
             password = levelTwoPasswords[Random.Range(0, levelTwoPasswords.Length)];
         }
         else
         {
             password = levelThreePasswords[Random.Range(0, levelThreePasswords.Length)];
         }
         startGame();
     }
 }
Ejemplo n.º 45
0
        public void GetTerminalByCardBrand(CardBrand expected, string cardNumber, params object[] brands)
        {
            //arrange
            var terminals = new List <Terminal>();

            var terminal1 = new Terminal();

            terminal1.CardBrands = new CardBrandList();
            terminal1.CardBrands.Items.Add((CardBrand)brands[0]);

            var terminal2 = new Terminal();

            terminal2.CardBrands = new CardBrandList();
            terminal2.CardBrands.Items.Add((CardBrand)brands[1]);

            terminals.Add(terminal1);
            terminals.Add(terminal2);

            //act
            var terminal = PaymentHelper.GetTerminal(Domain.Payment.PaymentUISection.CreditCard, terminals, "123456", cardNumber);

            //assert
            Assert.True(terminal.CardBrands.Contains(expected));
        }
Ejemplo n.º 46
0
    void StartGame()
    {
        currentScreen = Screen.Password;
        Terminal.ClearScreen();
        switch (level)
        {
        case 1:
            password = level1Passwords[UnityEngine.Random.Range(0, level1Passwords.Length)];
            break;

        case 2:
            password = level2Passwords[UnityEngine.Random.Range(0, level2Passwords.Length)];
            break;

        case 3:
            password = level3Passwords[UnityEngine.Random.Range(0, level3Passwords.Length)];
            break;

        default:
            Debug.LogError("Invalid Level Number");
            break;
        }
        Terminal.WriteLine("Enter Your Password, hint: " + password.Anagram());
    }
Ejemplo n.º 47
0
        public static bool AddTerminal(Terminal terminal)
        {
            var existingTerminal = GetTerminal(terminal.TerminalName);

            if (existingTerminal == null)
            {
                terminal.TerminalId = DatabaseCore.Instance.GetGeneratorValue("GEN_TERMINAL");
                var fbParameters = new List <QueryParameter>();
                fbParameters.Add(new QueryParameter("TERMINALID", terminal.TerminalId));
                fbParameters.Add(new QueryParameter("TERMINALNAME", terminal.TerminalName));
                fbParameters.Add(new QueryParameter("TERMINALIPADDRESS", terminal.TerminalIpAddress));
                fbParameters.Add(new QueryParameter("DISPLAY_NAME", terminal.DisplayName));
                fbParameters.Add(new QueryParameter("TERMINAL_TYPE", terminal.TerminalType));
                var queryString = DatabaseCore.Instance.BuildInsertQuery("TERMINALS", fbParameters);
                DatabaseCore.Instance.ExecuteNonQuery(queryString, fbParameters);
                return(true);
            }
            else
            {
                terminal.TerminalId = existingTerminal.TerminalId;
                UpdateTerminal(terminal);
                return(false);
            }
        }
Ejemplo n.º 48
0
        public Terminal GetTerminalRecord(string recordID, string UserSNo)
        {
            Terminal      t  = new Terminal();
            SqlDataReader dr = null;

            try
            {
                SqlParameter[] Parameters = { new SqlParameter("@SNo", (recordID)), new SqlParameter("@UserID", Convert.ToInt32(UserSNo)) };
                dr = SqlHelper.ExecuteReader(ReadConnectionString.WebConfigConnectionString, CommandType.StoredProcedure, "GetTerminalRecord", Parameters);
                if (dr.Read())
                {
                    t.SNo                  = Convert.ToInt32(dr["SNo"]);
                    t.TerminalName         = dr["TerminalName"].ToString().ToUpper();
                    t.CitySNo              = Convert.ToInt32(dr["CitySNo"].ToString());
                    t.Text_CitySNo         = dr["CityName"].ToString().ToUpper();
                    t.AirportSNo           = Convert.ToInt32(dr["AirportSNo"].ToString());
                    t.Text_AirportName     = dr["AirportName"].ToString().ToUpper();
                    t.IsActive             = Convert.ToBoolean(dr["IsActive"].ToString().ToUpper());
                    t.CityName             = dr["CityName"].ToString().ToUpper();
                    t.AirportName          = dr["AirportSNo"].ToString().ToUpper();
                    t.Active               = dr["Active"].ToString().ToUpper();
                    t.Text_XrayMachineName = dr["Text_XrayMachineName"].ToString().ToUpper();
                    t.VAccountNo           = dr["VAccountNo"].ToString();
                    t.XrayMachineName      = dr["XrayMachineName"].ToString().ToUpper();
                    t.UpdatedBy            = dr["UpdatedUser"].ToString().ToUpper();
                    t.CreatedBy            = dr["CreatedUser"].ToString().ToUpper();
                }
            }
            catch (Exception ex)//
            {
                dr.Close();
                throw ex;
            }
            dr.Close();
            return(t);
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Run engine command.
        /// </summary>
        /// <param name="context">The engine context.</param>
        /// <param name="command">The command.</param>
        /// <param name="commandSeparator">The command separator.</param>
        /// <param name="successCode">The expected success code.</param>
        /// <returns>The result.</returns>
        protected string RunEngine(EngineContext context, string command, string commandSeparator = " ", int successCode = 0, string stdin = "")
        {
            var result = Terminal.RunTerminal(command, Path.GetFullPath(context.WorkingDirectory), stdin: stdin);

            if (result.RunException != null)
            {
                throw new EngineException("Running engine exception", result.RunException.Message);
            }

            var stdError = result.Error.ToString().Trim();
            var stdOut   = result.Output.ToString().Trim();

            if (!string.IsNullOrEmpty(stdError) && result.ExitCode != successCode)
            {
                throw new EngineException(stdError);
            }

            if (result.ExitCode != successCode)
            {
                throw new EngineException($"Unexpected exit code: {result.ExitCode}", string.IsNullOrEmpty(stdOut) ? stdError : stdOut);
            }

            return(string.IsNullOrEmpty(stdOut) ? stdError : stdOut);
        }
        public ActionResult <Terminal> UpdateTerminal([FromBody] Terminal terminal)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            try
            {
                _unitOfWork.Terminals.UpdateTerminal(terminal);

                var terminalSettingsUpdate = new TerminalSettingUpdate
                {
                    Alias      = terminal.Alias,
                    TerminalId = terminal.Id
                };
                var updateTerminalCommand = new UpdateTerminalSettingsCommand(terminalSettingsUpdate);
                _unitOfWork.SourceEvent(updateTerminalCommand);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return(Ok(terminal));
        }
Ejemplo n.º 51
0
 public override string ToString()
 {
     return(Terminal.ToIString());
 }
Ejemplo n.º 52
0
 void DisplayWinScreen()
 {
     currentScreen = Screen.Result;
     Terminal.ClearScreen();
     ShowRewardScreen();
 }
Ejemplo n.º 53
0
 public ShiftExpressionAstNode(ExpressionAstNode e1, Terminal terminal,
                               ExpressionAstNode e2, int line, int column)
     : base(e1, terminal, e2, line, column)
 {
 }
Ejemplo n.º 54
0
 public SkippedTerminal(Terminal terminalToSkip)
     : base("skipped " + terminalToSkip.Name, TokenCategory.Outline, TermFlags.IsNonGrammar)
 {
 }
Ejemplo n.º 55
0
 void AskForPassword()
 {
     currentScreen = Screen.Password;
     Terminal.ClearScreen();
     Terminal.WriteLine("Enter your pass phrase (hint: \"" + password.Anagram() + "\"):");
 }
Ejemplo n.º 56
0
 void AskPlayerName()
 {
     Terminal.ClearScreen();
     currentScreen = Screen.Intro;
     Terminal.WriteLine("Please enter username to begin");
 }
Ejemplo n.º 57
0
 void DisplayWinScreeen()
 {
     currentScreen = Screen.Win;
     Terminal.ClearScreen();
     ShowLevelReward();
 }
Ejemplo n.º 58
0
 void PasswordHint()
 {
     Terminal.WriteLine("hint: " + password.Anagram());
 }
Ejemplo n.º 59
0
        public ReportingLanguage() : base(false)
        {
            // 1. Terminals

            var numberLiteral = TerminalFactory.CreateCSharpNumber("Number");

            var boolean = new ConstantTerminal("Boolean");

            boolean.Add("true", true);
            boolean.Add("false", false);
            boolean.Priority = 10;


            var nil = new ConstantTerminal("Null");

            nil.Add("null", null);
            nil.Add("nothing", null);
            nil.Priority = 10;

            var identifier = new IdentifierTerminal("Identifier");

            var stringLiteral = new StringLiteral("String", "'", StringFlags.AllowsDoubledQuote);

            stringLiteral.AddStartEnd("\"", StringFlags.AllowsAllEscapes);

            Terminal dot     = Symbol(".", "dot");
            Terminal less    = Symbol("<");
            Terminal greater = Symbol(">");
            Terminal LCb     = Symbol("(");
            Terminal RCb     = Symbol(")");
            Terminal RFb     = Symbol("}");
            Terminal LFb     = Symbol("{");
            Terminal comma   = Symbol(",");
//            Terminal LSb = Symbol("[");
//            Terminal RSb = Symbol("]");
            var exclamationMark = Symbol("!");

            Terminal and = Symbol("and");

            and.Priority = 10;

            Terminal or = Symbol("or");

            or.Priority = 10;

            var UserSection      = Symbol("User");
            var GlobalSection    = Symbol("Globals");
            var ParameterSection = Symbol("Parameters");
            var FieldsSection    = Symbol("Fields");

            // 2. Non-terminals

            var FieldRef             = new NonTerminal("FieldRef");
            var userSectionStmt      = new NonTerminal("UserSectionStmt");
            var globalSectionStmt    = new NonTerminal("GlobalSectionStmt");
            var parameterSectionStmt = new NonTerminal("ParameterSectionStmt");
            var fieldsSectionStmt    = new NonTerminal("FieldsSectionStmt");

            var QualifiedName      = new NonTerminal("QualifiedName");
            var FunctionExpression = new NonTerminal("FunctionExpression");

            var Condition   = new NonTerminal("Condition");
            var Conditional = new NonTerminal("IfThen");

            var Expr = new NonTerminal("Expr");

            var BinOp = new NonTerminal("BinOp");
            var LUnOp = new NonTerminal("LUnOp");


            var ExprList = new NonTerminal("ExprList");
            var BinExpr  = new NonTerminal("BinExpr", typeof(BinExprNode));

            var ProgramLine = new NonTerminal("ProgramLine");
            var Program     = new NonTerminal("Program", typeof(StatementListNode));

            // 3. BNF rules

            #region Reporting
            userSectionStmt.Rule = UserSection + exclamationMark + Symbol("UserId")
                                   | UserSection + exclamationMark + Symbol("Language");

            globalSectionStmt.Rule = GlobalSection + exclamationMark + Symbol("PageNumber")
                                     | GlobalSection + exclamationMark + Symbol("TotalPages")
                                     | GlobalSection + exclamationMark + Symbol("ExecutionTime")
                                     | GlobalSection + exclamationMark + Symbol("ReportFolder")
                                     | GlobalSection + exclamationMark + Symbol("ReportName");


            parameterSectionStmt.Rule = ParameterSection + exclamationMark + identifier;

            fieldsSectionStmt.Rule = FieldsSection + exclamationMark + identifier;
            #endregion

            Expr.Rule = Symbol("null")
                        | boolean
                        | nil
                        | stringLiteral
                        | numberLiteral
                        | QualifiedName
                        | FunctionExpression
                        | LCb + Expr + RCb
                        | LFb + QualifiedName + RFb
                        | Conditional
                        | BinExpr
                        //| Expr + BinOp + Expr
                        //| LUnOp + Expr

                        | parameterSectionStmt
                        | globalSectionStmt
                        | userSectionStmt
                        | fieldsSectionStmt;



            ExprList.Rule = MakePlusRule(ExprList, comma, Expr);

            BinOp.Rule = Symbol("+") | "-" | "*" | "%" | "^" | "&" | "|" | "/"
                         | "&&" | "||" | "==" | "!=" | greater | less
                         | ">=" | "<=" | "is" | "<>"
                         | "=" //| "+=" | "-="
                         | "." | and | or;

            LUnOp.Rule = Symbol("-")
                         | "!";

            FunctionExpression.Rule = QualifiedName + LCb + ExprList.Q() + RCb;

            QualifiedName.Rule = identifier
                                 | QualifiedName + dot + identifier
                                 | parameterSectionStmt + "!" + identifier
                                 | "#" + identifier;

            Condition.Rule = LCb + Expr + RCb;

            Conditional.Rule = "if" + Condition + "then" + Expr |
                               "if" + Condition + "then" + Expr + "else" + Expr |
                               "if" + Condition + "then" + Expr + "otherwise" + Expr;



            BinExpr.Rule = Expr + BinOp + Expr
                           | LUnOp + Expr;

            ProgramLine.Rule = Expr + NewLine;

            Program.Rule = MakeStarRule(Program, ProgramLine);
            this.Root    = Program;                // Set grammar root

            #region 5. Operators precedence
            RegisterOperators(1, "is", "=", "==", "!=", "<>", ">", "<", ">=", "<=");
            RegisterOperators(2, "+", "-");
            RegisterOperators(3, "*", "/", "%");
            RegisterOperators(4, Associativity.Right, "^");
            RegisterOperators(5, "|", "||", "or");
            RegisterOperators(6, "&", "&&", "and");
            RegisterOperators(7, "!");

            #endregion

            RegisterPunctuation("(", ")", "[", "]", "{", "}", ",", ";");
            MarkTransient(Expr, BinOp);

            //automatically add NewLine before EOF so that our BNF rules work correctly when there's no final line break in source
            this.SetLanguageFlags(LanguageFlags.NewLineBeforeEOF
                                  | LanguageFlags.SupportsInterpreter
                                  | LanguageFlags.AutoDetectTransient
                                  | LanguageFlags.CreateAst);
        }
Ejemplo n.º 60
0
		/// <summary>
		/// Execute the command
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ExecuteButton_Click(object sender, EventArgs e)
		{
			Terminal.ProcessCommand(InputBox.Text);
			InputBox.Text = "";
			InputBox.Focus();
		}