text:
// /*
//   SharpNative - C# to D Transpiler
//   (C) 2014 Irio Systems
// */

#region Imports

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

#endregion

namespace SharpNative.Compiler
{
    internal static class WriteType
    {
        public static void Go()
        {
            var partials = Context.Instance.Partials;
            var first = partials.First();
            Context.Instance.Namespace = first.Symbol.ContainingNamespace.FullName();
            Context.Instance.Type = first.Symbol;
            TypeProcessor.ClearUsedTypes();
            var mynamespace = Context.Instance.Type.ContainingNamespace.FullName().RemoveFromEndOfString(".Namespace");
            // + "." + TypeState.Instance.TypeName;
            Console.WriteLine("Writing out type: " + Context.Instance.Namespace + "." + Context.Instance.TypeName);
            if ((Context.Instance.Namespace + "." + Context.Instance.TypeName) ==
                "Mono.Security.X509.Namespace.X509Chain")
            {
            }

            var myUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(mynamespace));
            var SystemUsingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System"));
                // Required as certain functions like boxing are in this namespace
            var namespaces = first.Syntax.Parent.DescendantNodes().OfType<UsingDirectiveSyntax>().ToArray();
            var usingStatements = first.Syntax.Parent.DescendantNodes().OfType<UsingStatementSyntax>().ToArray();
            Context.Instance.UsingDeclarations = namespaces
                .Union(new[]
                {
                    myUsingDirective, SystemUsingDirective
                }).ToArray();

            var objectType =
                TypeProcessor.GetSemanticModel(partials.First().Syntax)
                    .Compilation.GetTypeByMetadataName("System.Object");

            using (var writer = new OutputWriter(Context.Instance.Namespace, Context.Instance.TypeName))
            {
                var bases = partials
                    .Select(o => o.Syntax.BaseList)
                    .Where(o => o != null)
                    .SelectMany(o => o.Types)
                    .Select(o => TypeProcessor.GetTypeInfo(o.Type).ConvertedType)
                    .Distinct()
                    .ToList();

                //                var interfaces = bases.Where(o => o.TypeKind == TypeKind.Interface).ToList();

                if (!bases.Any((j => j.TypeKind != TypeKind.Interface)) &&
                    !(first.Symbol.TypeKind == TypeKind.Interface || first.Symbol.TypeKind == TypeKind.Struct))
                    //TODO: fix structs using mixins / alias this
                    bases.Add(objectType);

                //                    WriteStandardIncludes.Go(writer);

                //                    writer.WriteLine(String.Format("#include \"{0}\"", TypeState.Instance.TypeName + ".h"));

                WriteBcl.Go(writer);

                //TypeState.Instance.DerivesFromObject = bases.Count == interfaces.Count;

                var @namespace = first.Symbol.ContainingNamespace.FullName();

                //Module name = namespace + "." + typename;

                WriteStandardIncludes.Go(writer);

                //                    var namespaces = @namespace.Split(new string[] { "." }, StringSplitOptions.None);
                //
                //                    if (@namespace.Length > 0)
                //                    {
                //                        foreach (var ns in namespaces)
                //                        {
                //                            writer.WriteLine("namespace " + ns + "\r\n{");
                //                            writer.WriteLine("namespace " + ns + "\r\n{");
                //                        }
                //
                //                    }

                //TODO: Fix enum support
                if (first.Syntax is EnumDeclarationSyntax)
                {
                    WriteEnum.Go(writer,
                        Context.Instance.Partials.Select(o => o.Syntax)
                            .Cast<EnumDeclarationSyntax>()
                            .SelectMany(o => o.Members)
                            .Where(o => !Program.DoNotWrite.ContainsKey(o)));

                    return;
                }

                Context.Instance.AllMembers =
                    partials.Select(o => o.Syntax)
                        .Cast<TypeDeclarationSyntax>()
                        .SelectMany(o => o.Members)
                        .Where(o => !Program.DoNotWrite.ContainsKey(o))
                        .ToList();

                var allMembersToWrite = Context.Instance.AllMembers
                    .Where(member => !(member is TypeDeclarationSyntax)
                                     && !(member is EnumDeclarationSyntax)
                                     && !(member is DelegateDeclarationSyntax) &&
                                     !(member is ConstructorDeclarationSyntax))
                    .ToList();

                var instanceCtors = Context.Instance.AllMembers.OfType<ConstructorDeclarationSyntax>()
                    .Where(o => !o.Modifiers.Any(SyntaxKind.StaticKeyword))
                    .ToList();

                var staticCtors = Context.Instance.AllMembers.OfType<ConstructorDeclarationSyntax>()
                    .Where(o => (o.Modifiers.Any(SyntaxKind.StaticKeyword)))
                    .ToList();

                //TODO: Add support for overloading constructing
                //                    if (instanceCtors.Count > 1)
                //                        throw new Exception(
                //                            "Overloaded constructors are not supported.  Consider changing all but one to static Create methods " +
                //                            Utility.Descriptor(first.Syntax));

                //                    var ctorOpt = instanceCtors.SingleOrDefault();
                //TODO: Handle interfaces by
                /*
                class Interface
                {
                    public:
                        virtual ~Interface() { }
                        virtual void test() = 0; // Functions, must all be virtual
                }
                */

                var membersToWrite = allMembersToWrite.ToList();
                //.Where(o => IsStatic(o) == staticMembers).ToList();

                //                    if (membersToWrite.Count == 0 && (partials.Any(o => o.Syntax.Modifiers.Any(SyntaxKind.StaticKeyword))))
                //                        continue;

                //                    if (staticMembers)
                //                        writer.Write("object ");
                //                    else if (first.Syntax.Kind == SyntaxKind.InterfaceDeclaration)
                //                        writer.Write("trait ");
                //                    else
                //                    {
                //                        if (partials.Any(o => o.Syntax.Modifiers.Any(SyntaxKind.AbstractKeyword)))
                //                            writer.Write("abstract ");

                //                    }

                // writer.Write(TypeState.Instance.TypeName);

                if (first.Syntax is TypeDeclarationSyntax)
                {
                    //Look for generic arguments
                    var genericArgs = partials
                        .Select(o => o.Syntax)
                        .Cast<TypeDeclarationSyntax>()
                        .Where(o => o.TypeParameterList != null)
                        .SelectMany(o => o.TypeParameterList.Parameters)
                        .ToList();

                    if (Context.Instance.Type.TypeKind == TypeKind.Class)
                        writer.Write("class ");
                    else if (Context.Instance.Type.TypeKind == TypeKind.Interface)
                        writer.Write("interface ");
                    else if (Context.Instance.Type.TypeKind == TypeKind.Struct)
                    {
                        writer.Write("struct ");
                        //						writer.Write (" class "); // Allows inheritance ... but too many issues, will look at this when it gets relevant
                    }
                    else
                        throw new Exception("don't know how to write type: " + Context.Instance.Type.TypeKind);
                    //writer.Write (((TypeState.Instance.Type.TypeKind== TypeKind.Interface)?" interface ": ) );

                    writer.Write(Context.Instance.TypeName);

                    if (genericArgs.Count > 0)
                    {
                        writer.Write("( ");
                        writer.Write(string.Join(" , ", genericArgs.Select(o => o)));
                        writer.Write(" )");
                    }

                    bool firstBase = true;

                    if (Context.Instance.Type.TypeKind != TypeKind.Struct)
                    {
                        foreach (var baseType in bases.OrderBy(o => o.TypeKind == TypeKind.Interface ? 1 : 0))
                        {
                            writer.Write(firstBase ? " : " : " ,");

                            writer.Write(TypeProcessor.ConvertType(baseType));

                            //                            if (firstBase && ctorOpt != null && ctorOpt.Initializer != null &&
                            //                                ctorOpt.Initializer.ArgumentList.Arguments.Count > 0)
                            //                            {
                            //                                writer.Write("(");
                            //                                bool firstArg = true;
                            //                                foreach (var init in ctorOpt.Initializer.ArgumentList.Arguments)
                            //                                {
                            //                                    if (firstArg)
                            //                                        firstArg = false;
                            //                                    else
                            //                                        writer.Write(", ");
                            //
                            //                                    Core.Write(writer, init.Expression);
                            //                                }
                            //                                writer.Write(")");
                            //                            }

                            firstBase = false;
                        }
                    }
                }

                writer.WriteLine();

                writer.OpenBrace();

                var fields = membersToWrite.OfType<FieldDeclarationSyntax>().ToList();
                var nonFields = membersToWrite.Except(fields); // also static fields should be separately dealt with

                var structLayout = first.Syntax.GetAttribute(Context.StructLayout);
                if (structLayout != null)
                {
                    LayoutKind value = LayoutKind.Auto;
                    if (
                        structLayout.ArgumentList.Arguments.Any(
                            k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "Value"))
                    {
                        value =
                            (LayoutKind)
                                Enum.Parse(typeof (LayoutKind),
                                    structLayout.ArgumentList.Arguments.FirstOrDefault(
                                        k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "Value")
                                        .Expression.ToFullString()
                                        .SubstringAfterLast('.'));
                        //structLayout.ArgumentList.Arguments.Where (k => k.Expression is MemberAccessExpressionSyntax).FirstOrDefault(k=>(k.Expression as MemberAccessExpressionSyntax).Name.ToFullString() == "Value");
                    }
                        //structLayout.ArgumentList.Arguments.Where (k => k.Expression is MemberAccessExpressionSyntax).FirstOrDefault(k=>(k.Expression as MemberAccessExpressionSyntax).Name.ToFullString() == "Value");
                    else if (structLayout.ArgumentList.Arguments.Count > 0 &&
                             structLayout.ArgumentList.Arguments[0].NameEquals == null)
                    {
                        value =
                            (LayoutKind)
                                Enum.Parse(typeof (LayoutKind),
                                    structLayout.ArgumentList.Arguments[0].Expression.ToFullString()
                                        .SubstringAfterLast('.'));
                    }
                    int pack = -1;
                    int size = -1;
                    CharSet charset = CharSet.Auto;
//					if (structLayout.ArgumentList.Arguments.Count > 1)
                    {
                        try
                        {
                            if (
                                structLayout.ArgumentList.Arguments.Any(
                                    k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "CharSet"))
                            {
                                charset =
                                    (CharSet)
                                        Enum.Parse(typeof (CharSet),
                                            structLayout.ArgumentList.Arguments.FirstOrDefault(
                                                k =>
                                                    k.NameEquals != null &&
                                                    k.NameEquals.Name.ToFullString().Trim() == "CharSet")
                                                .Expression.ToFullString()
                                                .SubstringAfterLast('.'));
                                //structLayout.ArgumentList.Arguments.Where (k => k.Expression is MemberAccessExpressionSyntax).FirstOrDefault(k=>(k.Expression as MemberAccessExpressionSyntax).Name.ToFullString() == "Value");
                            }
                                //structLayout.ArgumentList.Arguments.Where (k => k.Expression is MemberAccessExpressionSyntax).FirstOrDefault(k=>(k.Expression as MemberAccessExpressionSyntax).Name.ToFullString() == "Value");
                            else if (structLayout.ArgumentList.Arguments.Count > 1 &&
                                     structLayout.ArgumentList.Arguments[1].NameEquals == null)
                            {
                                charset =
                                    (CharSet)
                                        Enum.Parse(typeof (CharSet),
                                            structLayout.ArgumentList.Arguments[1].Expression.ToFullString()
                                                .SubstringAfterLast('.'));
                            }
                        }
                        catch (Exception ex)
                        {
                        }

                        try
                        {
                            if (
                                structLayout.ArgumentList.Arguments.Any(
                                    k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "Pack"))
                            {
                                pack =
                                    int.Parse(
                                        structLayout.ArgumentList.Arguments.FirstOrDefault(
                                            k =>
                                                k.NameEquals != null &&
                                                k.NameEquals.Name.ToFullString().Trim() == "Pack")
                                            .Expression.ToFullString());
                            }
                                //structLayout.ArgumentList.Arguments.Where (k => k.Expression is MemberAccessExpressionSyntax).FirstOrDefault(k=>(k.Expression as MemberAccessExpressionSyntax).Name.ToFullString() == "Value");
                            else if (structLayout.ArgumentList.Arguments.Count > 2 &&
                                     structLayout.ArgumentList.Arguments[2].NameEquals == null)
                                pack = int.Parse(structLayout.ArgumentList.Arguments[2].Expression.ToFullString());
                        }
                        catch (Exception ex)
                        {
                        }

                        try
                        {
                            if (
                                structLayout.ArgumentList.Arguments.Any(
                                    k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "Size"))
                            {
                                size =
                                    int.Parse(
                                        structLayout.ArgumentList.Arguments.FirstOrDefault(
                                            k => k.NameColon != null && k.NameColon.ToFullString().Trim() == "Size")
                                            .Expression.ToFullString());
                            }
                                //structLayout.ArgumentList.Arguments.Where (k => k.Expression is MemberAccessExpressionSyntax).FirstOrDefault(k=>(k.Expression as MemberAccessExpressionSyntax).Name.ToFullString() == "Value");
                            else if (structLayout.ArgumentList.Arguments.Count > 3 &&
                                     structLayout.ArgumentList.Arguments[3].NameEquals == null)
                                size = int.Parse(structLayout.ArgumentList.Arguments[3].Expression.ToFullString());
                        }
                        catch (Exception ex)
                        {
                        }

//						size = int.Parse (structLayout.ArgumentList.Arguments [3].Expression.ToFullString ());
                    }
                    //					var pack = structLayout.ArgumentList.Arguments.FirstOrDefault (k => k.NameColon.Name.ToFullString() == "Pack");
//					var charset = structLayout.ArgumentList.Arguments.FirstOrDefault (k => k.NameColon.Name.ToFullString() == "CharSet");
//					var size = structLayout.ArgumentList.Arguments.FirstOrDefault (k => k.NameColon.Name.ToFullString() == "Size");

                    if (value == LayoutKind.Explicit)
                    {
                        var fieldGroups =
                            fields.GroupBy(f => f.GetAttribute(Context.FieldOffset).ArgumentList.Arguments[0].ToString())
                                .OrderBy(k => k.Key);
                        writer.Indent++;

                        foreach (var group in fieldGroups)
                        {
                            writer.WriteLine("//FieldOffset(" + @group.Key + ")");
                            writer.WriteLine("union {");
                            foreach (var member in group)
                                Core.Write(writer, member);
                            writer.WriteLine("}");
                        }

//						foreach (var member in fields)
//						{
//							//                    writer.WriteLine();
//							Core.Write (writer, member);
//						}
                    }
                    else if (value == LayoutKind.Sequential)
                    {
                        fields = SortFields(fields);

                        writer.Indent++;

                        foreach (var member in fields)
                        {
                            if (pack != -1)
                                writer.WriteLine("align (" + pack + "): //Pack = " + pack);
                            //                    writer.WriteLine();
                            Core.Write(writer, member);
                        }
                    }

                    else
                    {
                        //Looks like C# aligns to 1 by default ... don't know about D...
                        fields = SortFields(fields);

                        writer.Indent++;
                        foreach (var member in fields)
                        {
                            pack = 1;
                            writer.WriteLine("align (" + pack + "): //Pack = " + pack + "C# default");
                            //                    writer.WriteLine();
                            Core.Write(writer, member);
                        }
                    }
                }
                else
                {
                    //Looks like C# aligns to 1 by default ... don't know about D...
                    fields = SortFields(fields);

                    writer.Indent++;
                    foreach (var member in fields)
                    {
                        var pack = 1;
                        writer.WriteLine("align (" + pack + "): //Pack = " + pack + "C# default");
                        //                    writer.WriteLine();
                        Core.Write(writer, member);
                    }
                }

                foreach (var member in nonFields)
                {
//                    writer.WriteLine();
                    Core.Write(writer, member);
                }

                foreach (var constructor in instanceCtors)
                {
//                    writer.WriteLine();
                    Core.Write(writer, constructor);
                }

                if (staticCtors.Count == 0)
                {
                    if (Context.Instance.StaticInits.Count > 0)
                    {
                        var constructor = SyntaxFactory.ConstructorDeclaration(Context.Instance.TypeName);
                        constructor =
                            constructor.WithModifiers(
                                SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.StaticKeyword)));

                        WriteConstructorBody.WriteStaticConstructor(writer, constructor, Context.Instance.StaticInits);

                        staticCtors.Add(constructor);
                    }
                }
                else
                {
                    var isFirst = true;
                    foreach (ConstructorDeclarationSyntax constructor in staticCtors)
                    {
                        if (isFirst)
                        {
                            WriteConstructorBody.WriteStaticConstructor(writer, constructor,
                                Context.Instance.StaticInits);
                        }
                        else
                            WriteConstructorBody.Go(writer, constructor);

                        isFirst = false;
                    }
                }

                var dllImports = Context.Instance.DllImports;
                    // This should only be written once ... I guess we have to put the detection logic in Program.cs

                if (Context.Instance.EntryMethod != null)
                {
                    if (dllImports.Count > 0)
                    {
                        writer.WriteLine();

                        writer.WriteLine(String.Format("static void * __DllImportMap[{0}];", dllImports.Count));
                        writer.WriteLine("static void __SetupDllImports()");

                        writer.OpenBrace();

                        for (int index = 0; index < dllImports.Count; index++)
                        {
                            var dllImport = dllImports[index];
                            writer.WriteLine(String.Format("__DllImportMap[{0}] = LoadNativeLibrary(cast(string){1});",
                                index, dllImport.ArgumentList.Arguments.FirstOrDefault(k => k.Expression != null)));
                        }
                        writer.CloseBrace();
                        writer.WriteLine();
                        writer.WriteLine("static void __FreeDllImports()");
                        writer.OpenBrace();
                        writer.WriteLine(String.Format(@"for(int i=0;i<{0};i++)", dllImports.Count));
                        writer.OpenBrace();
                        writer.WriteLine("if(__DllImportMap[i]!=null)");
                        writer.WriteLine("\tFreeNativeLibrary(__DllImportMap[i]);");
                        writer.CloseBrace();
                        writer.CloseBrace();

                        //                            if (hModule != null)
                        //                            {
                        //    ::FreeLibrary(hModule);
                        //                            }
                    }
                }
                writer.Indent--;
                writer.CloseBrace();

                //Implement Boxed!Interface
                if (Context.Instance.Type.TypeKind == TypeKind.Struct)
                {
                    writer.WriteLine();
                    var typeName = Context.Instance.TypeName;
                    writer.Write("public class __Boxed_" + typeName + " : Boxed!(" + typeName + ")");
                    foreach (var baseType in bases.OrderBy(o => o.TypeKind == TypeKind.Interface ? 1 : 0))
                    {
                        writer.Write(" ,");

                        writer.Write(TypeProcessor.ConvertType(baseType, false));
                    }

                    writer.OpenBrace();

                    //FIXME:This is giving issues, we will just generate them here

//					writer.WriteLine ("import Irio.Utilities;");

                    writer.WriteLine("import std.traits;");

                    foreach (var baseType in bases.Where(o => o.TypeKind == TypeKind.Interface))
                    {
                        //FIXME:This is giving issues, we will just generate them here
//						writer.WriteLine ("mixin(__ImplementInterface!({0}, Value));",TypeProcessor.ConvertType(baseType,false));
                        var ifacemembers = baseType.GetMembers();

                        foreach (var member in ifacemembers)
                        {
                            var ifacemethod =
                                Context.Instance.Type.FindImplementationForInterfaceMember(member)
                                    .DeclaringSyntaxReferences.First()
                                    .GetSyntax();
//								.Where(member => !(member is TypeDeclarationSyntax)
//									&& !(member is EnumDeclarationSyntax)
//									&& !(member is DelegateDeclarationSyntax) && !(member is ConstructorDeclarationSyntax))
//								.ToList();

                            //                    writer.WriteLine();
//							Core.Write(writer, member);

                            if (ifacemethod is MethodDeclarationSyntax)
                                WriteMethod.WriteIt(writer, (MethodDeclarationSyntax) ifacemethod);
                            else if (ifacemethod is PropertyDeclarationSyntax)
                                WriteProperty.Go(writer, (PropertyDeclarationSyntax) ifacemethod, true);
                        }
                    }

                    //This is required to be able to create an instance at runtime / reflection
//					this()
                    //					{
                    //						super(SimpleStruct.init);
                    //					}

                    writer.WriteLine();
                    writer.WriteLine("this()");
                    writer.OpenBrace();
                    writer.WriteLine("super({0}.init);", typeName);
                    writer.CloseBrace();

                    if (Context.Instance.Type.GetMembers("ToString").Count() >= 1) // Use better matching ?
                    {
                        //					writer.WriteLine ();
                        writer.WriteLine("override String ToString()");
                        writer.OpenBrace();
                        writer.WriteLine("return Value.ToString();");
                        writer.CloseBrace();
                    }

                    writer.WriteLine();
                    writer.WriteLine("this(ref " + typeName + " value)");
                    writer.OpenBrace();
                    writer.WriteLine("super(value);");
                    writer.CloseBrace();

                    writer.WriteLine();
                    writer.WriteLine("U opCast(U)()");
                    writer.WriteLine("if(is(U:{0}))", typeName);
                    writer.OpenBrace();
                    writer.WriteLine("return Value;");
                    writer.CloseBrace();

                    writer.WriteLine();
                    writer.WriteLine("U opCast(U)()");
                    writer.WriteLine("if(!is(U:{0}))", typeName);
                    writer.OpenBrace();
                    writer.WriteLine("return this;");
                    writer.CloseBrace();

                    writer.WriteLine();
                    writer.WriteLine("auto opDispatch(string op, Args...)(Args args)");
                    writer.OpenBrace();
                    writer.WriteLine("enum name = op;");
                    writer.WriteLine("return __traits(getMember, Value, name)(args);");
                    writer.CloseBrace();

                    writer.CloseBrace();
                }

                if (Context.Instance.EntryMethod != null)
                {
                    //TODO: DllImports should be centralized

                    //
                    writer.WriteLine();
                    writer.WriteLine("void main(string[] args)");
                    writer.OpenBrace();

                    if (dllImports.Count > 0)
                        writer.WriteLine(Context.Instance.TypeName + ".__SetupDllImports();");
                    writer.WriteLine(Context.Instance.EntryMethod);
                    if (dllImports.Count > 0)
                        writer.WriteLine(Context.Instance.TypeName + ".__FreeDllImports();");

                    writer.CloseBrace();
                }

                //				var mySpecializations = Program.AllGenericSpecializations.Where (t => t.OriginalDefinition == TypeState.Instance.Type);
                //
                //
                //				foreach (var specialization in mySpecializations) {
                //
                //					var specializationText = ("template class " + specialization.GetFullNameD (false) + " (" +
                //					                                            (string.Join (" , ",
                //						                                            specialization.TypeArguments.Select (
                //							                                            o =>
                //                                                                       TypeProcessor.ConvertType (o) +
                //							                                            ((o.IsValueType ||
                //							                                            o.TypeKind == TypeKind.TypeParameter)
                //                                                                           ? ""
                //                                                                           : "*"))) +
                //							");"));
                //					writer.Write (specializationText);
                //				}

                //                    if (@namespace.Length > 0)
                //                    {
                //                        foreach (var ns in namespaces)
                //                        {
                //                            writer.WriteLine("\n\n}");
                //                            writer.WriteLine("\n\n}");
                //                        }
                //                    }
            }
        }

        public static OutputWriter EntryPoint = null;

        private static List<FieldDeclarationSyntax> SortFields(List<FieldDeclarationSyntax> fields)
        {
            if (fields.Count == 0)
                return fields;

            var dependencies =
                fields.ToDictionary(
                    o => TypeProcessor.GetDeclaredSymbol(o.Declaration.Variables.First()).As<IFieldSymbol>(),
                    o => new {Syntax = o, Dependicies = new List<IFieldSymbol>()});

            foreach (var dep in dependencies)
            {
                foreach (
                    var fieldDepend in
                        dep.Value.Syntax.DescendantNodes()
                            .OfType<ExpressionSyntax>()
                            .Select(o => TypeProcessor.GetSymbolInfo(o).Symbol)
                            .OfType<IFieldSymbol>())
                {
                    if (dependencies.ContainsKey(fieldDepend))
                        dep.Value.Dependicies.Add(fieldDepend);
                }
            }

            var ret = new List<FieldDeclarationSyntax>();
            var symbolsAdded = new HashSet<IFieldSymbol>();

            while (dependencies.Count > 0)
            {
                foreach (var dep in dependencies.ToList())
                {
                    for (int i = 0; i < dep.Value.Dependicies.Count; i++)
                    {
                        if (symbolsAdded.Contains(dep.Value.Dependicies[i]))
                            dep.Value.Dependicies.RemoveAt(i--);
                    }

                    if (dep.Value.Dependicies.Count == 0)
                    {
                        ret.Add(dep.Value.Syntax);
                        symbolsAdded.Add(dep.Key);
                        dependencies.Remove(dep.Key);
                    }
                }
            }

            return ret;
        }

        private static string TypeParameter(TypeParameterSyntax type)
        {
            var ret = Utility.TypeConstraints(type,
                Context.Instance.Partials.SelectMany(z => z.Syntax.As<TypeDeclarationSyntax>().ConstraintClauses));

            return ret;
        }

        private static bool IsStatic(MemberDeclarationSyntax member)
        {
            var modifiers = member.GetModifiers();
            return modifiers.Any(SyntaxKind.StaticKeyword) || modifiers.Any(SyntaxKind.ConstKeyword);
        }

        public static string TypeName(INamedTypeSymbol type)
        {
            var sb =
                new StringBuilder(string.Join("_",
                    (new[] {type.Name}).Union(type.TypeArguments.Select(o => o.ToString()))));

            while (type.ContainingType != null)
            {
                type = type.ContainingType;
                sb.Insert(0,
                    string.Join("_", (new[] {type.Name}).Union(type.TypeArguments.Select(o => o.ToString()))) + "_");
                sb.Append(string.Join("_", type.TypeArguments.Select(o => o)));
            }

            return sb.ToString();
        }
    }
}


text:
layout: "page"
title: "About"
description: "This is what I do."
header_img:
  url: "assets/img/about-bg.jpg"
---
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe nostrum ullam eveniet pariatur voluptates odit, fuga atque ea nobis sit soluta odio, adipisci quas excepturi maxime quae totam ducimus consectetur?

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius praesentium recusandae illo eaque architecto error, repellendaboutus iusto reprehenderit, doloribus, minus sunt. Numquam at quae voluptatum in officia voluptas voluptatibus, minus!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum molestiae debitis nobis, quod sapiente qui voluptatum, placeat magni repudiandae accusantium fugit quas labore non rerum possimus, corrupti enim modi! Et.

redpajama_set_name: RedPajamaGithub


text:
#include "Viewport.h"

DC_BEGIN_DREEMCHEST

namespace Scene {

// ---------------------------------------- AbstractViewport ---------------------------------------- //

// ** AbstractViewport::rect
Rect AbstractViewport::rect( void ) const
{
    return Rect( 0.0f, 0.0f, width(), height() );
}

// ------------------------------------------ WindowViewport ------------------------------------------ //

// ** WindowViewport::WindowViewport
WindowViewport::WindowViewport( const Platform::WindowWPtr& window )
    : m_window( window )
    , m_lastX( -1 )
    , m_lastY( -1 )
{
    NIMBLE_ABORT_IF( !window.valid(), "invalid window" );
    m_window->subscribe<Platform::Window::TouchBegan>( dcThisMethod( WindowViewport::handleTouchBegan ) );
    m_window->subscribe<Platform::Window::TouchMoved>( dcThisMethod( WindowViewport::handleTouchMoved ) );
    m_window->subscribe<Platform::Window::TouchEnded>( dcThisMethod( WindowViewport::handleTouchEnded ) );
}

// ** WindowViewport::~WindowViewport
WindowViewport::~WindowViewport( void )
{
    if( !m_window.valid() ) {
        return;
    }

    m_window->unsubscribe<Platform::Window::TouchBegan>( dcThisMethod( WindowViewport::handleTouchBegan ) );
    m_window->unsubscribe<Platform::Window::TouchMoved>( dcThisMethod( WindowViewport::handleTouchMoved ) );
    m_window->unsubscribe<Platform::Window::TouchEnded>( dcThisMethod( WindowViewport::handleTouchEnded ) );
}

// ** WindowViewport::create
WindowViewportPtr WindowViewport::create( const Platform::WindowWPtr& window )
{
    return WindowViewportPtr( DC_NEW WindowViewport( window ) );
}

// ** WindowViewport::width
s32 WindowViewport::width( void ) const
{
    return m_window->width();
}

// ** WindowViewport::height
s32 WindowViewport::height( void ) const
{
    return m_window->height();
}

// ** WindowViewport::handleTouchBegan
void WindowViewport::handleTouchBegan( const Platform::Window::TouchBegan& e )
{
    m_lastX = e.x;
    m_lastY = e.y;
    notify<TouchBegan>( this, e.id, e.x, e.y );
}

// ** WindowViewport::handleTouchMoved
void WindowViewport::handleTouchMoved( const Platform::Window::TouchMoved& e )
{
    notify<TouchMoved>( this, e.id, e.x, e.y, e.x - m_lastX, e.y - m_lastY );
    m_lastX = e.x;
    m_lastY = e.y;
}

// ** WindowViewport::handleTouchEnded
void WindowViewport::handleTouchEnded( const Platform::Window::TouchEnded& e )
{
    notify<TouchEnded>( this, e.id, e.x, e.y );
}

} // namespace Scene

DC_END_DREEMCHEST


text:
package com.github.messenger4j.profile;

import com.github.messenger4j.exceptions.MessengerIOException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Created by Rafal Lebioda on 18.03.2017.
 */
@Getter
@EqualsAndHashCode(callSuper = true)
@ToString
public class GreetingsProfileResponse extends ProfileResponse {

    private final List<Greeting> greetings;

    public GreetingsProfileResponse(String result) {
        super(result);
        greetings = Collections.emptyList();
    }

    public GreetingsProfileResponse(String result, Greeting[] greetingsArray) {
        super(result);
        greetings = Arrays.asList(greetingsArray);
    }

    public static GreetingsProfileResponse fromJson(JsonObject jsonObject) throws MessengerIOException {
        JsonArray dataArray = getArray(jsonObject, "data");
        if (isJsonArrayEmpty(dataArray)) {
            return new GreetingsProfileResponse(jsonObject.toString());
        }

        JsonArray greetingsJsonArray = getArray(dataArray.get(0).getAsJsonObject(), "greeting");
        if (isJsonArrayEmpty(greetingsJsonArray)) {
            return new GreetingsProfileResponse(jsonObject.toString());
        }

        return new GreetingsProfileResponse(jsonObject.toString(), new Gson().fromJson(greetingsJsonArray, Greeting[].class));
    }

    private static JsonArray getArray(JsonObject jsonObject, String label) {
        return jsonObject.getAsJsonArray(label);
    }

    private static boolean isJsonArrayEmpty(JsonArray jsonArray) {
        return jsonArray == null || jsonArray.size() == 0;
    }

}


text:
DIRECTORIES = (
    ('docs/', 'make sphinx'),
    ('AUTHORS', 'make sphinx'),
    ('CHANGELOG', 'make sphinx'),
    ('CONTRIBUTING.rst', 'make sphinx'),
    ('INSTALL', 'make sphinx'),
    ('LICENSE', 'make sphinx'),
    ('README.rst', 'make documentation'),
    ('tests/', 'make test'),
    ('xal/', 'make test'),
)
IGNORE_EXTENSIONS = ('swp', 'swo', )


text:
require 'rails_helper'

RSpec.describe "magueyes/show", type: :view do
  before(:each) do
    @magueye = assign(:magueye, Magueye.create!(
      :title => "Title",
      :sub_title => "Sub Title",
      :text => "",
      :image => "Image",
      :language => 1
    ))
  end

  it "renders attributes in <p>" do
    render
    expect(rendered).to match(/Title/)
    expect(rendered).to match(/Sub Title/)
    expect(rendered).to match(//)
    expect(rendered).to match(/Image/)
    expect(rendered).to match(/1/)
  end
end


text:
package org.apache.cxf.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Used to attach multiple WSDLDocumentation annotations
 * to a method or type if documentation needs to be added
 * to more than one place in the wsdl.
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface WSDLDocumentationCollection {
    WSDLDocumentation[] value();

}


text:
//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.application.permissions;

import gov.nih.nci.caarray.application.ExceptionLoggingInterceptor;
import gov.nih.nci.caarray.application.GenericDataService;
import gov.nih.nci.caarray.dao.CollaboratorGroupDao;
import gov.nih.nci.caarray.dao.SearchDao;
import gov.nih.nci.caarray.domain.permissions.AccessProfile;
import gov.nih.nci.caarray.domain.permissions.CollaboratorGroup;
import gov.nih.nci.caarray.injection.InjectionInterceptor;
import gov.nih.nci.caarray.security.SecurityUtils;
import gov.nih.nci.caarray.util.CaArrayHibernateHelper;
import gov.nih.nci.caarray.util.CaArrayUsernameHolder;
import gov.nih.nci.caarray.util.io.logging.LogUtil;
import gov.nih.nci.security.AuthorizationManager;
import gov.nih.nci.security.authorization.domainobjects.Group;
import gov.nih.nci.security.authorization.domainobjects.User;
import gov.nih.nci.security.dao.UserSearchCriteria;
import gov.nih.nci.security.exceptions.CSException;
import gov.nih.nci.security.exceptions.CSObjectNotFoundException;
import gov.nih.nci.security.exceptions.CSTransactionException;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.interceptor.Interceptors;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;

import com.google.inject.Inject;

/**
 * Local implementation of interface.
 */
@Local(PermissionsManagementService.class)
@Stateless
@Interceptors({ExceptionLoggingInterceptor.class, InjectionInterceptor.class })
@SuppressWarnings("unchecked")
// CSM API is unchecked
public class PermissionsManagementServiceBean implements PermissionsManagementService {

    private static final Logger LOG = Logger.getLogger(PermissionsManagementServiceBean.class);

    @EJB
    private GenericDataService genericDataService;

    private CaArrayHibernateHelper hibernateHelper;
    private CollaboratorGroupDao collaboratorGroupDao;
    private SearchDao searchDao;

    /**
     * {@inheritDoc}
     */
    @Override
    public void delete(CollaboratorGroup group) throws CSTransactionException {
        LogUtil.logSubsystemEntry(LOG, group);
        if (!group.getOwner().equals(CaArrayUsernameHolder.getCsmUser())) {
            throw new IllegalArgumentException(String.format(
                    "%s cannot delete group %s, because they are not the group owner.",
                    CaArrayUsernameHolder.getUser(), group.getGroup().getGroupName()));
        }

        for (final AccessProfile ap : group.getAccessProfiles()) {
            ap.getProject().removeGroupProfile(group);
            getGenericDataService().delete(ap);
        }
        getGenericDataService().delete(group);
        SecurityUtils.removeGroup(group.getGroup().getGroupId());

        LogUtil.logSubsystemExit(LOG);
    }

    /**
     * @return the genericDataService
     */
    public GenericDataService getGenericDataService() {
        return this.genericDataService;
    }

    /**
     * @param genericDataService the genericDataService to set
     */
    public void setGenericDataService(GenericDataService genericDataService) {
        this.genericDataService = genericDataService;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public List<CollaboratorGroup> getCollaboratorGroups() {
        LogUtil.logSubsystemEntry(LOG);
        final List<CollaboratorGroup> result = this.collaboratorGroupDao.getAll();
        LogUtil.logSubsystemExit(LOG);
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public List<CollaboratorGroup> getCollaboratorGroupsForCurrentUser() {
        LogUtil.logSubsystemEntry(LOG);
        final List<CollaboratorGroup> result = this.collaboratorGroupDao.getAllForCurrentUser();
        LogUtil.logSubsystemExit(LOG);
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public CollaboratorGroup create(String name) throws CSTransactionException, CSObjectNotFoundException {
        LogUtil.logSubsystemEntry(LOG, name);

        final Group group = new Group();
        group.setGroupName(name);
        group.setGroupDesc("Collaborator Group");
        SecurityUtils.createGroup(group);

        final User user = CaArrayUsernameHolder.getCsmUser();

        final CollaboratorGroup cg = new CollaboratorGroup(group, user);
        this.collaboratorGroupDao.save(cg);

        LogUtil.logSubsystemExit(LOG);
        return cg;

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void addUsers(String groupName, String... usernames) throws CSTransactionException,
            CSObjectNotFoundException {
        LogUtil.logSubsystemEntry(LOG, groupName, usernames);
        final AuthorizationManager am = SecurityUtils.getAuthorizationManager();
        final Group group = SecurityUtils.findGroupByName(groupName);
        group.setGroupName(groupName);
        final List<Long> users = new ArrayList<Long>();
        for (final String username : usernames) {
            users.add(am.getUser(username).getUserId());
        }
        addUsersToGroup(group.getGroupId(), users, SecurityUtils.ANONYMOUS_GROUP.equals(groupName));
        LogUtil.logSubsystemExit(LOG);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void addUsers(CollaboratorGroup targetGroup, List<Long> users) throws CSObjectNotFoundException,
            CSTransactionException {
        LogUtil.logSubsystemEntry(LOG, targetGroup, users);
        final Long groupId = targetGroup.getGroup().getGroupId();
        addUsersToGroup(groupId, users, false);
        LogUtil.logSubsystemExit(LOG);
    }

    private void addUsersToGroup(Long groupId, List<Long> users, boolean allowAnonymousUser)
            throws CSObjectNotFoundException, CSTransactionException {
        final Set<User> curUsers = SecurityUtils.getUsers(groupId);
        final Set<Long> newUsers = new HashSet<Long>(curUsers.size() + users.size());
        newUsers.addAll(users);
        for (final User u : curUsers) {
            newUsers.add(u.getUserId());
        }
        if (!allowAnonymousUser) {
            newUsers.remove(SecurityUtils.getAnonymousUser().getUserId());
        }

        SecurityUtils.assignUsersToGroup(groupId, newUsers);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void removeUsers(CollaboratorGroup targetGroup, List<Long> userIds) throws CSTransactionException {
        LogUtil.logSubsystemEntry(LOG, targetGroup, userIds);
        for (final Long u : userIds) {
            SecurityUtils.removeUserFromGroup(targetGroup.getGroup().getGroupId(), u);
        }
        LogUtil.logSubsystemExit(LOG);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void rename(CollaboratorGroup targetGroup, String groupName) throws CSTransactionException,
            CSObjectNotFoundException {
        LogUtil.logSubsystemEntry(LOG, targetGroup, groupName);

        final Group g = targetGroup.getGroup();
        g.setGroupName(groupName);
        this.hibernateHelper.getCurrentSession().update(g);
        LogUtil.logSubsystemExit(LOG);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<User> getUsers(User u) {
        LogUtil.logSubsystemEntry(LOG);
        List<User> resultUsers;
        try {
            resultUsers =
                    SecurityUtils.getAuthorizationManager().getObjects(
                            new UserSearchCriteria(convertToLikeProperties(u)));
        } catch (final IllegalAccessException e) {
            throw new IllegalStateException("Could not create an example user", e);
        } catch (final InvocationTargetException e) {
            throw new IllegalStateException("Could not create an example user", e);
        } catch (final NoSuchMethodException e) {
            throw new IllegalStateException("Could not create an example user", e);
        }
        LogUtil.logSubsystemExit(LOG);
        return resultUsers;
    }

    private User convertToLikeProperties(User u) throws IllegalAccessException, InvocationTargetException,
            NoSuchMethodException {
        final User newUser = new User();
        if (u != null) {
            PropertyUtils.copyProperties(newUser, u);
            for (final PropertyDescriptor pd : PropertyUtils.getPropertyDescriptors(newUser)) {
                convertToLikeProperty(u, newUser, pd);
            }
        }
        return newUser;
    }

    private void convertToLikeProperty(User u, User newUser, PropertyDescriptor pd) throws IllegalAccessException,
            InvocationTargetException, NoSuchMethodException {
        if (pd.getPropertyType().equals(String.class)) {
            final String value = (String) PropertyUtils.getSimpleProperty(newUser, pd.getName());
            if (value != null) {
                PropertyUtils.setSimpleProperty(newUser, pd.getName(), value + "%");
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void saveAccessProfile(AccessProfile profile) {
        LogUtil.logSubsystemEntry(LOG, profile);
        this.collaboratorGroupDao.save(profile);
        LogUtil.logSubsystemExit(LOG);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void changeOwner(Long targetGroupId, String username) throws CSException {
        LogUtil.logSubsystemEntry(LOG, targetGroupId, username);
        final AuthorizationManager am = SecurityUtils.getAuthorizationManager();
        final CollaboratorGroup cg = this.searchDao.retrieve(CollaboratorGroup.class, targetGroupId);
        final User newOwner = am.getUser(username);
        cg.setOwner(newOwner);

        SecurityUtils.changeOwner(cg, newOwner);

        this.collaboratorGroupDao.save(cg);
        LogUtil.logSubsystemExit(LOG);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<CollaboratorGroup> getCollaboratorGroupsForOwner(long userId) {
        LogUtil.logSubsystemEntry(LOG, userId);
        final List<CollaboratorGroup> result = this.collaboratorGroupDao.getAllForUser(userId);
        LogUtil.logSubsystemExit(LOG);
        return result;
    }

    /**
     * @param hibernateHelper the hibernateHelper to set
     */
    @Inject
    public void setHibernateHelper(CaArrayHibernateHelper hibernateHelper) {
        this.hibernateHelper = hibernateHelper;
    }

    /**
     * @param collaboratorGroupDao the collaboratorGroupDao to set
     */
    @Inject
    public void setCollaboratorGroupDao(CollaboratorGroupDao collaboratorGroupDao) {
        this.collaboratorGroupDao = collaboratorGroupDao;
    }

    /**
     * @param searchDao the searchDao to set
     */
    @Inject
    public void setSearchDao(SearchDao searchDao) {
        this.searchDao = searchDao;
    }
}


text:
COPY (
  select
    urs
  from rnc_secondary_structure_layout layout
  join rnc_secondary_structure_layout_models models
  on
    models.id = layout.model_id
  where
    models.model_source = 'crw'
) TO STDOUT


text:
using System;
using System.Runtime.InteropServices;
using System.Security;

namespace Saserdote.GamingServices
{
	public class GameClock
	{
		#region --- Field Variables ---

		// Variables
		private long	ticksPerSecond=	0;
		private long	prevElapsedTime=	0;

		#endregion // Field Variables

		#region --- Constructors ---

		public GameClock()
		{
			QueryPerformanceFrequency(ref ticksPerSecond);
			getElapsedTime();
		}

		#endregion // Constructors

		#region --- Dll Imported Methods ---

		[SuppressUnmanagedCodeSecurity, DllImport("kernel32")]
			private static extern bool QueryPerformanceFrequency(ref long perfomanceFrequency);
		[SuppressUnmanagedCodeSecurity, DllImport("kernel32")]
			private static extern bool QueryPerformanceCounter(ref long performanceCount);

		#endregion // Dll Imported Methods

		#region --- Methods ---

		// Gets the elapsed time from before
		public float getElapsedTime()
		{
			// Variables
			long	time=	0;
			float	elapsedTime;

			QueryPerformanceCounter(ref time);
			elapsedTime=	(float)(time-prevElapsedTime)/(float)ticksPerSecond;
			prevElapsedTime=	time;

			return elapsedTime;
		}

		#endregion // Methods
	}
}

// End of File


text:
package com.all.client.view.music;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;

import java.io.File;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import com.all.appControl.control.ViewEngine;
import com.all.client.util.TrackRepository;
import com.all.core.model.Model;
import com.all.shared.model.Track;

public class TestDescriptionTableStyle {

	@InjectMocks
	private DescriptionTableStyle descriptionTableStyle = new DescriptionTableStyle();
	@Mock
	private Track track;
	@Mock
	private ViewEngine viewEngine;
	@Mock
	private TrackRepository trackRepository;
	@Mock
	private File file;

	private String hashcode = "hashcode";

	@Before
	public void setup() throws Exception {
		MockitoAnnotations.initMocks(this);
		when(track.getHashcode()).thenReturn(hashcode);
		when(viewEngine.get(Model.TRACK_REPOSITORY)).thenReturn(trackRepository);
	}

	@Test
	public void shouldSeeATrackInMyLibrary() throws Exception {
		when(trackRepository.getFile(track.getHashcode())).thenReturn(file);

		boolean trackInMyLibrary = descriptionTableStyle.isTrackInMyLibrary(track);

		assertTrue(trackInMyLibrary);
	}

	@Test
	public void shouldNotSeeATrackInMyLibrary() throws Exception {
		boolean trackInMyLibrary = descriptionTableStyle.isTrackInMyLibrary(track);

		assertFalse(trackInMyLibrary);
	}
}


text:
namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {

/// @test Verify that the IOStream operator works as expected.
TEST(BucketAccessControlTest, IOStream) {
  // The iostream operator is mostly there to support EXPECT_EQ() so it is
  // rarely called, and that breaks our code coverage metrics.
  std::string text = R"""({
      "bucket": "foo-bar",
      "domain": "example.com",
      "email": "foobar@example.com",
      "entity": "user-foobar",
      "entityId": "user-foobar-id-123",
      "etag": "XYZ=",
      "id": "bucket-foo-bar-acl-234",
      "kind": "storage#bucketAccessControl",
      "projectTeam": {
        "projectNumber": "3456789",
        "team": "a-team"
      },
      "role": "OWNER"
})""";

  auto meta = internal::BucketAccessControlParser::FromString(text).value();
  std::ostringstream os;
  os << meta;
  auto actual = os.str();
  using ::testing::HasSubstr;
  EXPECT_THAT(actual, HasSubstr("BucketAccessControl"));
  EXPECT_THAT(actual, HasSubstr("bucket=foo-bar"));
  EXPECT_THAT(actual, HasSubstr("id=bucket-foo-bar-acl-234"));
}

/// @test Verify BucketAccessControl::set_entity() works as expected.
TEST(BucketAccessControlTest, SetEntity) {
  BucketAccessControl tested;

  EXPECT_TRUE(tested.entity().empty());
  tested.set_entity("user-foo");
  EXPECT_EQ("user-foo", tested.entity());
}

/// @test Verify BucketAccessControl::set_role() works as expected.
TEST(BucketAccessControlTest, SetRole) {
  BucketAccessControl tested;

  EXPECT_TRUE(tested.role().empty());
  tested.set_role(BucketAccessControl::ROLE_READER());
  EXPECT_EQ("READER", tested.role());
}

/// @test Verify that comparison operators work as expected.
TEST(BucketAccessControlTest, Compare) {
  std::string text = R"""({
      "bucket": "foo-bar",
      "domain": "example.com",
      "email": "foobar@example.com",
      "entity": "user-foobar",
      "entityId": "user-foobar-id-123",
      "etag": "XYZ=",
      "id": "bucket-foo-bar-acl-234",
      "kind": "storage#bucketAccessControl",
      "projectTeam": {
        "projectNumber": "3456789",
        "team": "a-team"
      },
      "role": "OWNER"
})""";
  auto original = internal::BucketAccessControlParser::FromString(text).value();
  EXPECT_EQ(original, original);

  auto modified = original;
  modified.set_role(BucketAccessControl::ROLE_READER());
  EXPECT_NE(original, modified);
}

}  // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace storage
}  // namespace cloud
}  // namespace google


text:
#include <stdint.h>
#include <stdlib.h>

#include <openssl/aes.h>

#include "sysendian.h"

#include "crypto_aesctr.h"

struct crypto_aesctr {
	const AES_KEY * key;
	uint64_t nonce;
	uint64_t bytectr;
	uint8_t buf[16];
};

/**
 * crypto_aesctr_init(key, nonce):
 * Prepare to encrypt/decrypt data with AES in CTR mode, using the provided
 * expanded key and nonce.  The key provided must remain valid for the
 * lifetime of the stream.
 */
struct crypto_aesctr *
crypto_aesctr_init(const AES_KEY * key, uint64_t nonce)
{
	struct crypto_aesctr * stream;

	/* Allocate memory. */
	if ((stream = malloc(sizeof(struct crypto_aesctr))) == NULL)
		goto err0;

	/* Initialize values. */
	stream->key = key;
	stream->nonce = nonce;
	stream->bytectr = 0;

	/* Success! */
	return (stream);

err0:
	/* Failure! */
	return (NULL);
}

/**
 * crypto_aesctr_stream(stream, inbuf, outbuf, buflen):
 * Generate the next ${buflen} bytes of the AES-CTR stream and xor them with
 * bytes from ${inbuf}, writing the result into ${outbuf}.  If the buffers
 * ${inbuf} and ${outbuf} overlap, they must be identical.
 */
void
crypto_aesctr_stream(struct crypto_aesctr * stream, const uint8_t * inbuf,
    uint8_t * outbuf, size_t buflen)
{
	uint8_t pblk[16];
	size_t pos;
	int bytemod;

	for (pos = 0; pos < buflen; pos++) {
		/* How far through the buffer are we? */
		bytemod = stream->bytectr % 16;

		/* Generate a block of cipherstream if needed. */
		if (bytemod == 0) {
			be64enc(pblk, stream->nonce);
			be64enc(pblk + 8, stream->bytectr / 16);
			AES_encrypt(pblk, stream->buf, stream->key);
		}

		/* Encrypt a byte. */
		outbuf[pos] = inbuf[pos] ^ stream->buf[bytemod];

		/* Move to the next byte of cipherstream. */
		stream->bytectr += 1;
	}
}

/**
 * crypto_aesctr_free(stream):
 * Free the provided stream object.
 */
void
crypto_aesctr_free(struct crypto_aesctr * stream)
{
	int i;

	/* Be compatible with free(NULL). */
	if (stream == NULL)
		return;

	/* Zero potentially sensitive information. */
	for (i = 0; i < 16; i++)
		stream->buf[i] = 0;
	stream->bytectr = stream->nonce = 0;

	/* Free the stream. */
	free(stream);
}

/**
 * crypto_aesctr_buf(key, nonce, inbuf, outbuf, buflen):
 * Equivalent to init(key, nonce); stream(inbuf, outbuf, buflen); free.
 */
void
crypto_aesctr_buf(const AES_KEY * key, uint64_t nonce,
    const uint8_t * inbuf, uint8_t * outbuf, size_t buflen)
{
	struct crypto_aesctr stream_rec;
	struct crypto_aesctr * stream = &stream_rec;
	int i;

	/* Initialize values. */
	stream->key = key;
	stream->nonce = nonce;
	stream->bytectr = 0;

	/* Perform the encryption. */
	crypto_aesctr_stream(stream, inbuf, outbuf, buflen);

	/* Zero potentially sensitive information. */
	for (i = 0; i < 16; i++)
		stream->buf[i] = 0;
	stream->bytectr = stream->nonce = 0;
}


text:
<?php

declare(strict_types=1);

namespace QueueJitsu\Queue\Adapter;

use QueueJitsu\Job\Job;

/**
 * Interface AdapterInterface
 *
 * @package QueueJitsu\Queue\Adapter
 */
interface AdapterInterface
{
    /**
     * reserve
     *
     * @param string $queue
     *
     * @return null|\QueueJitsu\Job\Job
     */
    public function reserve(string $queue): ?Job;

    /**
     * getAllQueueNames
     *
     * @return array
     */
    public function getAllQueueNames(): array;
}


text:
package javacard.security;

/**
 * The RSAPublicKey is used to verify signatures on signed data
 * using the RSA algorithm. It may also used by the
 * javacardx.crypto.Cipher class to encrypt/decrypt messages.
 *

 * When both the modulus and exponent of the key are set, the key is initialized
 * and ready for use.
 *
 * @see RSAPrivateKey RSAPrivateKey
 * @see RSAPrivateCrtKey RSAPrivateCrtKey
 * @see KeyBuilder KeyBuilder
 * @see Signature Signature
 * @see javacardx.crypto.Cipher javacardx.crypto.Cipher
 * @see javacardx.crypto.KeyEncryption javacardx.crypto.KeyEncryption
 */

public interface RSAPublicKey extends PublicKey
{

    /**
     * Sets the modulus value of the key. The plaintext data format is
     * big-endian and right-aligned (the least significant bit is the least
     * significant bit of last byte). Input modulus data is copied into the
     * internal representation.
     *

     * Note:
     *

     *
If the key object implements the javacardx.crypto.KeyEncryption
     * interface and the Cipher object specified via setKeyCipher()
     * is not null, the modulus value is decrypted using the Cipher object.
     *

     *
     * @param buffer
     *            the input buffer
     * @param offset
     *            the offset into the input buffer at which the modulus value
     *            begins
     * @param length
     *            the byte length of the modulus
     * @exception CryptoException
     *                with the following reason code:
     *

     *
CryptoException.ILLEGAL_VALUE if the
     *                input modulus data length is inconsistent with the
     *                implementation or if input data decryption is required and
     *                fails.
     *

     */
    void setModulus(byte[] buffer, short offset, short length)
    throws CryptoException;

    /**
     * Sets the public exponent value of the key. The plaintext data format is
     * big-endian and right-aligned (the least significant bit is the least
     * significant bit of last byte). Input exponent data is copied into the
     * internal representation.
     *

     * Notes:
     *

     *
All implementations must support exponent values up to 4 bytes in length. Implementations
     * may also support exponent values greater than 4 bytes in length.
     *
If the key object implements the javacardx.crypto.KeyEncryption
     * interface and the Cipher object specified via setKeyCipher()
     * is not null, the exponent value is decrypted using the Cipher object.
     *

     *
     * @param buffer
     *            the input buffer
     * @param offset
     *            the offset into the input buffer at which the exponent value
     *            begins
     * @param length
     *            the byte length of the exponent
     * @exception CryptoException
     *                with the following reason code:
     *

     *
CryptoException.ILLEGAL_VALUE if the
     *                input exponent data length is inconsistent with the
     *                implementation or if input data decryption is required and
     *                fails or if the implementation does not support the
     *                specified exponent length.
     *

     */
    void setExponent(byte[] buffer, short offset, short length)
    throws CryptoException;

    /**
     * Returns the modulus value of the key in plain text. The data format is
     * big-endian and right-aligned (the least significant bit is the least
     * significant bit of last byte).
     *
     * @param buffer
     *            the output buffer
     * @param offset
     *            the offset into the input buffer at which the modulus value
     *            starts
     * @return the byte length of the modulus value returned
     * @exception CryptoException
     *                with the following reason code:
     *

     *
CryptoException.UNINITIALIZED_KEY if
     *                the modulus value of the key has not been successfully
     *                initialized since the time the initialized state of the
     *                key was set to false.
     *

     * @see Key Key
     */
    short getModulus(byte[] buffer, short offset);

    /**
     * Returns the public exponent value of the key in plain text. The data
     * format is big-endian and right-aligned (the least significant bit is the
     * least significant bit of last byte).
     *
     * @param buffer
     *            the output buffer
     * @param offset
     *            the offset into the output buffer at which the exponent value
     *            begins
     * @return the byte length of the public exponent returned
     * @exception CryptoException
     *                with the following reason code:
     *

     *
CryptoException.UNINITIALIZED_KEY if
     *                the public exponent value of the key has not been
     *                successfully initialized since the time the initialized
     *                state of the key was set to false.
     *

     * @see Key Key
     */
    short getExponent(byte[] buffer, short offset);

}


text:
package org.jbpm.services.task.query;

import java.util.Date;

public class DeadlineSummaryImpl implements org.kie.internal.task.api.model.DeadlineSummary {
    private long taskId;
    private long deadlineId;
    private Date date;

    public DeadlineSummaryImpl() {
        // default constructor
    }

    public DeadlineSummaryImpl(long taskId,
                           long deadlineId,
                           Date date) {
        super();
        this.taskId = taskId;
        this.deadlineId = deadlineId;
        this.date = date;
    }

    public long getTaskId() {
        return taskId;
    }

    public void setTaskId(long taskId) {
        this.taskId = taskId;
    }

    public long getDeadlineId() {
        return deadlineId;
    }

    public void setDeadlineId(long deadlineId) {
        this.deadlineId = deadlineId;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((date == null) ? 0 : date.hashCode());
        result = prime * result + (int) (deadlineId ^ (deadlineId >>> 32));
        result = prime * result + (int) (taskId ^ (taskId >>> 32));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if ( this == obj ) return true;
        if ( obj == null ) return false;
        if ( !(obj instanceof DeadlineSummaryImpl) ) return false;
        DeadlineSummaryImpl other = (DeadlineSummaryImpl) obj;
        if ( date == null ) {
            if ( other.date != null ) return false;
        } else if ( date.getTime() != other.date.getTime() ) return false;
        if ( deadlineId != other.deadlineId ) return false;
        if ( taskId != other.taskId ) return false;
        return true;
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.spi.resourceGroups;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;

import java.util.List;
import java.util.Optional;

import static java.util.Collections.emptyList;
import static java.util.Collections.unmodifiableList;
import static java.util.Objects.requireNonNull;

public class ResourceGroupInfo
{
    private final ResourceGroupId id;

    private final DataSize softMemoryLimit;
    private final int softConcurrencyLimit;
    private final int hardConcurrencyLimit;
    private final Duration runningTimeLimit;
    private final int maxQueuedQueries;
    private final Duration queuedTimeLimit;

    private final ResourceGroupState state;
    private final int numEligibleSubGroups;
    private final DataSize memoryUsage;
    private final int numAggregatedRunningQueries;
    private final int numAggregatedQueuedQueries;

    private final List<ResourceGroupInfo> subGroups;

    @JsonCreator
    public ResourceGroupInfo(
            @JsonProperty("id") ResourceGroupId id,
            @JsonProperty("softMemoryLimit") DataSize softMemoryLimit,
            @JsonProperty("softConcurrencyLimit") int softConcurrencyLimit,
            @JsonProperty("hardConcurrencyLimit") int hardConcurrencyLimit,
            @JsonProperty("runningTimeLimit") Duration runningTimeLimit,
            @JsonProperty("maxQueuedQueries") int maxQueuedQueries,
            @JsonProperty("queuedTimeLimit") Duration queuedTimeLimit,
            @JsonProperty("state") ResourceGroupState state,
            @JsonProperty("numEligibleSubGroups") int numEligibleSubGroups,
            @JsonProperty("memoryUsage") DataSize memoryUsage,
            @JsonProperty("numAggregatedRunningQueries") int numAggregatedRunningQueries,
            @JsonProperty("numAggregatedQueuedQueries") int numAggregatedQueuedQueries)
    {
        this(id, softMemoryLimit, softConcurrencyLimit, hardConcurrencyLimit, runningTimeLimit, maxQueuedQueries, queuedTimeLimit, state, numEligibleSubGroups, memoryUsage, numAggregatedRunningQueries, numAggregatedQueuedQueries, emptyList());
    }

    public ResourceGroupInfo(
            ResourceGroupId id,
            DataSize softMemoryLimit,
            int softConcurrencyLimit,
            int hardConcurrencyLimit,
            Duration runningTimeLimit,
            int maxQueuedQueries,
            Duration queuedTimeLimit,
            ResourceGroupState state,
            int numEligibleSubGroups,
            DataSize memoryUsage,
            int numAggregatedRunningQueries,
            int numAggregatedQueuedQueries,
            List<ResourceGroupInfo> subGroups)
    {
        this.id = requireNonNull(id, "id is null");
        this.softMemoryLimit = requireNonNull(softMemoryLimit, "softMemoryLimit is null");
        this.softConcurrencyLimit = softConcurrencyLimit;
        this.hardConcurrencyLimit = hardConcurrencyLimit;
        this.runningTimeLimit = runningTimeLimit;
        this.maxQueuedQueries = maxQueuedQueries;
        this.queuedTimeLimit = queuedTimeLimit;
        this.state = requireNonNull(state, "state is null");
        this.numEligibleSubGroups = numEligibleSubGroups;
        this.memoryUsage = requireNonNull(memoryUsage, "memoryUsage is null");
        this.numAggregatedRunningQueries = numAggregatedRunningQueries;
        this.numAggregatedQueuedQueries = numAggregatedQueuedQueries;
        this.subGroups = unmodifiableList(requireNonNull(subGroups, "subGroups is null"));
    }

    @JsonProperty
    public ResourceGroupId getId()
    {
        return id;
    }

    @JsonProperty
    public DataSize getSoftMemoryLimit()
    {
        return softMemoryLimit;
    }

    @JsonProperty
    public int getSoftConcurrencyLimit()
    {
        return softConcurrencyLimit;
    }

    @JsonProperty
    public int getHardConcurrencyLimit()
    {
        return hardConcurrencyLimit;
    }

    @JsonProperty
    @Deprecated
    public int getMaxRunningQueries()
    {
        // TODO: Remove when dependent tools are updated
        return hardConcurrencyLimit;
    }

    @JsonProperty
    public Duration getRunningTimeLimit()
    {
        return runningTimeLimit;
    }

    @JsonProperty
    public int getMaxQueuedQueries()
    {
        return maxQueuedQueries;
    }

    @JsonProperty
    public Duration getQueuedTimeLimit()
    {
        return queuedTimeLimit;
    }

    public List<ResourceGroupInfo> getSubGroups()
    {
        return subGroups;
    }

    @JsonProperty
    public DataSize getMemoryUsage()
    {
        return memoryUsage;
    }

    public Optional<ResourceGroupInfo> getSubGroup(ResourceGroupId resourceGroupId)
    {
        return subGroups.stream()
                .filter(subGroup -> subGroup.getId().equals(resourceGroupId) || subGroup.getId().isAncestorOf(resourceGroupId))
                .findFirst();
    }

    @JsonProperty
    public int getNumAggregatedRunningQueries()
    {
        return numAggregatedRunningQueries;
    }

    @JsonProperty
    public int getNumAggregatedQueuedQueries()
    {
        return numAggregatedQueuedQueries;
    }

    @JsonProperty
    public ResourceGroupState getState()
    {
        return state;
    }

    @JsonProperty
    public int getNumEligibleSubGroups()
    {
        return numEligibleSubGroups;
    }

    public ResourceGroupInfo createSingleNodeInfo()
    {
        return new ResourceGroupInfo(
                getId(),
                getSoftMemoryLimit(),
                getSoftConcurrencyLimit(),
                getHardConcurrencyLimit(),
                getRunningTimeLimit(),
                getMaxQueuedQueries(),
                getQueuedTimeLimit(),
                getState(),
                getNumEligibleSubGroups(),
                getMemoryUsage(),
                getNumAggregatedRunningQueries(),
                getNumAggregatedQueuedQueries());
    }
}


text:
::TEST FOR BUG 2520
sgs-sdl-debug -mainfile tests/control-devices.sgs


text:
package org.ovirt.engine.core.common.vdscommands;

import org.ovirt.engine.core.compat.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

//C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "SPMTaskGuidBaseVDSCommandParameters")
public class SPMTaskGuidBaseVDSCommandParameters extends IrsBaseVDSCommandParameters {
    public SPMTaskGuidBaseVDSCommandParameters(Guid storagePoolId, Guid taskId) {
        super(storagePoolId);
        setTaskId(taskId);
    }

    // C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to
    // .NET attributes:
    @XmlElement(name = "TaskId")
    private Guid privateTaskId = new Guid();

    public Guid getTaskId() {
        return privateTaskId;
    }

    private void setTaskId(Guid value) {
        privateTaskId = value;
    }

    public SPMTaskGuidBaseVDSCommandParameters() {
    }

    @Override
    public String toString() {
        return String.format("%s, taskId = %s", super.toString(), getTaskId());
    }
}


text:
void f(orchid::coroutine_handle co) {
    std::cout<<"f:hello world"<<std::endl;
}

void f1(orchid::coroutine_handle co,const char* str) {
    std::cout<<str<<std::endl;
}

struct printer {
    printer(const std::string& s):str(s) {

    }
    void operator()(orchid::coroutine_handle co) {
        std::cout<<str<<std::endl;
    }
    std::string str;
};

void stop(orchid::coroutine_handle co) {
    co -> get_scheduler().stop();
}

int main(int argc,char* argv[]) {
    orchid::scheduler sche;
    printer f2("f2:hello world");
    sche.spawn(f,orchid::coroutine::minimum_stack_size());
    sche.spawn(boost::bind(f1,_1,"f1:hello world"),orchid::coroutine::minimum_stack_size());
    sche.spawn(f2,orchid::coroutine::minimum_stack_size());
    sche.spawn(stop);
    sche.run();
    std::cout<<"done!"<<std::endl;
}


text:
<?php

/**
 * The Response holds all information which are outputtet at the end
 * of the request.
 *
 * @package Zepi\Turbo\Response
 * @author Matthias Zobrist <matthias.zobrist@zepi.net>
 * @copyright Copyright (c) 2015 zepi
 */

namespace Zepi\Turbo\Response;

use \Zepi\Turbo\Request\RequestAbstract;
use \Zepi\Turbo\Request\WebRequest;

/**
 * The Response holds all information which are outputtet at the end
 * of the request.
 *
 * @author Matthias Zobrist <matthias.zobrist@zepi.net>
 * @copyright Copyright (c) 2015 zepi
 */
class Response
{
    /**
     * @access protected
     * @var RequestAbstract
     */
    protected $request;

    /**
     * @access protected
     * @var array
     */
    protected $data = array();

    /**
     * @access protected
     * @var array
     */
    protected $outputParts = array();

    /**
     * @access protected
     * @var string
     */
    protected $output;

    /**
     * @var boolean
     */
    protected $outputLocked = false;

    /**
     * Constructs the object
     *
     * @access public
     * @param \Zepi\Turbo\Request\RequestAbstract $request
     */
    public function __construct(RequestAbstract $request)
    {
        $this->request = $request;
    }

    /**
     * Return the data for the given key. If the key does
     * not exists the function will return false.
     *
     * @access public
     * @param string $key
     * @return mixed
     */
    public function getData($key)
    {
        if (!$this->hasData($key)) {
            return false;
        }

        return $this->data[$key];
    }

    /**
     * Returns true if the given key is set.
     *
     * @access public
     * @param string $key
     * @return boolean
     */
    public function hasData($key)
    {
        return (isset($this->data[$key]));
    }

    /**
     * Saves the value for the given key in the response object.
     *
     * @access public
     * @param string $key
     * @param mixed $value
     */
    public function setData($key, $value)
    {
        $this->data[$key] = $value;
    }

    /**
     * Returns the output for the given key. If the key does
     * not exists the function will return false.
     *
     * @access public
     * @param string $key
     * @return false|string
     */
    public function getOutputPart($key)
    {
        if (!$this->hasOutputPart($key)) {
            return false;
        }

        return $this->outputParts[$key];
    }

    /**
     * Returns true if the given key exists as output key.
     *
     * @access public
     * @param string $key
     * @return boolean
     */
    public function hasOutputPart($key)
    {
        return (isset($this->outputParts[$key]));
    }

    /**
     * Saves the output for the given key in the Response object.
     *
     * @access public
     * @param string $key
     * @param string $output
     */
    public function setOutputPart($key, $output)
    {
        $this->outputParts[$key] = $output;
    }

    /**
     * Returns all output parts of the Response object.
     *
     * @access public
     * @return array
     */
    public function getOutputParts()
    {
        return $this->outputParts;
    }

    /**
     * Returns the output of the response.
     *
     * @access public
     * @return string
     */
    public function getOutput()
    {
        return $this->output;
    }

    /**
     * Returns true if the response has an output.
     *
     * @access public
     * @return boolean
     */
    public function hasOutput()
    {
        return ($this->output != '');
    }

    /**
     * Sets the output of the response.
     * If $lock is true the output will be locked and the method
     * will not accept any other output.
     *
     * @access public
     * @param string $output
     * @param boolean $lock
     * @return boolean
     */
    public function setOutput($output, $lock = false)
    {
        if ($this->outputLocked) {
            return false;
        }

        if ($lock) {
            $this->outputLocked = true;
        }

        $this->output = $output;
        return true;
    }

    /**
     * Returns true if the output in the response is locked.
     *
     * @return boolean
     */
    public function isOutputLocked()
    {
        return ($this->outputLocked);
    }

    /**
     * Set the Location header to redirect a request
     *
     * @access public
     * @param string $target
     * @param integer $headerCode
     * @param boolean $withOrigin
     */
    public function redirectTo($target, $headerCode = 301, $withOrigin = false)
    {
        if (!($this->request instanceof WebRequest)) {
            return;
        }

        if (!preg_match('/http(s?)\:\/\//', $target)) {
            $target = $this->request->getFullRoute($target);
        }

        if ($withOrigin) {
            $target = $this->addOriginToTargetUrl($target);
        }

        header("Location: " . $target, true, $headerCode);
    }

    /**
     * Sends a header
     *
     * @access public
     * @param string $message
     * @param integer $code
     */
    public function sendHeader($message, $code = null)
    {
        if (!($this->request instanceof WebRequest)) {
            return;
        }

        if ($code !== null) {
            header($message, true, $code);
        } else {
            header($message);
        }
    }

    /**
     * Sends the status code for the give code
     *
     * @access public
     * @param integer $code
     * @param boolean $resetOutput
     */
    public function sendHttpStatus($code, $resetOutput = false)
    {
        if (!($this->request instanceof WebRequest)) {
            return;
        }

        $codes = array(
            100 => 'Continue',
            101 => 'Switching Protocols',
            102 => 'Processing',
            200 => 'OK',
            201 => 'Created',
            202 => 'Accepted',
            203 => 'Non-Authoritative Information',
            204 => 'No Content',
            205 => 'Reset Content',
            206 => 'Partial Content',
            207 => 'Multi-Status',
            300 => 'Multiple Choices',
            301 => 'Moved Permanently',
            302 => 'Found',
            303 => 'See Other',
            304 => 'Not Modified',
            305 => 'Use Proxy',
            306 => 'Switch Proxy',
            307 => 'Temporary Redirect',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Timeout',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Request Entity Too Large',
            414 => 'Request-URI Too Long',
            415 => 'Unsupported Media Type',
            416 => 'Requested Range Not Satisfiable',
            417 => 'Expectation Failed',
            418 => 'I\'m a teapot',
            422 => 'Unprocessable Entity',
            423 => 'Locked',
            424 => 'Failed Dependency',
            425 => 'Unordered Collection',
            426 => 'Upgrade Required',
            449 => 'Retry With',
            450 => 'Blocked by Windows Parental Controls',
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Timeout',
            505 => 'HTTP Version Not Supported',
            506 => 'Variant Also Negotiates',
            507 => 'Insufficient Storage',
            509 => 'Bandwidth Limit Exceeded',
            510 => 'Not Extended'
        );

        if (!isset($codes[$code])) {
            return false;
        }

        $message = $this->request->getProtocol() . ' ' . $code . ' ' . $codes[$code];
        header($message, true, $code);

        if ($resetOutput) {
            $this->setOutput($message);
        }
    }

    /**
     * Returns a full url for the given url parts array
     * from the function `parse_url()`.
     *
     * @access public
     * @param array $urlParts
     * @return string
     */
    public function buildUrl($urlParts)
    {
        return http_build_url($urlParts);
    }

    /**
     * Adds the origin and returns the given target url
     * with the origin query parameter.
     *
     * @param string $target
     * @return void|string
     */
    protected function addOriginToTargetUrl($target)
    {
        $origin = $this->request->getFullRoute();
        $additionalQuery = '_origin=' . base64_encode($origin);

        $parts = parse_url($target);

        if ($parts === false) {
            return $target;
        }

        if (!isset($parts['query'])) {
            $parts['query'] = '';
        } else if ($parts['query'] !== '') {
            $parts['query'] .= '&';
        }

        $parts['query'] .= $additionalQuery;
        return $this->buildUrl($parts);
    }
}


text:
@interface NSObject (Definition)

+ (BOOL)customClass;

@end


text:
'use strict';

angular.module('matchstats')
  .controller('NavbarCtrl', function ($scope) {
    $scope.date = new Date();
  });


text:
#pragma once
#include <aws/kinesis-video-archived-media/KinesisVideoArchivedMedia_EXPORTS.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace KinesisVideoArchivedMedia
{
namespace Model
{

  /**
   *
The start and end of the timestamp range for the requested media.

This
   * value should not be present if PlaybackType is
   * LIVE.

The values in the
   * HLSTimestampRange are inclusive. Fragments that begin before the
   * start time but continue past it, or fragments that begin before the end time but
   * continue past it, are included in the session.

See Also:

   * AWS
   * API Reference

   */
  class AWS_KINESISVIDEOARCHIVEDMEDIA_API HLSTimestampRange
  {
  public:
    HLSTimestampRange();
    HLSTimestampRange(Aws::Utils::Json::JsonView jsonValue);
    HLSTimestampRange& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The start of the timestamp range for the requested media.

If the
     * HLSTimestampRange value is specified, the
     * StartTimestamp value is required.

This value is
     * inclusive. Fragments that start before the StartTimestamp and
     * continue past it are included in the session. If
     * FragmentSelectorType is SERVER_TIMESTAMP, the
     * StartTimestamp must be later than the stream head.

     */
    inline const Aws::Utils::DateTime& GetStartTimestamp() const{ return m_startTimestamp; }

    /**
     *
The start of the timestamp range for the requested media.

If the
     * HLSTimestampRange value is specified, the
     * StartTimestamp value is required.

This value is
     * inclusive. Fragments that start before the StartTimestamp and
     * continue past it are included in the session. If
     * FragmentSelectorType is SERVER_TIMESTAMP, the
     * StartTimestamp must be later than the stream head.

     */
    inline bool StartTimestampHasBeenSet() const { return m_startTimestampHasBeenSet; }

    /**
     *
The start of the timestamp range for the requested media.

If the
     * HLSTimestampRange value is specified, the
     * StartTimestamp value is required.

This value is
     * inclusive. Fragments that start before the StartTimestamp and
     * continue past it are included in the session. If
     * FragmentSelectorType is SERVER_TIMESTAMP, the
     * StartTimestamp must be later than the stream head.

     */
    inline void SetStartTimestamp(const Aws::Utils::DateTime& value) { m_startTimestampHasBeenSet = true; m_startTimestamp = value; }

    /**
     *
The start of the timestamp range for the requested media.

If the
     * HLSTimestampRange value is specified, the
     * StartTimestamp value is required.

This value is
     * inclusive. Fragments that start before the StartTimestamp and
     * continue past it are included in the session. If
     * FragmentSelectorType is SERVER_TIMESTAMP, the
     * StartTimestamp must be later than the stream head.

     */
    inline void SetStartTimestamp(Aws::Utils::DateTime&& value) { m_startTimestampHasBeenSet = true; m_startTimestamp = std::move(value); }

    /**
     *
The start of the timestamp range for the requested media.

If the
     * HLSTimestampRange value is specified, the
     * StartTimestamp value is required.

This value is
     * inclusive. Fragments that start before the StartTimestamp and
     * continue past it are included in the session. If
     * FragmentSelectorType is SERVER_TIMESTAMP, the
     * StartTimestamp must be later than the stream head.

     */
    inline HLSTimestampRange& WithStartTimestamp(const Aws::Utils::DateTime& value) { SetStartTimestamp(value); return *this;}

    /**
     *
The start of the timestamp range for the requested media.

If the
     * HLSTimestampRange value is specified, the
     * StartTimestamp value is required.

This value is
     * inclusive. Fragments that start before the StartTimestamp and
     * continue past it are included in the session. If
     * FragmentSelectorType is SERVER_TIMESTAMP, the
     * StartTimestamp must be later than the stream head.

     */
    inline HLSTimestampRange& WithStartTimestamp(Aws::Utils::DateTime&& value) { SetStartTimestamp(std::move(value)); return *this;}

    /**
     *
The end of the timestamp range for the requested media. This value must be
     * within 3 hours of the specified StartTimestamp, and it must be
     * later than the StartTimestamp value.

If
     * FragmentSelectorType for the request is
     * SERVER_TIMESTAMP, this value must be in the past.

The
     * EndTimestamp value is required for ON_DEMAND mode, but
     * optional for LIVE_REPLAY mode. If the EndTimestamp is
     * not set for LIVE_REPLAY mode then the session will continue to
     * include newly ingested fragments until the session expires.

This
     * value is inclusive. The EndTimestamp is compared to the (starting)
     * timestamp of the fragment. Fragments that start before the
     * EndTimestamp value and continue past it are included in the
     * session.

     */
    inline const Aws::Utils::DateTime& GetEndTimestamp() const{ return m_endTimestamp; }

    /**
     *
The end of the timestamp range for the requested media. This value must be
     * within 3 hours of the specified StartTimestamp, and it must be
     * later than the StartTimestamp value.

If
     * FragmentSelectorType for the request is
     * SERVER_TIMESTAMP, this value must be in the past.

The
     * EndTimestamp value is required for ON_DEMAND mode, but
     * optional for LIVE_REPLAY mode. If the EndTimestamp is
     * not set for LIVE_REPLAY mode then the session will continue to
     * include newly ingested fragments until the session expires.

This
     * value is inclusive. The EndTimestamp is compared to the (starting)
     * timestamp of the fragment. Fragments that start before the
     * EndTimestamp value and continue past it are included in the
     * session.

     */
    inline bool EndTimestampHasBeenSet() const { return m_endTimestampHasBeenSet; }

    /**
     *
The end of the timestamp range for the requested media. This value must be
     * within 3 hours of the specified StartTimestamp, and it must be
     * later than the StartTimestamp value.

If
     * FragmentSelectorType for the request is
     * SERVER_TIMESTAMP, this value must be in the past.

The
     * EndTimestamp value is required for ON_DEMAND mode, but
     * optional for LIVE_REPLAY mode. If the EndTimestamp is
     * not set for LIVE_REPLAY mode then the session will continue to
     * include newly ingested fragments until the session expires.

This
     * value is inclusive. The EndTimestamp is compared to the (starting)
     * timestamp of the fragment. Fragments that start before the
     * EndTimestamp value and continue past it are included in the
     * session.

     */
    inline void SetEndTimestamp(const Aws::Utils::DateTime& value) { m_endTimestampHasBeenSet = true; m_endTimestamp = value; }

    /**
     *
The end of the timestamp range for the requested media. This value must be
     * within 3 hours of the specified StartTimestamp, and it must be
     * later than the StartTimestamp value.

If
     * FragmentSelectorType for the request is
     * SERVER_TIMESTAMP, this value must be in the past.

The
     * EndTimestamp value is required for ON_DEMAND mode, but
     * optional for LIVE_REPLAY mode. If the EndTimestamp is
     * not set for LIVE_REPLAY mode then the session will continue to
     * include newly ingested fragments until the session expires.

This
     * value is inclusive. The EndTimestamp is compared to the (starting)
     * timestamp of the fragment. Fragments that start before the
     * EndTimestamp value and continue past it are included in the
     * session.

     */
    inline void SetEndTimestamp(Aws::Utils::DateTime&& value) { m_endTimestampHasBeenSet = true; m_endTimestamp = std::move(value); }

    /**
     *
The end of the timestamp range for the requested media. This value must be
     * within 3 hours of the specified StartTimestamp, and it must be
     * later than the StartTimestamp value.

If
     * FragmentSelectorType for the request is
     * SERVER_TIMESTAMP, this value must be in the past.

The
     * EndTimestamp value is required for ON_DEMAND mode, but
     * optional for LIVE_REPLAY mode. If the EndTimestamp is
     * not set for LIVE_REPLAY mode then the session will continue to
     * include newly ingested fragments until the session expires.

This
     * value is inclusive. The EndTimestamp is compared to the (starting)
     * timestamp of the fragment. Fragments that start before the
     * EndTimestamp value and continue past it are included in the
     * session.

     */
    inline HLSTimestampRange& WithEndTimestamp(const Aws::Utils::DateTime& value) { SetEndTimestamp(value); return *this;}

    /**
     *
The end of the timestamp range for the requested media. This value must be
     * within 3 hours of the specified StartTimestamp, and it must be
     * later than the StartTimestamp value.

If
     * FragmentSelectorType for the request is
     * SERVER_TIMESTAMP, this value must be in the past.

The
     * EndTimestamp value is required for ON_DEMAND mode, but
     * optional for LIVE_REPLAY mode. If the EndTimestamp is
     * not set for LIVE_REPLAY mode then the session will continue to
     * include newly ingested fragments until the session expires.

This
     * value is inclusive. The EndTimestamp is compared to the (starting)
     * timestamp of the fragment. Fragments that start before the
     * EndTimestamp value and continue past it are included in the
     * session.

     */
    inline HLSTimestampRange& WithEndTimestamp(Aws::Utils::DateTime&& value) { SetEndTimestamp(std::move(value)); return *this;}

  private:

    Aws::Utils::DateTime m_startTimestamp;
    bool m_startTimestampHasBeenSet;

    Aws::Utils::DateTime m_endTimestamp;
    bool m_endTimestampHasBeenSet;
  };

} // namespace Model
} // namespace KinesisVideoArchivedMedia
} // namespace Aws


text:
<!DOCTYPE html>

		<title>Welcome to jQuery</title>

Some Content 1

Some Content 2

Some Content 3


text:
namespace chrono {

/// Class for referencing a sphere shape that can be
/// visualized in some way.

class ChApi ChSphereShape : public ChVisualization {

  protected:
    //
    // DATA
    //
    geometry::ChSphere gsphere;

  public:
    //
    // CONSTRUCTORS
    //

    ChSphereShape(){}
    ChSphereShape(const geometry::ChSphere& msphere) : gsphere(msphere){}

    virtual ~ChSphereShape(){}

    //
    // FUNCTIONS
    //

    // Access the sphere geometry
    geometry::ChSphere& GetSphereGeometry() { return gsphere; }

    //
    // SERIALIZATION
    //

    virtual void ArchiveOUT(ChArchiveOut& marchive)
    {
        // version number
        marchive.VersionWrite<ChSphereShape>();
        // serialize parent class
        ChVisualization::ArchiveOUT(marchive);
        // serialize all member data:
        marchive << CHNVP(gsphere);
    }

    /// Method to allow de serialization of transient data from archives.
    virtual void ArchiveIN(ChArchiveIn& marchive)
    {
        // version number
        int version = marchive.VersionRead<ChSphereShape>();
        // deserialize parent class
        ChVisualization::ArchiveIN(marchive);
        // stream in all member data:
        marchive >> CHNVP(gsphere);
    }
};

CH_CLASS_VERSION(ChSphereShape,0)

}  // end namespace chrono

#endif