text:
namespace Microsoft.AspNetCore.Routing.Matching;

// This class includes features that we have not yet implemented in the DFA
// and instruction matchers.
//
// As those matchers add features we can move tests from this class into
// MatcherConformanceTest and delete this.
public abstract class FullFeaturedMatcherConformanceTest : MatcherConformanceTest
{
    [Theory]
    [InlineData("/a/{b=15}", "/a/b", new string[] { "b", }, new string[] { "b", })]
    [InlineData("/a/{b=15}", "/a/", new string[] { "b", }, new string[] { "15", })]
    [InlineData("/a/{b=15}", "/a", new string[] { "b", }, new string[] { "15", })]
    [InlineData("/{a}/{b=15}", "/54/b", new string[] { "a", "b", }, new string[] { "54", "b", })]
    [InlineData("/{a=19}/{b=15}", "/54/b", new string[] { "a", "b", }, new string[] { "54", "b", })]
    [InlineData("/{a=19}/{b=15}", "/54/", new string[] { "a", "b", }, new string[] { "54", "15", })]
    [InlineData("/{a=19}/{b=15}", "/54", new string[] { "a", "b", }, new string[] { "54", "15", })]
    [InlineData("/{a=19}/{b=15}", "/", new string[] { "a", "b", }, new string[] { "19", "15", })]
    public virtual async Task Match_DefaultValues(string template, string path, string[] keys, string[] values)
    {
        // Arrange
        var (matcher, endpoint) = CreateMatcher(template);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, endpoint, keys, values);
    }

    [Fact]
    public virtual async Task Match_NonInlineDefaultValues()
    {
        // Arrange
        var endpoint = CreateEndpoint("/a/{b}/{c}", new { b = "17", c = "18", });
        var matcher = CreateMatcher(endpoint);
        var httpContext = CreateContext("/a");

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, endpoint, new { b = "17", c = "18", });
    }

    [Fact]
    public virtual async Task Match_ExtraDefaultValues()
    {
        // Arrange
        var endpoint = CreateEndpoint("/a/{b}/{c}", new { b = "17", c = "18", d = "19" });
        var matcher = CreateMatcher(endpoint);
        var httpContext = CreateContext("/a");

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, endpoint, new { b = "17", c = "18", d = "19" });
    }

    [Theory]
    [InlineData("/a/{b=15}", "/54/b")]
    [InlineData("/a/{b=15}", "/54/")]
    [InlineData("/a/{b=15}", "/54")]
    [InlineData("/a/{b=15}", "/a//")]
    [InlineData("/a/{b=15}", "/54/43/23")]
    [InlineData("/{a=19}/{b=15}", "/54/b/c")]
    [InlineData("/a/{b=15}/c", "/a/b")] // Intermediate default values don't act like optional segments
    [InlineData("a/{b=3}/c/{d?}/e/{*f}", "/a")]
    [InlineData("a/{b=3}/c/{d?}/e/{*f}", "/a/b")]
    [InlineData("a/{b=3}/c/{d?}/e/{*f}", "/a/b/c")]
    [InlineData("a/{b=3}/c/{d?}/e/{*f}", "/a/b/c/d")]
    public virtual async Task NotMatch_DefaultValues(string template, string path)
    {
        // Arrange
        var (matcher, endpoint) = CreateMatcher(template);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertNotMatch(httpContext);
    }

    [Theory]
    [InlineData("/{a?}/{b?}/{c?}", "/", null, null)]
    [InlineData("/{a?}/{b?}/{c?}", "/a", new[] { "a", }, new[] { "a", })]
    [InlineData("/{a?}/{b?}/{c?}", "/a/", new[] { "a", }, new[] { "a", })]
    [InlineData("/{a?}/{b?}/{c?}", "/a/b", new[] { "a", "b", }, new[] { "a", "b", })]
    [InlineData("/{a?}/{b?}/{c?}", "/a/b/", new[] { "a", "b", }, new[] { "a", "b", })]
    [InlineData("/{a?}/{b?}/{c?}", "/a/b/c", new[] { "a", "b", "c", }, new[] { "a", "b", "c", })]
    [InlineData("/{a?}/{b?}/{c?}", "/a/b/c/", new[] { "a", "b", "c", }, new[] { "a", "b", "c", })]
    [InlineData("/{c}/{a?}", "/h/i", new[] { "c", "a", }, new[] { "h", "i", })]
    [InlineData("/{c}/{a?}", "/h/", new[] { "c", }, new[] { "h", })]
    [InlineData("/{c}/{a?}", "/h", new[] { "c", }, new[] { "h", })]
    [InlineData("/{c?}/{a?}", "/", null, null)]
    [InlineData("/{c}/{a?}/{id?}", "/h/i/18", new[] { "c", "a", "id", }, new[] { "h", "i", "18", })]
    [InlineData("/{c}/{a?}/{id?}", "/h/i", new[] { "c", "a", }, new[] { "h", "i", })]
    [InlineData("/{c}/{a?}/{id?}", "/h", new[] { "c", }, new[] { "h", })]
    [InlineData("template/{p:int?}", "/template/5", new[] { "p", }, new[] { "5", })]
    [InlineData("template/{p:int?}", "/template", null, null)]
    [InlineData("a/{b=3}/c/{d?}/e/{*f}", "/a/b/c/d/e", new[] { "b", "d", "f" }, new[] { "b", "d", null, })]
    [InlineData("a/{b=3}/c/{d?}/e/{*f}", "/a/b/c/d/e/f", new[] { "b", "d", "f", }, new[] { "b", "d", "f", })]
    public virtual async Task Match_OptionalParameter(string template, string path, string[] keys, string[] values)
    {
        // Arrange
        var (matcher, endpoint) = CreateMatcher(template);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, endpoint, keys, values);
    }

    [Theory]
    [InlineData("/{a?}/{b?}/{c?}", "///")]
    [InlineData("/{a?}/{b?}/{c?}", "/a//")]
    [InlineData("/{a?}/{b?}/{c?}", "/a/b//")]
    [InlineData("/{a?}/{b?}/{c?}", "//b//")]
    [InlineData("/{a?}/{b?}/{c?}", "///c")]
    [InlineData("/{a?}/{b?}/{c?}", "///c/")]
    [InlineData("/{a?}/{b?}/{c?}", "/a/b/c/d")]
    [InlineData("/a/{b?}/{c?}", "/")]
    [InlineData("template/{parameter:int?}", "/template/qwer")]
    public virtual async Task NotMatch_OptionalParameter(string template, string path)
    {
        // Arrange
        var (matcher, endpoint) = CreateMatcher(template);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertNotMatch(httpContext);
    }

    [Theory]
    [InlineData("/{a}/{*b}", "/a", new[] { "a", "b", }, new[] { "a", null, })]
    [InlineData("/{a}/{*b}", "/a/", new[] { "a", "b", }, new[] { "a", null, })]
    [InlineData("/{a}/{*b=b}", "/a", new[] { "a", "b", }, new[] { "a", "b", })]
    [InlineData("/{a}/{*b=b}", "/a/", new[] { "a", "b", }, new[] { "a", "b", })]
    [InlineData("/{a}/{*b=b}", "/a/hello", new[] { "a", "b", }, new[] { "a", "hello", })]
    [InlineData("/{a}/{*b=b}", "/a/hello/goodbye", new[] { "a", "b", }, new[] { "a", "hello/goodbye", })]
    [InlineData("/{a}/{*b=b}", "/a/b//", new[] { "a", "b", }, new[] { "a", "b//", })]
    [InlineData("/{a}/{*b=b}", "/a/b/c/", new[] { "a", "b", }, new[] { "a", "b/c/", })]
    [InlineData("/{a=1}/{b=2}/{c=3}/{d=4}", "/a/b/c", new[] { "a", "b", "c", "d", }, new[] { "a", "b", "c", "4", })]
    [InlineData("a/{*path:regex(10/20/30)}", "/a/10/20/30", new[] { "path", }, new[] { "10/20/30" })]
    public virtual async Task Match_CatchAllParameter(string template, string path, string[] keys, string[] values)
    {
        // Arrange
        var (matcher, endpoint) = CreateMatcher(template);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, endpoint, keys, values);
    }

    // Historically catchall segments don't match an empty segment, but only if it's
    // the first one. So `/a/b//` would match, but `/a//` would not. This is pretty
    // weird and inconsistent with the intent of using a catch all. The DfaMatcher
    // fixes this issue.
    [Theory]
    [InlineData("/{a}/{*b=b}", "/a///", new[] { "a", "b", }, new[] { "a", "//" })]
    [InlineData("/{a}/{*b=b}", "/a//c/", new[] { "a", "b", }, new[] { "a", "/c/" })]
    public virtual async Task Quirks_CatchAllParameter(string template, string path, string[] keys, string[] values)
    {
        // Arrange
        var (matcher, endpoint) = CreateMatcher(template);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertNotMatch(httpContext);

        // Need to access these to prevent a warning from the xUnit analyzer.
        // Some of these tests will match (and process the values) and some will not.
        GC.KeepAlive(keys);
        GC.KeepAlive(values);
    }

    [Theory]
    [InlineData("{p}x{s}", "/xxxxxxxxxx", new[] { "p", "s" }, new[] { "xxxxxxxx", "x", })]
    [InlineData("{p}xyz{s}", "/xxxxyzxyzxxxxxxyz", new[] { "p", "s" }, new[] { "xxxxyz", "xxxxxxyz", })]
    [InlineData("{p}xyz{s}", "/abcxxxxyzxyzxxxxxxyzxx", new[] { "p", "s" }, new[] { "abcxxxxyzxyzxxxxx", "xx", })]
    [InlineData("{p}xyz{s}", "/xyzxyzxyzxyzxyz", new[] { "p", "s" }, new[] { "xyzxyzxyz", "xyz", })]
    [InlineData("{p}xyz{s}", "/xyzxyzxyzxyzxyz1", new[] { "p", "s" }, new[] { "xyzxyzxyzxyz", "1", })]
    [InlineData("{p}xyz{s}", "/xyzxyzxyz", new[] { "p", "s" }, new[] { "xyz", "xyz", })]
    [InlineData("{p}aa{s}", "/aaaaa", new[] { "p", "s" }, new[] { "aa", "a", })]
    [InlineData("{p}aaa{s}", "/aaaaa", new[] { "p", "s" }, new[] { "a", "a", })]
    [InlineData("language/{lang=en}-{region=US}", "/language/xx-yy", new[] { "lang", "region" }, new[] { "xx", "yy", })]
    [InlineData("language/{lang}-{region}", "/language/en-US", new[] { "lang", "region" }, new[] { "en", "US", })]
    [InlineData("language/{lang}-{region}a", "/language/en-USa", new[] { "lang", "region" }, new[] { "en", "US", })]
    [InlineData("language/a{lang}-{region}", "/language/aen-US", new[] { "lang", "region" }, new[] { "en", "US", })]
    [InlineData("language/a{lang}-{region}a", "/language/aen-USa", new[] { "lang", "region" }, new[] { "en", "US", })]
    [InlineData("language/{lang}-", "/language/en-", new[] { "lang", }, new[] { "en", })]
    [InlineData("language/a{lang}", "/language/aen", new[] { "lang", }, new[] { "en", })]
    [InlineData("language/a{lang}a", "/language/aena", new[] { "lang", }, new[] { "en", })]
    public virtual async Task Match_ComplexSegment(string template, string path, string[] keys, string[] values)
    {
        // Arrange
        var (matcher, endpoint) = CreateMatcher(template);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, endpoint, keys, values);
    }

    [Theory]
    [InlineData("language/a{lang}-{region}a", "/language/a-USa")]
    [InlineData("language/a{lang}-{region}a", "/language/aen-a")]
    [InlineData("language/{lang=en}-{region=US}", "/language")]
    [InlineData("language/{lang=en}-{region=US}", "/language/-")]
    [InlineData("language/{lang=en}-{region=US}", "/language/xx-")]
    [InlineData("language/{lang=en}-{region=US}", "/language/-xx")]
    public virtual async Task NotMatch_ComplexSegment(string template, string path)
    {
        // Arrange
        var (matcher, endpoint) = CreateMatcher(template);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertNotMatch(httpContext);
    }

    [Theory]
    [InlineData("moo/{p1}.{p2?}", "/moo/foo.bar", new[] { "p1", "p2", }, new[] { "foo", "bar" })]
    [InlineData("moo/{p1}.{p2?}", "/moo/foo", new[] { "p1", }, new[] { "foo", })]
    [InlineData("moo/{p1}.{p2?}", "/moo/.foo", new[] { "p1", }, new[] { ".foo", })]
    [InlineData("moo/{p1}.{p2?}", "/moo/foo..bar", new[] { "p1", "p2", }, new[] { "foo.", "bar" })]
    [InlineData("moo/{p1}.{p2?}", "/moo/foo.moo.bar", new[] { "p1", "p2", }, new[] { "foo.moo", "bar" })]
    [InlineData("moo/foo.{p1}.{p2?}", "/moo/foo.moo", new[] { "p1", }, new[] { "moo", })]
    [InlineData("moo/foo.{p1}.{p2?}", "/moo/foo.foo.bar", new[] { "p1", "p2", }, new[] { "foo", "bar" })]
    [InlineData("moo/.{p2?}", "/moo/.foo", new[] { "p2", }, new[] { "foo", })]
    [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo.bar", new[] { "p1", "p2", "p3" }, new[] { "foo", "moo", "bar" })]
    [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo", new[] { "p1", "p2", }, new[] { "foo", "moo" })]
    [InlineData("moo/{p1}.{p2}.{p3}.{p4?}", "/moo/foo.moo.bar", new[] { "p1", "p2", "p3" }, new[] { "foo", "moo", "bar" })]
    [InlineData("{p1}.{p2?}/{p3}", "/foo.moo/bar", new[] { "p1", "p2", "p3" }, new[] { "foo", "moo", "bar" })]
    [InlineData("{p1}.{p2?}/{p3}", "/foo/bar", new[] { "p1", "p3" }, new[] { "foo", "bar" })]
    [InlineData("{p1}.{p2?}/{p3}", "/.foo/bar", new[] { "p1", "p3" }, new[] { ".foo", "bar" })]
    [InlineData("{p1}/{p2}/{p3?}", "/foo/bar/baz", new[] { "p1", "p2", "p3" }, new[] { "foo", "bar", "baz" })]
    public virtual async Task Match_OptionalSeparator(string template, string path, string[] keys, string[] values)
    {
        // Arrange
        var (matcher, endpoint) = CreateMatcher(template);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, endpoint, keys, values);
    }

    [Theory]
    [InlineData("moo/{p1}.{p2?}", "/moo/foo.")]
    [InlineData("moo/{p1}.{p2?}", "/moo/.")]
    [InlineData("moo/{p1}.{p2}", "/foo.")]
    [InlineData("moo/{p1}.{p2}", "/foo")]
    [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo.")]
    [InlineData("moo/foo.{p2}.{p3?}", "/moo/bar.foo.moo")]
    [InlineData("moo/foo.{p2}.{p3?}", "/moo/kungfoo.moo.bar")]
    [InlineData("moo/foo.{p2}.{p3?}", "/moo/kungfoo.moo")]
    [InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo")]
    [InlineData("{p1}.{p2?}/{p3}", "/foo./bar")]
    [InlineData("moo/.{p2?}", "/moo/.")]
    [InlineData("{p1}.{p2}/{p3}", "/.foo/bar")]
    public virtual async Task NotMatch_OptionalSeparator(string template, string path)
    {
        // Arrange
        var (matcher, endpoint) = CreateMatcher(template);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertNotMatch(httpContext);
    }

    // Most of are copied from old routing tests that date back to the VS 2010 era. Enjoy!
    [Theory]
    [InlineData("{Controller}.mvc/../{action}", "/Home.mvc/../index", new string[] { "Controller", "action" }, new string[] { "Home", "index" })]
    [InlineData("{Controller}.mvc/.../{action}", "/Home.mvc/.../index", new string[] { "Controller", "action" }, new string[] { "Home", "index" })]
    [InlineData("{Controller}.mvc/../../../{action}", "/Home.mvc/../../../index", new string[] { "Controller", "action" }, new string[] { "Home", "index" })]
    [InlineData("{Controller}.mvc!/{action}", "/Home.mvc!/index", new string[] { "Controller", "action" }, new string[] { "Home", "index" })]
    [InlineData("../{Controller}.mvc", "/../Home.mvc", new string[] { "Controller", }, new string[] { "Home", })]
    [InlineData(@"\{Controller}.mvc", @"/\Home.mvc", new string[] { "Controller", }, new string[] { "Home", })]
    [InlineData(@"{Controller}.mvc\{id}\{Param1}", @"/Home.mvc\123\p1", new string[] { "Controller", "id", "Param1" }, new string[] { "Home", "123", "p1" })]
    [InlineData("(Controller).mvc", "/(Controller).mvc", new string[] { }, new string[] { })]
    [InlineData("Controller.mvc/ ", "/Controller.mvc/ ", new string[] { }, new string[] { })]
    [InlineData("Controller.mvc ", "/Controller.mvc ", new string[] { }, new string[] { })]
    public virtual async Task Match_WeirdCharacterCases(string template, string path, string[] keys, string[] values)
    {
        // Arrange
        var (matcher, endpoint) = CreateMatcher(template);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, endpoint, keys, values);
    }

    [Theory]
    [InlineData("template/5", "template/{parameter:int}")]
    [InlineData("template/5", "template/{parameter}")]
    [InlineData("template/5", "template/{*parameter:int}")]
    [InlineData("template/5", "template/{*parameter}")]
    [InlineData("template/{parameter}", "template/{parameter:alpha}")] // constraint doesn't match
    [InlineData("template/{parameter:int}", "template/{parameter}")]
    [InlineData("template/{parameter:int}", "template/{*parameter:int}")]
    [InlineData("template/{parameter:int}", "template/{*parameter}")]
    [InlineData("template/{parameter}", "template/{*parameter:int}")]
    [InlineData("template/{parameter}", "template/{*parameter}")]
    [InlineData("template/{*parameter:int}", "template/{*parameter}")]
    public virtual async Task Match_SelectEndpoint_BasedOnPrecedence(string template1, string template2)
    {
        // Arrange
        var expected = CreateEndpoint(template1);
        var other = CreateEndpoint(template2);
        var path = "/template/5";

        // Arrange
        var matcher = CreateMatcher(other, expected);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, expected, ignoreValues: true);
    }

    [Theory]
    [InlineData("template/5", "template/{parameter:int}")]
    [InlineData("template/5", "template/{parameter}")]
    [InlineData("template/5", "template/{*parameter:int}")]
    [InlineData("template/5", "template/{*parameter}")]
    [InlineData("template/{parameter:int}", "template/{parameter}")]
    [InlineData("template/{parameter:int}", "template/{*parameter:int}")]
    [InlineData("template/{parameter:int}", "template/{*parameter}")]
    [InlineData("template/{parameter}", "template/{*parameter:int}")]
    [InlineData("template/{parameter}", "template/{*parameter}")]
    [InlineData("template/{*parameter:int}", "template/{*parameter}")]
    [InlineData("template/5", "template/5")]
    [InlineData("template/{parameter:int}", "template/{parameter:int}")]
    [InlineData("template/{parameter}", "template/{parameter}")]
    [InlineData("template/{*parameter:int}", "template/{*parameter:int}")]
    [InlineData("template/{*parameter}", "template/{*parameter}")]
    public virtual async Task Match_SelectEndpoint_BasedOnOrder(string template1, string template2)
    {
        // Arrange
        var expected = CreateEndpoint(template1, order: 0);
        var other = CreateEndpoint(template2, order: 1);
        var path = "/template/5";

        // Arrange
        var matcher = CreateMatcher(other, expected);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, expected, ignoreValues: true);
    }

    [Theory]
    [InlineData("/", "")]
    [InlineData("/Literal1", "Literal1")]
    [InlineData("/Literal1/Literal2", "Literal1/Literal2")]
    [InlineData("/Literal1/Literal2/Literal3", "Literal1/Literal2/Literal3")]
    [InlineData("/Literal1/Literal2/Literal3/4", "Literal1/Literal2/Literal3/{*constrainedCatchAll:int}")]
    [InlineData("/Literal1/Literal2/Literal3/Literal4", "Literal1/Literal2/Literal3/{*catchAll}")]
    [InlineData("/1", "{constrained1:int}")]
    [InlineData("/1/2", "{constrained1:int}/{constrained2:int}")]
    [InlineData("/1/2/3", "{constrained1:int}/{constrained2:int}/{constrained3:int}")]
    [InlineData("/1/2/3/4", "{constrained1:int}/{constrained2:int}/{constrained3:int}/{*constrainedCatchAll:int}")]
    [InlineData("/1/2/3/CatchAll4", "{constrained1:int}/{constrained2:int}/{constrained3:int}/{*catchAll}")]
    [InlineData("/parameter1", "{parameter1}")]
    [InlineData("/parameter1/parameter2", "{parameter1}/{parameter2}")]
    [InlineData("/parameter1/parameter2/parameter3", "{parameter1}/{parameter2}/{parameter3}")]
    [InlineData("/parameter1/parameter2/parameter3/4", "{parameter1}/{parameter2}/{parameter3}/{*constrainedCatchAll:int}")]
    [InlineData("/parameter1/parameter2/parameter3/CatchAll4", "{parameter1}/{parameter2}/{parameter3}/{*catchAll}")]
    public virtual async Task Match_IntegrationTest_MultipleEndpoints(string path, string expectedTemplate)
    {
        // Arrange
        var templates = new[]
        {
                "",
                "Literal1",
                "Literal1/Literal2",
                "Literal1/Literal2/Literal3",
                "Literal1/Literal2/Literal3/{*constrainedCatchAll:int}",
                "Literal1/Literal2/Literal3/{*catchAll}",
                "{constrained1:int}",
                "{constrained1:int}/{constrained2:int}",
                "{constrained1:int}/{constrained2:int}/{constrained3:int}",
                "{constrained1:int}/{constrained2:int}/{constrained3:int}/{*constrainedCatchAll:int}",
                "{constrained1:int}/{constrained2:int}/{constrained3:int}/{*catchAll}",
                "{parameter1}",
                "{parameter1}/{parameter2}",
                "{parameter1}/{parameter2}/{parameter3}",
                "{parameter1}/{parameter2}/{parameter3}/{*constrainedCatchAll:int}",
                "{parameter1}/{parameter2}/{parameter3}/{*catchAll}",
            };

        var endpoints = templates.Select((t) => CreateEndpoint(t)).ToArray();
        var expected = endpoints[Array.IndexOf(templates, expectedTemplate)];

        var matcher = CreateMatcher(endpoints);
        var httpContext = CreateContext(path);

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, expected, ignoreValues: true);
    }

    // https://github.com/dotnet/aspnetcore/issues/16579
    [Fact]
    public virtual async Task Match_Regression_16579_Order1()
    {
        var endpoints = new RouteEndpoint[]
        {
                EndpointFactory.CreateRouteEndpoint(
                    "{controller}/folder/{*path}",
                    order: 0,
                    defaults: new { controller = "File", action = "Folder", },
                    requiredValues: new { controller = "File", }),
                EndpointFactory.CreateRouteEndpoint(
                    "{controller}/{action}/{filename}",
                    order: 1,
                    defaults: new { controller = "File", action = "Index", },
                    requiredValues: new { controller = "File", action = "Index", }),
        };

        var expected = endpoints[0];

        var matcher = CreateMatcher(endpoints);
        var httpContext = CreateContext("/file/folder/abc/abc");

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, expected, ignoreValues: true);
    }

    // https://github.com/dotnet/aspnetcore/issues/16579
    [Fact]
    public virtual async Task Match_Regression_16579_Order2()
    {
        var endpoints = new RouteEndpoint[]
        {
                EndpointFactory.CreateRouteEndpoint(
                    "{controller}/{action}/{filename}",
                    order: 0,
                    defaults: new { controller = "File", action = "Index", },
                    requiredValues: new { controller = "File", action = "Index", }),

                EndpointFactory.CreateRouteEndpoint(
                    "{controller}/folder/{*path}",
                    order: 1,
                    defaults: new { controller = "File", action = "Folder", },
                    requiredValues: new { controller = "File", }),
        };

        var expected = endpoints[1];

        var matcher = CreateMatcher(endpoints);
        var httpContext = CreateContext("/file/folder/abc/abc");

        // Act
        await matcher.MatchAsync(httpContext);

        // Assert
        MatcherAssert.AssertMatch(httpContext, expected, ignoreValues: true);
    }
}


text:
package org.apache.cordova;

import java.io.ByteArrayInputStream;
import java.util.Hashtable;

import org.apache.cordova.CordovaInterface;

import org.apache.cordova.LOG;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.util.Log;
import android.view.View;
//import android.webkit.HttpAuthHandler;
//import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebResourceResponse;
//import android.webkit.WebView;
//import android.webkit.WebViewClient;
import org.chromium.net.NetError;
import org.xwalk.core.XWalkResourceClient;
import org.xwalk.core.XWalkView;

/**
 * This class is the XWalkResourceClient that implements callbacks for our web view.
 * The kind of callbacks that happen here are regarding the rendering of the
 * document instead of the chrome surrounding it, such as onPageStarted(),
 * shouldOverrideUrlLoading(), etc. Related to but different than
 * CordovaChromeClient.
 *
 * @see WebViewClient
 * @see WebView guide
 * @see CordovaChromeClient
 * @see CordovaWebView
 */
public class CordovaWebViewClient extends XWalkResourceClient {

	private static final String TAG = "CordovaWebViewClient";
	private static final String CORDOVA_EXEC_URL_PREFIX = "http://cdv_exec/";
    CordovaInterface cordova;
    CordovaWebView appView;

    // Success
    public static final int ERROR_OK = 0;
    // Generic error
    public static final int ERROR_UNKNOWN = -1;
    // Server or proxy hostname lookup failed
    public static final int ERROR_HOST_LOOKUP = -2;
    // Unsupported authentication scheme (not basic or digest)
    public static final int ERROR_UNSUPPORTED_AUTH_SCHEME = -3;
    // User authentication failed on server
    public static final int ERROR_AUTHENTICATION = -4;
    // User authentication failed on proxy
    public static final int ERROR_PROXY_AUTHENTICATION = -5;
    // Failed to connect to the server
    public static final int ERROR_CONNECT = -6;
    // Failed to read or write to the server
    public static final int ERROR_IO = -7;
    // Connection timed out
    public static final int ERROR_TIMEOUT = -8;
    // Too many redirects
    public static final int ERROR_REDIRECT_LOOP = -9;
    // Unsupported URI scheme
    public static final int ERROR_UNSUPPORTED_SCHEME = -10;
    // Failed to perform SSL handshake
    public static final int ERROR_FAILED_SSL_HANDSHAKE = -11;
    // Malformed URL
    public static final int ERROR_BAD_URL = -12;
    // Generic file error
    public static final int ERROR_FILE = -13;
    // File not found
    public static final int ERROR_FILE_NOT_FOUND = -14;
    // Too many requests during this load
    public static final int ERROR_TOO_MANY_REQUESTS = -15;

    /** The authorization tokens. */
    private Hashtable<String, AuthenticationToken> authenticationTokens = new Hashtable<String, AuthenticationToken>();

    /**
     * Constructor.
     *
     * @param cordova
     */
    public CordovaWebViewClient(CordovaInterface cordova) {
        super(null);
        this.cordova = cordova;
    }

    /**
     * Constructor.
     *
     * @param cordova
     * @param view
     */
    public CordovaWebViewClient(CordovaInterface cordova, CordovaWebView view) {
        super(view);
        this.cordova = cordova;
        this.appView = view;
    }

    /**
     * Constructor.
     *
     * @param view
     */
    public void setWebView(CordovaWebView view) {
        this.appView = view;
    }

    // Parses commands sent by setting the webView's URL to:
    // cdvbrg:service/action/callbackId#jsonArgs
	private void handleExecUrl(String url) {
		int idx1 = CORDOVA_EXEC_URL_PREFIX.length();
		int idx2 = url.indexOf('#', idx1 + 1);
		int idx3 = url.indexOf('#', idx2 + 1);
		int idx4 = url.indexOf('#', idx3 + 1);
		if (idx1 == -1 || idx2 == -1 || idx3 == -1 || idx4 == -1) {
			Log.e(TAG, "Could not decode URL command: " + url);
			return;
		}
		String service    = url.substring(idx1, idx2);
		String action     = url.substring(idx2 + 1, idx3);
		String callbackId = url.substring(idx3 + 1, idx4);
		String jsonArgs   = url.substring(idx4 + 1);
        appView.pluginManager.exec(service, action, callbackId, jsonArgs);
	}

     /**
     * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
     * The errorCode parameter corresponds to one of the ERROR_* constants.
     *
     * @param view          The WebView that is initiating the callback.
     * @param errorCode     The error code corresponding to an ERROR_* value.
     * @param description   A String describing the error.
     * @param failingUrl    The url that failed to load.
     */
    @Override
    public void onReceivedLoadError(XWalkView view, int errorCode, String description,
            String failingUrl) {
        LOG.d(TAG, "CordovaWebViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);

        // Clear timeout flag
        this.appView.loadUrlTimeout++;

        // Handle error
        JSONObject data = new JSONObject();
        try {
            data.put("errorCode", errorCode);
            data.put("description", description);
            data.put("url", failingUrl);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        this.appView.postMessage("onReceivedError", data);
    }

    @Override
    public boolean shouldOverrideUrlLoading(XWalkView view, String url) {
    	// Check if it's an exec() bridge command message.
    	if (NativeToJsMessageQueue.ENABLE_LOCATION_CHANGE_EXEC_MODE && url.startsWith(CORDOVA_EXEC_URL_PREFIX)) {
    		handleExecUrl(url);
    	}

        // Give plugins the chance to handle the url
    	else if ((this.appView.pluginManager != null) && this.appView.pluginManager.onOverrideUrlLoading(url)) {
        }

        // If dialing phone (tel:5551212)
        else if (url.startsWith("tel:")) {
            try {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse(url));
                this.cordova.getActivity().startActivity(intent);
            } catch (android.content.ActivityNotFoundException e) {
                LOG.e(TAG, "Error dialing " + url + ": " + e.toString());
            }
        }

        // If displaying map (geo:0,0?q=address)
        else if (url.startsWith("geo:")) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                this.cordova.getActivity().startActivity(intent);
            } catch (android.content.ActivityNotFoundException e) {
                LOG.e(TAG, "Error showing map " + url + ": " + e.toString());
            }
        }

        // If sending email (mailto:abc@corp.com)
        else if (url.startsWith("mailto:")) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                this.cordova.getActivity().startActivity(intent);
            } catch (android.content.ActivityNotFoundException e) {
                LOG.e(TAG, "Error sending email " + url + ": " + e.toString());
            }
        }

        // If sms:5551212?body=This is the message
        else if (url.startsWith("sms:")) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);

                // Get address
                String address = null;
                int parmIndex = url.indexOf('?');
                if (parmIndex == -1) {
                    address = url.substring(4);
                }
                else {
                    address = url.substring(4, parmIndex);

                    // If body, then set sms body
                    Uri uri = Uri.parse(url);
                    String query = uri.getQuery();
                    if (query != null) {
                        if (query.startsWith("body=")) {
                            intent.putExtra("sms_body", query.substring(5));
                        }
                    }
                }
                intent.setData(Uri.parse("sms:" + address));
                intent.putExtra("address", address);
                intent.setType("vnd.android-dir/mms-sms");
                this.cordova.getActivity().startActivity(intent);
            } catch (android.content.ActivityNotFoundException e) {
                LOG.e(TAG, "Error sending sms " + url + ":" + e.toString());
            }
        }

        //Android Market
        else if(url.startsWith("market:")) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                this.cordova.getActivity().startActivity(intent);
            } catch (android.content.ActivityNotFoundException e) {
                LOG.e(TAG, "Error loading Google Play Store: " + url, e);
            }
        }

        // All else
        else {

            // If our app or file:, then load into a new Cordova webview container by starting a new instance of our activity.
            // Our app continues to run.  When BACK is pressed, our app is redisplayed.
            if (url.startsWith("file://") || url.startsWith("data:")  || Config.isUrlWhiteListed(url)) {
                return false;
            }

            // If not our application, let default viewer handle
            else {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    this.cordova.getActivity().startActivity(intent);
                } catch (android.content.ActivityNotFoundException e) {
                    LOG.e(TAG, "Error loading url " + url, e);
                }
            }
        }
        return true;
    }

    /**
     * Sets the authentication token.
     *
     * @param authenticationToken
     * @param host
     * @param realm
     */
    public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) {
        if (host == null) {
            host = "";
        }
        if (realm == null) {
            realm = "";
        }
        this.authenticationTokens.put(host.concat(realm), authenticationToken);
    }

    /**
     * Removes the authentication token.
     *
     * @param host
     * @param realm
     *
     * @return the authentication token or null if did not exist
     */
    public AuthenticationToken removeAuthenticationToken(String host, String realm) {
        return this.authenticationTokens.remove(host.concat(realm));
    }

    /**
     * Gets the authentication token.
     *
     * In order it tries:
     * 1- host + realm
     * 2- host
     * 3- realm
     * 4- no host, no realm
     *
     * @param host
     * @param realm
     *
     * @return the authentication token
     */
    public AuthenticationToken getAuthenticationToken(String host, String realm) {
        AuthenticationToken token = null;
        token = this.authenticationTokens.get(host.concat(realm));

        if (token == null) {
            // try with just the host
            token = this.authenticationTokens.get(host);

            // Try the realm
            if (token == null) {
                token = this.authenticationTokens.get(realm);
            }

            // if no host found, just query for default
            if (token == null) {
                token = this.authenticationTokens.get("");
            }
        }

        return token;
    }

    /**
     * Clear all authentication tokens.
     */
    public void clearAuthenticationTokens() {
        this.authenticationTokens.clear();
    }

}

redpajama_set_name: RedPajamaGithub


text:
NS_CC_BEGIN

int Device::getDPI()
{
    static int dpi = -1;
    if (dpi == -1)
    {
        dpi = (int)getDPIJNI();
    }
    return dpi;
}

void Device::setAccelerometerEnabled(bool isEnabled)
{
    if (isEnabled)
    {
        enableAccelerometer();
    }
    else
    {
        disableAccelerometer();
    }
}

void Device::setAccelerometerInterval(float interval)
{
	setAccelerometerInterval(interval);
}

NS_CC_END


text:
import os
import tarfile
import mxnet as mx
import numpy as np
from mxnet import gluon

def test_array_dataset():
    X = np.random.uniform(size=(10, 20))
    Y = np.random.uniform(size=(10,))
    dataset = gluon.data.ArrayDataset(X, Y)
    loader = gluon.data.DataLoader(dataset, 2)

    for i, (x, y) in enumerate(loader):
        assert mx.test_utils.almost_equal(x.asnumpy(), X[i*2:(i+1)*2])
        assert mx.test_utils.almost_equal(y.asnumpy(), Y[i*2:(i+1)*2])

def prepare_record():
    if not os.path.isdir("data/test_images"):
        os.makedirs('data/test_images')
    if not os.path.isdir("data/test_images/test_images"):
        gluon.utils.download("http://data.mxnet.io/data/test_images.tar.gz", "data/test_images.tar.gz")
        tarfile.open('data/test_images.tar.gz').extractall('data/test_images/')
    if not os.path.exists('data/test.rec'):
        imgs = os.listdir('data/test_images/test_images')
        record = mx.recordio.MXIndexedRecordIO('data/test.idx', 'data/test.rec', 'w')
        for i, img in enumerate(imgs):
            str_img = open('data/test_images/test_images/'+img, 'rb').read()
            s = mx.recordio.pack((0, i, i, 0), str_img)
            record.write_idx(i, s)
    return 'data/test.rec'

def test_recordimage_dataset():
    recfile = prepare_record()
    dataset = gluon.data.vision.ImageRecordDataset(recfile)
    loader = gluon.data.DataLoader(dataset, 1)

    for i, (x, y) in enumerate(loader):
        assert x.shape[0] == 1 and x.shape[3] == 3
        assert y.asscalar() == i

def test_sampler():
    seq_sampler = gluon.data.SequentialSampler(10)
    assert list(seq_sampler) == list(range(10))
    rand_sampler = gluon.data.RandomSampler(10)
    assert sorted(list(rand_sampler)) == list(range(10))
    seq_batch_keep = gluon.data.BatchSampler(seq_sampler, 3, 'keep')
    assert sum(list(seq_batch_keep), []) == list(range(10))
    seq_batch_discard = gluon.data.BatchSampler(seq_sampler, 3, 'discard')
    assert sum(list(seq_batch_discard), []) == list(range(9))
    rand_batch_keep = gluon.data.BatchSampler(rand_sampler, 3, 'keep')
    assert sorted(sum(list(rand_batch_keep), [])) == list(range(10))

def test_datasets():
    assert len(gluon.data.vision.MNIST(root='data/mnist')) == 60000
    assert len(gluon.data.vision.MNIST(root='data/mnist', train=False)) == 10000
    assert len(gluon.data.vision.FashionMNIST(root='data/fashion-mnist')) == 60000
    assert len(gluon.data.vision.FashionMNIST(root='data/fashion-mnist', train=False)) == 10000
    assert len(gluon.data.vision.CIFAR10(root='data/cifar10')) == 50000
    assert len(gluon.data.vision.CIFAR10(root='data/cifar10', train=False)) == 10000
    assert len(gluon.data.vision.CIFAR100(root='data/cifar100')) == 50000
    assert len(gluon.data.vision.CIFAR100(root='data/cifar100', fine_label=True)) == 50000
    assert len(gluon.data.vision.CIFAR100(root='data/cifar100', train=False)) == 10000

def test_image_folder_dataset():
    prepare_record()
    dataset = gluon.data.vision.ImageFolderDataset('data/test_images')
    assert dataset.synsets == ['test_images']
    assert len(dataset.items) == 16

if __name__ == '__main__':
    import nose
    nose.runmodule()


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(Hopnscotch.Portal.Web.Startup))]

namespace Hopnscotch.Portal.Web
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
package com.qingbo.ginkgo.ygb.base.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.qingbo.ginkgo.ygb.base.entity.BankType;
import com.qingbo.ginkgo.ygb.base.entity.CodeList;
import com.qingbo.ginkgo.ygb.base.entity.StateCity;
import com.qingbo.ginkgo.ygb.base.repository.BankTypeRepository;
import com.qingbo.ginkgo.ygb.base.repository.CodeListRepository;
import com.qingbo.ginkgo.ygb.base.repository.StateCityRepository;
import com.qingbo.ginkgo.ygb.base.service.CodeListService;
import com.qingbo.ginkgo.ygb.common.result.Result;
import com.qingbo.ginkgo.ygb.common.util.ErrorMessage;

@Service("codeListService")
public class CodeListServiceImpl implements CodeListService {
	private List<CodeList> emptyList = new ArrayList<>();
	private ErrorMessage errors = new ErrorMessage("base-error.properties");

	@Autowired private CodeListRepository codeListRepository;
	@Autowired private StateCityRepository stateCityRepository;
	@Autowired private BankTypeRepository bankTypeRepository;

	@Cacheable(value="itemList", key="#type")
	public Result<List<CodeList>> list(String type) {
		if(StringUtils.isBlank(type)) return errors.newFailure("BAS0001", type);

		List<CodeList> list = codeListRepository.findByTypeAndDeletedFalse(type);
		if(list==null || list.size()==0) return Result.newSuccess(emptyList);

		return Result.newSuccess(list);
	}

	@Cacheable(value="itemList", key="#type+'-'+#code")
	public Result<CodeList> item(String type, String code) {
		if(StringUtils.isBlank(type)) return errors.newFailure("BAS0001", type);
		if(StringUtils.isBlank(code)) return errors.newFailure("BAS0002", type, code);

		CodeList codeList = codeListRepository.findByTypeAndCode(type, code);
		if(codeList==null) return errors.newFailure("BAS0003");

		return Result.newSuccess(codeList);
	}

	@Cacheable(value="stateCity", key="states")
	public Result<List<CodeList>> states() {
		List<StateCity> list = stateCityRepository.findByParentCodeNullAndDeletedFalse();
		if(list==null || list.size()==0) return Result.newSuccess(emptyList);

		List<CodeList> codeList = new ArrayList<>(list.size());
		for(StateCity state:list) {
			CodeList item = new CodeList();
			item.setName(state.getName());
			item.setCode(state.getCode());
			codeList.add(item);
		}
		return Result.newSuccess(codeList);
	}

	@Cacheable(value="stateCity", key="'cities-'+#state")
	public Result<List<CodeList>> cities(String state) {
		if(StringUtils.isBlank(state)) return errors.newFailure("BAS0004", state);

		List<StateCity> list = stateCityRepository.findByParentCodeAndDeletedFalse(state);
		if(list==null || list.size()==0) return Result.newSuccess(emptyList);

		List<CodeList> codeList = new ArrayList<>(list.size());
		for(StateCity city:list) {
			CodeList item = new CodeList();
			item.setName(city.getName());
			item.setCode(city.getCode());
			codeList.add(item);
		}
		return Result.newSuccess(codeList);
	}

	@Cacheable(value="stateCity", key="#code")
	public Result<StateCity> stateCity(String code) {
		if(StringUtils.isBlank(code)) return errors.newFailure("BAS0005", code);

		StateCity stateCity = stateCityRepository.findByCode(code);
		if(stateCity==null) return errors.newFailure("BAS0006");

		return Result.newSuccess(stateCity);
	}

	@Cacheable(value="banks", key="banks")
	public Result<List<CodeList>> banks() {
		List<BankType> list = bankTypeRepository.findByDeletedFalse();
		if(list==null || list.size()==0) return Result.newSuccess(emptyList);

		List<CodeList> codeList = new ArrayList<>(list.size());
		for(BankType bank:list) {
			CodeList item = new CodeList();
			item.setName(bank.getName());
			item.setCode(bank.getCode());
			codeList.add(item);
		}
		return Result.newSuccess(codeList);
	}

	@Cacheable(value="banks", key="#code")
	public Result<BankType> bank(String code) {
		if(StringUtils.isBlank(code)) return errors.newFailure("BAS0007", code);

		BankType bankType = bankTypeRepository.findByCode(code);
		if(bankType==null) return errors.newFailure("BAS0008");

		return Result.newSuccess(bankType);
	}

}


text:
dojo.provide("dojo.html.metrics");
dojo.require("dojo.html.layout");

/*  dojo.html.metrics
 *  Methods to help determine font metrics, including things like
 *  how much of a string will fit inside a certain width, what size
 *  something might be if you were to place it in a certain node, etc.
 *
 *  Based partially on a submitted patch by Morris Johns, and work
 *  done with 13th Parallel and f( m ) (the 13th columns and the
 *  unreleased f( m ) layout manager.
 */

//  derived from Morris John's scrollbar measurer.
dojo.html.getScrollbar=function(){
    //  summary
    //  returns the width of a scrollbar.

    //  set up the test nodes.
    var scroll = document.createElement("div");
    scroll.style.width="100px";
    scroll.style.height="100px";
    scroll.style.overflow="scroll";
    scroll.style.position="absolute";
    scroll.style.top="-300px";
    scroll.style.left="0px"

    var test = document.createElement("div");
    test.style.width="400px";
    test.style.height="400px";
    scroll.appendChild(test);
    dojo.body().appendChild(scroll);

    var width=scroll.offsetWidth - scroll.clientWidth;

    dojo.body().removeChild(scroll);
    scroll.removeChild(test);
    scroll=test=null;

    //  we return an object because we may add additional info in the future.
    return { width: width };    //  object
};

//  derived from Morris John's emResized measurer
dojo.html.getFontMeasurements = function(){
    //  summary
    //  Returns an object that has pixel equivilents of standard font size values.
    var heights = {
        '1em':0, '1ex':0, '100%':0, '12pt':0, '16px':0, 'xx-small':0, 'x-small':0,
        'small':0, 'medium':0, 'large':0, 'x-large':0, 'xx-large':0
    };

    if(dojo.render.html.ie){
        //  we do a font-size fix if and only if one isn't applied already.
        //  NOTE: If someone set the fontSize on the HTML Element, this will kill it.
        document.documentElement.style.fontSize="100%";
    }

    //  set up the measuring node.
    var div=document.createElement("div");
    div.style.position="absolute";
    div.style.left="-100px";
    div.style.top="0";
    div.style.width="30px";
    div.style.height="1000em";
    div.style.border="0";
    div.style.margin="0";
    div.style.padding="0";
    div.style.outline="0";
    div.style.lineHeight="1";
    div.style.overflow="hidden";
    dojo.body().appendChild(div);

    //  do the measurements.
    for(var p in heights){
        div.style.fontSize = p;
        heights[p] = Math.round(div.offsetHeight * 12/16) * 16/12 / 1000;
    }

    dojo.body().removeChild(div);
    div = null;
    return heights;     //  object
};

dojo.html._fontMeasurements = null;

dojo.html.getCachedFontMeasurements = function(recalculate){
    if(recalculate || !dojo.html._fontMeasurements){
        dojo.html._fontMeasurements = dojo.html.getFontMeasurements();
    }
    return dojo.html._fontMeasurements;
};

dojo.html.measureFragment = function(/* HTMLElement */node, /* string */html, /* string? */boxType){
    //  summary
    //  get the dimensions of passed node if it were populated with passed html.
    var clone = node.cloneNode(true);
    clone.innerHTML = html;
    node.parentNode.appendChild(clone);
    var ret = dojo.html.getElementBox(clone, boxType);
    node.parentNode.removeChild(clone);
    clone=null;
    return ret; // object
};

//  the following are derived from the 13th Parallel Column script, as
//      reinterpreted by trt.  http://www.13thparallel.org/archive/column-script
//  Original by Dan Pupius and Michael van Ouwerkerk.
dojo.html.getFittedFragment = function(/* HTMLElement */node, /* string */html){
    //  summary
    //  Given html, return the fragment that will fit on one line of passed node.
    function cl(node){
        var element = document.createElement(node.tagName);
        element.id = node.id + "-clone";
        element.className = node.className;
        for (var j = 0; j < node.attributes.length; j++) {
            if (node.attributes[j].specified) {
                if (node.attributes[j].nodeName.toLowerCase() != "style"
                    && node.attributes[j].nodeName.toLowerCase() != "edited"
                    && node.attributes[j].nodeName.toLowerCase() != "contenteditable"
                    && node.attributes[j].nodeName.toLowerCase() != "id"
                    && node.attributes[j].nodeName.toLowerCase() != "class"
                ){
                    element.setAttribute(node.attributes[j].nodeName.toLowerCase(), node.attributes[j].nodeValue);
                }
            }
        }
        return element;
    }
    var height = dojo.html.getFontMeasurements()["16px"];
    var n=cl(node);
    n.style.width=dojo.html.getBorderBox(node).width+"px";
    n.style.height=(height+4)+"px";
    node.parentNode.appendChild(n);
    var rem = dojo.html.fitToElement(n, html);
    var ret = n.innerHTML;
    n.parentNode.removeChild(n);
    return ret;
};

dojo.html.fitToElement = function(/* HTMLElement */node, /* string */html){
    //  summary
    //  will fit as much html as possible into node, and return the unused
    //  portion, with tag corrections.
    function cl(node){
        var element = document.createElement(node.tagName);
        element.id = node.id + "-clone";
        element.className = node.className;
        for (var j = 0; j < node.attributes.length; j++) {
            if (node.attributes[j].specified) {
                if (node.attributes[j].nodeName.toLowerCase() != "style"
                    && node.attributes[j].nodeName.toLowerCase() != "edited"
                    && node.attributes[j].nodeName.toLowerCase() != "contenteditable"
                    && node.attributes[j].nodeName.toLowerCase() != "id"
                    && node.attributes[j].nodeName.toLowerCase() != "class"
                ){
                    element.setAttribute(node.attributes[j].nodeName.toLowerCase(), node.attributes[j].nodeValue);
                }
            }
        }
        return element;
    }

    var clone = cl(node);
    node.parentNode.appendChild(clone);
    var t=dojo.html.getBorderBox(node);
    clone.style.width = t.width+"px";

    var singletons = ["br","img", "hr", "input", "!--"];
    var chop = ["
","
","
","
","

","

"];
    var openTags = [];

    var str = html;
    var i = 0;
    var limit = str.length;
    var add = 0;
    var doLoop = true;
    clone.innerHTML = str;
    while (doLoop) {
        add = Math.round((limit - i) / 2);
        if (add <= 1) doLoop = false;
        i += add;
        clone.innerHTML = str.substr(0, i);
        if (clone.offsetHeight > t.height) {
            limit = i;
            i -= add;
        }
    }
    if (str.substr(0, i) != str) {
        var lastSpace = str.substr(0, i).lastIndexOf(" ");
        var lastNewLine = str.substr(0, i).lastIndexOf("\n");
        var lastGreater = str.substr(0, i).lastIndexOf(">");
        var lastLess = str.substr(0, i).lastIndexOf("<");
        if (lastLess <= lastGreater && lastNewLine == i - 1) i = i;
        else if (lastSpace != -1 && lastSpace > lastGreater && lastGreater > lastLess) i = lastSpace + 1;
        else if (lastLess > lastGreater) i = lastLess;
        else if (lastGreater != -1) i = lastGreater + 1;
    }

    str = str.substr(0, i);
    var ret = html.substr(str.length);  //  get the rest of the passed text.

    var doPush = true;
    var tags = str.split("<");
    tags.shift();
    for (var j = 0; j < tags.length; j++) {
        tags[j] = tags[j].split(">")[0];
        if (tags[j].charAt(tags[j].length - 1) == "/"){ continue; }
        if (tags[j].charAt(0) != "/") {
            for (var k = 0; k < singletons.length; k++) {
                if (tags[j].split(" ")[0].toLowerCase() == singletons[k]){
                    doPush = false;
                }
            }
            if (doPush){
                openTags.push(tags[j]);
            }
            doPush = true;
        } else {
            openTags.pop();
        }
    }

    //  close any open tags and prepend them to ret as well.
    for(var j=0; j<chop.length; j++){
        if(ret.charAt(0) == "\n"){ ret = ret.substr(1); }
        while(ret.indexOf(chop[j]) == 0){
            ret = ret.substr(chop[j].length);
        }
    }

    for(var j=openTags.length-1; j>=0; j--){
        if(str.lastIndexOf(openTags[j]) == (str.length-openTags[j].length-1)){
            str = str.substring(0, str.lastIndexOf(openTags[j]));
        } else {
            str += "</"+openTags[j]+">";
        }
        if(ret.length > 0){
            ret = "<"+openTags[j]+">"+ret;
        }
    }

    for(var j=0; j<chop.length; j++){
        if(ret.charAt(0) == "\n"){ ret = ret.substr(1); }
        while(ret.indexOf(chop[j]) == 0){
            ret = ret.substr(chop[j].length);
        }
    }
    //  push it into the node and pull the temp one.
    node.innerHTML = str;
    clone.parentNode.removeChild(clone);
    clone = null;

    //  return the remainder.
    return ret; //  string
};


text:
CREATE TABLE measurement (
        id INTEGER PRIMARY KEY AUTO_INCREMENT
    ,   batchId INTEGER NOT NULL
    ,   sampleId INTEGER NOT NULL
    ,	t1 DECIMAL(5,2) NOT NULL
    ,	s1 DECIMAL(5,2) NOT NULL
    ,	t2 DECIMAL(5,2) NOT NULL
    ,	s2 DECIMAL(5,2) NOT NULL
    ,	tsRatio DECIMAL(5,2) NOT NULL
	,	CONSTRAINT fk_measurement_batch FOREIGN KEY (batchId) REFERENCES batch(Id)
	,	CONSTRAINT fk_measurement_sample FOREIGN KEY (sampleId) REFERENCES sample(Id)
    )
;

CREATE INDEX idx_measurement_batchId
ON measurement (batchId)
;

CREATE INDEX idx_measurement_sampleId
ON measurement (sampleId)
;


text:
require 'locomotive/liquid/drops/contents'

module Locomotive
  module Liquid
    module Drops

      class AssetCollections < Contents

        def before_method(meth)
          Rails.logger.warn "\n[WARNING] asset_collections is deprecated and will be removed in the next commits. Please, use contents.<slug> instead.\n\n"
          super(meth)
        end

      end

    end
  end
end


text:
<?php

namespace Phamda\CodeGen\Builder\Tests;

use Phamda\CodeGen\Builder\AbstractMethodBuilder;
use Phamda\CodeGen\Functions\FunctionWrap;
use Phamda\Phamda;
use PhpParser\BuilderFactory;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Name;
use PhpParser\Node\Param;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt;

class BasicTestMethodBuilder extends AbstractMethodBuilder
{
    protected $factory;

    public function __construct(FunctionWrap $source)
    {
        parent::__construct($source);
        $this->factory = new BuilderFactory();
    }

    protected function getName()
    {
        return $this->source->getHelperMethodName('test%s');
    }

    protected function createComment()
    {
        return <<<EOT
/**
 * @dataProvider {$this->source->getHelperMethodName('get%sData')}
 */
EOT;
    }

    protected function createParams()
    {
        $convertVariadic = function (Param $param) {
            if ($param->variadic && $this->source->getInnerFunctionParams() !== []) {
                $param->type     = 'array';
                $param->variadic = false;
            }
        };

        $process = Phamda::pipe(
            Phamda::map(Phamda::clone_()),
            Phamda::each($convertVariadic),
            Phamda::prepend($this->factory->param('expected')),
            Phamda::merge(Phamda::_(), $this->source->getInnerFunctionParams())
        );

        return $process($this->source->params);
    }

    protected function createStatements()
    {
        return array_merge($this->createResultTestStatements(), $this->createCurryTestStatements());
    }

    private function createResultTestStatements()
    {
        $statements     = [];
        $function       = null;
        $argumentSource = $this->source->params;

        if ($this->source->returnsCallable()) {
            $call           = $this->createFunctionCall($argumentSource, $function);
            $function       = new Expr\Variable('main0');
            $statements[]   = new Expr\Assign($function, $call);
            $argumentSource = $this->source->getInnerFunctionParams();
        }

        $statements[] = $this->createAssert($this->createFunctionCall($argumentSource, $function), true);

        return $statements;
    }

    private function createCurryTestStatements()
    {
        if (count($this->source->params) === 0 || ! $this->source->isCurried()) {
            return [];
        }

        $result    = new Expr\Variable('result');
        $arguments = $this->source->params;

        if ($this->source->returnsCallable()) {
            $resultExpr = $this->createFunctionCall($this->source->getInnerFunctionParams(), $result);
        } elseif ($this->source->isVariadic()) {
            $resultExpr = $this->createFunctionCall(array_slice($this->source->params, -1), $result);
            $arguments  = array_slice($this->source->params, 0, -1);
        } else {
            $resultExpr = $result;
        }

        $foreach = new Stmt\Foreach_(
            new Expr\MethodCall(new Expr\Variable('this'), 'getCurriedResults', array_merge(
                [$this->createFunctionCall([])],
                $this->createArguments($arguments)
            )),
            $result
        );

        $foreach->stmts = [$this->createAssert($resultExpr, false)];

        return [$foreach];
    }

    private function createAssert(Expr $call, $isDirectCall)
    {
        return new Expr\MethodCall(new Expr\Variable('this'), 'assertSame', [
            new Expr\Variable('expected'),
            $call,
            new String_(sprintf($isDirectCall ? '%s produces correct results.' : '%s is curried correctly.', $this->source->getName())),
        ]);
    }

    private function createFunctionCall(array $argumentSource, Expr\Variable $function = null)
    {
        $arguments = $this->createArguments($argumentSource);

        return $function !== null
            ? new Expr\FuncCall($function, $arguments)
            : new Expr\StaticCall(new Name('P'), $this->source->getName(), $arguments);
    }

    private function createArguments(array $sources)
    {
        $create = function (Param $source) {
            return new Arg(new Expr\Variable($source->name), false, $source->variadic);
        };

        return Phamda::map($create, $sources);
    }
}


text:
"""Mimic pyquick exercise -- optional extra exercise.
Google's Python Class

Read in the file specified on the command line.
Do a simple split() on whitespace to obtain all the words in the file.
Rather than read the file line by line, it's easier to read
it into one giant string and split it once.

Build a "mimic" dict that maps each word that appears in the file
to a list of all the words that immediately follow that word in the file.
The list of words can be be in any order and should include
duplicates. So for example the key "and" might have the list
["then", "best", "then", "after", ...] listing
all the words which came after "and" in the text.
We'll say that the empty string is what comes before
the first word in the file.

With the mimic dict, it's fairly easy to emit random
text that mimics the original. Print a word, then look
up what words might come next and pick one at random as
the next work.
Use the empty string as the first word to prime things.
If we ever get stuck with a word that is not in the dict,
go back to the empty string to keep things moving.

Note: the standard python module 'random' includes a
random.choice(list) method which picks a random element
from a non-empty list.

For fun, feed your program to itself as input.
Could work on getting it to put in linebreaks around 70
columns, so the output looks better.

"""

import random
import sys

def mimic_dict(filename):
    """Returns mimic dict mapping each word to list of words which follow it."""
    # +++your code here+++
    # LAB(begin solution)
    mimic_dict = {}
    f = open(filename, 'r')
    text = f.read()
    f.close()
    words = text.split()
    prev = ''
    for word in words:
        if not prev in mimic_dict:
            mimic_dict[prev] = [word]
        else:
            mimic_dict[prev].append(word)
        # Could write as: mimic_dict[prev] = mimic_dict.get(prev, []) + [word]
        # It's one line, but not totally satisfying.
        prev = word
    return mimic_dict
    # LAB(replace solution)
    # return
    # LAB(end solution)

def print_mimic(mimic_dict, word):
    """Given mimic dict and start word, prints 200 random words."""
    # +++your code here+++
    # LAB(begin solution)
    for unused_i in range(200):
        print(word, end=' ')
        nexts = mimic_dict.get(word)          # Returns None if not found
        if not nexts:
            nexts = mimic_dict['']  # Fallback to '' if not found
        word = random.choice(nexts)
    # The 'unused_' prefix turns off the lint warning about the unused variable.
    # LAB(replace solution)
    # return
    # LAB(end solution)

# Provided main(), calls mimic_dict() and mimic()
def main():
    if len(sys.argv) != 2:
        print('usage: ./mimic.py file-to-read')
        sys.exit(1)

    dict = mimic_dict(sys.argv[1])
    print_mimic(dict, '')

if __name__ == '__main__':
    main()


text:
angular.module('one4all').filter('unsafe', ['$sce', function ($sce) {
    return function (val) {
        return $sce.trustAsHtml(val);
    };
}]);


text:
#include <boost/uuid/uuid_io.hpp>

#include <cmn/agent_cmn.h>
#include <oper/ecmp_load_balance.h>
#include <oper/route_common.h>
#include <oper/peer.h>
#include <oper/nexthop.h>
#include <oper/peer.h>
#include <oper/mirror_table.h>
#include "oper/tunnel_nh.h"

#include <controller/controller_vrf_export.h>
#include <controller/controller_init.h>
#include <controller/controller_export.h>
#include <controller/controller_peer.h>
#include <controller/controller_types.h>

RouteExport::State::State() :
    DBState(), exported_(false), fabric_multicast_exported_(false),
    force_chg_(false), label_(MplsTable::kInvalidLabel), vn_(), sg_list_(),
    tag_list_(), tunnel_type_(TunnelType::INVALID), path_preference_(),
    destination_(), source_(), ecmp_load_balance_(), isid_(0), tunnel_bmap_(0) {
}

bool RouteExport::State::Changed(const AgentRoute *route, const AgentPath *path) const {
    if (exported_ == false)
        return true;

    if (force_chg_ == true)
        return true;

    if (label_ != path->GetActiveLabel())
        return true;

    if (tunnel_type_ != path->tunnel_type()) {
        return true;
    };

    if (vn_ != path->dest_vn_name())
        return true;

    if (sg_list_ != path->sg_list())
        return true;

    if (tag_list_ != path->tag_list())
        return true;

    if (communities_ != path->communities())
        return true;

    if (path_preference_ != path->path_preference())
        return true;

    if(ecmp_load_balance_ != path->ecmp_load_balance())
        return true;

    if (etree_leaf_ != path->etree_leaf())
        return true;

    if (tunnel_bmap_ != path->tunnel_bmap())
        return true;

    return false;
}

void RouteExport::State::Update(const AgentRoute *route, const AgentPath *path) {
    force_chg_ = false;
    label_ = path->GetActiveLabel();
    vn_ = path->dest_vn_name();
    sg_list_ = path->sg_list();
    tag_list_ = path->tag_list();
    communities_ = path->communities();
    tunnel_type_ = path->tunnel_type();
    path_preference_ = path->path_preference();
    ecmp_load_balance_ = path->ecmp_load_balance();
    etree_leaf_ = path->etree_leaf();
    tunnel_bmap_ = path->tunnel_bmap();
}

RouteExport::RouteExport(AgentRouteTable *rt_table):
    rt_table_(rt_table), marked_delete_(false),
    table_delete_ref_(this, rt_table->deleter()) {
    walk_ref_ = rt_table->AllocWalker(
            boost::bind(&RouteExport::DeleteState, this, _1, _2),
            boost::bind(&RouteExport::Walkdone, _1, _2, this));
}

RouteExport::~RouteExport() {
    if (rt_table_) {
        rt_table_->Unregister(id_);
        rt_table_->ReleaseWalker(walk_ref_);
    }
    table_delete_ref_.Reset(NULL);
}

void RouteExport::ManagedDelete() {
    marked_delete_ = true;
}

// Route entry add/change/del notification handler
void RouteExport::Notify(const Agent *agent,
                         AgentXmppChannel *bgp_xmpp_peer,
                         bool associate,
                         Agent::RouteTableType type,
                         DBTablePartBase *partition,
                         DBEntryBase *e) {
    AgentRoute *route = static_cast<AgentRoute *>(e);

    // Primitive checks for non-delete notification
    if (!route->IsDeleted()) {
        // If there is no active BGP peer attached to channel, ignore
        // non-delete notification for this channel
        if (!AgentXmppChannel::IsBgpPeerActive(agent, bgp_xmpp_peer))
            return;

        if (route->GetActivePath()->inactive())
            return;

        // Extract the listener ID of active BGP peer for route table to which
        // this route entry belongs to. Listeners of route table can be active
        // bgp peers as well as decommisioned BGP peers(if they exist). Active
        // and decommisoned BGP peer can co-exist till cleanup timer is fired.
        // During this interval ignore notification for decommisioned bgp peer
        // listener id
        VrfEntry *vrf = route->vrf();
        BgpPeer *bgp_peer = static_cast<BgpPeer *>(bgp_xmpp_peer->
                                                   bgp_peer_id());
        DBTableBase::ListenerId vrf_id = bgp_peer->GetVrfExportListenerId();
        VrfExport::State *vs =
            static_cast<VrfExport::State *>(vrf->GetState(vrf->get_table(),
                                                          vrf_id));
        // If VRF state is not present then listener has not been added.
        // Addition of listener later will result in walk to notify all routes.
        // That in turn will add state as well by calling current routine.
        // Therefore return when empty VRF state is found.
        if (!vs)
            return;

        //Make sure that vrf has been subscribed before route is published.
        if (vs->IsExportable(bgp_xmpp_peer->sequence_number()))
            return;

        // There may be instances when decommisioned peer is not yet
        // unregistered while a new peer is already present. So there will be
        // two notifications. If its for decommisioned peer then ignore the same
        // by checking the listener id with active bgp peer listener id.
        DBTableBase::ListenerId id = vs->rt_export_[route->GetTableType()]->
            GetListenerId();
        if (id != id_)
            return;
    }

    //If channel is no more active, ignore any updates.
    //It may happen that notify is enqueued before channel is removed.
    if (!AgentXmppChannel::IsBgpPeerActive(agent, bgp_xmpp_peer))
        return;

    if (route->is_multicast()) {
        MulticastNotify(bgp_xmpp_peer, associate, partition, e);
    } else {
        UnicastNotify(bgp_xmpp_peer, partition, e, type);
    }
}

void RouteExport::UnicastNotify(AgentXmppChannel *bgp_xmpp_peer,
                                DBTablePartBase *partition, DBEntryBase *e,
                                Agent::RouteTableType type) {
    AgentRoute *route = static_cast<AgentRoute *>(e);
    //TODO Currently BRIDGE notifications are coming because multicast route
    //are installed in same. Once multicast route is shifted to EVPN table
    //then there will be no export from Bridge and check below can be removed.
    if (route->GetTableType() == Agent::BRIDGE)
        return;

    if (route->vrf()->ShouldExportRoute() == false) {
        return;
    }

    AgentRouteTable *table = static_cast<AgentRouteTable *>
        (partition->parent());
    State *state = static_cast<State *>(route->GetState(partition->parent(),
                                                        id_));
    AgentPath *path = NULL;
    path = route->FindLocalVmPortPath();

    std::stringstream path_str;
    if (path && path->peer())
        path_str << path->peer()->GetName();
    else
        path_str << "None";

    if (marked_delete_) {
        //Ignore route updates on delete marked vrf
        goto done;
    }

    if (path && route->vrf()->GetName() == table->agent()->fabric_vrf_name()) {
        if (path->peer() != table->agent()->fabric_rt_export_peer()) {
            path = NULL;
        }

        //Dont export vhost IP path to control-node
        const InetUnicastRouteEntry *inet_rt =
            dynamic_cast<const InetUnicastRouteEntry *>(route);
        if (inet_rt && inet_rt->addr() == table->agent()->router_id()) {
            path = NULL;
        }
    }

    if (!state && route->IsDeleted()) {
        goto done;
    }

    if (state == NULL) {
        state = new State();
        route->SetState(partition->parent(), id_, state);
    }

    if (path && !path->is_local()) {
        if (state->Changed(route, path)) {
            state->Update(route, path);
            VnListType vn_list;
            vn_list.insert(state->vn_);
            state->exported_ =
                AgentXmppChannel::ControllerSendRouteAdd(bgp_xmpp_peer,
                        static_cast<AgentRoute * >(route),
                        path->NexthopIp(table->agent()), vn_list,
                        state->label_, path->GetTunnelBmap(),
                        &path->sg_list(), &path->tag_list(), &path->communities(),
                        type, state->path_preference_,
                        state->ecmp_load_balance_);
        }
    } else {
        if (state->exported_ == true) {
            VnListType vn_list;
            vn_list.insert(state->vn_);
            AgentXmppChannel::ControllerSendRouteDelete(bgp_xmpp_peer,
                    static_cast<AgentRoute *>(route), vn_list,
                    (state->tunnel_type_ == TunnelType::VXLAN ?
                     state->label_ : 0),
                    TunnelType::AllType(), NULL, NULL, NULL,
                    type, state->path_preference_);
            state->exported_ = false;
        }
    }
done:
    if (route->IsDeleted()) {
        if (state) {
            route->ClearState(partition->parent(), id_);
            delete state;
        }
    }
}

static const AgentPath *GetMulticastExportablePath(const Agent *agent,
                                                   const AgentRoute *route) {
    const AgentPath *active_path = route->FindPath(agent->local_vm_peer());
    //OVS peer path
    if (active_path == NULL) {
        const EvpnRouteEntry *evpn_route =
            dynamic_cast<const EvpnRouteEntry *>(route);
        active_path = evpn_route ? evpn_route->FindOvsPath() : NULL;
    }
    //If no loca peer, then look for tor peer as that should also result
    //in export of route.
    if (active_path == NULL)
        active_path = route->FindPath(agent->multicast_tor_peer());
    //Subnet discard
    if (active_path == NULL) {
        const AgentPath *local_path = route->FindPath(agent->local_peer());
        if (local_path && !agent->tor_agent_enabled()) {
            return local_path;
        }
    }

    return active_path;
}

bool RouteExport::MulticastRouteCanDissociate(const AgentRoute *route) {
    bool can_dissociate = route->IsDeleted();
    Agent *agent = static_cast<AgentRouteTable*>(route->get_table())->
        agent();
    const AgentPath *local_path = route->FindPath(agent->local_peer());
    if (local_path && !agent->tor_agent_enabled()) {
        return can_dissociate;
    }
    if (route->is_multicast()) {
        const AgentPath *active_path = GetMulticastExportablePath(agent, route);
        if (active_path == NULL)
            return true;
        const NextHop *nh = active_path ? active_path->ComputeNextHop(agent) : NULL;
        const CompositeNH *cnh = static_cast<const CompositeNH *>(nh);
        if (cnh && cnh->ComponentNHCount() == 0)
            return true;
    }
    return can_dissociate;
}

void RouteExport::SubscribeFabricMulticast(const Agent *agent,
                                           AgentXmppChannel *bgp_xmpp_peer,
                                           AgentRoute *route,
                                           RouteExport::State *state) {
    const AgentPath *active_path = GetMulticastExportablePath(agent, route);
    //Agent running as tor(simulate_evpn_tor) - dont subscribe
    //Route has path with peer OVS_PEER i.e. TOR agent mode - dont subscribe
    //Subscribe condition:
    //first time subscription or force change
    if (!(agent->simulate_evpn_tor()) &&
        (active_path->peer()->GetType() != Peer::OVS_PEER) &&
        ((state->fabric_multicast_exported_ == false) ||
         (state->force_chg_ == true))) {
        //TODO optimize by checking for force_chg? In other cases duplicate
        //request can be filtered.
        if (state->fabric_multicast_exported_ == true) {
            //Unsubscribe before re-sending subscription, this makes sure in any
            //corner case control-node does not see this as a duplicate request.
            AgentXmppChannel::ControllerSendMcastRouteDelete(bgp_xmpp_peer,
                                                             route);
            state->fabric_multicast_exported_ = false;
        }
        //Sending 255.255.255.255 for fabric tree
        state->fabric_multicast_exported_ =
            AgentXmppChannel::ControllerSendMcastRouteAdd(bgp_xmpp_peer,
                                                          route);
    }
}

// Handles subscription of multicast routes.
// Following are the kind of subscription:
// Fabric - For fabric replication tree
// EVPN Ingress replication - For adding compute node in EVPN replication list.
// TOR Ingress replication - For adding in TOR replication list (relevant for
// TSN).
//
// For Tor-agent its a route with tunnel NH and there is no subscription.
void RouteExport::MulticastNotify(AgentXmppChannel *bgp_xmpp_peer,
                                  bool associate,
                                  DBTablePartBase *partition,
                                  DBEntryBase *e) {
    Agent *agent = bgp_xmpp_peer->agent();
    AgentRoute *route = static_cast<AgentRoute *>(e);
    State *state = static_cast<State *>(route->GetState(partition->parent(), id_));
    bool route_can_be_dissociated = MulticastRouteCanDissociate(route);

    if (marked_delete_ && state) {
        route->ClearState(partition->parent(), id_);
        delete state;
        state = NULL;
        return;
    }
    //Handle withdraw for following cases:
    //- Route is not having any active multicast exportable path or is deleted.
    //- associate(false): Bgp Peer has gone down and state needs to be removed.
    if (route_can_be_dissociated || !associate) {
        if (state == NULL) {
            return;
        }

        if (state->fabric_multicast_exported_ == true) {
            AgentXmppChannel::ControllerSendMcastRouteDelete(bgp_xmpp_peer,
                                                             route);
            state->fabric_multicast_exported_ = false;
        }

        if ((state->ingress_replication_exported_ == true)) {
            uint32_t label = state->label_;
            if (route->vrf()->IsPbbVrf()) {
                label = state->isid_;
            }
            state->tunnel_type_ = TunnelType::INVALID;
            AgentXmppChannel::ControllerSendEvpnRouteDelete(bgp_xmpp_peer,
                                                            route,
                                                            state->vn_,
                                                            label,
                                                            state->destination_,
                                                            state->source_,
                                                            TunnelType::AllType());
            state->ingress_replication_exported_ = false;
        }

        route->ClearState(partition->parent(), id_);
        delete state;
        state = NULL;
        return;
    }

    if (marked_delete_) {
        //Ignore route updates on delete marked vrf
        return;
    }

    if (state == NULL) {
        state = new State();
        route->SetState(partition->parent(), id_, state);
    }

    if (route->vrf()->ShouldExportRoute()) {
        SubscribeFabricMulticast(agent, bgp_xmpp_peer, route, state);
    }
    SubscribeIngressReplication(agent, bgp_xmpp_peer, route, state);

    state->force_chg_ = false;
    return;
}

void RouteExport::SubscribeIngressReplication(Agent *agent,
                                              AgentXmppChannel *bgp_xmpp_peer,
                                              AgentRoute *route,
                                              RouteExport::State *state) {
    //Check if bridging mode is enabled for this VN by verifying bridge flag
    //in local peer path.
    bool bridging = false;
    if (route->vrf() && route->vrf()->vn() && route->vrf()->vn()->bridging())
        bridging = true;

    const AgentPath *active_path = GetMulticastExportablePath(agent, route);
    //Sending ff:ff:ff:ff:ff:ff for evpn replication
    TunnelType::Type old_tunnel_type = state->tunnel_type_;
    uint32_t old_label = state->label_;
    TunnelType::Type new_tunnel_type = active_path->tunnel_type();
    uint32_t new_label = active_path->GetActiveLabel();

    //Evaluate if ingress replication subscription needs to be withdrawn.
    //Conditions: Tunnel type changed (VXLAN to MPLS) in turn label change,
    //bridging is disabled/enabled on VN
    if ((state->ingress_replication_exported_ == true) ||
        (state->force_chg_ == true)) {
        bool withdraw = false;
        uint32_t withdraw_label = 0;

        if (old_tunnel_type == TunnelType::VXLAN) {
            if ((new_tunnel_type != TunnelType::VXLAN) ||
                (old_label != new_label)) {
                withdraw_label = old_label;
                withdraw = true;
            }
        } else if (new_tunnel_type == TunnelType::VXLAN) {
            withdraw = true;
        }

        if (route->vrf()->IsPbbVrf()) {
            if (state->isid_ != active_path->vxlan_id()) {
                uint32_t old_isid = state->isid_;
                state->isid_ = active_path->vxlan_id();
                withdraw_label = old_isid;
                withdraw = true;
            } else {
                state->isid_ = active_path->vxlan_id();
            }
        }

        if (bridging == false)
            withdraw = true;

        if (withdraw) {
            AgentXmppChannel::ControllerSendEvpnRouteDelete
                (bgp_xmpp_peer, route, state->vn_, withdraw_label,
                 state->destination_, state->source_,
                 state->tunnel_type_);
            state->ingress_replication_exported_ = false;
        }
    }

    state->isid_ = active_path->vxlan_id();
    //Update state values with new values if there is any change.
    //Also force change same i.e. update.
    if (active_path->tunnel_type() != state->tunnel_type_) {
        state->force_chg_ = true;
        state->tunnel_type_ = active_path->tunnel_type();
    }

    if (active_path->GetActiveLabel() != state->label_) {
        state->force_chg_ = true;
        state->label_ = active_path->GetActiveLabel();
    }

    if (route->vrf()->IsPbbVrf()) {
        if (active_path->vxlan_id() == 0) {
            return;
        }
    }

    //Subcribe if:
    //- Bridging is enabled
    //- First time (ingress_replication_exported is false)
    //- Forced Change
    if (bridging &&
        ((state->ingress_replication_exported_ == false) ||
        (state->force_chg_ == true))) {
        state->label_ = active_path->GetActiveLabel();
        state->vn_ = route->dest_vn_name();
        const TunnelNH *tnh =
            dynamic_cast<const TunnelNH *>(active_path->nexthop());
        if (tnh) {
            state->destination_ = tnh->GetDip()->to_string();
            state->source_ = tnh->GetSip()->to_string();
        }
        SecurityGroupList sg;
        TagList tag;
        state->ingress_replication_exported_ =
            AgentXmppChannel::ControllerSendEvpnRouteAdd
            (bgp_xmpp_peer, route,
             active_path->NexthopIp(agent),
             route->dest_vn_name(), state->label_,
             TunnelType::GetTunnelBmap(state->tunnel_type_),
             &sg, &tag, NULL, state->destination_,
             state->source_, PathPreference());
    }
}

bool RouteExport::DeleteState(DBTablePartBase *partition,
                              DBEntryBase *entry) {
    State *state = static_cast<State *>
                       (entry->GetState(partition->parent(), id_));
    if (state) {
        entry->ClearState(partition->parent(), id_);
        delete state;
    }
    return true;
}

void RouteExport::Walkdone(DBTable::DBTableWalkRef walk_ref,
                           DBTableBase *partition,
                           RouteExport *rt_export) {
    delete rt_export;
}

void RouteExport::Unregister() {
    //Start unregister process
    rt_table_->WalkTable(walk_ref_);
}

RouteExport* RouteExport::Init(AgentRouteTable *table,
                               AgentXmppChannel *bgp_xmpp_peer) {
    RouteExport *rt_export = new RouteExport(table);
    bool associate = true;
    rt_export->id_ = table->Register(boost::bind(&RouteExport::Notify,
                                     rt_export, table->agent(), bgp_xmpp_peer,
                                     associate, table->GetTableType(), _1, _2));
    return rt_export;
}


text:
package com.amazonaws.services.mediapackage.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.mediapackage.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * HlsIngestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class HlsIngestMarshaller {

    private static final MarshallingInfo<List> INGESTENDPOINTS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ingestEndpoints").build();

    private static final HlsIngestMarshaller instance = new HlsIngestMarshaller();

    public static HlsIngestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(HlsIngest hlsIngest, ProtocolMarshaller protocolMarshaller) {

        if (hlsIngest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(hlsIngest.getIngestEndpoints(), INGESTENDPOINTS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<?php
namespace Chamilo\Core\Reporting\Viewer\Rendition\Template\Type;

use Chamilo\Core\Reporting\Viewer\Rendition\Template\TemplateRendition;

/**
 *
 * @author Hans De Bisschop & Magali Gillard
 * @package reporting.viewer
 */
class Html extends TemplateRendition
{
    const FORMAT = 'html';
}


text:
package com.tectonica.jonix.onix3;

import com.tectonica.jonix.common.JPU;
import com.tectonica.jonix.common.OnixElement;
import com.tectonica.jonix.common.codelist.RecordSourceTypes;

import java.io.Serializable;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DO NOT EDIT MANUALLY
 */

/**
 *
Complexity code

 *

 * A code specifying the level of complexity of a text. Mandatory in each occurrence of the <Complexity>
 * composite, and non-repeating.
 *

 *

 *

 * Format
 * Variable length alphanumeric, suggested maximum length 20 characters, according to the code type specified in the
 * <ComplexitySchemeIdentifier> element
 *

 *

 * Reference name
 * <tt><ComplexityCode></tt>
 *

 *

 * Short tag
 * <tt><b078></tt>
 *

 *

 * Cardinality
 * 1
 *

 *

 * Example
 * <tt><ComplexityCode>880L</ComplexityCode></tt>
 *

 *

 *

 * This tag may be included in the following composites:
 *

 *
<{@link Complexity}>

 *

 *

 * Possible placements within ONIX message:
 *

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link DescriptiveDetail} ⯈ {@link Complexity} ⯈
 * {@link ComplexityCode}

 *

 */
public class ComplexityCode implements OnixElement<String>, Serializable {
    private static final long serialVersionUID = 1L;

    public static final String refname = "ComplexityCode";
    public static final String shortname = "b078";

    /////////////////////////////////////////////////////////////////////////////////
    // ATTRIBUTES
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * (type: dt.DateOrDateTime)
     */
    public String datestamp;

    /**
     * (type: dt.NonEmptyString)
     */
    public String sourcename;

    public RecordSourceTypes sourcetype;

    /////////////////////////////////////////////////////////////////////////////////
    // VALUE MEMBER
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * This is the raw content of ComplexityCode. Could be null if {@code exists() == false}. Use {@link #value()}
     * instead if you want to get this as an {@link java.util.Optional}.
     *

     * Raw Format: Variable length alphanumeric, suggested maximum length 20 characters, according to the code type
     * specified in the <ComplexitySchemeIdentifier> element
     *

     * (type: dt.NonEmptyString)
     */
    public String value;

    /**
     * Internal API, use the {@link #value()} method or the {@link #value} field instead
     */
    @Override
    public String _value() {
        return value;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // SERVICES
    /////////////////////////////////////////////////////////////////////////////////

    private final boolean exists;
    public static final ComplexityCode EMPTY = new ComplexityCode();

    public ComplexityCode() {
        exists = false;
    }

    public ComplexityCode(org.w3c.dom.Element element) {
        exists = true;
        datestamp = JPU.getAttribute(element, "datestamp");
        sourcename = JPU.getAttribute(element, "sourcename");
        sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype"));

        value = JPU.getContentAsString(element);
    }

    /**
     * @return whether this tag (<ComplexityCode> or <b078>) is explicitly provided in the ONIX XML
     */
    @Override
    public boolean exists() {
        return exists;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.apache.jmeter.timers (Apache JMeter API)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.apache.jmeter.timers

Interfaces

ModifiableTimer

Timer

Classes

BeanShellTimer

BeanShellTimerBeanInfo

BSFTimer

BSFTimerBeanInfo

ConstantThroughputTimer

ConstantThroughputTimerBeanInfo

ConstantTimer

GaussianRandomTimer

JSR223Timer

JSR223TimerBeanInfo

PoissonRandomTimer

RandomTimer

SyncTimer

SyncTimerBeanInfo

UniformRandomTimer

Enums

ConstantThroughputTimer.Mode


text:
def indentshell(context,allcontent):
    '''
    indentshell indents each line between <shell>...</shell> tags by 12 spaces
    attention: this function only works if:
        1. the shell tag is present once or not at all in allcontent
        2. <shell> must not be at the first position
    :param context:
    :param allcontent: all output up to this time
    :return:
    '''
    try:
        allcontent = str(allcontent)
        left = allcontent.split("<shell>")
        right = left[1].split("</shell>")
        master_bash = right[0]
        master_bash_lines = master_bash.splitlines(True)
        masterbash = ""
        for line in master_bash_lines:
            masterbash += ' '*12+line
        if len(right)==1:
            return str(left[0]+masterbash)
        return str(left[0]+masterbash+right[1])
    except:
        return allcontent


text:
using System;

namespace Facade
{
    public class Rectangle : IShape
    {
        public void Draw()
        {
            Console.WriteLine("Drawing rectangle");
        }
    }
}


text:
using System;
using RegTesting.Contracts.Domain;

namespace RegTesting.Contracts
{
	/// <summary>
	/// Model for a testsystem summary
	/// </summary>
	public class TestsystemSummary
	{
		/// <summary>
		/// The Testsuite
		/// </summary>
		public string TestsuiteName { get; set; }

		/// <summary>
		/// The Testsuite
		/// </summary>
		public int TestsuiteID { get; set; }

		/// <summary>
		/// The Testsystem
		/// </summary>
		public string TestsystemName { get; set; }

		/// <summary>
		/// The Testsystem
		/// </summary>
		public int TestsystemID { get; set; }

		/// <summary>
		/// The Date when the testsystem changed
		/// </summary>
		public DateTime LastChangeDate { get; set; }

		/// <summary>
		/// The Status of the TestsystemStatus
		/// </summary>
		public TestState TestsystemStatus { get; set; }

	}
}


text:
package net.tatans.coeus.SearchOOM;

import com.squareup.haha.perflib.ArrayInstance;
import com.squareup.haha.perflib.ClassInstance;
import com.squareup.haha.perflib.ClassObj;
import com.squareup.haha.perflib.Field;
import com.squareup.haha.perflib.Heap;
import com.squareup.haha.perflib.Instance;
import com.squareup.haha.perflib.Type;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static net.tatans.coeus.SearchOOM.Preconditions.checkNotNull;
import static java.util.Arrays.asList;

public final class HahaHelper {

  private static final Set<String> WRAPPER_TYPES = new HashSet<String>(
      asList(Boolean.class.getName(), Character.class.getName(), Float.class.getName(),
          Double.class.getName(), Byte.class.getName(), Short.class.getName(),
          Integer.class.getName(), Long.class.getName()));

  static String fieldToString(Map.Entry<Field, Object> entry) {
    return fieldToString(entry.getKey(), entry.getValue());
  }

  static String fieldToString(ClassInstance.FieldValue fieldValue) {
    return fieldToString(fieldValue.getField(), fieldValue.getValue());
  }

  static String fieldToString(Field field, Object value) {
    return field.getName() + " = " + value;
  }

  static String threadName(Instance holder) {
    List<ClassInstance.FieldValue> values = classInstanceValues(holder);
    Object nameField = fieldValue(values, "name");
    if (nameField == null) {
      // Sometimes we can't find the String at the expected memory address in the heap dump.
      // See https://github.com/square/leakcanary/issues/417 .
      return "Thread name not available";
    }
    return asString(nameField);
  }

  static boolean extendsThread(ClassObj clazz) {
    boolean extendsThread = false;
    ClassObj parentClass = clazz;
    while (parentClass.getSuperClassObj() != null) {
      if (clazz.getClassName().equals(Thread.class.getName())) {
        extendsThread = true;
        break;
      }
      parentClass = parentClass.getSuperClassObj();
    }
    return extendsThread;
  }

  static String asString(Object stringObject) {
    Instance instance = (Instance) stringObject;
    List<ClassInstance.FieldValue> values = classInstanceValues(instance);

    Integer count = fieldValue(values, "count");
    Object value = fieldValue(values, "value");
    Integer offset;
    ArrayInstance charArray;
    if (isCharArray(value)) {
      charArray = (ArrayInstance) value;
      offset = 0;
      // < API 23
      // As of Marshmallow, substrings no longer share their parent strings' char arrays
      // eliminating the need for String.offset
      // https://android-review.googlesource.com/#/c/83611/
      if (hasField(values, "offset")) {
        offset = fieldValue(values, "offset");
      }
    } else {
      // In M preview 2, the underlying char buffer resides in the heap with ID equaling the
      // String's ID + 16.
      // https://android-review.googlesource.com/#/c/160380/2/android/src/com/android/tools/idea/
      // editors/hprof/descriptors/InstanceFieldDescriptorImpl.java
      // This workaround is only needed for M preview 2, as it has been fixed on the hprof
      // generation end by reintroducing a virtual "value" variable.
      // https://android.googlesource.com/platform/art/+/master/runtime/hprof/hprof.cc#1242
      Heap heap = instance.getHeap();
      Instance inlineInstance = heap.getInstance(instance.getId() + 16);
      if (isCharArray(inlineInstance)) {
        charArray = (ArrayInstance) inlineInstance;
        offset = 0;
      } else {
        throw new UnsupportedOperationException("Could not find char array in " + instance);
      }
    }
    checkNotNull(count, "count");
    checkNotNull(charArray, "charArray");
    checkNotNull(offset, "offset");

    if (count == 0) {
      return "";
    }

    char[] chars = charArray.asCharArray(offset, count);

    return new String(chars);
  }

  public static boolean isPrimitiveWrapper(Object value) {
    if (!(value instanceof ClassInstance)) {
      return false;
    }
    return WRAPPER_TYPES.contains(((ClassInstance) value).getClassObj().getClassName());
  }

  public static boolean isPrimitiveOrWrapperArray(Object value) {
    if (!(value instanceof ArrayInstance)) {
      return false;
    }
    ArrayInstance arrayInstance = (ArrayInstance) value;
    if (arrayInstance.getArrayType() != Type.OBJECT) {
      return true;
    }
    return WRAPPER_TYPES.contains(arrayInstance.getClassObj().getClassName());
  }

  private static boolean isCharArray(Object value) {
    return value instanceof ArrayInstance && ((ArrayInstance) value).getArrayType() == Type.CHAR;
  }

  static List<ClassInstance.FieldValue> classInstanceValues(Instance instance) {
    ClassInstance classInstance = (ClassInstance) instance;
    return classInstance.getValues();
  }

  static <T> T fieldValue(List<ClassInstance.FieldValue> values, String fieldName) {
    for (ClassInstance.FieldValue fieldValue : values) {
      if (fieldValue.getField().getName().equals(fieldName)) {
        //noinspection unchecked
        return (T) fieldValue.getValue();
      }
    }
    throw new IllegalArgumentException("Field " + fieldName + " does not exists");
  }

  static boolean hasField(List<ClassInstance.FieldValue> values, String fieldName) {
    for (ClassInstance.FieldValue fieldValue : values) {
      if (fieldValue.getField().getName().equals(fieldName)) {
        //noinspection unchecked
        return true;
      }
    }
    return false;
  }

  private HahaHelper() {
    throw new AssertionError();
  }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Zap. 15: 283-292 (1900)

#### Original name
Fulminaria mucophila Gobi, 1900

### Remarks
null


text:
using System;
using System.Threading;
using Moq;
using Xunit;

namespace NCode.Disposables.Test
{
  public class DisposableContextTests
  {
    [Fact]
    public void Dispose_Sync()
    {
      var context = new Mock<SynchronizationContext>(MockBehavior.Strict);
      context.Setup(_ => _.Send(It.IsAny<SendOrPostCallback>(), It.IsAny<object>())).Callback((SendOrPostCallback c, object s) => c(s));

      var item = new Mock<IDisposable>(MockBehavior.Strict);
      item.Setup(_ => _.Dispose());

      var disposable = new DisposableContext(item.Object, context.Object);
      disposable.Dispose();

      context.Verify(_ => _.Send(It.IsAny<SendOrPostCallback>(), It.IsAny<object>()), Times.Once);
      item.Verify(_ => _.Dispose(), Times.Once);
    }

    [Fact]
    public void Dispose_Async()
    {
      var context = new Mock<SynchronizationContext>(MockBehavior.Strict);
      context.Setup(_ => _.OperationStarted());
      context.Setup(_ => _.Post(It.IsAny<SendOrPostCallback>(), It.IsAny<object>())).Callback((SendOrPostCallback c, object s) => c(s));
      context.Setup(_ => _.OperationCompleted());

      var item = new Mock<IDisposable>(MockBehavior.Strict);
      item.Setup(_ => _.Dispose());

      var disposable = new DisposableContext(item.Object, context.Object, true);
      disposable.Dispose();

      context.Verify(_ => _.OperationStarted(), Times.Once);
      context.Verify(_ => _.Post(It.IsAny<SendOrPostCallback>(), It.IsAny<object>()), Times.Once);
      context.Verify(_ => _.OperationCompleted(), Times.Once);
      item.Verify(_ => _.Dispose(), Times.Once);
    }

  }
}