text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseConditionalExpression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseConditionalExpression
{
    public partial class UseConditionalExpressionForReturnTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
    {
        internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
            => (new CSharpUseConditionalExpressionForReturnDiagnosticAnalyzer(),
                new CSharpUseConditionalExpressionForReturnCodeFixProvider());

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestOnSimpleReturn()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            return 0;
        }
        else
        {
            return 1;
        }
    }
}",
@"
class C
{
    int M()
    {
        return true ? 0 : 1;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestOnSimpleReturn_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            throw new System.Exception();
        }
        else
        {
            return 1;
        }
    }
}",
@"
class C
{
    int M()
    {
        return true ? throw new System.Exception() : 1;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestOnSimpleReturn_Throw2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            return 0;
        }
        else
        {
            throw new System.Exception();
        }
    }
}",
@"
class C
{
    int M()
    {
        return true ? 0 : throw new System.Exception();
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestNotWithTwoThrows()
        {
            await TestMissingAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            throw new System.Exception();
        }
        else
        {
            throw new System.Exception();
        }
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestNotOnSimpleReturn_Throw1_CSharp6()
        {
            await TestMissingAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            throw new System.Exception();
        }
        else
        {
            return 1;
        }
    }
}", parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)));
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestNotWithSimpleThrow()
        {
            await TestMissingAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            throw;
        }
        else
        {
            return 1;
        }
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestOnSimpleReturnNoBlocks()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        [||]if (true)
            return 0;
        else
            return 1;
    }
}",
@"
class C
{
    int M()
    {
        return true ? 0 : 1;
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestOnSimpleReturnNoBlocks_NotInBlock()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        if (true)
            [||]if (true)
                return 0;
            else
                return 1;
    }
}",
@"
class C
{
    int M()
    {
        if (true)
            return true ? 0 : 1;
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestMissingReturnValue1()
        {
            await TestMissingInRegularAndScriptAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            return 0;
        }
        else
        {
            return;
        }
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestMissingReturnValue1_Throw()
        {
            await TestMissingInRegularAndScriptAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            throw new System.Exception();
        }
        else
        {
            return;
        }
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestMissingReturnValue2()
        {
            await TestMissingInRegularAndScriptAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            return;
        }
        else
        {
            return 1;
        }
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestMissingReturnValue2_Throw()
        {
            await TestMissingInRegularAndScriptAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            return;
        }
        else
        {
            throw new System.Exception();
        }
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestMissingReturnValue3()
        {
            await TestMissingInRegularAndScriptAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            return;
        }
        else
        {
            return;
        }
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestWithNoElseBlockButFollowingReturn()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    void M()
    {
        [||]if (true)
        {
            return 0;
        }

        return 1;
    }
}",
@"
class C
{
    void M()
    {
        return true ? 0 : 1;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestWithNoElseBlockButFollowingReturn_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    void M()
    {
        [||]if (true)
        {
            throw new System.Exception();
        }

        return 1;
    }
}",
@"
class C
{
    void M()
    {
        return true ? throw new System.Exception() : 1;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestWithNoElseBlockButFollowingReturn_Throw2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    void M()
    {
        [||]if (true)
        {
            return 0;
        }

        throw new System.Exception();
    }
}",
@"
class C
{
    void M()
    {
        return true ? 0 : throw new System.Exception();
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestMissingWithoutElse()
        {
            await TestMissingInRegularAndScriptAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            return 0;
        }
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestMissingWithoutElse_Throw()
        {
            await TestMissingInRegularAndScriptAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            throw new System.Exception();
        }
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestConversion1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    object M()
    {
        [||]if (true)
        {
            return ""a"";
        }
        else
        {
            return ""b"";
        }
    }
}",
@"
class C
{
    object M()
    {
        return true ? ""a"" : ""b"";
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44036"), Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestConversion1_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    object M()
    {
        [||]if (true)
        {
            throw new System.Exception();
        }
        else
        {
            return ""b"";
        }
    }
}",
@"
class C
{
    object M()
    {
        return true ? throw new System.Exception() : ""b"";
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44036"), Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestConversion1_Throw2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    object M()
    {
        [||]if (true)
        {
            return ""a"";
        }
        else
        {
            throw new System.Exception();
        }
    }
}",
@"
class C
{
    object M()
    {
        return true ? ""a"" : throw new System.Exception();
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestConversion2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    string M()
    {
        [||]if (true)
        {
            return ""a"";
        }
        else
        {
            return null;
        }
    }
}",
@"
class C
{
    string M()
    {
        return true ? ""a"" : null;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestConversion2_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    string M()
    {
        [||]if (true)
        {
            throw new System.Exception();
        }
        else
        {
            return null;
        }
    }
}",
@"
class C
{
    string M()
    {
        return true ? throw new System.Exception() : (string)null;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestConversion2_Throw2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    string M()
    {
        [||]if (true)
        {
            return ""a"";
        }
        else
        {
            throw new System.Exception();
        }
    }
}",
@"
class C
{
    string M()
    {
        return true ? ""a"" : throw new System.Exception();
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestConversion3()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    string M()
    {
        [||]if (true)
        {
            return null;
        }
        else
        {
            return null;
        }
    }
}",
@"
class C
{
    string M()
    {
        return true ? null : (string)null;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestConversion3_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    string M()
    {
        [||]if (true)
        {
            throw new System.Exception();
        }
        else
        {
            return null;
        }
    }
}",
@"
class C
{
    string M()
    {
        return true ? throw new System.Exception() : (string)null;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestConversion3_Throw2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    string M()
    {
        [||]if (true)
        {
            return null;
        }
        else
        {
            throw new System.Exception();
        }
    }
}",
@"
class C
{
    string M()
    {
        return true ? (string)null : throw new System.Exception();
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestKeepTriviaAroundIf()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        // leading
        [||]if (true)
        {
            return 0;
        }
        else
        {
            return 1;
        } // trailing
    }
}",
@"
class C
{
    int M()
    {
        // leading
        return true ? 0 : 1; // trailing
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestFixAll1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        {|FixAllInDocument:if|} (true)
        {
            return 0;
        }
        else
        {
            return 1;
        }

        if (true)
        {
            return 2;
        }

        return 3;
    }
}",
@"
class C
{
    int M()
    {
        return true ? 0 : 1;

        return true ? 2 : 3;
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestMultiLine1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            return Foo(
                1, 2, 3);
        }
        else
        {
            return 1;
        }
    }
}",
@"
class C
{
    int M()
    {
        return true
            ? Foo(
                1, 2, 3)
            : 1;
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestMultiLine2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            return 0;
        }
        else
        {
            return Foo(
                1, 2, 3);
        }
    }
}",
@"
class C
{
    int M()
    {
        return true
            ? 0
            : Foo(
                1, 2, 3);
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestMultiLine3()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            return Foo(
                1, 2, 3);
        }
        else
        {
            return Foo(
                4, 5, 6);
        }
    }
}",
@"
class C
{
    int M()
    {
        return true
            ? Foo(
                1, 2, 3)
            : Foo(
                4, 5, 6);
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestElseIfWithBlock()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        if (true)
        {
        }
        else [||]if (false)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
}",
@"
class C
{
    int M()
    {
        if (true)
        {
        }
        else
        {
            return false ? 1 : 0;
        }
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestElseIfWithBlock_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        if (true)
        {
        }
        else [||]if (false)
        {
            throw new System.Exception();
        }
        else
        {
            return 0;
        }
    }
}",
@"
class C
{
    int M()
    {
        if (true)
        {
        }
        else
        {
            return false ? throw new System.Exception() : 0;
        }
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestElseIfWithBlock_Throw2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        if (true)
        {
        }
        else [||]if (false)
        {
            return 1;
        }
        else
        {
            throw new System.Exception();
        }
    }
}",
@"
class C
{
    int M()
    {
        if (true)
        {
        }
        else
        {
            return false ? 1 : throw new System.Exception();
        }
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestElseIfWithoutBlock()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        if (true) return 2;
        else [||]if (false) return 1;
        else return 0;
    }
}",
@"
class C
{
    int M()
    {
        if (true) return 2;
        else return false ? 1 : 0;
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestRefReturns1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    ref int M(ref int i, ref int j)
    {
        [||]if (true)
        {
            return ref i;
        }
        else
        {
            return ref j;
        }
    }
}",
@"
class C
{
    ref int M(ref int i, ref int j)
    {
        return ref true ? ref i : ref j;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestRefReturns1_Throw1()
        {
            await TestMissingAsync(
@"
class C
{
    ref int M(ref int i, ref int j)
    {
        [||]if (true)
        {
            throw new System.Exception();
        }
        else
        {
            return ref j;
        }
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestRefReturns1_Throw2()
        {
            await TestMissingAsync(
@"
class C
{
    ref int M(ref int i, ref int j)
    {
        [||]if (true)
        {
            return ref i;
        }
        else
        {
            throw new System.Exception();
        }
    }
}");
        }

        [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestOnYieldReturn()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            yield return 0;
        }
        else
        {
            yield return 1;
        }
    }
}",
@"
class C
{
    int M()
    {
        yield return true ? 0 : 1;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestOnYieldReturn_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            throw new System.Exception();
        }
        else
        {
            yield return 1;
        }
    }
}",
@"
class C
{
    int M()
    {
        yield return true ? throw new System.Exception() : 1;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestOnYieldReturn_Throw2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            yield return 0;
        }
        else
        {
            throw new System.Exception();
        }
    }
}",
@"
class C
{
    int M()
    {
        yield return true ? 0 : throw new System.Exception();
    }
}");
        }

        [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestOnYieldReturn_IEnumerableReturnType()
        {
            await TestInRegularAndScript1Async(
@"
using System.Collections.Generic;

class C
{
    IEnumerable<int> M()
    {
        [||]if (true)
        {
            yield return 0;
        }
        else
        {
            yield return 1;
        }
    }
}",
@"
using System.Collections.Generic;

class C
{
    IEnumerable<int> M()
    {
        yield return true ? 0 : 1;
    }
}");
        }

        [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestNotOnMixedYields()
        {
            await TestMissingAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            yield break;
        }
        else
        {
            yield return 1;
        }
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestNotOnMixedYields_Throw1()
        {
            await TestMissingAsync(
@"
class C
{
    int M()
    {
        [||]if (true)
        {
            yield break;
        }
        else
        {
            throw new System.Exception();
        }
    }
}");
        }

        [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestNotOnMixedYields_IEnumerableReturnType()
        {
            await TestMissingAsync(
@"
using System.Collections.Generic;

class C
{
    IEnumerable<int> M()
    {
        [||]if (true)
        {
            yield break;
        }
        else
        {
            yield return 1;
        }
    }
}");
        }

        [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestNotWithNoElseBlockButFollowingYieldReturn()
        {
            await TestMissingAsync(
@"
class C
{
    void M()
    {
        [||]if (true)
        {
            yield return 0;
        }

        yield return 1;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestWithNoElseBlockButFollowingYieldReturn_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    void M()
    {
        [||]if (true)
        {
            throw new System.Exception();
        }

        yield return 1;
    }
}",

@"
class C
{
    void M()
    {
        yield return true ? throw new System.Exception() : 1;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestNotWithNoElseBlockButFollowingYieldReturn_Throw2()
        {
            await TestMissingAsync(
@"
class C
{
    void M()
    {
        [||]if (true)
        {
            yield return 0;
        }

        throw new System.Exception();
    }
}");
        }

        [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestNotWithNoElseBlockButFollowingYieldReturn_IEnumerableReturnType()
        {
            await TestMissingAsync(
@"
using System.Collections.Generic;

class C
{
    IEnumerable<int> M()
    {
        [||]if (true)
        {
            yield return 0;
        }

        yield return 1;
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    bool M(int a)
    {
        [||]if (a == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}",
@"
class C
{
    bool M(int a)
    {
        return a == 0;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse1_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    bool M(int a)
    {
        [||]if (a == 0)
        {
            throw new System.Exception();
        }
        else
        {
            return false;
        }
    }
}",
@"
class C
{
    bool M(int a)
    {
        return a == 0 ? throw new System.Exception() : false;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse1_Throw2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    bool M(int a)
    {
        [||]if (a == 0)
        {
            return true;
        }
        else
        {
            throw new System.Exception();
        }
    }
}",
@"
class C
{
    bool M(int a)
    {
        return a == 0 ? true : throw new System.Exception();
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    bool M(int a)
    {
        [||]if (a == 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}",
@"
class C
{
    bool M(int a)
    {
        return a != 0;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse2_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    bool M(int a)
    {
        [||]if (a == 0)
        {
            throw new System.Exception();
        }
        else
        {
            return true;
        }
    }
}",
@"
class C
{
    bool M(int a)
    {
        return a == 0 ? throw new System.Exception() : true;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse2_Throw2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    bool M(int a)
    {
        [||]if (a == 0)
        {
            return false;
        }
        else
        {
            throw new System.Exception();
        }
    }
}",
@"
class C
{
    bool M(int a)
    {
        return a == 0 ? false : throw new System.Exception();
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse3()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    bool M(int a)
    {
        [||]if (a == 0)
        {
            return false;
        }

        return true;
    }
}",
@"
class C
{
    bool M(int a)
    {
        return a != 0;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse3_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    bool M(int a)
    {
        [||]if (a == 0)
        {
            throw new System.Exception();
        }

        return true;
    }
}",
@"
class C
{
    bool M(int a)
    {
        return a == 0 ? throw new System.Exception() : true;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse3_Throw2()
        {
            await TestInRegularAndScript1Async(
@"
class C
{
    bool M(int a)
    {
        [||]if (a == 0)
        {
            return false;
        }

        throw new System.Exception();
    }
}",
@"
class C
{
    bool M(int a)
    {
        return a == 0 ? false : throw new System.Exception();
    }
}");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse4()
        {
            await TestInRegularAndScript1Async(
@"
using System.Collections.Generic;

class C
{
    IEnumerable<bool> M(int a)
    {
        [||]if (a == 0)
        {
            yield return false;
        }
        else
        {
            yield return true;
        }
    }
}",
@"
using System.Collections.Generic;

class C
{
    IEnumerable<bool> M(int a)
    {
        yield return a != 0;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse4_Throw1()
        {
            await TestInRegularAndScript1Async(
@"
using System.Collections.Generic;

class C
{
    IEnumerable<bool> M(int a)
    {
        [||]if (a == 0)
        {
            throw new System.Exception();
        }
        else
        {
            yield return true;
        }
    }
}",
@"
using System.Collections.Generic;

class C
{
    IEnumerable<bool> M(int a)
    {
        yield return a == 0 ? throw new System.Exception() : true;
    }
}");
        }

        [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestReturnTrueFalse4_Throw2()
        {
            await TestInRegularAndScript1Async(
@"
using System.Collections.Generic;

class C
{
    IEnumerable<bool> M(int a)
    {
        [||]if (a == 0)
        {
            yield return false;
        }
        else
        {
            throw new System.Exception();
        }
    }
}",
@"
using System.Collections.Generic;

class C
{
    IEnumerable<bool> M(int a)
    {
        yield return a == 0 ? false : throw new System.Exception();
    }
}");
        }

        [WorkItem(36117, "https://github.com/dotnet/roslyn/issues/36117")]
        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)]
        public async Task TestMissingWhenCrossingPreprocessorDirective()
        {
            await TestMissingInRegularAndScriptAsync(
@"
class C
{
    int M()
    {
        bool check = true;
#if true
        [||]if (check)
            return 3;
#endif
        return 2;
    }
}");
        }
    }
}


text:
using System;
using System.Numerics;

namespace Catalan
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int first = 2 * n;
            int second = (n + 1);
            BigInteger factFirst = 1;
            BigInteger factSecond = 1;
            BigInteger factN = 1;
            int i = n;

            while (first > 0)
            {
                factFirst *= first;
                first--;
            }
            while (i > 0)
            {
                factSecond *= second;
                factN *= i;
                second--;
                i--;
            }
            Console.WriteLine(factFirst / (factSecond * factN));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <vector>

#include "TextureLoader.h"
#include "RefCntAutoPtr.hpp"
#include "ObjectBase.hpp"

namespace Diligent
{

/// Implementation of ITextureLoader.
class TextureLoaderImpl final : public ObjectBase<ITextureLoader>
{
public:
    using TBase = ObjectBase<ITextureLoader>;

    TextureLoaderImpl(IReferenceCounters*        pRefCounters,
                      const TextureLoadInfo&     TexLoadInfo,
                      const Uint8*               pData,
                      size_t                     DataSize,
                      RefCntAutoPtr<IDataBlob>&& pDataBlob);

    TextureLoaderImpl(IReferenceCounters*    pRefCounters,
                      const TextureLoadInfo& TexLoadInfo,
                      Image*                 pImage);

    IMPLEMENT_QUERY_INTERFACE_IN_PLACE(IID_TextureLoader, TBase);

    virtual void DILIGENT_CALL_TYPE CreateTexture(IRenderDevice* pDevice,
                                                  ITexture**     ppTexture) override final;

    virtual const TextureDesc& DILIGENT_CALL_TYPE GetTextureDesc() const override final
    {
        return m_TexDesc;
    }

    virtual const TextureSubResData& DILIGENT_CALL_TYPE GetSubresourceData(Uint32 MipLevel,
                                                                           Uint32 ArraySlice) const override final
    {
        const auto Subres = ArraySlice * m_TexDesc.MipLevels + MipLevel;
        VERIFY_EXPR(Subres < m_SubResources.size());
        return m_SubResources[Subres];
    }

private:
    void LoadFromImage(const TextureLoadInfo& TexLoadInfo);
    void LoadFromKTX(const TextureLoadInfo& TexLoadInfo, const Uint8* pData, size_t DataSize);
    void LoadFromDDS(const TextureLoadInfo& TexLoadInfo, const Uint8* pData, size_t DataSize);

private:
    RefCntAutoPtr<IDataBlob> m_pDataBlob;
    RefCntAutoPtr<Image>     m_pImage;

    const std::string m_Name;
    TextureDesc       m_TexDesc;

    std::vector<TextureSubResData>  m_SubResources;
    std::vector<std::vector<Uint8>> m_Mips;
};

} // namespace Diligent


text:
package de.learnlib.testsupport.it.learner;

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

import de.learnlib.api.algorithm.PassiveLearningAlgorithm;
import net.automatalib.automata.fsa.DFA;
import net.automatalib.automata.transducers.MealyMachine;
import net.automatalib.words.Word;

public class PassiveLearnerVariantListImpl<M, I, D> implements PassiveLearnerVariantList<M, I, D> {

    private final List<PassiveLearnerVariant<M, I, D>> learnerVariants = new ArrayList<>();

    public List<PassiveLearnerVariant<M, I, D>> getLearnerVariants() {
        return learnerVariants;
    }

    @Override
    public void addLearnerVariant(String name, PassiveLearningAlgorithm<? extends M, I, D> learner) {
        learnerVariants.add(new PassiveLearnerVariant<>(name, learner));
    }

    public static class DFAPassiveLearnerVariantListImpl<I> extends PassiveLearnerVariantListImpl<DFA<?, I>, I, Boolean>
            implements PassiveLearnerVariantList.DFALearnerVariantList<I> {}

    public static class MealyLearnerVariantListImpl<I, O>
            extends PassiveLearnerVariantListImpl<MealyMachine<?, I, ?, O>, I, Word<O>>
            implements PassiveLearnerVariantList.MealyLearnerVariantList<I, O> {}
}


text:
The ILLUMINATOR Command Line
============================

Illuminator employs a Ruby script wrapper to Instruments, which imposes some order on the somewhat-unreliable Instruments binary and provides other capabilities such as simulator selection and JUnit reporting.

The Basic, Quick-Start Instant-Gratification Command
----------------------------------------------------

Included in the `scripts/` directory is `scripts/automationTests.rb` -- a script that exposes Illuminator's core options on the command line.

```
$ ruby scripts/automationTests.rb  --help
Usage: automationTests.rb [options]
    -a, --appName APPNAME            Name of the app to build / run
    -s, --scheme SCHEME              Build and run specific tests on given workspace scheme
    -d, --hardwareID ID              hardware id of device to run on instead of simulator
    -q, --sdk SDK                    SDK to build against   ::   Defaults to "iphonesimulator"
  ---------------------------------------------------------------------------------
    -x, --entryPoint LABEL           The execution entry point {runTestsByTag, runTestsByName, describe}   ::   Defaults to "runTestsByTag"
    -t, --tags-any TAGSANY           Run tests with any of the given tags
    -o, --tags-all TAGSALL           Run tests with all of the given tags
    -n, --tags-none TAGSNONE         Run tests with none of the given tags
    -i, --implementation IMPL        Device tests implementation
  ---------------------------------------------------------------------------------
    -r, --retest OPTIONS             Immediately retest failed tests with comma-separated options {1x, solo}
    -v, --verbose                    Show verbose output from instruments
    -m, --timeout TIMEOUT            Seconds to wait for instruments tool to start tests   ::   Defaults to "30"
    -w, --random-seed SEED           Randomize test order based on given integer seed
  ---------------------------------------------------------------------------------
    -b, --simDevice DEVICE           Run on given simulated device   ::   Defaults to "iPhone 5"
    -z, --simVersion VERSION         Run on given simulated iOS version   ::   Defaults to "8.2"
    -l, --simLanguage LANGUAGE       Run on given simulated iOS language   ::   Defaults to "en"
  ---------------------------------------------------------------------------------
    -B, --skip-automate              Don't automate; build only   ::   Defaults to "false"
    -f, --skip-build                 Just automate; assume already built   ::   Defaults to "false"
    -e, --skip-set-sim               Assume that simulator has already been chosen and properly reset   ::   Defaults to "false"
    -k, --skip-kill-after            Leave the simulator open after the run   ::   Defaults to "false"
  ---------------------------------------------------------------------------------
    -h, --help                       Show this help message

```

By simply pointing to your top-level Javascript file, this script can serve your needs for testing.

A Better Command-Line Script
----------------------------

Many of the options you want to send to Illuminator will be the same every time.  It would make sense to simply hard-code these values into your own command-line ruby script.

For example, the Illuminator [`smokeTests.rb`](../scripts/smokeTests.rb) script:

```ruby
require File.join(File.expand_path(File.dirname(__FILE__)), 'classes/IlluminatorFramework.rb')
require File.join(File.expand_path(File.dirname(__FILE__)), 'classes/IlluminatorOptions.rb')
require File.join(File.expand_path(File.dirname(__FILE__)), 'classes/XcodeUtils.rb')
require File.join(File.expand_path(File.dirname(__FILE__)), 'classes/HostUtils.rb')

# Change directory to sample app and use that for the workspace
Dir.chdir 'SampleApp/AutomatorSampleApp'
workspace = Dir.pwd

allTestPath = '../../SampleApp/SampleTests/tests/AllTests.js'
allTestPath = HostUtils.realpath(allTestPath)

# Hard-coded options

options = IlluminatorOptions.new
options.xcode.appName = 'AutomatorSampleApp'
options.xcode.scheme = 'AutomatorSampleApp'

options.illuminator.entryPoint = 'runTestsByTag'
options.illuminator.test.tags.any = ['smoke']
options.illuminator.clean.xcode = true
options.illuminator.clean.artifacts = true
options.illuminator.clean.noDelay = true
options.illuminator.task.build = true
options.illuminator.task.automate = true
options.illuminator.task.setSim = true
options.simulator.device = 'iPhone 5'
options.simulator.language = 'en'
options.simulator.killAfter = true

options.instruments.doVerbose = false
options.instruments.timeout = 30

options.javascript.testPath = allTestPath
options.javascript.implementation = 'iPhone'

if XcodeUtils.instance.isXcodeMajorVersion 5
  options.simulator.device = 'iPhone Retina (4-inch)'
end

options.simulator.version = '8.1'
success8 = IlluminatorFramework.runWithOptions options, workspace

options.illuminator.clean.artifacts = false
options.illuminator.task.build = false
options.simulator.version = '7.1'
success7 = IlluminatorFramework.runWithOptions options, workspace

exit 1 unless success7 and success8

```

In short:
1. a `workspace` directory is chosen
2. the options object is created with `IlluminatorOptions.new`
3. the object is filled in with values _(see below)_
4. the framework is run using the options and workspace, with `IlluminatorFramework.runWithOptions options, workspace`
5. the framework returns a result which in turn is passed to the shell

Illuminator Options
--------------------

The following options are defined in Illuminator (assuming `options = IlluminatorOptions.new`).

### Xcode options

#### `options.xcode.project` (string)
The project name to build, available in the directory identified by the `workspace` parameter.  This argument is optional unless you have more than one project in the `workspace` directory.

#### `options.xcode.appName` (string)
The name of the application that will be built by Xcode (and run by Instruments)

#### `options.xcode.sdk` (string)
The SDK that will be used by Xcode.  This defaults to `iphonesimulator` for simulator runs, and `iphoneos` for real hardware runs, so there should be no reason to supply it manually.

#### `options.xcode.scheme` (string)
The scheme to build, corresponding to a scheme in the given Xcode project.

#### `options.xcode.environmentVars` (hash)
A hash of any project-specific environment variables that should be specified on the `xcodebuild` command line.

### Illuminator options

#### `options.illuminator.entryPoint` (string)
The major function that will be performed by Illuminator -- can be one of `runTestsByTag`, `runTestsByName`, `describe`.
* `runTestsByTag` parses the three `.test.tags.*` options (below) to decide which set of tests should be run
* `runTestsByName` uses the `.test.names` option for the list of tests to run
* `describe` simply prints out descriptions of the test environment for documentation or debugging purposes.

#### `options.illuminator.test.randomSeed` (integer)
If provided, Illuminator uses this value as a seed to randomize the order of the test runs.

#### `options.illuminator.test.tags.any` (string array)
Under the `runTestsByTag` entry point, this option specifies that any tests with a tag in this list will be selected to run, unless overridden by one of the other two `.test.tags.*` options.

#### `options.illuminator.test.tags.all` (string array)
Under the `runTestsByTag` entry point, this option specifies that only tests that include _all_ tags in this list will be selected to run.

#### `options.illuminator.test.tags.none` (string array)
Under the `runTestsByTag` entry point, this option specifies that any tests that include _any_ tags in this list will **not** be selected to run.

#### `options.illuminator.test.names` (string array)
Under the `runTestsByName` entry point, this option specifies the list of tests (in order) that should be run.

#### `options.illuminator.test.retest.attempts` (integer)
Under the `runTestsByTag` and `runTestsByName` entry point, this specifies the number of times that failed tests will be re-tested.

#### `options.illuminator.test.retest.solo` (boolean)
When retesting failed tests, this option specifies that they should be run in their own individual Instruments instance, without any other tests.

#### `options.illuminator.clean.xcode` (boolean)
This option specfies that `xcodebuild` should clean the project before building.

#### `options.illuminator.clean.derived` (boolean)
This option specifies that the `DerivedData` directory should be deleted before building.

#### `options.illuminator.clean.artifacts` (boolean)
This option specifies that the entire Illuminator `buildArtifacts` (output) directory should be deleted before building.

#### `options.illuminator.clean.noDelay` (boolean)
This option specifes that the default 3-second command-line countdown (giving you a chance to abort any directory deletions) will be skipped.

#### `options.illuminator.task.build` (boolean)
This option specifies that the Xcode project should be built before automating, even if it has already been built.

#### `options.illuminator.task.automate` (boolean)
This option specifies that the Instruments automation should run.

#### `options.illuminator.task.setSim` (boolean)
This option specifies that Illuminator should select and reset the simulator from the command line.

#### `options.illuminator.task.coverage` (boolean)
This option specifies that `gcovr` should be run after the automation completes, to determine coverage.  This coverage report will only include the last set of tests that ran without crashing.

#### `options.illuminator.hardwareID` (string)
This option specifies that the automation should run on physical hardware, specified by the ID.

### Simulator options

#### `options.simulator.device` (string)
This option selects the simulator device that should be run.

#### `options.simulator.version` (string)
This option selects the iOS version of the simulator.

#### `options.simulator.language` (string)
This option selects the language of the simulator (currently unsupported).

#### `options.simulator.killAfter` (boolean)
This option specifies whether to close the simulator after automation is complete.

### Instruments options

#### `options.instruments.doVerbose` (boolean)
This option specifies whether verbose output (vs pretty output) of Instruments is sent to the console.  Full output of Instruments is logged to disk regardless.

#### `options.instruments.timeout` (integer)
The number of seconds to spend waiting for Instruments to start up and begin executing the Javascript code, before simply killing it and starting again.

#### `options.instruments.attempts` (integer)
The number of times to attempt starting and restarting Instruments before giving up.
> Under Xcode 5, this number needed to be set as high as 30.  No joke.

#### `options.instruments.appLocation` (string)
The location of the compiled application that Instruments will automate.  This option should be specified if you are automating a pre-built binary; otherwise, Illuminator defaults to using the application that it built itself.

### Javascript options

#### `options.javascript.testPath` (string)
The location of the Javascript file containing your top-level entry point.  This file should define (or import) all the tests that you have defined.  The specific tests to run will be determined by the `entryPoint`.

#### `options.javascript.appSpecificConfig` (hash)
A hash of values that will be passed into the Javascript environment, made available under `config.customConfig`.  Yes, **Illuminator can pass structured values directly from Ruby, through Instruments, into Javascript**.

#### `options.javascript.implementation` (string)
The implementation to use when automating.  This should match one of the implementations you defined in your [`AppMap`](AppMap.md).

Using and Extending the Illuminator Argument Parser
---------------------------------------------------

Here is an example of how to mix hard-coded values with Illuminator command-line options, as well as custom command-line options.

```ruby
require File.join(File.expand_path(File.dirname(__FILE__)), 'classes/IlluminatorArgumentParsing.rb')
require File.join(File.expand_path(File.dirname(__FILE__)), 'classes/IlluminatorFramework.rb')
require File.join(File.expand_path(File.dirname(__FILE__)), 'classes/XcodeUtils.rb')
require File.join(File.expand_path(File.dirname(__FILE__)), 'classes/HostUtils.rb')

workspace = Dir.pwd

# Set up the default parser
parserFactory = IlluminatorParserFactory.new

# Prepare the parser.  We will add the switch -g, aka --word-starting-with-g
#   and override -p, aka --ipad to be a simple switch for iPad testing

                       # default values for all the named switches
parserFactory.prepare({"g" => "gundalow", "i" => "myImplementation", "s" => "iPhone", "a" => "My App", "b" => 'iPhone Retina (4-inch)'},
                       # the keys in the output array that will store the values for these command line switches
                      {"g" => "word-starting-with-g", "p" => "do-ipad"},
                       # Custom processing for any switches.  Since we're overriding 'p', we need to nil-out any processing function for it
                      {"p" => nil})
# Add our custom switch, and the replacement switch
parserFactory.addSwitch("g", ["-g", "--word-starting-with-g WORD", "A word starting with G, for fun"])
parserFactory.addSwitch("p", ["-p", "--do-ipad", "Run ipad implementation"])

# build the parser using letters from IlluminatorArgumentParsing plus our custom ones
parser = parserFactory.buildParser({}, "xtondispaE#bzl#fBeky#crvmw#g")

# Now use the parser to get input arguments
options = parser.parse ARGV

options.javascript.testPath = HostUtils.realpath("path/to/my/AllTests.js")

# Storing our custom value in custom javascript config
storage = {}
storage["gWord"] = options.appSpecific["word-starting-with-g"]
options.javascript.appSpecificConfig = storage

# Setting up several settings at once if iPad was specfied##########################################

if options.appSpecific["do-ipad"]
  options.xcode.appName = "My App HD"
  options.xcode.scheme = "iPad"
  options.javascript.implementation = "iPad"
  unless options.simulator.device.start_with? "iPad"
    options.simulator.device = 'iPad'
    if XcodeUtils.instance.isXcodeMajorVersion 6
      options.simulator.device = "iPad 2"
    end
  end
end

# Run it
success = IlluminatorFramework.runWithOptions options, workspace
exit 1 unless success
```

The strangest piece of this code is probably the `"xtondispaE#bzl#fBeky#crvmw#g"`.  This tells the Parser Factor which command line switches to use (by their single-letter code), and the order in which to list them in the help file (`#` indicating separators).

The second-strangest piece of code is probably the `parserFactory.prepare` line.  If you're reading this far, you should [make contact via one of the Help channels listed in the README](../README.md) and ask for help, so that I can improve this documentation based on your questions.  But the comments in [IlluminatorArgumentParsing.rb](../scripts/classes/IlluminatorArgumentParsing.rb) should help somewhat.


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

/*=============================================================================
	BuildPatchChunk.cpp: Implements classes involved with chunks for the build system.
=============================================================================*/

#include "BuildPatchServicesPrivatePCH.h"

// The chunk header magic codeword, for quick checking that the opened file is a chunk file.
#define CHUNK_HEADER_MAGIC		0xB1FE3AA2

// The chunk header version number.
#define CHUNK_HEADER_VERSION	2

/* FSHAHashData implementation
*****************************************************************************/
FSHAHashData::FSHAHashData()
{
	FMemory::Memset(Hash, 0, FSHA1::DigestSize);
}

bool FSHAHashData::operator==(const FSHAHashData& Other) const
{
	return FMemory::Memcmp(Hash, Other.Hash, FSHA1::DigestSize) == 0;
}

bool FSHAHashData::operator!=(const FSHAHashData& Other) const
{
	return !(*this == Other);
}

FString FSHAHashData::ToString() const
{
	return BytesToHex(Hash, FSHA1::DigestSize);
}

bool FSHAHashData::isZero() const
{
	for (const auto& digit : Hash)
	{
		if (digit != 0)
		{
			return false;
		}
	}
	return true;
}

/* FChunkHeader implementation
*****************************************************************************/
FChunkHeader::FChunkHeader()
	: Magic(CHUNK_HEADER_MAGIC)
	, Version(CHUNK_HEADER_VERSION)
	, HashType(HASH_ROLLING)
{

}

const bool FChunkHeader::IsValidMagic() const
{
	return Magic == CHUNK_HEADER_MAGIC;
}

FArchive& operator<<(FArchive& Ar, FChunkHeader& Header)
{
	// The constant sizes for each version of a header struct. Must be updated
	// If new member variables are added the version MUST be bumped and handled properly here,
	// and these values must never change.
	static const uint32 Version1Size = 41;
	static const uint32 Version2Size = 62;
	// Calculate how much space left in the archive for reading data ( will be 0 when writing )
	const int64 ArchiveSizeLeft = Ar.TotalSize() - Ar.Tell();
	// Make sure the archive has enough data to read from, or we are saving instead.
	bool bSuccess = Ar.IsSaving() || (ArchiveSizeLeft >= Version1Size);
	if (bSuccess)
	{
		Ar << Header.Magic
			<< Header.Version
			<< Header.HeaderSize
			<< Header.DataSize
			<< Header.Guid
			<< Header.RollingHash
			<< Header.StoredAs;

		// From version 2, we have a hash type choice. Previous versions default as only rolling
		if (Header.Version >= 2)
		{
			bSuccess = Ar.IsSaving() || (ArchiveSizeLeft >= Version2Size);
			if (bSuccess)
			{
				Ar.Serialize(Header.SHAHash.Hash, FSHA1::DigestSize);
				Ar << Header.HashType;
			}
		}
	}

	// If we had a size error, zero out the header values
	if (!bSuccess)
	{
		Header.Magic = 0;
		Header.Version = 0;
		Header.HeaderSize = 0;
		Header.DataSize = 0;
		Header.Guid.Invalidate();
		Header.RollingHash = 0;
		Header.StoredAs = 0;
	}

	return Ar;
}

/* FChunkFile implementation
*****************************************************************************/
FChunkFile::FChunkFile( const uint32& InReferenceCount, const bool& bInIsFromDisk )
	: bIsFromDisk( bInIsFromDisk )
	, ReferenceCount(InReferenceCount)
{
	LastAccessTime = FPlatformTime::Seconds();
}

void FChunkFile::GetDataLock( uint8** OutChunkData, FChunkHeader** OutChunkHeader )
{
	ThreadLock.Lock();
	if( OutChunkData )
	{
		(*OutChunkData) = ChunkData;
	}
	if( OutChunkHeader )
	{
		(*OutChunkHeader) = &ChunkHeader;
	}
}

void FChunkFile::ReleaseDataLock()
{
	LastAccessTime = FPlatformTime::Seconds();
	ThreadLock.Unlock();
}

const uint32 FChunkFile::GetRefCount() const
{
	return ReferenceCount;
}

uint32 FChunkFile::Dereference()
{
	FScopeLock ScopeLock( &ThreadLock );
	check( ReferenceCount > 0 );
	return --ReferenceCount;
}

const double FChunkFile::GetLastAccessTime() const
{
	return LastAccessTime;
}

#if WITH_BUILDPATCHGENERATION

/* FQueuedChunkWriter implementation
*****************************************************************************/
FChunkWriter::FQueuedChunkWriter::FQueuedChunkWriter()
{
	bMoreChunks = true;
}

FChunkWriter::FQueuedChunkWriter::~FQueuedChunkWriter()
{
	for( auto QueuedIt = ChunkFileQueue.CreateConstIterator(); QueuedIt; ++QueuedIt)
	{
		FChunkFile* ChunkFile = *QueuedIt;
		delete ChunkFile;
	}
	ChunkFileQueue.Empty();
}

bool FChunkWriter::FQueuedChunkWriter::Init()
{
	IFileManager::Get().MakeDirectory( *ChunkDirectory, true );
	return IFileManager::Get().DirectoryExists( *ChunkDirectory );
}

uint32 FChunkWriter::FQueuedChunkWriter::Run()
{
	StatFileCreateTime = StatsCollector->CreateStat(TEXT("Chunk Writer: Create Time"), EStatFormat::Timer);
	StatCheckExistsTime = StatsCollector->CreateStat(TEXT("Chunk Writer: Check Exist Time"), EStatFormat::Timer);
	StatCompressTime = StatsCollector->CreateStat(TEXT("Chunk Writer: Compress Time"), EStatFormat::Timer);
	StatSerlialiseTime = StatsCollector->CreateStat(TEXT("Chunk Writer: Serialise Time"), EStatFormat::Timer);
	StatChunksSaved = StatsCollector->CreateStat(TEXT("Chunk Writer: Num Saved"), EStatFormat::Value);
	StatDataWritten = StatsCollector->CreateStat(TEXT("Chunk Writer: Data Size Written"), EStatFormat::DataSize);
	StatDataWriteSpeed = StatsCollector->CreateStat(TEXT("Chunk Writer: Data Write Speed"), EStatFormat::DataSpeed);
	StatCompressionRatio = StatsCollector->CreateStat(TEXT("Chunk Writer: Compression Ratio"), EStatFormat::Percentage);

	// Loop until there's no more chunks
	while ( ShouldBeRunning() )
	{
		FChunkFile* ChunkFile = GetNextChunk();
		if( ChunkFile != NULL )
		{
			const FGuid& ChunkGuid = ChunkFile->ChunkHeader.Guid;
			const uint64& ChunkHash = ChunkFile->ChunkHeader.RollingHash;
#if SAVE_OLD_CHUNKDATA_FILENAMES
			const FString OldChunkFilename = FBuildPatchUtils::GetChunkOldFilename( ChunkDirectory, ChunkGuid );
#endif
			const FString NewChunkFilename = FBuildPatchUtils::GetChunkNewFilename( EBuildPatchAppManifestVersion::GetLatestVersion(), ChunkDirectory, ChunkGuid, ChunkHash );

			// To be a bit safer, make a few attempts at writing chunks
			int32 RetryCount = 5;
			bool bChunkSaveSuccess = false;
			while ( RetryCount > 0 )
			{
				// Write out chunks
				bChunkSaveSuccess = WriteChunkData( NewChunkFilename, ChunkFile, ChunkGuid );
#if SAVE_OLD_CHUNKDATA_FILENAMES
				bChunkSaveSuccess = bChunkSaveSuccess && WriteChunkData( OldChunkFilename, ChunkFile, ChunkGuid );
#endif
				// Check success
				if( bChunkSaveSuccess )
				{
					RetryCount = 0;
				}
				else
				{
					// Retry after a second if failed
					--RetryCount;
					FPlatformProcess::Sleep( 1.0f );
				}
			}

			// If we really could not save out chunk data successfully, this build will never work, so panic flush logs and then cause a hard error.
			if( !bChunkSaveSuccess )
			{
				GLog->PanicFlushThreadedLogs();
				check( bChunkSaveSuccess );
			}

			// Delete the data memory
			delete ChunkFile;
		}
		double TotalTime = FStatsCollector::CyclesToSeconds(*StatFileCreateTime + *StatSerlialiseTime);
		if(TotalTime > 0.0)
		{
			FStatsCollector::Set(StatDataWriteSpeed, *StatDataWritten / TotalTime);
		}
		FPlatformProcess::Sleep( 0.0f );
	}
	return 0;
}

const bool FChunkWriter::FQueuedChunkWriter::WriteChunkData(const FString& ChunkFilename, FChunkFile* ChunkFile, const FGuid& ChunkGuid)
{
	uint64 TempTimer;
	// Chunks are saved with GUID, so if a file already exists it will never be different.
	// Skip with return true if already exists
	FStatsCollector::AccumulateTimeBegin(TempTimer);
	const int64 ChunkFilesSize = IFileManager::Get().FileSize(*ChunkFilename);
	FStatsCollector::AccumulateTimeEnd(StatCheckExistsTime, TempTimer);
	if(ChunkFilesSize > 0)
	{
		FStatsCollector::AccumulateTimeEnd(StatCheckExistsTime, TempTimer);
		ChunkFileSizesCS.Lock();
		ChunkFileSizes.Add(ChunkGuid, ChunkFilesSize);
		ChunkFileSizesCS.Unlock();
		return true;
	}
	FStatsCollector::AccumulateTimeBegin(TempTimer);
	FArchive* FileOut = IFileManager::Get().CreateFileWriter( *ChunkFilename );
	FStatsCollector::AccumulateTimeEnd(StatFileCreateTime, TempTimer);
	bool bSuccess = FileOut != NULL;
	if( bSuccess )
	{
		// Setup to handle compression
		bool bDataIsCompressed = true;
		uint8* ChunkDataSource = ChunkFile->ChunkData;
		int32 ChunkDataSourceSize = FBuildPatchData::ChunkDataSize;
		TArray< uint8 > TempCompressedData;
		TempCompressedData.Empty( ChunkDataSourceSize );
		TempCompressedData.AddUninitialized( ChunkDataSourceSize );
		int32 CompressedSize = ChunkDataSourceSize;

		// Compressed can increase in size, but the function will return as failure in that case
		// we can allow that to happen since we would not keep larger compressed data anyway.
		FStatsCollector::AccumulateTimeBegin(TempTimer);
		bDataIsCompressed = FCompression::CompressMemory(
			static_cast< ECompressionFlags >( COMPRESS_ZLIB | COMPRESS_BiasMemory ),
			TempCompressedData.GetData(),
			CompressedSize,
			ChunkFile->ChunkData,
			FBuildPatchData::ChunkDataSize );
		FStatsCollector::AccumulateTimeEnd(StatCompressTime, TempTimer);

		// If compression succeeded, set data vars
		if( bDataIsCompressed )
		{
			ChunkDataSource = TempCompressedData.GetData();
			ChunkDataSourceSize = CompressedSize;
		}

		// Setup Header
		FStatsCollector::AccumulateTimeBegin(TempTimer);
		FChunkHeader& Header = ChunkFile->ChunkHeader;
		*FileOut << Header;
		Header.HeaderSize = FileOut->Tell();
		Header.StoredAs = bDataIsCompressed ? FChunkHeader::STORED_COMPRESSED : FChunkHeader::STORED_RAW;
		Header.DataSize = ChunkDataSourceSize;
		Header.HashType = FChunkHeader::HASH_ROLLING;

		// Write out files
		FileOut->Seek(0);
		*FileOut << Header;
		FileOut->Serialize(ChunkDataSource, ChunkDataSourceSize);
		const int64 NewChunkFilesSize = FileOut->TotalSize();
		FileOut->Close();
		FStatsCollector::AccumulateTimeEnd(StatSerlialiseTime, TempTimer);
		FStatsCollector::Accumulate(StatChunksSaved, 1);
		FStatsCollector::Accumulate(StatDataWritten, NewChunkFilesSize);
		FStatsCollector::SetAsPercentage(StatCompressionRatio, 1.0 - (*StatDataWritten / double(*StatChunksSaved * FBuildPatchData::ChunkDataSize)));

		ChunkFileSizesCS.Lock();
		ChunkFileSizes.Add(ChunkGuid, NewChunkFilesSize);
		ChunkFileSizesCS.Unlock();

		bSuccess = !FileOut->GetError();

		delete FileOut;
	}
	// Log errors
	if( !bSuccess )
	{
		GLog->Logf( TEXT( "BuildPatchServices: Error: Could not save out generated chunk file %s" ), *ChunkFilename );
	}
	return bSuccess;
}

const bool FChunkWriter::FQueuedChunkWriter::ShouldBeRunning()
{
	bool rtn;
	MoreChunksCS.Lock();
	rtn = bMoreChunks;
	MoreChunksCS.Unlock();
	rtn = rtn || HasQueuedChunk();
	return rtn;
}

const bool FChunkWriter::FQueuedChunkWriter::HasQueuedChunk()
{
	bool rtn;
	ChunkFileQueueCS.Lock();
	rtn = ChunkFileQueue.Num() > 0;
	ChunkFileQueueCS.Unlock();
	return rtn;
}

const bool FChunkWriter::FQueuedChunkWriter::CanQueueChunk()
{
	bool rtn;
	ChunkFileQueueCS.Lock();
	rtn = ChunkFileQueue.Num() < FBuildPatchData::ChunkQueueSize;
	ChunkFileQueueCS.Unlock();
	return rtn;
}

FChunkFile* FChunkWriter::FQueuedChunkWriter::GetNextChunk()
{
	FChunkFile* rtn = NULL;
	ChunkFileQueueCS.Lock();
	if( ChunkFileQueue.Num() > 0 )
	{
		rtn = ChunkFileQueue.Last();
		ChunkFileQueue.RemoveAt( ChunkFileQueue.Num() - 1 );
	}
	ChunkFileQueueCS.Unlock();
	return rtn;
}

void FChunkWriter::FQueuedChunkWriter::QueueChunk( const uint8* ChunkData, const FGuid& ChunkGuid, const uint64& ChunkHash )
{
	// Create the FChunkFile and copy data
	FChunkFile* NewChunk = new FChunkFile();
	NewChunk->ChunkHeader.Guid = ChunkGuid;
	NewChunk->ChunkHeader.RollingHash = ChunkHash;
	FMemory::Memcpy( NewChunk->ChunkData, ChunkData, FBuildPatchData::ChunkDataSize );
	// Wait until we can fit this chunk in the queue
	while ( !CanQueueChunk() )
	{
		FPlatformProcess::Sleep( 0.0f );
	}
	// Queue the chunk
	ChunkFileQueueCS.Lock();
	ChunkFileQueue.Add( NewChunk );
	ChunkFileQueueCS.Unlock();
}

void FChunkWriter::FQueuedChunkWriter::SetNoMoreChunks()
{
	MoreChunksCS.Lock();
	bMoreChunks = false;
	MoreChunksCS.Unlock();
}

void FChunkWriter::FQueuedChunkWriter::GetChunkFilesizes(TMap<FGuid, int64>& OutChunkFileSizes)
{
	FScopeLock ScopeLock(&ChunkFileSizesCS);
	OutChunkFileSizes.Append(ChunkFileSizes);
}

/* FChunkWriter implementation
*****************************************************************************/
FChunkWriter::FChunkWriter(const FString& ChunkDirectory, FStatsCollectorRef StatsCollector)
{
	QueuedChunkWriter.ChunkDirectory = ChunkDirectory;
	QueuedChunkWriter.StatsCollector = StatsCollector;
	WriterThread = FRunnableThread::Create(&QueuedChunkWriter, TEXT("QueuedChunkWriterThread"));
}

FChunkWriter::~FChunkWriter()
{
	if( WriterThread != NULL )
	{
		delete WriterThread;
		WriterThread = NULL;
	}
}

void FChunkWriter::QueueChunk( const uint8* ChunkData, const FGuid& ChunkGuid, const uint64& ChunkHash )
{
	QueuedChunkWriter.QueueChunk( ChunkData, ChunkGuid, ChunkHash);
}

void FChunkWriter::NoMoreChunks()
{
	QueuedChunkWriter.SetNoMoreChunks();
}

void FChunkWriter::WaitForThread()
{
	if( WriterThread != NULL )
	{
		WriterThread->WaitForCompletion();
	}
}

void FChunkWriter::GetChunkFilesizes(TMap<FGuid, int64>& OutChunkFileSizes)
{
	QueuedChunkWriter.GetChunkFilesizes(OutChunkFileSizes);
}

#endif // WITH_BUILDPATCHGENERATION


text:
import unittest
from calendar import timegm
from datetime import datetime, timedelta
import time

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from django import get_version
from django.test import TestCase
from django.test.utils import override_settings
from rest_framework import status
from rest_framework.test import APIClient

from rest_framework_jwt import utils, views
from rest_framework_jwt.compat import get_user_model
from rest_framework_jwt.settings import api_settings, DEFAULTS

from . import utils as test_utils

User = get_user_model()

NO_CUSTOM_USER_MODEL = 'Custom User Model only supported after Django 1.5'

orig_datetime = datetime

class BaseTestCase(TestCase):

    def setUp(self):
        self.email = 'jpueblo@example.com'
        self.username = 'jpueblo'
        self.password = 'password'
        self.user = User.objects.create_user(
            self.username, self.email, self.password)

        self.data = {
            'username': self.username,
            'password': self.password
        }

class TestCustomResponsePayload(BaseTestCase):

    def setUp(self):
        self.original_handler = views.jwt_response_payload_handler
        views.jwt_response_payload_handler = test_utils\
            .jwt_response_payload_handler
        return super(TestCustomResponsePayload, self).setUp()

    def test_jwt_login_custom_response_json(self):
        """
        Ensure JWT login view using JSON POST works.
        """
        client = APIClient(enforce_csrf_checks=True)

        response = client.post('/auth-token/', self.data, format='json')

        decoded_payload = utils.jwt_decode_handler(response.data['token'])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(decoded_payload['username'], self.username)
        self.assertEqual(response.data['user'], self.username)

    def tearDown(self):
        views.jwt_response_payload_handler = self.original_handler

class ObtainJSONWebTokenTests(BaseTestCase):

    def test_jwt_login_json(self):
        """
        Ensure JWT login view using JSON POST works.
        """
        client = APIClient(enforce_csrf_checks=True)

        response = client.post('/auth-token/', self.data, format='json')

        decoded_payload = utils.jwt_decode_handler(response.data['token'])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(decoded_payload['username'], self.username)

    def test_jwt_login_json_bad_creds(self):
        """
        Ensure JWT login view using JSON POST fails
        if bad credentials are used.
        """
        client = APIClient(enforce_csrf_checks=True)

        self.data['password'] = 'wrong'
        response = client.post('/auth-token/', self.data, format='json')

        self.assertEqual(response.status_code, 400)

    def test_jwt_login_json_missing_fields(self):
        """
        Ensure JWT login view using JSON POST fails if missing fields.
        """
        client = APIClient(enforce_csrf_checks=True)

        response = client.post('/auth-token/',
                               {'username': self.username}, format='json')

        self.assertEqual(response.status_code, 400)

    def test_jwt_login_form(self):
        """
        Ensure JWT login view using form POST works.
        """
        client = APIClient(enforce_csrf_checks=True)

        response = client.post('/auth-token/', self.data)

        decoded_payload = utils.jwt_decode_handler(response.data['token'])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(decoded_payload['username'], self.username)

    def test_jwt_login_with_expired_token(self):
        """
        Ensure JWT login view works even if expired token is provided
        """
        payload = utils.jwt_payload_handler(self.user)
        payload['exp'] = 1
        token = utils.jwt_encode_handler(payload)

        auth = 'JWT {0}'.format(token)
        client = APIClient(enforce_csrf_checks=True)
        response = client.post(
            '/auth-token/', self.data,
            HTTP_AUTHORIZATION=auth, format='json')

        decoded_payload = utils.jwt_decode_handler(response.data['token'])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(decoded_payload['username'], self.username)

    def test_jwt_login_using_zero(self):
        """
        Test to reproduce issue #33
        """
        client = APIClient(enforce_csrf_checks=True)

        data = {
            'username': '0',
            'password': '0'
        }

        response = client.post('/auth-token/', data, format='json')

        self.assertEqual(response.status_code, 400)

@unittest.skipIf(get_version() < '1.5.0', 'No Configurable User model feature')
@override_settings(AUTH_USER_MODEL='tests.CustomUser')
class CustomUserObtainJSONWebTokenTests(TestCase):
    """JSON Web Token Authentication"""

    def setUp(self):
        from .models import CustomUser

        self.email = 'jpueblo@example.com'
        self.password = 'password'
        user = CustomUser.objects.create(email=self.email)
        user.set_password(self.password)
        user.save()
        self.user = user

        self.data = {
            'email': self.email,
            'password': self.password
        }

    def test_jwt_login_json(self):
        """
        Ensure JWT login view using JSON POST works.
        """
        client = APIClient(enforce_csrf_checks=True)

        response = client.post('/auth-token/', self.data, format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        decoded_payload = utils.jwt_decode_handler(response.data['token'])
        self.assertEqual(decoded_payload['email'], self.email)

    def test_jwt_login_json_bad_creds(self):
        """
        Ensure JWT login view using JSON POST fails
        if bad credentials are used.
        """
        client = APIClient(enforce_csrf_checks=True)

        self.data['password'] = 'wrong'
        response = client.post('/auth-token/', self.data, format='json')

        self.assertEqual(response.status_code, 400)

@override_settings(AUTH_USER_MODEL='tests.CustomUserUUID')
class CustomUserUUIDObtainJSONWebTokenTests(TestCase):
    """JSON Web Token Authentication"""

    def setUp(self):
        from .models import CustomUserUUID

        self.email = 'jpueblo@example.com'
        self.password = 'password'
        user = CustomUserUUID.objects.create(email=self.email)
        user.set_password(self.password)
        user.save()
        self.user = user

        self.data = {
            'email': self.email,
            'password': self.password
        }

    def test_jwt_login_json(self):
        """
        Ensure JWT login view using JSON POST works.
        """
        client = APIClient(enforce_csrf_checks=True)

        response = client.post('/auth-token/', self.data, format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        decoded_payload = utils.jwt_decode_handler(response.data['token'])
        self.assertEqual(decoded_payload['user_id'], str(self.user.id))

    def test_jwt_login_json_bad_creds(self):
        """
        Ensure JWT login view using JSON POST fails
        if bad credentials are used.
        """
        client = APIClient(enforce_csrf_checks=True)

        self.data['password'] = 'wrong'
        response = client.post('/auth-token/', self.data, format='json')

        self.assertEqual(response.status_code, 400)

class TokenTestCase(BaseTestCase):
    """
    Handlers for getting tokens from the API, or creating arbitrary ones.
    """

    def setUp(self):
        super(TokenTestCase, self).setUp()

    def get_token(self):
        client = APIClient(enforce_csrf_checks=True)
        response = client.post('/auth-token/', self.data, format='json')
        return response.data['token']

    def create_token(self, user, exp=None, orig_iat=None):
        payload = utils.jwt_payload_handler(user)
        if exp:
            payload['exp'] = exp

        if orig_iat:
            payload['orig_iat'] = timegm(orig_iat.utctimetuple())

        token = utils.jwt_encode_handler(payload)
        return token

class VerifyJSONWebTokenTestsSymmetric(TokenTestCase):

    def test_verify_jwt(self):
        """
        Test that a valid, non-expired token will return a 200 response
        and itself when passed to the validation endpoint.
        """
        client = APIClient(enforce_csrf_checks=True)
        orig_token = self.get_token()

        # Now try to get a refreshed token
        response = client.post('/auth-token-verify/', {'token': orig_token},
                               format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(response.data['token'], orig_token)

    def test_verify_jwt_fails_with_expired_token(self):
        """
        Test that an expired token will fail with the correct error.
        """
        client = APIClient(enforce_csrf_checks=True)

        # Make an expired token..
        token = self.create_token(
            self.user,
            exp=datetime.utcnow() - timedelta(seconds=5),
            orig_iat=datetime.utcnow() - timedelta(hours=1)
        )

        response = client.post('/auth-token-verify/', {'token': token},
                               format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertRegexpMatches(response.data['non_field_errors'][0],
                                 'Signature has expired')

    def test_verify_jwt_fails_with_bad_token(self):
        """
        Test that an invalid token will fail with the correct error.
        """
        client = APIClient(enforce_csrf_checks=True)

        token = "i am not a correctly formed token"

        response = client.post('/auth-token-verify/', {'token': token},
                               format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertRegexpMatches(response.data['non_field_errors'][0],
                                 'Error decoding signature')

    def test_verify_jwt_fails_with_missing_user(self):
        """
        Test that an invalid token will fail with a user that does not exist.
        """
        client = APIClient(enforce_csrf_checks=True)

        user = User.objects.create_user(
            email='jsmith@example.com', username='jsmith', password='password')

        token = self.create_token(user)
        # Delete the user used to make the token
        user.delete()

        response = client.post('/auth-token-verify/', {'token': token},
                               format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertRegexpMatches(response.data['non_field_errors'][0],
                                 "User doesn't exist")

class VerifyJSONWebTokenTestsAsymmetric(TokenTestCase):

    def setUp(self):

        super(VerifyJSONWebTokenTestsAsymmetric, self).setUp()

        private_key = rsa.generate_private_key(public_exponent=65537,
                                               key_size=2048,
                                               backend=default_backend())
        public_key = private_key.public_key()

        api_settings.JWT_PRIVATE_KEY = private_key
        api_settings.JWT_PUBLIC_KEY = public_key
        api_settings.JWT_ALGORITHM = 'RS512'

    def test_verify_jwt_with_pub_pvt_key(self):
        """
        Test that a token can be signed with asymmetrics keys
        """
        client = APIClient(enforce_csrf_checks=True)

        orig_token = self.get_token()

        # Now try to get a refreshed token
        response = client.post('/auth-token-verify/', {'token': orig_token},
                               format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['token'], orig_token)

    def test_verify_jwt_fails_with_expired_token(self):
        """
        Test that an expired token will fail with the correct error.
        """
        client = APIClient(enforce_csrf_checks=True)

        # Make an expired token..
        token = self.create_token(
            self.user,
            exp=datetime.utcnow() - timedelta(seconds=5),
            orig_iat=datetime.utcnow() - timedelta(hours=1)
        )

        response = client.post('/auth-token-verify/', {'token': token},
                               format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertRegexpMatches(response.data['non_field_errors'][0],
                                 'Signature has expired')

    def test_verify_jwt_fails_with_bad_token(self):
        """
        Test that an invalid token will fail with the correct error.
        """

        client = APIClient(enforce_csrf_checks=True)

        token = "i am not a correctly formed token"

        response = client.post('/auth-token-verify/', {'token': token},
                               format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertRegexpMatches(response.data['non_field_errors'][0],
                                 'Error decoding signature')

    def test_verify_jwt_fails_with_bad_pvt_key(self):
        """
        Test that an mismatched private key token will fail with
        the correct error.
        """

        # Generate a new private key
        private_key = rsa.generate_private_key(public_exponent=65537,
                                               key_size=2048,
                                               backend=default_backend())

        # Don't set the private key
        api_settings.JWT_PRIVATE_KEY = private_key

        client = APIClient(enforce_csrf_checks=True)
        orig_token = self.get_token()

        # Now try to get a refreshed token
        response = client.post('/auth-token-verify/', {'token': orig_token},
                               format='json')

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertRegexpMatches(response.data['non_field_errors'][0],
                                 'Error decoding signature')

    def tearDown(self):
        # Restore original settings
        api_settings.JWT_ALGORITHM = DEFAULTS['JWT_ALGORITHM']
        api_settings.JWT_PRIVATE_KEY = DEFAULTS['JWT_PRIVATE_KEY']
        api_settings.JWT_PUBLIC_KEY = DEFAULTS['JWT_PUBLIC_KEY']

class RefreshJSONWebTokenTests(TokenTestCase):

    def setUp(self):
        super(RefreshJSONWebTokenTests, self).setUp()
        api_settings.JWT_ALLOW_REFRESH = True

    def test_refresh_jwt(self):
        """
        Test getting a refreshed token from original token works

        No date/time modifications are neccessary because it is assumed
        that this operation will take less than 300 seconds.
        """
        client = APIClient(enforce_csrf_checks=True)
        orig_token = self.get_token()
        orig_token_decoded = utils.jwt_decode_handler(orig_token)

        expected_orig_iat = timegm(datetime.utcnow().utctimetuple())

        # Make sure 'orig_iat' exists and is the current time (give some slack)
        orig_iat = orig_token_decoded['orig_iat']
        self.assertLessEqual(orig_iat - expected_orig_iat, 1)

        time.sleep(1)

        # Now try to get a refreshed token
        response = client.post('/auth-token-refresh/', {'token': orig_token},
                               format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        new_token = response.data['token']
        new_token_decoded = utils.jwt_decode_handler(new_token)

        # Make sure 'orig_iat' on the new token is same as original
        self.assertEquals(new_token_decoded['orig_iat'], orig_iat)
        self.assertGreater(new_token_decoded['exp'], orig_token_decoded['exp'])

    def test_refresh_jwt_after_refresh_expiration(self):
        """
        Test that token can't be refreshed after token refresh limit
        """
        client = APIClient(enforce_csrf_checks=True)

        orig_iat = (datetime.utcnow() - api_settings.JWT_REFRESH_EXPIRATION_DELTA -
                    timedelta(seconds=5))
        token = self.create_token(
            self.user,
            exp=datetime.utcnow() + timedelta(hours=1),
            orig_iat=orig_iat
        )

        response = client.post('/auth-token-refresh/', {'token': token},
                               format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.data['non_field_errors'][0],
                         'Refresh has expired.')

    def tearDown(self):
        # Restore original settings
        api_settings.JWT_ALLOW_REFRESH = DEFAULTS['JWT_ALLOW_REFRESH']


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.PatternMatching
{
    internal sealed partial class PatternMatcher : IDisposable
    {
        /// <summary>
        /// Encapsulated matches responsible for mathcing an all lowercase pattern against
        /// a candidate using CamelCase matching. i.e. this code is responsible for finding the
        /// match between "cofipro" and "CodeFixProvider".
        /// </summary>
        private struct AllLowerCamelCaseMatcher
        {
            private readonly string _candidate;
            private readonly bool _includeMatchedSpans;
            private readonly StringBreaks _candidateHumps;
            private readonly TextChunk _patternChunk;
            private readonly string _patternText;

            public AllLowerCamelCaseMatcher(string candidate, bool includeMatchedSpans, StringBreaks candidateHumps, TextChunk patternChunk)
            {
                _candidate = candidate;
                _includeMatchedSpans = includeMatchedSpans;
                _candidateHumps = candidateHumps;
                _patternChunk = patternChunk;
                _patternText = _patternChunk.Text;
            }

            /// <summary>
            /// Returns null if no match was found, 1 if a contiguous match was found, 2 if a
            /// match as found that starts at the beginning of the candidate, and 3 if a continguous
            /// match was found that starts at the beginning of the candidate.
            /// </summary>
            public int? TryMatch(out List<TextSpan> matchedSpans)
            {
                // We have something like cofipro and we want to match CodeFixProvider.
                //
                // Note that this is incredibly ambiguous.  We'd also want this to match
                // CorporateOfficePartsRoom So, for example, if we were to consume the "co"
                // as matching "Corporate", then "f" wouldn't match any camel hump.  So we
                // basically have to branch out and try all options at every character
                // in the pattern chunk.

                var patternIndex = 0;
                var candidateHumpIndex = 0;

                var (bestWeight, localMatchedSpans) = TryMatch(
                   patternIndex, candidateHumpIndex, contiguous: null);

                matchedSpans = localMatchedSpans;
                return bestWeight;
            }

            private (int? bestWeight, List<TextSpan> matchedSpans) TryMatch(
                int patternIndex, int candidateHumpIndex, bool? contiguous)
            {
                if (patternIndex == _patternText.Length)
                {
                    // We hit the end.  So we were able to match against this candidate.
                    return (bestWeight: contiguous == false ? 0 : CamelCaseContiguousBonus,
                            matchedSpans: _includeMatchedSpans ? new List<TextSpan>() : null);
                }

                var bestWeight = default(int?);
                var bestMatchedSpans = default(List<TextSpan>);

                // Look for a hump in the candidate that matches the current letter we're on.
                var patternCharacter = _patternText[patternIndex];
                for (var humpIndex = candidateHumpIndex; humpIndex < _candidateHumps.Count; humpIndex++)
                {
                    // If we've been contiguous, but we jumped past a hump, then we're no longer contiguous.
                    if (contiguous.HasValue && contiguous.Value)
                    {
                        contiguous = humpIndex == candidateHumpIndex;
                    }

                    var candidateHump = _candidateHumps[humpIndex];
                    if (char.ToLower(_candidate[candidateHump.Start]) == patternCharacter)
                    {
                        // Found a hump in the candidate string that matches the current pattern
                        // character we're on.  i.e. we matched the c in cofipro against the C in
                        // CodeFixProvider.
                        //
                        // Now, for each subsequent character, we need to both try to consume it
                        // as part of the current hump, or see if it should match the next hump.
                        //
                        // Note, if the candidate is something like CodeFixProvider and our pattern
                        // is cofipro, and we've matched the 'f' against the 'F', then the max of
                        // the pattern we'll want to consume is "fip" against "Fix".  We don't want
                        // consume parts of the pattern once we reach the next hump.

                        // We matched something.  If this was our first match, consider ourselves
                        // contiguous.
                        if (contiguous == null)
                        {
                            contiguous = true;
                        }

                        var (weight, matchedSpans) = TryConsumePatternOrMatchNextHump(
                            patternIndex, humpIndex, contiguous.Value);
                        if (weight == null)
                        {
                            // Even though we matched this current candidate hump we failed to match
                            // the remainder of the pattern.  Continue to the next candidate hump
                            // to see if our pattern character will match it and potentially succed.
                            continue;
                        }

                        Debug.Assert(weight >= 0);
                        if (weight == CamelCaseMaxWeight)
                        {
                            // We found a path that allowed us to match everything contiguously
                            // from the beginning.  This is the best match possible.  So we can
                            // just stop now and return this result.
                            return (weight, matchedSpans);
                        }

                        // This is a decent match.  But something else could beat it, store
                        // it if it's the best match we have so far, but keep searching.
                        if (bestWeight == null || weight > bestWeight)
                        {
                            bestWeight = weight;
                            bestMatchedSpans = matchedSpans;
                        }
                    }
                }

                return (bestWeight, bestMatchedSpans);
            }

            private (int? bestWeight, List<TextSpan> matchedSpans) TryConsumePatternOrMatchNextHump(
                int patternIndex, int humpIndex, bool contiguous)
            {
                var bestWeight = default(int?);
                var bestMatchedSpans = default(List<TextSpan>);

                var candidateHump = _candidateHumps[humpIndex];

                var maxPatternHumpLength = _patternText.Length - patternIndex;
                var maxCandidateHumpLength = candidateHump.Length;
                var maxHumpMatchLength = Math.Min(maxPatternHumpLength, maxCandidateHumpLength);
                for (var possibleHumpMatchLength = 1; possibleHumpMatchLength <= maxHumpMatchLength; possibleHumpMatchLength++)
                {
                    if (!LowercaseSubstringsMatch(
                        _candidate, candidateHump.Start,
                        _patternText, patternIndex, possibleHumpMatchLength))
                    {
                        // Stop trying to consume once the pattern contents no longer matches
                        // against the current candidate hump.
                        break;
                    }

                    // This is the span of the hump of the candidate we matched.
                    var candidateMatchSpan = new TextSpan(candidateHump.Start, possibleHumpMatchLength);

                    // The pattern substring 'f' has matched against 'F', or 'fi' has matched
                    // against 'Fi'.  recurse and let the rest of the pattern match the remainder
                    // of the candidate.

                    var (weight, matchedSpans) = TryMatch(
                        patternIndex + possibleHumpMatchLength, humpIndex + 1, contiguous);

                    if (weight == null)
                    {
                        // Didn't match when we recursed.  Try to consume more and see if that gets us
                        // somewhere.
                        continue;
                    }

                    Debug.Assert(weight <= CamelCaseContiguousBonus);

                    if (humpIndex == 0)
                    {
                        weight += CamelCaseMatchesFromStartBonus;
                    }

                    if (weight == CamelCaseMaxWeight)
                    {
                        // We found a path that allowed us to match everything contiguously
                        // from the beginning.  This is the best match possible.  So we can
                        // just stop now and return thie result.
                        matchedSpans?.Insert(0, candidateMatchSpan);
                        return (weight, matchedSpans);
                    }

                    // This is a decent match.  But something else could beat it, store
                    // it if it's the best match we have so far, but keep searching.
                    if (bestWeight == null || weight > bestWeight)
                    {
                        matchedSpans?.Insert(0, candidateMatchSpan);

                        bestWeight = weight;
                        bestMatchedSpans = matchedSpans;
                    }
                }

                return (bestWeight, bestMatchedSpans);
            }

            private bool LowercaseSubstringsMatch(
                string s1, int start1, string s2, int start2, int length)
            {
                for (var i = 0; i < length; i++)
                {
                    if (char.ToLower(s1[start1 + i]) != char.ToLower(s2[start2 + i]))
                    {
                        return false;
                    }
                }

                return true;
            }
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.fluent.models;

import com.azure.core.annotation.Immutable;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Application security group properties. */
@Immutable
public final class ApplicationSecurityGroupPropertiesFormat {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(ApplicationSecurityGroupPropertiesFormat.class);

    /*
     * The resource GUID property of the application security group resource.
     * It uniquely identifies a resource, even if the user changes its name or
     * migrate the resource across subscriptions or resource groups.
     */
    @JsonProperty(value = "resourceGuid", access = JsonProperty.Access.WRITE_ONLY)
    private String resourceGuid;

    /*
     * The provisioning state of the application security group resource.
     * Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
     */
    @JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY)
    private String provisioningState;

    /**
     * Get the resourceGuid property: The resource GUID property of the application security group resource. It uniquely
     * identifies a resource, even if the user changes its name or migrate the resource across subscriptions or resource
     * groups.
     *
     * @return the resourceGuid value.
     */
    public String resourceGuid() {
        return this.resourceGuid;
    }

    /**
     * Get the provisioningState property: The provisioning state of the application security group resource. Possible
     * values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
     *
     * @return the provisioningState value.
     */
    public String provisioningState() {
        return this.provisioningState;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_erase"
        app:showAsAction="never"
        android:title="@string/action_erase" />

</menu>


text:
import _plotly_utils.basevalidators

class RangeValidator(_plotly_utils.basevalidators.InfoArrayValidator):
    def __init__(
        self, plotly_name="range", parent_name="indicator.gauge.step", **kwargs
    ):
        super(RangeValidator, self).__init__(
            plotly_name=plotly_name,
            parent_name=parent_name,
            edit_type=kwargs.pop("edit_type", "plot"),
            items=kwargs.pop(
                "items",
                [
                    {"valType": "number", "editType": "plot"},
                    {"valType": "number", "editType": "plot"},
                ],
            ),
            role=kwargs.pop("role", "info"),
            **kwargs
        )


text:
@interface UILabel (YNAttributeText)

- (NSMutableAttributedString *)setText:(NSString *)text withFont:(UIFont *)font withRange:(NSRange)range;
- (NSMutableAttributedString *)setText:(NSString *)text withColor:(UIColor *)color withRange:(NSRange)range;

- (NSMutableAttributedString *)setText:(NSString *)text withColor:(UIColor *)color withFont:(UIFont *)font withRange:(NSRange)range;

- (NSMutableAttributedString *)setText:(NSString *)text withParagraphHeight:(CGFloat)paragraphHeight withKernAttributeHeight:(CGFloat)kernHeight;

@end