예제 #1
0
        public void ParseBinaryExpression(string expression)
        {
            var code = $"let x = {expression}";
            var node = ParsingHelper.ParseFirstStatementFrom <IVariableStatement>(code, roundTripTesting: false);

            Assert.Equal(code, node.GetFormattedText());
        }
예제 #2
0
    static void Main(string[] args)
    {
        string console = "";
        string input;

        //Read from console
        while ((input = Console.ReadLine()) != null)
        {
            console += input;
        }

        //Parse console input
        List <JToken> jTokenList = ParsingHelper.ParseJson(console);

        List <JToken> finalList = new List <JToken>();

        PlayerAdapter aiPlayer = new PlayerAdapter(false);
        JToken        toAdd;

        foreach (JToken jtoken in jTokenList)
        {
            toAdd = aiPlayer.JsonCommand(jtoken);
            if (toAdd.Type != JTokenType.Null)
            {
                finalList.Add(toAdd);
            }
        }

        Console.WriteLine(JsonConvert.SerializeObject(finalList));

        Console.ReadLine();
    }
예제 #3
0
        void IViewTab.Fill(Protocol protocol, ViewerItem item)
        {
            ((IViewTab)this).Reset();

            m_datas = ParsingHelper.ExtractBinaryDatas(protocol, item);
            int count = m_datas.Length;

            if (count > 0)
            {
                ui_cbDatas.Items.Clear();

                for (int i = 0; i < count; i++)
                {
                    ui_cbDatas.Items.Add(ParsingHelper.GetContentName(m_datas[i].Item1, i));
                }

                ui_cbDatas.SelectedIndex = 0;

                if (count > 1)
                {
                    ui_cbDatas.IsEnabled = true;
                }

                //this.SelectData(0);
            }

            this.IsFilled = true;
        }
예제 #4
0
        /*
         * Returns all adjacent liberties (if they exist)
         */
        public List <string> GetAdjacentLiberties(string point)
        {
            List <string> adj = new List <string>();

            int[]  p         = ParsingHelper.ParsePoint(point);
            string eastPoint = (p[0] + 1).ToString() + "-" + (p[1] + 2).ToString();

            if (p[1] != _size - 1 && Occupies(" ", eastPoint))
            {
                adj.Add(eastPoint);
            }

            string southPoint = (p[0] + 2).ToString() + "-" + (p[1] + 1).ToString();

            if (p[0] != _size - 1 && Occupies(" ", southPoint))
            {
                adj.Add(southPoint);
            }

            string westPoint = (p[0] + 1).ToString() + "-" + (p[1]).ToString();

            if (p[1] != 0 && Occupies(" ", westPoint))
            {
                adj.Add(westPoint);
            }

            string northPoint = (p[0]).ToString() + "-" + (p[1] + 1).ToString();

            if (p[0] != 0 && Occupies(" ", northPoint))
            {
                adj.Add(northPoint);
            }

            return(adj);
        }
예제 #5
0
        public void TestDifferentLiteralKinds(string code, LiteralExpressionKind expectedKind)
        {
            var node        = ParsingHelper.ParseFirstStatementFrom <IVariableStatement>(code);
            var initializer = node.DeclarationList.Declarations[0].Initializer.As <IStringLiteral>();

            Assert.Equal(expectedKind, initializer.LiteralKind);
        }
예제 #6
0
            public void OperatorOverloadTests()
            {
                ParsingHelper helper = new ParsingHelper(LongTest);

                for (int i = 0; !helper.EndOfText; i++, helper++)
                {
                    Assert.AreEqual(i, helper.Index);
                    Assert.AreEqual(LongTest[i], helper.Peek());
                }

                helper.Reset();
                helper++;
                Assert.AreEqual(1, helper);
                helper += 2;
                Assert.AreEqual(3, helper);
                helper = helper + 2;
                Assert.AreEqual(5, helper);
                helper -= 2;
                Assert.AreEqual(3, helper);
                helper = helper - 2;
                Assert.AreEqual(1, helper);
                helper--;
                Assert.AreEqual(0, helper);
                helper += 10000;
                Assert.AreEqual(LongTest.Length, helper);
                helper -= 10000;
                Assert.AreEqual(0, helper);
            }
        // if accountId is not null, this client registration is allocated in the login servers for the account (and restricted to users of that account) instead of the root login servers.
        public static OAuth2Client NewClient(string loginServerId, string accountId)
        {
            OAuth2Client resultClient = new OAuth2Client();

            resultClient._secretIsHashed = false;
            //
            ParsingHelper.ServerDetails?loginServerDetails = ParsingHelper.ExtractServerDetailsFromAccountServerId(loginServerId);
            if (loginServerDetails == null)
            {
                throw new Exception();
            }
            resultClient._loginServerDetails = loginServerDetails.Value;
            resultClient._id = null;
            //
            resultClient._accountId         = accountId;
            resultClient._accountId_IsDirty = true;
            //
            resultClient._tokenEndpointAuthMethod         = OAuth2TokenEndpointAuthMethod.None;
            resultClient._tokenEndpointAuthMethod_IsDirty = true;
            //
            resultClient._redirectUris  = new ListWithDirtyFlag <string>();
            resultClient._grantTypes    = new ListWithDirtyFlag <OAuth2GrantType>();
            resultClient._responseTypes = new ListWithDirtyFlag <OAuth2ResponseType>();
            resultClient._scopes        = new ListWithDirtyFlag <string>();
            //
            resultClient._registrationTokenIsHashed = false;
            //
            return(resultClient);
        }
예제 #8
0
        public void TestBackslashEscapingInStringInterpolation()
        {
            var code = @"`\\`";
            var node = ParsingHelper.ParseExpressionStatement <ILiteralExpression>(code, roundTripTesting: false, parsingOptions: m_options);

            Assert.Equal(@"\", node.Text);
        }
예제 #9
0
        private static List <AlertHistoryItemModel> ProduceAlertHistoryItemsAsync(Stream stream)
        {
            Debug.Assert(stream != null, "stream is a null reference.");

            var models = new List <AlertHistoryItemModel>();

            try
            {
                stream.Position = 0;
                using (var reader = new StreamReader(stream))
                {
                    IEnumerable <ExpandoObject> expandos = ParsingHelper.ParseCsv(reader).ToExpandoObjects();
                    foreach (ExpandoObject expando in expandos)
                    {
                        AlertHistoryItemModel model = ProduceAlertHistoryItem(expando);

                        if (model != null)
                        {
                            models.Add(model);
                        }
                    }
                }
            }
            finally
            {
            }

            return(models);
        }
예제 #10
0
        public void TestNodeAfterSingleAndMultilineComment()
        {
            Func <int, string> makeNewLines = (n) => string.Join(string.Empty, Enumerable.Repeat(Environment.NewLine, n));

            string code =
                @"function foo(): number {
    let a = 1; 
    /** blah */

    // return
    return a + 1;
}";

            var sourceFile = ParsingHelper.ParseSourceFile(code);
            var foo        = (IFunctionDeclaration)sourceFile.Statements[0];
            var @let       = foo.Body.Statements[0];
            var @return    = foo.Body.Statements[1];

            var fooLineInfo    = foo.GetLineInfo(sourceFile);
            var letLineInfo    = @let.GetLineInfo(sourceFile);
            var returnLineInfo = @return.GetLineInfo(sourceFile);

            Assert.Equal(1, fooLineInfo.Line);
            Assert.Equal(2, letLineInfo.Line);
            Assert.Equal(6, returnLineInfo.Line);
        }
예제 #11
0
        private string TestJson(string filePath)
        {
            string json = ExtractJson(filePath);

            //Parse console input
            List <JToken> jTokenList = ParsingHelper.ParseJson(json);
            List <JToken> finalList  = new List <JToken>();

            PlayerWrapper player1 = new PlayerWrapper("human");
            PlayerWrapper player2 = new PlayerWrapper("human");

            RefereeAdapter referee = new RefereeAdapter(player1, player2);

            foreach (JToken jtoken in jTokenList)
            {
                try
                {
                    referee.JsonCommand(jtoken, finalList);
                }
                catch (RefereeException)
                {
                    break;
                }
            }

            return(JsonConvert.SerializeObject(finalList));
        }
예제 #12
0
        public IResponseBase ProcessResponse(IResultResponse response, IRequestParameter parameters)
        {
            var result = new Response <StringResponse>();
            var xDoc   = response.XDocument;

            try
            {
                result.resultset.Model = ParsingHelper.GetDWQuery(xDoc, "NewPasswordForm");
                if (string.IsNullOrEmpty(result.resultset.Model))
                {
                    result.resultset.Model = ParsingHelper.GetDWQuery(xDoc, "PasswordResetForm");
                    if (string.IsNullOrEmpty(result.resultset.Model))
                    {
                        _errors.Add(new SiteError
                        {
                            Message  = new ErrorMessage(Config.Constants.GenericError, Config.Constants.GenericError),
                            Severity = ErrorSeverity.UserActionRequired,
                            Type     = ErrorType.UserActionRequired
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                _errors.Add(ex.Handle("ResetPasswordForm.ProcessResponse", ErrorSeverity.FollowUp, ErrorType.Parsing));
            }

            return(result);
        }
예제 #13
0
        private List <FuriganaPart> CutFurigana(string furigana)
        {
            List <FuriganaPart> output = new List <FuriganaPart>();

            string[] parts = furigana.Split(';');
            foreach (string part in parts)
            {
                FuriganaPart f = new FuriganaPart();

                string[] bodySplit = part.Split(':');
                f.Value = bodySplit[1];

                string[] indexSplit = bodySplit[0].Split('-');
                f.StartIndex = ParsingHelper.ForceInt(indexSplit[0]);
                if (indexSplit.Count() == 1)
                {
                    f.EndIndex = f.StartIndex;
                }
                else
                {
                    f.EndIndex = ParsingHelper.ForceInt(indexSplit[1]);
                }

                output.Add(f);
            }

            return(output);
        }
예제 #14
0
    public static void ValidatePoint(JToken point, int size = 19)
    {
        string strPoint;

        int[] newPoint;
        try
        {
            strPoint = point.ToObject <string>();
        }
        catch
        {
            throw new InvalidJsonInputException("Invalid point passed to Adapter: cannot be converted into a string");
        }
        try
        {
            newPoint = ParsingHelper.ParsePoint(strPoint);
        }
        catch
        {
            throw new InvalidJsonInputException("Invalid point passed to Adapter: cannot be parsed");
        }
        try
        {
            if (0 <= newPoint[0] && newPoint[0] <= size - 1 && 0 <= newPoint[1] && newPoint[1] <= size - 1)
            {
                return;
            }
        }
        catch
        {
            throw new InvalidJsonInputException("Invalid point passed to Adapter: does not contain two valid points");
        }
        throw new InvalidJsonInputException("Invalid point passed to Adapter: coordinates are not > 0 and < 20");
    }
예제 #15
0
        private static ISourceFile ParseAndCheck(string code)
        {
            var sourceFile = ParsingHelper.ParseSourceFile(code);
            var checker    = CreateTypeChecker(sourceFile);

            return(sourceFile);
        }
예제 #16
0
        public void TestBackslashEscapingInNonPathLikeInterpolation()
        {
            var code = @"anotherFactoryMethod`\\`";
            var node = ParsingHelper.ParseExpressionStatement <ITaggedTemplateExpression>(code, roundTripTesting: false, parsingOptions: m_options);

            Assert.Equal(@"\", node.TemplateExpression.GetTemplateText());
        }
예제 #17
0
        public void ForLoopWithCSharpStyleOfDeclarationShouldNotCrash()
        {
            string code        = @"for (int i = 0 ; i < 10; i = i + 1) {;}";
            var    diagnostics = ParsingHelper.ParseAndGetDiagnostics(code);

            Assert.NotEmpty(diagnostics);
        }
예제 #18
0
        public void TestInterpolatedPathWithBackslashes()
        {
            var code = @"p`a\path\to\a\file`";
            var node = ParsingHelper.ParseExpressionStatement <ITaggedTemplateExpression>(code, roundTripTesting: false, parsingOptions: m_options);

            Assert.Equal(@"a\path\to\a\file", node.TemplateExpression.GetTemplateText());
        }
예제 #19
0
        public void ParseObjectLiteralWithFunction()
        {
            string code =
                @"{
    interface Foo {
        x: number;
        func: () => string;
        func2: (x: number) => string;
        func3: (x: number, y: string) => {x: number};
    }
    let foo: Foo = {
        x: 42,
        func: function() {
            return 'foo';
        },
        func2: function(x: number) {
            return x.toString();
        },
        func3: function(x, y) {
            return {x: x};
        },
    };
}";

            var node = ParsingHelper.ParseFirstStatementFrom <IBlock>(code);

            Console.WriteLine(node.GetFormattedText());
            Assert.Equal(code, node.GetFormattedText());
        }
예제 #20
0
            public void ExtractTests()
            {
                ParsingHelper helper = new ParsingHelper(LongTest);
                string        s      = "consecrated it";

                Assert.IsTrue(helper.SkipTo(s));
                int start = helper.Index;

                helper.Next(s.Length);
                Assert.AreEqual(s, helper.Extract(start, helper.Index));
                Assert.AreEqual(@"consecrated it, far above our poor power to add or
detract. The world will little note, nor long remember what we say here, but it can never forget what they
did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought
here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining
before us -- that from these honored dead we take increased devotion to that cause for which they gave the
last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain --
that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the
people, for the people, shall not perish from the earth.", helper.Extract(start));
                Assert.AreEqual(LongTest, helper.Extract(0, LongTest.Length));
                Assert.AreEqual("score", helper.Extract(5, 10));
                Assert.AreNotEqual("score", helper.Extract(5, 11));
                Assert.AreNotEqual("score", helper.Extract(4, 10));
                Assert.AreEqual(string.Empty, helper.Extract(0, 0));
                Assert.AreEqual(string.Empty, helper.Extract(LongTest.Length, LongTest.Length));
            }
예제 #21
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //var par = ParamExtractor.ExtractUrlParams(filterContext.HttpContext.Request);
            string        catFilter    = ParsingHelper.ParseObject <string>(filterContext.HttpContext.Request.QueryString, "cats");
            string        specs        = ParsingHelper.ParseObject <string>(filterContext.HttpContext.Request.QueryString, "specs");
            int?          pack         = ParsingHelper.ParseObject <int?>(filterContext.HttpContext.Request.QueryString, "pack");
            int?          country      = ParsingHelper.ParseObject <int?>(filterContext.HttpContext.Request.QueryString, "country");
            int?          manufacturer = ParsingHelper.ParseObject <int?>(filterContext.HttpContext.Request.QueryString, "mnf");
            int?          minPrice     = ParsingHelper.ParseObject <int?>(filterContext.HttpContext.Request.QueryString, "minp");
            int?          maxPrice     = ParsingHelper.ParseObject <int?>(filterContext.HttpContext.Request.QueryString, "maxp");
            SortCriterion?sort         = null;

            if (filterContext.HttpContext.Request.QueryString["sort"] != null)
            {
                sort = ParsingHelper.ParseObject <SortCriterion>(filterContext.HttpContext.Request.QueryString, "sort");
            }

            filterContext.Controller.ViewBag.PackId    = pack;
            filterContext.Controller.ViewBag.CountryId = country;
            filterContext.Controller.ViewBag.Sort      = sort;


            filterContext.ActionParameters["packId"]         = pack;
            filterContext.ActionParameters["countryId"]      = country;
            filterContext.ActionParameters["manufacturerId"] = manufacturer;
            filterContext.ActionParameters["sort"]           = sort;
            filterContext.ActionParameters["catFilter"]      = ParseCategoryFilter(catFilter);
            filterContext.ActionParameters["specs"]          = ParseSpecs(specs);
            filterContext.ActionParameters["minPrice"]       = minPrice;
            filterContext.ActionParameters["maxPrice"]       = maxPrice;

            base.OnActionExecuting(filterContext);
        }
    public static void Main(string[] args)
    {
        string         input;
        string         console = "";
        List <JToken>  jTokenList;
        RefereeAdapter referee = new RefereeAdapter();

        //Read from console
        while ((input = Console.ReadLine()) != null)
        {
            console   += input;
            jTokenList = ParsingHelper.ParseJson(console);
            if (jTokenList.Count != 0)
            {
                while (jTokenList.Count != 0)
                {
                    try
                    {
                        referee.JsonCommand(jTokenList[0]);
                    }
                    catch (RefereeException)
                    {
                        break;
                    }
                    jTokenList.RemoveAt(0);
                }
                console = "";
            }
        }

        Console.ReadLine();
    }
예제 #23
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            int  pageSize;
            int  page;
            bool allPages = ParsingHelper.ParseObject <string>(filterContext.HttpContext.Request.QueryString, "pgsize") == "all";

            if (allPages)
            {
                page     = 1;
                pageSize = int.MaxValue;
            }
            else
            {
                page     = ParsingHelper.ParseObject <int?>(filterContext.HttpContext.Request.QueryString, "page") ?? 1;
                pageSize = ParsingHelper.ParseObject <int?>(filterContext.HttpContext.Request.QueryString, "pgsize") ?? _defaultPageSize;
            }
            filterContext.Controller.ViewBag.Page            = page;
            filterContext.Controller.ViewBag.PageSize        = pageSize;
            filterContext.Controller.ViewBag.DefaultPageSize = _defaultPageSize;


            filterContext.ActionParameters["pageSize"]   = (int)pageSize;
            filterContext.ActionParameters["pageNumber"] = page;

            base.OnActionExecuting(filterContext);
        }
예제 #24
0
    public void Execute(string input, ref CGAContext context)
    {
        string            ax     = ParsingHelper.QSString(input);
        ExtrudeAxis       sa     = (ExtrudeAxis)Enum.Parse(typeof(ExtrudeAxis), ax);;
        string            target = ParsingHelper.GetTarget(input);
        List <GameObject> t      = null;

        if (!string.IsNullOrEmpty(target) && context.namedObjects.ContainsKey(target))
        {
            t = context.namedObjects[target];
            foreach (GameObject g in t)
            {
                switch (sa)
                {
                case ExtrudeAxis.X:
                    break;

                case ExtrudeAxis.Y:
                    break;

                case ExtrudeAxis.Z:
                    break;
                }
            }
        }
        else
        {
            Debug.LogWarning("Cannot extrude without any target");
            return;
        }
    }
예제 #25
0
        public void TestBacktickEscapingInPathLikeInterpolation(string factoryName)
        {
            var code = $"{factoryName}`a``b`";
            var node = ParsingHelper.ParseExpressionStatement <ITaggedTemplateExpression>(code, roundTripTesting: false, parsingOptions: m_options);

            Assert.Equal("a`b", node.TemplateExpression.GetTemplateText());
        }
예제 #26
0
        public static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));

            // This app uses a mutex to make sure it is started only one time.
            // In this context, keep in mind that the mutex is the only
            // shared resource between instances of the application.

            // Acquire parameters.
            // There is one optional parameter:
            //
            // [0] - Boolean - Indicates if the Main Window should be started.
            // - Default is True.

            RunMainWindow = (args.Any() ? ParsingHelper.ParseBool(args[0]) : null) ?? true;

            // Check the mutex.
            if (RunOnceMutex.WaitOne(TimeSpan.Zero, true))
            {
                // The application is not already running. So let's start it.
                Run();

                // Once the application is shutdown, release the mutex.
                RunOnceMutex.ReleaseMutex();
            }
            else
            {
                // The application is already running.
                // Transmit a command to open/focus the main window using the pipe system.
                using (NamedPipeHandler handler = new NamedPipeHandler(InstanceHelper.InterfaceApplicationGuid))
                {
                    handler.Write(PipeMessageEnum.OpenOrFocus.ToString());
                }
            }
        }
예제 #27
0
        public void UnionWithTwoQuotesInQuotes()
        {
            string code = @"export type X = ""'"" | '""'";

            var node = ParsingHelper.ParseFirstStatementFrom <ITypeAliasDeclaration>(code);

            Assert.Equal(code, node.GetFormattedText());
        }
예제 #28
0
        public void ImportStarAsImportWithDoubleQuotes()
        {
            string code = @"import * as X from ""blah.dsc""";

            var node = ParsingHelper.ParseFirstStatementFrom <IImportDeclaration>(code);

            Assert.Equal(code, node.GetFormattedText());
        }
예제 #29
0
        public void Simple()
        {
            string code = @"export type X = ""simple""";

            var node = ParsingHelper.ParseFirstStatementFrom <ITypeAliasDeclaration>(code);

            Assert.Equal(code, node.GetFormattedText());
        }
예제 #30
0
        /// <summary>
        /// Parses the given command line and populates <see cref="Arguments"></see> with the
        /// results. It is assumed that <paramref name="commandLine"/> does not include the
        /// application name. If you want to parse <see cref="Environment.CommandLine"></see>,
        /// you should use <see cref="Parse"></see> instead as it will automatically discard
        /// the application name.
        /// </summary>
        /// <param name="commandLine">Command line to parse.</param>
        public void Parse(string commandLine)
        {
            // Create parsing helper
            ParsingHelper parser = new ParsingHelper(commandLine);

            // Call main parser
            ParseInternal(parser);
        }