text:
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Xml.Linq;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Composing.Composers;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.Dtos;
using Umbraco.Core.PropertyEditors;
using Umbraco.Tests.Testing;

namespace Umbraco.Tests.Services.Importing
{
    [TestFixture]
    [Category("Slow")]
    [Apartment(ApartmentState.STA)]
    [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)]
    public class PackageImportTests : TestWithSomeContentBase
    {
        [HideFromTypeFinder]
        public class Editor1 : DataEditor
        {
            public Editor1(ILogger logger)
                : base(logger)
            {
                Alias = "7e062c13-7c41-4ad9-b389-41d88aeef87c";
            }
        }

        [HideFromTypeFinder]
        public class Editor2 : DataEditor
        {
            public Editor2(ILogger logger)
                : base(logger)
            {
                Alias = "d15e1281-e456-4b24-aa86-1dda3e4299d5";
            }
        }

        protected override void Compose()
        {
            base.Compose();

            // the packages that are used by these tests reference totally bogus property
            // editors that must exist - so they are defined here - and in order not to
            // pollute everything, they are ignored by the type finder and explicitely
            // added to the editors collection

            Composition.WithCollectionBuilder<DataEditorCollectionBuilder>()
                .Add<Editor1>()
                .Add<Editor2>();
        }

        protected override void ComposeApplication(bool withApplication)
        {
            base.ComposeApplication(withApplication);

            if (!withApplication) return;

            // re-register with actual media fs
            Composition.ComposeFileSystems();
        }

        [Test]
        public void PackagingService_Can_Import_uBlogsy_ContentTypes_And_Verify_Structure()
        {
            // Arrange
            string strXml = ImportResources.uBlogsy_Package;
            var xml = XElement.Parse(strXml);
            var dataTypeElement = xml.Descendants("DataTypes").First();
            var templateElement = xml.Descendants("Templates").First();
            var docTypeElement = xml.Descendants("DocumentTypes").First();
            var packagingService = ServiceContext.PackagingService;

            // Act
            var dataTypes = packagingService.ImportDataTypeDefinitions(dataTypeElement);
            var templates = packagingService.ImportTemplates(templateElement);
            var contentTypes = packagingService.ImportContentTypes(docTypeElement);

            var numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count();
            var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count();

            // Assert
            Assert.That(dataTypes.Any(), Is.True);
            Assert.That(templates.Any(), Is.True);
            Assert.That(templates.Count(), Is.EqualTo(numberOfTemplates));
            Assert.That(contentTypes.Any(), Is.True);
            Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes));

            var uBlogsyBaseDocType = contentTypes.First(x => x.Alias == "uBlogsyBaseDocType");
            Assert.That(uBlogsyBaseDocType.PropertyTypes.Count(), Is.EqualTo(5));
            Assert.That(uBlogsyBaseDocType.PropertyGroups.Any(), Is.False);

            var uBlogsyBasePage = contentTypes.First(x => x.Alias == "uBlogsyBasePage");
            Assert.That(uBlogsyBasePage.ContentTypeCompositionExists("uBlogsyBaseDocType"), Is.True);
            Assert.That(uBlogsyBasePage.PropertyTypes.Count(), Is.EqualTo(7));
            Assert.That(uBlogsyBasePage.PropertyGroups.Count, Is.EqualTo(3));
            Assert.That(uBlogsyBasePage.PropertyGroups["Content"].PropertyTypes.Count, Is.EqualTo(3));
            Assert.That(uBlogsyBasePage.PropertyGroups["SEO"].PropertyTypes.Count(), Is.EqualTo(3));
            Assert.That(uBlogsyBasePage.PropertyGroups["Navigation"].PropertyTypes.Count(), Is.EqualTo(1));
            Assert.That(uBlogsyBasePage.CompositionPropertyTypes.Count(), Is.EqualTo(12));

            var uBlogsyLanding = contentTypes.First(x => x.Alias == "uBlogsyLanding");
            Assert.That(uBlogsyLanding.ContentTypeCompositionExists("uBlogsyBasePage"), Is.True);
            Assert.That(uBlogsyLanding.ContentTypeCompositionExists("uBlogsyBaseDocType"), Is.True);
            Assert.That(uBlogsyLanding.PropertyTypes.Count(), Is.EqualTo(5));
            Assert.That(uBlogsyLanding.PropertyGroups.Count(), Is.EqualTo(2));
            Assert.That(uBlogsyLanding.CompositionPropertyTypes.Count(), Is.EqualTo(17));
            Assert.That(uBlogsyLanding.CompositionPropertyGroups.Count(), Is.EqualTo(5));
        }

        [Test]
        public void PackagingService_Can_Import_Inherited_ContentTypes_And_Verify_PropertyTypes_UniqueIds()
        {
            // Arrange
            var strXml = ImportResources.InheritedDocTypes_Package;
            var xml = XElement.Parse(strXml);
            var dataTypeElement = xml.Descendants("DataTypes").First();
            var templateElement = xml.Descendants("Templates").First();
            var docTypeElement = xml.Descendants("DocumentTypes").First();
            var packagingService = ServiceContext.PackagingService;

            // Act
            var dataTypes = packagingService.ImportDataTypeDefinitions(dataTypeElement);
            var templates = packagingService.ImportTemplates(templateElement);
            var contentTypes = packagingService.ImportContentTypes(docTypeElement);

            // Assert
            var mRBasePage = contentTypes.First(x => x.Alias == "MRBasePage");
            using (var scope = ScopeProvider.CreateScope())
            foreach (var propertyType in mRBasePage.PropertyTypes)
            {
                var propertyTypeDto = scope.Database.First<PropertyTypeDto>("WHERE id = @id", new { id = propertyType.Id });
                Assert.AreEqual(propertyTypeDto.UniqueId, propertyType.Key);
            }
        }

        [Test]
        public void PackagingService_Can_Import_Inherited_ContentTypes_And_Verify_PropertyGroups_And_PropertyTypes()
        {
            // Arrange
            string strXml = ImportResources.InheritedDocTypes_Package;
            var xml = XElement.Parse(strXml);
            var dataTypeElement = xml.Descendants("DataTypes").First();
            var templateElement = xml.Descendants("Templates").First();
            var docTypeElement = xml.Descendants("DocumentTypes").First();
            var packagingService = ServiceContext.PackagingService;

            // Act
            var dataTypes = packagingService.ImportDataTypeDefinitions(dataTypeElement);
            var templates = packagingService.ImportTemplates(templateElement);
            var contentTypes = packagingService.ImportContentTypes(docTypeElement);

            var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count();

            // Assert
            Assert.That(dataTypes.Any(), Is.False);
            Assert.That(templates.Any(), Is.False);
            Assert.That(contentTypes.Any(), Is.True);
            Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes));

            var mRBasePage = contentTypes.First(x => x.Alias == "MRBasePage");
            Assert.That(mRBasePage.PropertyTypes.Count(), Is.EqualTo(3));
            Assert.That(mRBasePage.PropertyGroups.Count(), Is.EqualTo(1));
            Assert.That(mRBasePage.PropertyGroups["Metadaten"].PropertyTypes.Count(), Is.EqualTo(2));

            var mRStartPage = contentTypes.First(x => x.Alias == "MRStartPage");
            Assert.That(mRStartPage.ContentTypeCompositionExists("MRBasePage"), Is.True);
            Assert.That(mRStartPage.PropertyTypes.Count(), Is.EqualTo(28));
            Assert.That(mRStartPage.PropertyGroups.Count(), Is.EqualTo(7));

            var propertyGroups = mRStartPage.CompositionPropertyGroups.Where(x => x.Name == "Metadaten");
            var propertyTypes = propertyGroups.SelectMany(x => x.PropertyTypes);
            Assert.That(propertyGroups.Count(), Is.EqualTo(2));
            Assert.That(propertyTypes.Count(), Is.EqualTo(6));
        }

        [Test]
        public void PackagingService_Can_Import_Template_Package_Xml()
        {
            // Arrange
            string strXml = ImportResources.StandardMvc_Package;
            var xml = XElement.Parse(strXml);
            var element = xml.Descendants("Templates").First();
            var packagingService = ServiceContext.PackagingService;
            var init = ServiceContext.FileService.GetTemplates().Count();

            // Act
            var templates = packagingService.ImportTemplates(element);
            var numberOfTemplates = (from doc in element.Elements("Template") select doc).Count();
            var allTemplates = ServiceContext.FileService.GetTemplates();

            // Assert
            Assert.That(templates, Is.Not.Null);
            Assert.That(templates.Any(), Is.True);
            Assert.That(templates.Count(), Is.EqualTo(numberOfTemplates));

            Assert.AreEqual(init + numberOfTemplates, allTemplates.Count());
            Assert.IsTrue(allTemplates.All(x => x.Content.Contains("UmbracoViewPage")));
        }

        [Test]
        public void PackagingService_Can_Import_Single_Template()
        {
            // Arrange
            string strXml = ImportResources.StandardMvc_Package;
            var xml = XElement.Parse(strXml);
            var element = xml.Descendants("Templates").First().Element("Template");
            var packagingService = ServiceContext.PackagingService;

            // Act
            var templates = packagingService.ImportTemplates(element);

            // Assert
            Assert.That(templates, Is.Not.Null);
            Assert.That(templates.Any(), Is.True);
            Assert.That(templates.Count(), Is.EqualTo(1));
        }

        [Test]
        public void PackagingService_Can_Import_StandardMvc_ContentTypes_Package_Xml()
        {
            // Arrange
            string strXml = ImportResources.StandardMvc_Package;
            var xml = XElement.Parse(strXml);
            var dataTypeElement = xml.Descendants("DataTypes").First();
            var templateElement = xml.Descendants("Templates").First();
            var docTypeElement = xml.Descendants("DocumentTypes").First();
            var packagingService = ServiceContext.PackagingService;

            // Act
            var dataTypeDefinitions = packagingService.ImportDataTypeDefinitions(dataTypeElement);
            var templates = packagingService.ImportTemplates(templateElement);
            var contentTypes = packagingService.ImportContentTypes(docTypeElement);
            var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count();

            // Assert
            Assert.That(dataTypeDefinitions, Is.Not.Null);
            Assert.That(dataTypeDefinitions.Any(), Is.True);
            Assert.That(templates.Any(), Is.True);
            Assert.That(contentTypes, Is.Not.Null);
            Assert.That(contentTypes.Any(), Is.True);
            Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes));
            Assert.That(contentTypes.Count(x => x.ParentId == -1), Is.EqualTo(1));

            var contentMaster = contentTypes.First(x => x.Alias == "ContentMaster");
            Assert.That(contentMaster.PropertyTypes.Count(), Is.EqualTo(3));
            Assert.That(contentMaster.PropertyGroups.Count(), Is.EqualTo(1));
            Assert.That(contentMaster.PropertyGroups["SEO"].PropertyTypes.Count(), Is.EqualTo(3));
            Assert.That(contentMaster.ContentTypeCompositionExists("Base"), Is.True);

            var propertyGroupId = contentMaster.PropertyGroups["SEO"].Id;
            Assert.That(contentMaster.PropertyGroups["SEO"].PropertyTypes.Any(x => x.PropertyGroupId.Value != propertyGroupId), Is.False);
        }

        [Test]
        public void PackagingService_Can_Import_StandardMvc_ContentTypes_And_Templates_Xml()
        {
            // Arrange
            string strXml = ImportResources.StandardMvc_Package;
            var xml = XElement.Parse(strXml);
            var dataTypeElement = xml.Descendants("DataTypes").First();
            var templateElement = xml.Descendants("Templates").First();
            var docTypeElement = xml.Descendants("DocumentTypes").First();

            // Act
            var dataTypeDefinitions = ServiceContext.PackagingService.ImportDataTypeDefinitions(dataTypeElement);
            var templates = ServiceContext.PackagingService.ImportTemplates(templateElement);
            var contentTypes = ServiceContext.PackagingService.ImportContentTypes(docTypeElement);
            var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count();

            //Assert - Re-Import contenttypes doesn't throw
            Assert.DoesNotThrow(() => ServiceContext.PackagingService.ImportContentTypes(docTypeElement));
            Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes));
            Assert.That(dataTypeDefinitions, Is.Not.Null);
            Assert.That(dataTypeDefinitions.Any(), Is.True);
            Assert.That(templates.Any(), Is.True);
        }

        [Test]
        public void PackagingService_Can_Import_Fanoe_Starterkit_ContentTypes_And_Templates_Xml()
        {
            // Arrange
            string strXml = ImportResources.Fanoe_Package;
            var xml = XElement.Parse(strXml);
            var dataTypeElement = xml.Descendants("DataTypes").First();
            var templateElement = xml.Descendants("Templates").First();
            var docTypeElement = xml.Descendants("DocumentTypes").First();

            // Act
            var dataTypeDefinitions = ServiceContext.PackagingService.ImportDataTypeDefinitions(dataTypeElement);
            var templates = ServiceContext.PackagingService.ImportTemplates(templateElement);
            var contentTypes = ServiceContext.PackagingService.ImportContentTypes(docTypeElement);
            var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count();

            //Assert - Re-Import contenttypes doesn't throw
            Assert.DoesNotThrow(() => ServiceContext.PackagingService.ImportContentTypes(docTypeElement));
            Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes));
            Assert.That(dataTypeDefinitions, Is.Not.Null);
            Assert.That(dataTypeDefinitions.Any(), Is.True);
            Assert.That(templates.Any(), Is.True);
        }

        [Test]
        public void PackagingService_Can_Import_Content_Package_Xml()
        {
            // Arrange
            string strXml = ImportResources.StandardMvc_Package;
            var xml = XElement.Parse(strXml);
            var dataTypeElement = xml.Descendants("DataTypes").First();
            var docTypesElement = xml.Descendants("DocumentTypes").First();
            var element = xml.Descendants("DocumentSet").First();
            var packagingService = ServiceContext.PackagingService;

            // Act
            var dataTypeDefinitions = packagingService.ImportDataTypeDefinitions(dataTypeElement);
            var contentTypes = packagingService.ImportContentTypes(docTypesElement);
            var contents = packagingService.ImportContent(element);
            var numberOfDocs = (from doc in element.Descendants()
                                where (string) doc.Attribute("isDoc") == ""
                                select doc).Count();

            // Assert
            Assert.That(contents, Is.Not.Null);
            Assert.That(dataTypeDefinitions.Any(), Is.True);
            Assert.That(contentTypes.Any(), Is.True);
            Assert.That(contents.Any(), Is.True);
            Assert.That(contents.Count(), Is.EqualTo(numberOfDocs));
        }

        [Test]
        public void PackagingService_Can_Import_CheckboxList_Content_Package_Xml_With_Property_Editor_Aliases()
        {
            AssertCheckBoxListTests(ImportResources.CheckboxList_Content_Package);
        }

        private void AssertCheckBoxListTests(string strXml)
        {
            // Arrange
            var xml = XElement.Parse(strXml);
            var dataTypeElement = xml.Descendants("DataTypes").First();
            var docTypesElement = xml.Descendants("DocumentTypes").First();
            var element = xml.Descendants("DocumentSet").First();
            var packagingService = ServiceContext.PackagingService;

            // Act
            var dataTypeDefinitions = packagingService.ImportDataTypeDefinitions(dataTypeElement);
            var contentTypes = packagingService.ImportContentTypes(docTypesElement);
            var contents = packagingService.ImportContent(element);
            var numberOfDocs = (from doc in element.Descendants()
                                where (string)doc.Attribute("isDoc") == ""
                                select doc).Count();

            string configuration;
            using (var scope = ScopeProvider.CreateScope())
            {
                var dtos = scope.Database.Fetch<DataTypeDto>("WHERE nodeId = @Id", new { dataTypeDefinitions.First().Id });
                configuration = dtos.Single().Configuration;
            }

            // Assert
            Assert.That(dataTypeDefinitions, Is.Not.Null);
            Assert.That(dataTypeDefinitions.Any(), Is.True);
            Assert.AreEqual(Constants.PropertyEditors.Aliases.CheckBoxList, dataTypeDefinitions.First().EditorAlias);
            Assert.That(contents, Is.Not.Null);
            Assert.That(contentTypes.Any(), Is.True);
            Assert.That(contents.Any(), Is.True);
            Assert.That(contents.Count(), Is.EqualTo(numberOfDocs));
            Assert.AreEqual("{\"items\":[{\"id\":59,\"value\":\"test\"},{\"id\":60,\"value\":\"test3\"},{\"id\":61,\"value\":\"test2\"}]}", configuration);
        }

        [Test]
        public void PackagingService_Can_Import_Templates_Package_Xml_With_Invalid_Master()
        {
            // Arrange
            string strXml = ImportResources.XsltSearch_Package;
            var xml = XElement.Parse(strXml);
            var templateElement = xml.Descendants("Templates").First();
            var packagingService = ServiceContext.PackagingService;

            // Act
            var templates = packagingService.ImportTemplates(templateElement);
            var numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count();

            // Assert
            Assert.That(templates.Any(), Is.True);
            Assert.That(templates.Count(), Is.EqualTo(numberOfTemplates));
        }

        [Test]
        public void PackagingService_Can_Import_Single_DocType()
        {
            // Arrange
            string strXml = ImportResources.SingleDocType;
            var docTypeElement = XElement.Parse(strXml);
            var packagingService = ServiceContext.PackagingService;

            // Act
            var contentTypes = packagingService.ImportContentTypes(docTypeElement);

            // Assert
            Assert.That(contentTypes.Any(), Is.True);
            Assert.That(contentTypes.Any(x => x.HasIdentity == false), Is.False);
            Assert.That(contentTypes.Count(), Is.EqualTo(1));
        }

        [Test]
        public void PackagingService_Can_Export_Single_DocType()
        {
            // Arrange
            string strXml = ImportResources.SingleDocType;
            var docTypeElement = XElement.Parse(strXml);
            var packagingService = ServiceContext.PackagingService;

            // Act
            var contentTypes = packagingService.ImportContentTypes(docTypeElement);
            var contentType = contentTypes.FirstOrDefault();
            var element = packagingService.Export(contentType);

            // Assert
            Assert.That(element, Is.Not.Null);
            Assert.That(element.Element("Info"), Is.Not.Null);
            Assert.That(element.Element("Structure"), Is.Not.Null);
            Assert.That(element.Element("GenericProperties"), Is.Not.Null);
            Assert.That(element.Element("Tabs"), Is.Not.Null);
            //Can't compare this XElement because the templates are not imported (they don't exist)
            //Assert.That(XNode.DeepEquals(docTypeElement, element), Is.True);
        }

        [Test]
        public void PackagingService_Can_ReImport_Single_DocType()
        {
            // Arrange
            string strXml = ImportResources.SingleDocType;
            var docTypeElement = XElement.Parse(strXml);

            // Act
            var contentTypes = ServiceContext.PackagingService.ImportContentTypes(docTypeElement);
            var contentTypesUpdated = ServiceContext.PackagingService.ImportContentTypes(docTypeElement);

            // Assert
            Assert.That(contentTypes.Any(), Is.True);
            Assert.That(contentTypes.Any(x => x.HasIdentity == false), Is.False);
            Assert.That(contentTypes.Count(), Is.EqualTo(1));
            Assert.That(contentTypes.First().AllowedContentTypes.Count(), Is.EqualTo(1));

            Assert.That(contentTypesUpdated.Any(), Is.True);
            Assert.That(contentTypesUpdated.Any(x => x.HasIdentity == false), Is.False);
            Assert.That(contentTypesUpdated.Count(), Is.EqualTo(1));
            Assert.That(contentTypesUpdated.First().AllowedContentTypes.Count(), Is.EqualTo(1));
        }

        [Test]
        public void PackagingService_Can_ReImport_Templates_To_Update()
        {
            var newPackageXml = XElement.Parse(ImportResources.TemplateOnly_Package);
            var updatedPackageXml = XElement.Parse(ImportResources.TemplateOnly_Updated_Package);

            var templateElement = newPackageXml.Descendants("Templates").First();
            var templateElementUpdated = updatedPackageXml.Descendants("Templates").First();
            var packagingService = ServiceContext.PackagingService;
            var fileService = ServiceContext.FileService;

            // kill default test data
            fileService.DeleteTemplate("Textpage");

            // Act
            var numberOfTemplates = (from doc in templateElement.Elements("Template") select doc).Count();
            var templates = packagingService.ImportTemplates(templateElement);
            var templatesAfterUpdate = packagingService.ImportTemplates(templateElementUpdated);
            var allTemplates = fileService.GetTemplates();

            // Assert
            Assert.That(templates.Any(), Is.True);
            Assert.That(templates.Count(), Is.EqualTo(numberOfTemplates));
            Assert.That(templatesAfterUpdate.Count(), Is.EqualTo(numberOfTemplates));
            Assert.That(allTemplates.Count(), Is.EqualTo(numberOfTemplates));
            Assert.That(allTemplates.First(x => x.Alias == "umbHomepage").Content, Contains.Substring("THIS HAS BEEN UPDATED!"));
        }

        [Test]
        public void PackagingService_Can_Import_DictionaryItems()
        {
            // Arrange
            const string expectedEnglishParentValue = "ParentValue";
            const string expectedNorwegianParentValue = "ForelderVerdi";
            const string expectedEnglishChildValue = "ChildValue";
            const string expectedNorwegianChildValue = "BarnVerdi";

            var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package);
            var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First();

            AddLanguages();

            // Act
            ServiceContext.PackagingService.ImportDictionaryItems(dictionaryItemsElement);

            // Assert
            AssertDictionaryItem("Parent", expectedEnglishParentValue, "en-GB");
            AssertDictionaryItem("Parent", expectedNorwegianParentValue, "nb-NO");
            AssertDictionaryItem("Child", expectedEnglishChildValue, "en-GB");
            AssertDictionaryItem("Child", expectedNorwegianChildValue, "nb-NO");
        }

        [Test]
        public void PackagingService_Can_Import_Nested_DictionaryItems()
        {
            // Arrange
            const string parentKey = "Parent";
            const string childKey = "Child";

            var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package);
            var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First();

            AddLanguages();

            // Act
            var dictionaryItems = ServiceContext.PackagingService.ImportDictionaryItems(dictionaryItemsElement);

            // Assert
            Assert.That(ServiceContext.LocalizationService.DictionaryItemExists(parentKey), "DictionaryItem parentKey does not exist");
            Assert.That(ServiceContext.LocalizationService.DictionaryItemExists(childKey), "DictionaryItem childKey does not exist");

            var parentDictionaryItem = ServiceContext.LocalizationService.GetDictionaryItemByKey(parentKey);
            var childDictionaryItem = ServiceContext.LocalizationService.GetDictionaryItemByKey(childKey);

            Assert.That(parentDictionaryItem.ParentId, Is.Not.EqualTo(childDictionaryItem.ParentId));
            Assert.That(childDictionaryItem.ParentId, Is.EqualTo(parentDictionaryItem.Key));
        }

        [Test]
        public void PackagingService_WhenExistingDictionaryKey_ImportsNewChildren()
        {
            // Arrange
            const string expectedEnglishParentValue = "ExistingParentValue";
            const string expectedNorwegianParentValue = "EksisterendeForelderVerdi";
            const string expectedEnglishChildValue = "ChildValue";
            const string expectedNorwegianChildValue = "BarnVerdi";

            var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package);
            var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First();

            AddLanguages();
            AddExistingEnglishAndNorwegianParentDictionaryItem(expectedEnglishParentValue, expectedNorwegianParentValue);

            // Act
            ServiceContext.PackagingService.ImportDictionaryItems(dictionaryItemsElement);

            // Assert
            AssertDictionaryItem("Parent", expectedEnglishParentValue, "en-GB");
            AssertDictionaryItem("Parent", expectedNorwegianParentValue, "nb-NO");
            AssertDictionaryItem("Child", expectedEnglishChildValue, "en-GB");
            AssertDictionaryItem("Child", expectedNorwegianChildValue, "nb-NO");
        }

        [Test]
        public void PackagingService_WhenExistingDictionaryKey_OnlyAddsNewLanguages()
        {
            // Arrange
            const string expectedEnglishParentValue = "ExistingParentValue";
            const string expectedNorwegianParentValue = "ForelderVerdi";
            const string expectedEnglishChildValue = "ChildValue";
            const string expectedNorwegianChildValue = "BarnVerdi";

            var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package);
            var dictionaryItemsElement = newPackageXml.Elements("DictionaryItems").First();

            AddLanguages();
            AddExistingEnglishParentDictionaryItem(expectedEnglishParentValue);

            // Act
            ServiceContext.PackagingService.ImportDictionaryItems(dictionaryItemsElement);

            // Assert
            AssertDictionaryItem("Parent", expectedEnglishParentValue, "en-GB");
            AssertDictionaryItem("Parent", expectedNorwegianParentValue, "nb-NO");
            AssertDictionaryItem("Child", expectedEnglishChildValue, "en-GB");
            AssertDictionaryItem("Child", expectedNorwegianChildValue, "nb-NO");
        }

        [Test]
        public void PackagingService_Can_Import_Languages()
        {
            // Arrange
            var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package);
            var LanguageItemsElement = newPackageXml.Elements("Languages").First();

            // Act
            var languages = ServiceContext.PackagingService.ImportLanguages(LanguageItemsElement);
            var allLanguages = ServiceContext.LocalizationService.GetAllLanguages();

            // Assert
            Assert.That(languages.Any(x => x.HasIdentity == false), Is.False);
            foreach (var language in languages)
            {
                Assert.That(allLanguages.Any(x => x.IsoCode == language.IsoCode), Is.True);
            }
        }

        [Test]
        public void PackagingService_Can_Import_Macros()
        {
            // Arrange
            string strXml = ImportResources.uBlogsy_Package;
            var xml = XElement.Parse(strXml);
            var macrosElement = xml.Descendants("Macros").First();
            var packagingService = ServiceContext.PackagingService;

            // Act
            var macros = packagingService.ImportMacros(macrosElement).ToList();

            // Assert
            Assert.That(macros.Any(), Is.True);

            var allMacros = ServiceContext.MacroService.GetAll().ToList();
            foreach (var macro in macros)
            {
                Assert.That(allMacros.Any(x => x.Alias == macro.Alias), Is.True);
            }
        }

        [Test]
        public void PackagingService_Can_Import_Macros_With_Properties()
        {
            // Arrange
            string strXml = ImportResources.XsltSearch_Package;
            var xml = XElement.Parse(strXml);
            var macrosElement = xml.Descendants("Macros").First();
            var packagingService = ServiceContext.PackagingService;

            // Act
            var macros = packagingService.ImportMacros(macrosElement).ToList();

            // Assert
            Assert.That(macros.Any(), Is.True);
            Assert.That(macros.First().Properties.Values.Any(), Is.True);

            var allMacros = ServiceContext.MacroService.GetAll().ToList();
            foreach (var macro in macros)
            {
                Assert.That(allMacros.Any(x => x.Alias == macro.Alias), Is.True);
            }
        }

        [Test]
        public void PackagingService_Can_Import_Package_With_Compositions()
        {
            // Arrange
            string strXml = ImportResources.CompositionsTestPackage;
            var xml = XElement.Parse(strXml);
            var templateElement = xml.Descendants("Templates").First();
            var docTypeElement = xml.Descendants("DocumentTypes").First();
            var packagingService = ServiceContext.PackagingService;

            // Act
            var templates = packagingService.ImportTemplates(templateElement);
            var contentTypes = packagingService.ImportContentTypes(docTypeElement);
            var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count();

            // Assert
            Assert.That(contentTypes, Is.Not.Null);
            Assert.That(contentTypes.Any(), Is.True);
            Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes));
            Assert.That(contentTypes.Count(x => x.ParentId == -1), Is.EqualTo(3));

            var textpage = contentTypes.First(x => x.Alias.Equals("umbTextyPage"));
            Assert.That(textpage.ParentId, Is.Not.EqualTo(-1));
            Assert.That(textpage.ContentTypeComposition.Count(), Is.EqualTo(3));
            Assert.That(textpage.ContentTypeCompositionExists("umbMaster"), Is.True);
            Assert.That(textpage.ContentTypeCompositionExists("Meta"), Is.True);
            Assert.That(textpage.ContentTypeCompositionExists("Seo"), Is.True);
        }

        [Test]
        public void PackagingService_Can_Import_Package_With_Compositions_Ordered()
        {
            // Arrange
            string strXml = ImportResources.CompositionsTestPackage_Random;
            var xml = XElement.Parse(strXml);
            var docTypeElement = xml.Descendants("DocumentTypes").First();
            var packagingService = ServiceContext.PackagingService;

            // Act
            var contentTypes = packagingService.ImportContentTypes(docTypeElement);
            var numberOfDocTypes = (from doc in docTypeElement.Elements("DocumentType") select doc).Count();

            // Assert
            Assert.That(contentTypes, Is.Not.Null);
            Assert.That(contentTypes.Any(), Is.True);
            Assert.That(contentTypes.Count(), Is.EqualTo(numberOfDocTypes));

            var testContentType = contentTypes.First(x => x.Alias.Equals("CompositeTest"));
            Assert.That(testContentType.ContentTypeComposition.Count(), Is.EqualTo(3));
            Assert.That(testContentType.ContentTypeCompositionExists("Content"), Is.True);
            Assert.That(testContentType.ContentTypeCompositionExists("Meta"), Is.True);
            Assert.That(testContentType.ContentTypeCompositionExists("Seo"), Is.True);
        }

        private void AddLanguages()
        {
            var norwegian = new Core.Models.Language("nb-NO");
            var english = new Core.Models.Language("en-GB");
            ServiceContext.LocalizationService.Save(norwegian, 0);
            ServiceContext.LocalizationService.Save(english, 0);
        }

        private void AssertDictionaryItem(string key, string expectedValue, string cultureCode)
        {
            Assert.That(ServiceContext.LocalizationService.DictionaryItemExists(key), "DictionaryItem key does not exist");
            var dictionaryItem = ServiceContext.LocalizationService.GetDictionaryItemByKey(key);
            var translation = dictionaryItem.Translations.SingleOrDefault(i => i.Language.IsoCode == cultureCode);
            Assert.IsNotNull(translation, "Translation to {0} was not added", cultureCode);
            var value = translation.Value;
            Assert.That(value, Is.EqualTo(expectedValue), "Translation value was not set");
        }

        private void AddExistingEnglishParentDictionaryItem(string expectedEnglishParentValue)
        {
            var languages = ServiceContext.LocalizationService.GetAllLanguages().ToList();
            var englishLanguage = languages.Single(l => l.IsoCode == "en-GB");
            ServiceContext.LocalizationService.Save(
                new DictionaryItem("Parent")
                {
                    Translations = new List<IDictionaryTranslation>
                                    {
                                            new DictionaryTranslation(englishLanguage, expectedEnglishParentValue),
                                    }
                }
            );
        }

        private void AddExistingEnglishAndNorwegianParentDictionaryItem(string expectedEnglishParentValue, string expectedNorwegianParentValue)
        {
            var languages = ServiceContext.LocalizationService.GetAllLanguages().ToList();
            var englishLanguage = languages.Single(l => l.IsoCode == "en-GB");
            var norwegianLanguage = languages.Single(l => l.IsoCode == "nb-NO");
            ServiceContext.LocalizationService.Save(
                new DictionaryItem("Parent")
                {
                    Translations = new List<IDictionaryTranslation>
                                    {
                                            new DictionaryTranslation(englishLanguage, expectedEnglishParentValue),
                                            new DictionaryTranslation(norwegianLanguage, expectedNorwegianParentValue),
                                    }
                }
            );
        }
    }
}


text:
require 'ruboty/gen'
require 'ruboty/gen/article'
require 'ruboty/gen/version'
require 'ruboty/dsl'
require 'ruboty/models'

module Ruboty
  # Generator
  module Gen
  end
end

redpajama_set_name: RedPajamaGithub


text:
#include "Timer_private.h"

#include <time.h>

namespace alvar {

class TimerPrivateData
{
public:
    TimerPrivateData()
        : mStart()
    {
    }

    timespec mStart;
};

TimerPrivate::TimerPrivate()
    : d(new TimerPrivateData())
{
}

TimerPrivate::~TimerPrivate()
{
    delete d;
}

void TimerPrivate::start()
{
    clock_gettime(CLOCK_MONOTONIC, &d->mStart);
}

double TimerPrivate::stop()
{
    timespec stop;
    clock_gettime(CLOCK_MONOTONIC, &stop);
    return (stop.tv_sec - d->mStart.tv_sec) +
           (stop.tv_nsec - d->mStart.tv_nsec) / 1000000000.0;
}

} // namespace alvar


text:
#import <AppKit/AppKit.h>

#import <React/RCTView.h>
#import <React/NSView+React.h>

#import "RCTBaseTextInputView.h"

@class RCTBridge;

@interface RCTMultilineTextInputView : RCTBaseTextInputView

//@property (nonatomic, assign) BOOL blurOnSubmit;
//@property (nonatomic, assign) BOOL clearTextOnFocus;
//@property (nonatomic, assign) BOOL selectTextOnFocus;
@property (nonatomic, assign) NSEdgeInsets contentInset;
@property (nonatomic, assign) BOOL automaticallyAdjustContentInsets;
@property (nonatomic, copy) NSString *text;
@property (nonatomic, strong) NSColor *placeholderTextColor;
@property (nonatomic, copy) NSString *placeholder;
@property (nonatomic, strong) NSFont *font;
// @property (nonatomic, assign) NSInteger mostRecentEventCount;
@property (nonatomic, strong) NSNumber *maxLength;

@property (nonatomic, copy) RCTDirectEventBlock onChange;
@property (nonatomic, copy) RCTDirectEventBlock onTextInput;
@property (nonatomic, copy) RCTDirectEventBlock onScroll;

- (void)performTextUpdate;

@end


text:
@interface AuthorAndDynastyDetailVC : UITableViewController

@property (nonatomic, strong) id dataSource;

@end


text:
using Samurai;
using Samurai.GLFW;
using Samurai.Graphics;
using System;
using System.IO;
using System.Runtime.InteropServices;

namespace WavingFlagSample
{
    public class WavingFlagSample : Game
	{
		[StructLayout(LayoutKind.Sequential)]
		struct Vertex
		{
			public Vector2 Position;

			public Vector2 UV;
		}

		ShaderProgram shader;
		Texture2D texture;
		StaticVertexBuffer<Vertex> vertexBuffer;
		StaticIndexBuffer<ushort> indexBuffer;

		float totalElapsedSeconds;

		public WavingFlagSample()
			: base()
		{
			this.Window.Title = "Samurai Waving Flag Sample";

			this.shader = new ShaderProgram(
				this.Graphics,
				VertexShader.Compile(this.Graphics, File.ReadAllText("WavingFlagSample.vert")),
				FragmentShader.Compile(this.Graphics, File.ReadAllText("WavingFlagSample.frag")));

			this.Graphics.ShaderProgram = this.shader;

			this.texture = Texture2D.LoadFromFile(this.Graphics, "Flag.png", TextureParams.Default);

			int totalChunks = 100;
			int chunkSize = this.texture.Width / totalChunks;
			Rectangle destination = new Rectangle(
				(this.Window.Width - this.texture.Width) / 2,
				(this.Window.Height - this.texture.Height) / 2,
				chunkSize,
				this.texture.Height);

			Rectangle source = new Rectangle(0, 0, chunkSize, this.texture.Height);

			Vertex[] vertexData = new Vertex[totalChunks * 4];

			for (int i = 0; i < totalChunks * 4; i += 4)
			{
				vertexData[i] = new Vertex() { Position = new Vector2(destination.X, destination.Y), UV = new Vector2(source.X / (float)texture.Width, 0) };
				vertexData[i + 1] = new Vertex() { Position = new Vector2(destination.X + chunkSize, destination.Y), UV = new Vector2((source.X + chunkSize) / (float)texture.Width, 0) };
				vertexData[i + 2] = new Vertex() { Position = new Vector2(destination.X + chunkSize, destination.Y + this.texture.Height), UV = new Vector2((source.X + chunkSize) / (float)texture.Width, 1.0f) };
				vertexData[i + 3] = new Vertex() { Position = new Vector2(destination.X, destination.Y + this.texture.Height), UV = new Vector2(source.X / (float)texture.Width, 1.0f) };

				destination.X += chunkSize;
				source.X += chunkSize;
			}

			this.vertexBuffer = new StaticVertexBuffer<Vertex>(this.Graphics, vertexData);

			ushort[] indexData = new ushort[vertexData.Length * 6];

			for (ushort i = 0, vertex = 0; i < indexData.Length; i += 6, vertex += 4)
			{
				indexData[i] = vertex;
				indexData[i + 1] = (ushort)(vertex + 1);
				indexData[i + 2] = (ushort)(vertex + 2);
				indexData[i + 3] = vertex;
				indexData[i + 4] = (ushort)(vertex + 2);
				indexData[i + 5] = (ushort)(vertex + 3);
			}

			this.indexBuffer = new StaticIndexBuffer<ushort>(this.Graphics, indexData);
		}

		protected override void Draw(TimeSpan elapsed)
		{
			this.Graphics.Clear(Color4.CornflowerBlue);

			Matrix4 projection = new Matrix4()
			{
				M11 = 2f / this.Window.Width,
				M22 = -2f / this.Window.Height,
				M33 = 1f,
				M44 = 1f,
				M41 = -1f,
				M42 = 1f
			};

			totalElapsedSeconds += (float)elapsed.TotalSeconds;

			this.shader.SetValue("projection", ref projection);
			this.shader.SetValue("startX", (float)((this.Window.Width - this.texture.Width) / 2));
			this.shader.SetValue("time", totalElapsedSeconds);
			this.shader.SetValue("texture0", this.texture);

			this.Graphics.Draw(PrimitiveType.Triangles, this.vertexBuffer, this.indexBuffer);

			this.Graphics.SwapBuffers();
		}

		public static void Main()
		{
			using (WavingFlagSample sample = new WavingFlagSample())
				sample.Run();
		}
	}
}


text:
{% extends 'layouts/default.html' %}
{% block content %}
  <section data-ui-view></section>
  <script type="text/javascript">
    window.user = {{user|json|safe}};
    window.modules = null;
  </script>
{% endblock %}


text:
> see https://aka.ms/autorest

``` yaml
input-file: petstore.json

csharp:
  namespace: Petstore
  output-folder: Client
  # azure-arm: true               # uncomment this line to enable code generation in the Azure flavor
```


text:
#ifndef SkAddIntersections_DEFINED
#define SkAddIntersections_DEFINED

#include "SkIntersectionHelper.h"
#include "SkIntersections.h"
#include "SkTArray.h"

bool AddIntersectTs(SkOpContour* test, SkOpContour* next);
void AddSelfIntersectTs(SkOpContour* test);
void CoincidenceCheck(SkTArray<SkOpContour*, true>* contourList, int total);

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/top_tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabSelectedTextColor="@color/colorAccent"
        app:tabTextColor="@android:color/black"
        app:tabBackground="@color/white"
        app:tabGravity="fill"
        app:tabMode="scrollable"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/news_view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>


text:
<?xml version="1.0" encoding="utf-8"?>

<!-- $Revision: 334345 $ -->
<refentry xml:id="mongogridfs.remove" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>MongoGridFS::remove</refname>
  <refpurpose>Remove files and their chunks from the database</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <type>bool|array</type><methodname>MongoGridFS::remove</methodname>
   <methodparam choice="opt"><type>array</type><parameter>criteria</parameter><initializer>array()</initializer></methodparam>
   <methodparam choice="opt"><type>array</type><parameter>options</parameter><initializer>array()</initializer></methodparam>
  </methodsynopsis>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term>
      <parameter>criteria</parameter>
     </term>
     <listitem>
      <para>
       The filename or criteria for which to search.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term>
      <parameter>options</parameter>
     </term>
     <listitem>
      <para>
       An array of options for the remove operations executed against the
       <literal>chunks</literal> and <literal>files</literal> collections. See
       <function>MongoCollection::remove</function> for documentation on these
       options.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   Returns an array containing the status of the removal (with respect to the
   <literal>files</literal> collection) if the <literal>"w"</literal> option is
   set. Otherwise, returns &true;.
  </para>
  <para>
   Fields in the status array are described in the documentation for
   <function>MongoCollection::insert</function>.
  </para>
 </refsect1>

 <refsect1 role="errors">
  &reftitle.errors;
  &mongo.errors.exceptions.writeconcern;
 </refsect1>

</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
'use strict';

const linz = require('linz');

let UserSchema;

// Wait for the database
beforeAll((done) => {

    // Init Linz.
    linz.init({
        options: {
            'mongo': 'mongodb://mongodb:27017/versions-test',
            'user model': 'user',
            'load models': false,
            'load configs': false
        }
    });

    linz.once('initialised', () => {

        linz.init({
            'mongo': 'mongodb://127.0.0.1/concurrency-control-test',
            'user model': 'user',
            'load models': false,
            'load configs': false
        });

        // setup a basic user model
        var UserSchema = new linz.mongoose.Schema({
            username: String,
            password: String,
            email: String
        });

        UserSchema.virtual('hasAdminAccess').get(() => {
            return true;
        });

        return done();

    });

}, 10000);

afterAll((done) => linz.mongoose.connection.close(done));

describe('concurrency control', () => {

    const modifiedByProperty = 'modifiedBy';
    const modifiedByCellRenderer = () => {};
    const exclusions = ['createdBy'];

    describe('extends the schema', () => {

        let TestSchema;
        let TestSchema1;

        beforeAll(() => {

            TestSchema = new linz.mongoose.Schema({ label: String });
            TestSchema1 = new linz.mongoose.Schema({ modifiedBy: String });

        });

        test('should throw error if options is not provided', () => {
            expect(() => {
                TestSchema.plugin(linz.concurrencyControl.plugin);
            }).toThrow('options is required');

        });

        test('should throw error if options.modifiedByProperty is not provided', () => {

            expect(() => {
                TestSchema.plugin(linz.concurrencyControl.plugin, {});
            }).toThrow('options.modifiedByProperty is required');
        });

        test('should throw error if options.modifiedByCellRenderer is not provided', () => {

            expect(() => {
                TestSchema.plugin(linz.concurrencyControl.plugin, {
                    modifiedByProperty: modifiedByProperty
                });
            }).toThrow('options.modifiedByCellRenderer is required');
        });

        test('should throw error if options.modifiedByProperty is not defined in the provided schema', () => {

            expect(() => {
                TestSchema.plugin(linz.concurrencyControl.plugin, {
                    modifiedByProperty: modifiedByProperty,
                    modifiedByCellRenderer: modifiedByCellRenderer
                });
            }).toThrow('settings.modifiedByProperty "' + modifiedByProperty + '" has been provided, but it is not defined in your schema.');

        });

        test('should throw error if options.modifiedByProperty is included in the exclusions settings', () => {

            expect(() => {
                TestSchema1.plugin(linz.concurrencyControl.plugin, {
                    modifiedByProperty: modifiedByProperty,
                    modifiedByCellRenderer: modifiedByCellRenderer,
                    settings: {
                        exclusions: [modifiedByProperty]
                    }
                });
            }).toThrow('settings.modifiedByProperty "' + modifiedByProperty + '" is required and cannot be excluded.');

        });

    })

    describe('sets versions options', () => {

        describe('defaults', () => {

            let ccSettings;
            let TestModel;
            let TestSchema;

            beforeAll((done) => {

                TestSchema = new linz.mongoose.Schema({ modifiedBy: String });

                TestSchema.plugin(linz.concurrencyControl.plugin, {
                    modifiedByProperty: modifiedByProperty,
                    modifiedByCellRenderer: modifiedByCellRenderer
                });

                TestModel = linz.mongoose.model('TestModel', TestSchema);

                TestModel.getConcurrencyControlOptions((err, settings) => {
                    ccSettings = settings;
                    return done(err);
                });

            });

            test('options.settings.exclusions should defaults to ["_id","dateCreated","dateModified"]', () => {

                expect(ccSettings).toBeTruthy();
                expect(ccSettings.settings).toBeTruthy();
                expect(ccSettings.settings.exclusions).toBeTruthy();
                expect(ccSettings.settings.exclusions[0]).toEqual('_id');
                expect(ccSettings.settings.exclusions[1]).toEqual('dateCreated');
                expect(ccSettings.settings.exclusions[2]).toEqual('dateModified');

            });

        });

        describe('overwrites', () => {

            let TestSchema;
            let ccSettings;
            let TestModel;

            beforeAll((done) => {

                TestSchema = new linz.mongoose.Schema({ modifiedBy: String });

                TestSchema.plugin(linz.concurrencyControl.plugin, {
                    modifiedByProperty: modifiedByProperty,
                    modifiedByCellRenderer: modifiedByCellRenderer,
                    settings: {
                        exclusions: exclusions
                    }
                });

                TestModel = linz.mongoose.model('TestModel1', TestSchema);

                TestModel.getConcurrencyControlOptions((err, settings) => {
                    ccSettings = settings;
                    return done(err);
                });

            });

            test('should overwrite options.settings.exclusions if provided', () => {
                expect(ccSettings).toBeTruthy();
                expect(ccSettings.settings).toBeTruthy();
                expect(ccSettings.settings.exclusions).toBeTruthy();
                expect(ccSettings.settings.exclusions).toHaveLength(1);
                expect(ccSettings.settings.exclusions[0]).toEqual('createdBy');
            });

        });

    });

});


text:
#ifndef _HPM_BOARD_H
#define _HPM_BOARD_H
#include <stdio.h>
#include "hpm_common.h"
#include "hpm_clock_drv.h"
#include "hpm_soc.h"
#include "hpm_soc_feature.h"
#include "pinmux.h"

#define BOARD_NAME "hpm6300evk"
#define BOARD_UF2_SIGNATURE (0x0A4D5048UL)

/* dma section */
#define BOARD_APP_XDMA HPM_XDMA
#define BOARD_APP_HDMA HPM_HDMA
#define BOARD_APP_XDMA_IRQ IRQn_XDMA
#define BOARD_APP_HDMA_IRQ IRQn_HDMA
#define BOARD_APP_DMAMUX HPM_DMAMUX

/* uart section */
#ifndef BOARD_RUNNING_CORE
#define BOARD_RUNNING_CORE HPM_CORE0
#endif
#ifndef BOARD_APP_UART_BASE
#define BOARD_APP_UART_BASE HPM_UART0
#define BOARD_APP_UART_IRQ  IRQn_UART0
#else
#ifndef BOARD_APP_UART_IRQ
#warning no IRQ specified for applicaiton uart
#endif
#endif

#define BOARD_APP_UART_BAUDRATE (115200UL)
#define BOARD_APP_UART_CLK_NAME clock_uart0

#ifndef BOARD_CONSOLE_TYPE
#define BOARD_CONSOLE_TYPE console_type_uart
#endif

#if console_type_uart == BOARD_CONSOLE_TYPE
#ifndef BOARD_CONSOLE_BASE
#if BOARD_RUNNING_CORE == HPM_CORE0
#define BOARD_CONSOLE_BASE HPM_UART0
#define BOARD_CONSOLE_CLK_NAME clock_uart0
#else
#define BOARD_CONSOLE_BASE HPM_UART13
#define BOARD_CONSOLE_CLK_NAME clock_uart13
#endif
#endif
#define BOARD_CONSOLE_BAUDRATE (115200UL)
#endif

#define BOARD_FREEMASTER_UART_BASE HPM_UART0
#define BOARD_FREEMASTER_UART_IRQ IRQn_UART0
#define BOARD_FREEMASTER_UART_CLK_NAME clock_uart0

/* uart rx idle demo section */
#define BOARD_UART_IDLE HPM_UART2
#define BOARD_UART_IDLE_DMA_SRC HPM_DMA_SRC_UART2_RX

#define BOARD_UART_IDLE_TRGM HPM_TRGM1
#define BOARD_UART_IDLE_TRGM_PIN IOC_PAD_PA24
#define BOARD_UART_IDLE_TRGM_INPUT_SRC HPM_TRGM1_INPUT_SRC_TRGM1_P4
#define BOARD_UART_IDLE_TRGM_OUTPUT_GPTMR_IN HPM_TRGM1_OUTPUT_SRC_GPTMR2_IN2
#define BOARD_UART_IDLE_TRGM_OUTPUT_GPTMR_SYNCI HPM_TRGM1_OUTPUT_SRC_GPTMR2_SYNCI

#define BOARD_UART_IDLE_GPTMR HPM_GPTMR2
#define BOARD_UART_IDLE_GPTMR_CLK_NAME clock_gptmr2
#define BOARD_UART_IDLE_GPTMR_IRQ IRQn_GPTMR2
#define BOARD_UART_IDLE_GPTMR_CMP_CH 0
#define BOARD_UART_IDLE_GPTMR_CAP_CH 2

/* sdram section */
#define BOARD_SDRAM_ADDRESS  (0x40000000UL)
#define BOARD_SDRAM_SIZE     (32*SIZE_1MB)
#define BOARD_SDRAM_CS       DRAM_SDRAM_CS0
#define BOARD_SDRAM_PORT_SIZE DRAM_SDRAM_PORT_SIZE_16_BITS
#define BOARD_SDRAM_REFRESH_COUNT (8192UL)
#define BOARD_SDRAM_REFRESH_IN_MS (64UL)
#define BOARD_SDRAM_DATA_WIDTH_IN_BYTE (4UL)

/* nor flash section */
#define BOARD_FLASH_BASE_ADDRESS (0x80000000UL)
#define BOARD_FLASH_SIZE (16 * SIZE_1MB)

/* i2c section */
#define BOARD_APP_I2C_BASE HPM_I2C0
#define BOARD_APP_I2C_CLK_NAME clock_i2c0
#define BOARD_APP_I2C_DMA HPM_HDMA
#define BOARD_APP_I2C_DMAMUX HPM_DMAMUX
#define BOARD_APP_I2C_DMA_SRC HPM_DMA_SRC_I2C0
#define BOARD_APP_I2C_DMAMUX_CH DMAMUX_MUXCFG_HDMA_MUX0

/* ACMP desction */
#define BOARD_ACMP HPM_ACMP
#define BOARD_ACMP_CHANNEL ACMP_CHANNEL_CHN1
#define BOARD_ACMP_IRQ IRQn_ACMP_1
#define BOARD_ACMP_PLUS_INPUT ACMP_INPUT_DAC_OUT /* use internal DAC */
#define BOARD_ACMP_MINUS_INPUT ACMP_INPUT_ANALOG_5 /* align with used pin */

/* dma section */
#define BOARD_APP_XDMA HPM_XDMA
#define BOARD_APP_HDMA HPM_HDMA
#define BOARD_APP_XDMA_IRQ IRQn_XDMA
#define BOARD_APP_HDMA_IRQ IRQn_HDMA
#define BOARD_APP_DMAMUX HPM_DMAMUX

/* gptmr section */
#define BOARD_GPTMR HPM_GPTMR2
#define BOARD_GPTMR_IRQ IRQn_GPTMR2
#define BOARD_GPTMR_CHANNEL 0
#define BOARD_GPTMR_PWM HPM_GPTMR2
#define BOARD_GPTMR_PWM_CHANNEL 0

/* gpio section */
#define BOARD_APP_GPIO_INDEX GPIO_DI_GPIOZ
#define BOARD_APP_GPIO_PIN 2

/* pinmux section */
#define USING_GPIO0_FOR_GPIOZ
#ifndef USING_GPIO0_FOR_GPIOZ
#define BOARD_APP_GPIO_CTRL HPM_BGPIO
#define BOARD_APP_GPIO_IRQ IRQn_BGPIO
#else
#define BOARD_APP_GPIO_CTRL HPM_GPIO0
#define BOARD_APP_GPIO_IRQ IRQn_GPIO0_Z
#endif

/* gpiom section */
#define BOARD_APP_GPIOM_BASE            HPM_GPIOM
#define BOARD_APP_GPIOM_USING_CTRL      HPM_FGPIO
#define BOARD_APP_GPIOM_USING_CTRL_NAME gpiom_core0_fast

/* spi section */
#define BOARD_APP_SPI_BASE HPM_SPI3
#define BOARD_APP_SPI_CLK_SRC_FREQ      (24000000UL)
#define BOARD_APP_SPI_SCLK_FREQ         (1562500UL)
#define BOARD_APP_SPI_ADDR_LEN_IN_BYTES (1U)
#define BOARD_APP_SPI_DATA_LEN_IN_BITS  (8U)
#define BOARD_APP_SPI_RX_DMA HPM_DMA_SRC_SPI3_RX
#define BOARD_APP_SPI_RX_DMAMUX_CH DMAMUX_MUXCFG_HDMA_MUX0
#define BOARD_APP_SPI_TX_DMA HPM_DMA_SRC_SPI3_TX
#define BOARD_APP_SPI_TX_DMAMUX_CH DMAMUX_MUXCFG_HDMA_MUX1
#define BOARD_SPI_CS_GPIO_CTRL           HPM_GPIO0
#define BOARD_SPI_CS_PIN                 IOC_PAD_PC18
#define BOARD_SPI_CS_ACTIVE_LEVEL        (0U)

/* Flash section */
#define BOARD_APP_XPI_NOR_XPI_BASE            (HPM_XPI0)
#define BOARD_APP_XPI_NOR_CFG_OPT_HDR         (0xfcf90001U)
#define BOARD_APP_XPI_NOR_CFG_OPT_OPT0        (0x00000005U)
#define BOARD_APP_XPI_NOR_CFG_OPT_OPT1        (0x00001000U)

/* i2s section */
#define BOARD_APP_I2S_BASE HPM_I2S0
#define BOARD_APP_I2S_DATA_LINE      (2U)
#define BOARD_APP_I2S_CLK_NAME clock_i2s0
#define BOARD_APP_AUDIO_CLK_SRC clock_source_pll2_clk0
#define BOARD_APP_AUDIO_CLK_SRC_NAME clk_pll2clk0

/* enet section */
#define BOARD_ENET_RMII                 HPM_ENET0
#define BOARD_ENET_RMII_RST_GPIO
#define BOARD_ENET_RMII_RST_GPIO_INDEX
#define BOARD_ENET_RMII_RST_GPIO_PIN
#define BOARD_ENET_RMII                 HPM_ENET0
#define BOARD_ENET_RMII_INT_REF_CLK     (1U)
#define BOARD_ENET_RMII_PTP_CLOCK       (clock_ptp0)

/* ADC section */
#define BOARD_APP_ADC16_NAME "ADC0"
#define BOARD_APP_ADC16_BASE HPM_ADC0
#define BOARD_APP_ADC16_IRQn IRQn_ADC0
#define BOARD_APP_ADC16_CH_1                     (13U)
#define BOARD_APP_ADC_TRIG_PWMT0                 HPM_PWM0
#define BOARD_APP_ADC_TRIG_PWMT1                 HPM_PWM1
#define BOARD_APP_ADC_TRIG_TRGM0                 HPM_TRGM0
#define BOARD_APP_ADC_TRIG_TRGM1                 HPM_TRGM1
#define BOARD_APP_ADC_TRIG_PWM_SYNC              HPM_SYNT

/* DAC section */
#define BOARD_DAC_BASE       HPM_DAC
#define BOARD_DAC_IRQn       IRQn_DAC
#define BOARD_DAC_CLOCK_NAME clock_dac0

/* CAN section */
#define BOARD_APP_CAN_BASE                       HPM_CAN1
#define BOARD_APP_CAN_IRQn                       IRQn_CAN1

/*
 * timer for board delay
 */
#define BOARD_DELAY_TIMER (HPM_GPTMR3)
#define BOARD_DELAY_TIMER_CH 0
#define BOARD_DELAY_TIMER_CLK_NAME (clock_gptmr3)

#define BOARD_CALLBACK_TIMER (HPM_GPTMR3)
#define BOARD_CALLBACK_TIMER_CH 1
#define BOARD_CALLBACK_TIMER_IRQ IRQn_GPTMR3
#define BOARD_CALLBACK_TIMER_CLK_NAME (clock_gptmr3)

/* SDXC section */
#define BOARD_APP_SDCARD_SDXC_BASE                  (HPM_SDXC0)
#define BOARD_APP_SDCARD_SUPPORT_1V8                (0)
#define BOARD_APP_SDCARD_SUPPORT_CARD_DETECTION     (1)
#define BOARD_APP_SDCARD_CARD_DETECTION_USING_GPIO  (0)
#if BOARD_APP_SDCARD_CARD_DETECTION_USING_GPIO
#define BOARD_APP_SDCARD_CARD_DETECTION_GPIO        NULL
#define BOARD_APP_SDCARD_CARD_DETECTION_GPIO_INDEX  0
#define BOARD_APP_SDCARD_CARD_DETECTION_PIN_INDEX   0
#endif

/* USB section */
#define BOARD_USB0_ID_PORT       (HPM_GPIO0)
#define BOARD_USB0_ID_GPIO_INDEX (GPIO_DO_GPIOC)
#define BOARD_USB0_ID_GPIO_PIN   (23)

/*BLDC pwm*/

/*PWM define*/
#define BOARD_BLDCPWM                     HPM_PWM0
#define BOARD_BLDC_UH_PWM_OUTPIN         (0U)
#define BOARD_BLDC_UL_PWM_OUTPIN         (1U)
#define BOARD_BLDC_VH_PWM_OUTPIN         (2U)
#define BOARD_BLDC_VL_PWM_OUTPIN         (3U)
#define BOARD_BLDC_WH_PWM_OUTPIN         (4U)
#define BOARD_BLDC_WL_PWM_OUTPIN         (5U)
#define BOARD_BLDCPWM_TRGM                HPM_TRGM0
#define BOARD_BLDCAPP_PWM_IRQ             IRQn_PWM0
#define BOARD_BLDCPWM_CMP_INDEX_0         (0U)
#define BOARD_BLDCPWM_CMP_INDEX_1         (1U)
#define BOARD_BLDCPWM_CMP_INDEX_2         (2U)
#define BOARD_BLDCPWM_CMP_INDEX_3         (3U)
#define BOARD_BLDCPWM_CMP_INDEX_4         (4U)
#define BOARD_BLDCPWM_CMP_INDEX_5         (5U)

/*HALL define*/

#define BOARD_BLDC_HALL_BASE                 HPM_HALL0
#define BOARD_BLDC_HALL_TRGM                 HPM_TRGM0
#define BOARD_BLDC_HALL_IRQ                  IRQn_HALL0
#define BOARD_BLDC_HALL_TRGM_HALL_U_SRC      HPM_TRGM0_INPUT_SRC_TRGM0_IN8
#define BOARD_BLDC_HALL_TRGM_HALL_V_SRC      HPM_TRGM0_INPUT_SRC_TRGM0_IN7
#define BOARD_BLDC_HALL_TRGM_HALL_W_SRC      HPM_TRGM0_INPUT_SRC_TRGM0_IN6
#define BOARD_BLDC_HALL_MOTOR_PHASE_COUNT_PER_REV        (1000U)

/*QEI*/

#define BOARD_BLDC_QEI_BASE              HPM_QEI0
#define BOARD_BLDC_QEI_IRQ               IRQn_QEI0
#define BOARD_BLDC_QEI_TRGM              HPM_TRGM0
#define BOARD_BLDC_QEI_TRGM_QEI_A_SRC    HPM_TRGM0_INPUT_SRC_TRGM0_IN9
#define BOARD_BLDC_QEI_TRGM_QEI_B_SRC    HPM_TRGM0_INPUT_SRC_TRGM0_IN10
#define BOARD_BLDC_QEI_MOTOR_PHASE_COUNT_PER_REV     (16U)
#define BOARD_BLDC_QEI_CLOCK_SOURCE      clock_mot0
#define BOARD_BLDC_QEI_FOC_PHASE_COUNT_PER_REV       (4000U)

/*Timer define*/

#define BOARD_BLDC_TMR_1MS                       HPM_GPTMR2
#define BOARD_BLDC_TMR_CH                        0
#define BOARD_BLDC_TMR_CMP                       0
#define BOARD_BLDC_TMR_IRQ                       IRQn_GPTMR2
#define BOARD_BLDC_TMR_RELOAD                    (100000U)

/*adc*/
#define BOARD_BLDC_ADC_MODULE                  ADCX_MODULE_ADC16
#define BOARD_BLDC_ADC_U_BASE                  HPM_ADC1
#define BOARD_BLDC_ADC_V_BASE                  HPM_ADC0
#define BOARD_BLDC_ADC_W_BASE                  HPM_ADC2
#define BOARD_BLDC_ADC_TRIG_FLAG               adc16_event_trig_complete

#define BOARD_BLDC_ADC_CH_U                    (14U)
#define BOARD_BLDC_ADC_CH_V                    (12U)
#define BOARD_BLDC_ADC_CH_W                    (5U)
#define BOARD_BLDC_ADC_IRQn                    IRQn_ADC1
#define BOARD_BLDC_ADC_SEQ_DMA_SIZE_IN_4BYTES  (40U)
#define BOARD_BLDC_ADC_TRG                    ADC16_CONFIG_TRG0A
#define BOARD_BLDC_ADC_PREEMPT_TRIG_LEN        (1U)
#define BOARD_BLDC_PWM_TRIG_CMP_INDEX          (8U)
#define BOARD_BLDC_TRIGMUX_IN_NUM              HPM_TRGM0_INPUT_SRC_PWM0_CH8REF
#define BOARD_BLDC_TRG_NUM                     TRGM_TRGOCFG_ADCX_PTRGI0A

/* APP PWM */
#define BOARD_APP_PWM HPM_PWM0
#define BOARD_APP_PWM_CLOCK_NAME clock_mot0
#define BOARD_APP_PWM_OUT1 0
#define BOARD_APP_PWM_OUT2 1
#define BOARD_APP_TRGM HPM_TRGM0

#define BOARD_CPU_FREQ (480000000UL)

/* LED */
#define BOARD_LED_GPIO_CTRL HPM_GPIO0
#define BOARD_LED_GPIO_INDEX GPIO_DI_GPIOA
#define BOARD_LED_GPIO_PIN 7
#define BOARD_LED_OFF_LEVEL 1
#define BOARD_LED_ON_LEVEL 0

#ifndef BOARD_SHOW_CLOCK
#define BOARD_SHOW_CLOCK 1
#endif
#ifndef BOARD_SHOW_BANNER
#define BOARD_SHOW_BANNER 1
#endif

#if defined(__cplusplus)
extern "C" {
#endif /* __cplusplus */

typedef void (*board_timer_cb)(void);

void board_init(void);
void board_init_console(void);

void board_init_uart(UART_Type *ptr);
void board_init_i2c(I2C_Type *ptr);

void board_init_can(CAN_Type *ptr);

uint32_t board_init_dram_clock(void);

void board_init_sdram_pins(void);
void board_init_gpio_pins(void);
void board_init_spi_pins(SPI_Type *ptr);
void board_init_spi_pins_with_gpio_as_cs(SPI_Type *ptr);
void board_write_spi_cs(uint32_t pin, uint8_t state);
void board_init_led_pins(void);

void board_led_write(uint8_t state);
void board_led_toggle(void);

/* Initialize SoC overall clocks */
void board_init_clock(void);

uint32_t board_init_spi_clock(SPI_Type *ptr);

uint32_t board_init_adc16_clock(ADC16_Type *ptr);

uint32_t board_init_dac_clock(DAC_Type *ptr, bool clk_src_ahb);

void board_init_adc16_pins(void);

void board_init_dac_pins(DAC_Type *ptr);

uint32_t board_init_can_clock(CAN_Type *ptr);

uint32_t board_init_i2s_clock(I2S_Type *ptr);
uint32_t board_init_pdm_clock(void);
uint32_t board_init_dao_clock(void);

void board_init_sd_pins(SDXC_Type *ptr);
uint32_t board_sd_configure_clock(SDXC_Type *ptr, uint32_t freq);
void board_sd_switch_pins_to_1v8(SDXC_Type *ptr);
bool board_sd_detect_card(SDXC_Type *ptr);

void board_init_usb_pins(void);
void board_usb_vbus_ctrl(uint8_t usb_index, uint8_t level);
uint8_t board_get_usb_id_status(void);

hpm_stat_t board_init_enet_pins(ENET_Type *ptr);
hpm_stat_t board_init_enet_rmii_reference_clock(ENET_Type *ptr, bool internal);
hpm_stat_t board_init_enet_ptp_clock(ENET_Type *ptr);

/*
 * @brief Initialize PMP and PMA for but not limited to the following purposes:
 *      -- non-cacheable memory initialization
 */
void board_init_pmp(void);

void board_delay_us(uint32_t us);
void board_delay_ms(uint32_t ms);

void board_timer_create(uint32_t ms, board_timer_cb cb);
void board_ungate_mchtmr_at_lp_mode(void);

/* Initialize the UART clock */
uint32_t board_init_uart_clock(UART_Type *ptr);

#if defined(__cplusplus)
}
#endif /* __cplusplus */
#endif /* _HPM_BOARD_H */


text:
<#
.SYNOPSIS
    Stub around Invoke-Pester command used by VSCode PowerShell extension.
.DESCRIPTION
    The stub checks the version of Pester and if >= 4.6.0, invokes Pester
    using the LineNumber parameter (if specified). Otherwise, it invokes
    using the TestName parameter (if specified). If the All parameter
    is specified, then all the tests are invoked in the specifed file.
    Finally, if none of these three parameters are specified, all tests
    are invoked and a warning is issued indicating what the user can do
    to allow invocation of individual Describe blocks.
.EXAMPLE
    PS C:\> .\InvokePesterStub.ps1 ~\project\test\foo.tests.ps1 -LineNumber 14
    Invokes a specific test by line number in the specified file.
.EXAMPLE
    PS C:\> .\InvokePesterStub.ps1 ~\project\test\foo.tests.ps1 -TestName 'Foo Tests'
    Invokes a specific test by test name in the specified file.
.EXAMPLE
    PS C:\> .\InvokePesterStub.ps1 ~\project\test\foo.tests.ps1 -All
    Invokes all tests in the specified file.
.INPUTS
    None
.OUTPUTS
    None
#>
param(
    # Specifies the path to the test script.
    [Parameter(Position=0, Mandatory)]
    [ValidateNotNullOrEmpty()]
    [string]
    $ScriptPath,

    # Specifies the name of the test taken from the Describe block's name.
    [Parameter()]
    [string]
    $TestName,

    # Specifies the starting line number of the DescribeBlock.  This feature requires
    # Pester 4.6.0 or higher.
    [Parameter()]
    [ValidatePattern('\d*')]
    [string]
    $LineNumber,

    # If specified, executes all the tests in the specified test script.
    [Parameter()]
    [switch]
    $All,

    [Parameter()]
    [switch] $MinimumVersion5,

    [Parameter(Mandatory)]
    [string] $Output,

    [Parameter()]
    [string] $OutputPath
)

$pesterModule = Microsoft.PowerShell.Core\Get-Module Pester
# add one line, so the subsequent output is not shifted to the side
Write-Output ''

if (!$pesterModule) {
    Write-Output "Importing Pester module..."
    if ($MinimumVersion5) {
        $pesterModule = Microsoft.PowerShell.Core\Import-Module Pester -ErrorAction Ignore -PassThru -MinimumVersion 5.0.0
    }

    if (!$pesterModule) {
        $pesterModule = Microsoft.PowerShell.Core\Import-Module Pester -ErrorAction Ignore -PassThru
    }

    if (!$pesterModule) {
        Write-Warning "Failed to import Pester. You must install Pester module to run or debug Pester tests."
        Write-Warning "$(if ($MinimumVersion5) {"Recommended version to install is Pester 5.0.0 or newer. "})You can install Pester by executing: Install-Module Pester$(if ($MinimumVersion5) {" -MinimumVersion 5.0.0" }) -Scope CurrentUser -Force"
        return
    }
}

$pester4Output = switch ($Output) {
    "None" { "None" }
    "Minimal" { "Fails" }
    default { "All" }
}

if ($MinimumVersion5 -and $pesterModule.Version -lt "5.0.0") {
    Write-Warning "Pester 5.0.0 or newer is required because setting PowerShell > Pester: Use Legacy Code Lens is disabled, but Pester $($pesterModule.Version) is loaded. Some of the code lens features might not work as expected."
}

function Get-InvokePesterParams {
    $invokePesterParams = @{
        Script = $ScriptPath
    }

    if ($pesterModule.Version -ge '3.4.0') {
        # -PesterOption was introduced before 3.4.0, and VSCodeMarker in 4.0.3-rc,
        # but because no-one checks the integrity of this hashtable we can call
        # all of the versions down to 3.4.0 like this
        $invokePesterParams.Add("PesterOption", @{ IncludeVSCodeMarker = $true })
    }

    if ($pesterModule.Version -ge '3.4.5') {
        # -Show was introduced in 3.4.5
        $invokePesterParams.Add("Show", $pester4Output)
    }

    return $invokePesterParams
}

if ($All) {
    if ($pesterModule.Version -ge '5.0.0') {
        $configuration = @{
            Run = @{
                Path = $ScriptPath
            }
        }
        # only override this if user asks us to do it, to allow Pester to pick up
        # $PesterPreference from caller context and merge it with the configuration
        # we provide below, this way user can specify his output (and other) settings
        # using the standard [PesterConfiguration] object, and we can avoid providing
        # settings for everything
        if ("FromPreference" -ne $Output) {
            $configuration.Add('Output', @{ Verbosity = $Output })
        }

        if ($OutputPath) {
            $configuration.Add('TestResult', @{
                Enabled = $true
                OutputPath = $OutputPath
            })
        }
        Pester\Invoke-Pester -Configuration $configuration | Out-Null
    }
    else {
        $invokePesterParams = Get-InvokePesterParams
        Pester\Invoke-Pester @invokePesterParams
    }
}
elseif (($LineNumber -match '\d+') -and ($pesterModule.Version -ge '4.6.0')) {
    if ($pesterModule.Version -ge '5.0.0') {
        $configuration = @{
            Run = @{
                Path = $ScriptPath
            }
            Filter = @{
                Line = "${ScriptPath}:$LineNumber"
            }
        }
        if ("FromPreference" -ne $Output) {
            $configuration.Add('Output', @{ Verbosity = $Output })
        }

        if ($OutputPath) {
            $configuration.Add('TestResult', @{
                Enabled = $true
                OutputPath = $OutputPath
            })
        }

        Pester\Invoke-Pester -Configuration $configuration | Out-Null
    }
    else {
        Pester\Invoke-Pester -Script $ScriptPath -PesterOption (New-PesterOption -ScriptBlockFilter @{
            IncludeVSCodeMarker=$true; Line=$LineNumber; Path=$ScriptPath}) -Show $pester4Output
    }
}
elseif ($TestName) {
    if ($pesterModule.Version -ge '5.0.0') {
       throw "Running tests by test name is unsafe. This should not trigger for Pester 5."
    }
    else {
        $invokePesterParams = Get-InvokePesterParams
        Pester\Invoke-Pester @invokePesterParams
    }
}
else {
    if ($pesterModule.Version -ge '5.0.0') {
       throw "Running tests by expandable string is unsafe. This should not trigger for Pester 5."
    }

    # We get here when the TestName expression is of type ExpandableStringExpressionAst.
    # PSES will not attempt to "evaluate" the expression so it returns null for the TestName.
    Write-Warning "The Describe block's TestName cannot be evaluated. EXECUTING ALL TESTS instead."
    Write-Warning "To avoid this, install Pester >= 4.6.0 or remove any expressions in the TestName."

    $invokePesterParams = Get-InvokePesterParams
    Pester\Invoke-Pester @invokePesterParams
}


text:
package org.drools.examples.decisiontable;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.StatelessKieSession;

import java.util.Arrays;

/**
 * This shows off a decision table.
 */
public class PricingRuleDTExample {

    public static final void main(String[] args) {
        KieContainer kc = KieServices.Factory.get().getKieClasspathContainer();
        System.out.println(kc.verify().getMessages().toString());
        execute( kc );
    }

    public static void execute( KieContainer kc ) {
        StatelessKieSession ksession = kc.newStatelessKieSession( "DecisionTableKS");

        //now create some test data
        Driver driver = new Driver();
        Policy policy = new Policy();

        ksession.execute( Arrays.asList( new Object[]{driver, policy} ) );

        System.out.println( "BASE PRICE IS: " + policy.getBasePrice() );
        System.out.println( "DISCOUNT IS: " + policy.getDiscountPercent() );

        policy.getBasePrice();
    }

}


text:
<?xml version='1.0' encoding='UTF-8'?>
<com.tikal.jenkins.plugins.multijob.MultiJobProject plugin="jenkins-multijob-plugin@1.10-SNAPSHOT">
  <actions/>
  <description>All known working tests in a sequence</description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.model.ParametersDefinitionProperty>
      <parameterDefinitions>
        <hudson.model.StringParameterDefinition>
          <name>repo_url</name>
          <description>Eutester repository to clone tests from</description>
          <defaultValue>git://github.com/eucalyptus/eutester.git</defaultValue>
        </hudson.model.StringParameterDefinition>
        <hudson.model.TextParameterDefinition>
          <name>eucarc</name>
          <description>Eucarc file containing credentials of eucalyptus/admin</description>
          <defaultValue></defaultValue>
        </hudson.model.TextParameterDefinition>
        <hudson.model.TextParameterDefinition>
          <name>topology</name>
          <description>Machine configuration topology.</description>
          <defaultValue><ipaddress> CENTOS 6.4 64 REPO [CLC WS CC00 SC00]
<ipaddress> CENTOS 6.4 64 REPO [NC00]
</defaultValue>
        </hudson.model.TextParameterDefinition>
        <hudson.model.StringParameterDefinition>
          <name>imgurl</name>
          <description>Image URL for BFEBS image.</description>
          <defaultValue></defaultValue>
        </hudson.model.StringParameterDefinition>
        <hudson.model.ChoiceParameterDefinition>
          <name>branch</name>
          <description>Eutester branch to use</description>
          <choices class="java.util.Arrays$ArrayList">
            <a class="string-array">
              <string>master</string>
              <string>testing</string>
            </a>
          </choices>
        </hudson.model.ChoiceParameterDefinition>
      </parameterDefinitions>
    </hudson.model.ParametersDefinitionProperty>
    <hudson.plugins.throttleconcurrents.ThrottleJobProperty plugin="throttle-concurrents@1.7.2">
      <maxConcurrentPerNode>0</maxConcurrentPerNode>
      <maxConcurrentTotal>0</maxConcurrentTotal>
      <throttleEnabled>false</throttleEnabled>
      <throttleOption>project</throttleOption>
    </hudson.plugins.throttleconcurrents.ThrottleJobProperty>
  </properties>
  <scm class="hudson.scm.NullSCM"/>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
      <phaseName>Instance</phaseName>
      <phaseJobs>
        <com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
          <jobName>Instance Suite</jobName>
          <currParams>true</currParams>
          <exposedSCM>false</exposedSCM>
          <configs class="empty-list"/>
        </com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
      </phaseJobs>
      <continuationCondition>SUCCESSFUL</continuationCondition>
    </com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
    <com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
      <phaseName>EBS Tests</phaseName>
      <phaseJobs>
        <com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
          <jobName>EBS Suite</jobName>
          <currParams>true</currParams>
          <exposedSCM>false</exposedSCM>
          <configs class="empty-list"/>
        </com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
      </phaseJobs>
      <continuationCondition>SUCCESSFUL</continuationCondition>
    </com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
    <com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
      <phaseName>Walrus Tests</phaseName>
      <phaseJobs>
        <com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
          <jobName>Walrus Bucket Tests</jobName>
          <currParams>true</currParams>
          <exposedSCM>false</exposedSCM>
          <configs class="empty-list"/>
        </com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
        <com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
          <jobName>Walrus Object Tests</jobName>
          <currParams>true</currParams>
          <exposedSCM>false</exposedSCM>
          <configs class="empty-list"/>
        </com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
      </phaseJobs>
      <continuationCondition>SUCCESSFUL</continuationCondition>
    </com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
    <com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
      <phaseName>CloudWatch Monitoring</phaseName>
      <phaseJobs>
        <com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
          <jobName>CloudWatch</jobName>
          <currParams>true</currParams>
          <exposedSCM>false</exposedSCM>
          <configs class="empty-list"/>
        </com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
      </phaseJobs>
      <continuationCondition>SUCCESSFUL</continuationCondition>
    </com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
    <com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
      <phaseName>Create Users/Accounts using IAM</phaseName>
      <phaseJobs>
        <com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
          <jobName>Create Users</jobName>
          <currParams>true</currParams>
          <exposedSCM>false</exposedSCM>
          <configs class="empty-list"/>
        </com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
      </phaseJobs>
      <continuationCondition>SUCCESSFUL</continuationCondition>
    </com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
    <com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
      <phaseName>Create Resources for non-admin users</phaseName>
      <phaseJobs>
        <com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
          <jobName>Create Resources</jobName>
          <currParams>true</currParams>
          <exposedSCM>false</exposedSCM>
          <configs class="empty-list"/>
        </com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
      </phaseJobs>
      <continuationCondition>SUCCESSFUL</continuationCondition>
    </com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
    <com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
      <phaseName>Resource Tagging and Filtering</phaseName>
      <phaseJobs>
        <com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
          <jobName>Tagging+Filtering</jobName>
          <currParams>true</currParams>
          <exposedSCM>false</exposedSCM>
          <configs class="empty-list"/>
        </com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
      </phaseJobs>
      <continuationCondition>SUCCESSFUL</continuationCondition>
    </com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
    <com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
      <phaseName>Migration of Instances (only works w/ 2+ nodes)</phaseName>
      <phaseJobs>
        <com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
          <jobName>Migration</jobName>
          <currParams>true</currParams>
          <exposedSCM>false</exposedSCM>
          <configs class="empty-list"/>
        </com.tikal.jenkins.plugins.multijob.PhaseJobsConfig>
      </phaseJobs>
      <continuationCondition>SUCCESSFUL</continuationCondition>
    </com.tikal.jenkins.plugins.multijob.MultiJobBuilder>
  </builders>
  <publishers/>
  <buildWrappers/>
</com.tikal.jenkins.plugins.multijob.MultiJobProject>


text:
package org.killbill.billing.util.entity.dao;

import org.killbill.billing.util.cache.CacheControllerDispatcher;
import org.killbill.billing.util.callcontext.InternalCallContextFactory;
import org.killbill.billing.util.dao.NonEntityDao;
import org.killbill.billing.util.entity.Entity;
import org.killbill.clock.Clock;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.IDBI;
import org.skife.jdbi.v2.Transaction;
import org.skife.jdbi.v2.TransactionIsolationLevel;
import org.skife.jdbi.v2.TransactionStatus;

/**
 * Transaction manager for EntitySqlDao queries
 */
public class EntitySqlDaoTransactionalJdbiWrapper {

    private final IDBI dbi;
    private final Clock clock;
    private final CacheControllerDispatcher cacheControllerDispatcher;
    private final NonEntityDao nonEntityDao;
    private final InternalCallContextFactory internalCallContextFactory;

    public EntitySqlDaoTransactionalJdbiWrapper(final IDBI dbi, final Clock clock, final CacheControllerDispatcher cacheControllerDispatcher,
                                                final NonEntityDao nonEntityDao, final InternalCallContextFactory internalCallContextFactory) {
        this.dbi = dbi;
        this.clock = clock;
        this.cacheControllerDispatcher = cacheControllerDispatcher;
        this.nonEntityDao = nonEntityDao;
        this.internalCallContextFactory = internalCallContextFactory;
    }

    public <M extends EntityModelDao> void populateCaches(final M refreshedEntity) {
        EntitySqlDaoWrapperInvocationHandler.populateCaches(cacheControllerDispatcher, refreshedEntity);
    }

    class JdbiTransaction<ReturnType, M extends EntityModelDao<E>, E extends Entity> implements Transaction<ReturnType, EntitySqlDao<M, E>> {

        private final Handle h;
        private final EntitySqlDaoTransactionWrapper<ReturnType> entitySqlDaoTransactionWrapper;

        JdbiTransaction(final Handle h, final EntitySqlDaoTransactionWrapper<ReturnType> entitySqlDaoTransactionWrapper) {
            this.h = h;
            this.entitySqlDaoTransactionWrapper = entitySqlDaoTransactionWrapper;
        }

        @Override
        public ReturnType inTransaction(final EntitySqlDao<M, E> transactionalSqlDao, final TransactionStatus status) throws Exception {
            final EntitySqlDaoWrapperFactory factoryEntitySqlDao = new EntitySqlDaoWrapperFactory(h, clock, cacheControllerDispatcher, nonEntityDao, internalCallContextFactory);
            return entitySqlDaoTransactionWrapper.inTransaction(factoryEntitySqlDao);
        }
    }

    // To handle warnings only
    interface InitialEntitySqlDao extends EntitySqlDao<EntityModelDao<Entity>, Entity> {}

    /**
     * @param entitySqlDaoTransactionWrapper transaction to execute
     * @param <ReturnType>                   object type to return from the transaction
     * @return result from the transaction fo type ReturnType
     */
    public <ReturnType> ReturnType execute(final EntitySqlDaoTransactionWrapper<ReturnType> entitySqlDaoTransactionWrapper) {
        final Handle handle = dbi.open();
        try {
            final EntitySqlDao<EntityModelDao<Entity>, Entity> entitySqlDao = handle.attach(InitialEntitySqlDao.class);
            return entitySqlDao.inTransaction(TransactionIsolationLevel.READ_COMMITTED, new JdbiTransaction<ReturnType, EntityModelDao<Entity>, Entity>(handle, entitySqlDaoTransactionWrapper));
        } finally {
            handle.close();
        }
    }

    //
    // This is only used in the pagination APIs when streaming results. We want to keep the connection open, and also there is no need
    // to send bus events, record notifications where we need to keep the Connection through the jDBI Handle.
    //
    public <M extends EntityModelDao<E>, E extends Entity, T extends EntitySqlDao<M, E>> T onDemandForStreamingResults(final Class<T> sqlObjectType) {
        return dbi.onDemand(sqlObjectType);
    }

    /**
     * @param entitySqlDaoTransactionWrapper transaction to execute
     * @param <ReturnType>                   object type to return from the transaction
     * @param <E>                            checked exception which can be thrown from the transaction
     * @return result from the transaction fo type ReturnType
     */
    public <ReturnType, E extends Exception> ReturnType execute(final Class<E> exception, final EntitySqlDaoTransactionWrapper<ReturnType> entitySqlDaoTransactionWrapper) throws E {
        try {
            return execute(entitySqlDaoTransactionWrapper);
        } catch (RuntimeException e) {
            if (e.getCause() != null && e.getCause().getClass().isAssignableFrom(exception)) {
                throw (E) e.getCause();
            } else if (e.getCause() != null && e.getCause() instanceof RuntimeException) {
                throw (RuntimeException) e.getCause();
            } else {
                throw e;
            }
        }
    }
}


text:
package io.github.swagger2markup;

import io.github.swagger2markup.assertions.DiffUtils;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;

public class GeneralConverterTest {

    private static final String[] EXPECTED_FILES = new String[]{"definitions.adoc", "overview.adoc", "paths.adoc", "security.adoc"};
    private List<String> expectedFiles;

    @Before
    public void setUp(){
        expectedFiles = new ArrayList<>(asList(EXPECTED_FILES));
    }

    @Test
    public void testToFileWithoutExtension() throws IOException, URISyntaxException {
        //Given
        String swaggerJsonString = IOUtils.toString(getClass().getResourceAsStream("/yaml/swagger_petstore.yaml"));
        Path outputFile = Paths.get("build/test/asciidoc/toFile/outputFile.adoc");

        //When
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withGeneratedExamples()
                .build();

        Swagger2MarkupConverter.from(swaggerJsonString)
                .withConfig(config)
                .build()
                .toFileWithoutExtension(outputFile);

        //Then
        Path expectedFile = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/toFile/outputFile.adoc").toURI());
        DiffUtils.assertThatFileIsEqual(expectedFile, outputFile, "testOutputFile.html");
    }

    @Test
    public void testFromHttpURI() throws IOException, URISyntaxException {
        //Given
        Path outputDirectory = Paths.get("build/test/asciidoc/fromUri");
        FileUtils.deleteQuietly(outputDirectory.toFile());

        //When
        Swagger2MarkupConverter.from(URI.create("http://petstore.swagger.io/v2/swagger.json")).build()
                .toFolder(outputDirectory);

        //Then
        String[] files = outputDirectory.toFile().list();
        assertThat(files).hasSize(4).containsAll(expectedFiles);
    }

    @Test
    public void testFromResourceURI() throws IOException, URISyntaxException {
        //Given
        Path outputDirectory = Paths.get("build/test/asciidoc/fileUri");
        FileUtils.deleteQuietly(outputDirectory.toFile());

        //When
        Swagger2MarkupConverter.from(GeneralConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI()).build()
                .toFolder(outputDirectory);

        //Then
        String[] files = outputDirectory.toFile().list();
        assertThat(files).hasSize(4).containsAll(expectedFiles);
    }

    @Test
    public void testFromPathURI() throws IOException, URISyntaxException {
        //Given
        Path outputDirectory = Paths.get("build/test/asciidoc/pathUri");
        FileUtils.deleteQuietly(outputDirectory.toFile());

        //When
        Swagger2MarkupConverter.from(Paths.get("src/test/resources/yaml/swagger_petstore.yaml").toUri()).build()
                .toFolder(outputDirectory);

        //Then
        String[] files = outputDirectory.toFile().list();
        assertThat(files).hasSize(4).containsAll(expectedFiles);
    }

    @Test
    public void testFromStringURIWithoutScheme() throws IOException, URISyntaxException {
        //Given
        Path outputDirectory = Paths.get("build/test/asciidoc/pathUri");
        FileUtils.deleteQuietly(outputDirectory.toFile());

        //When
        Swagger2MarkupConverter.from(URI.create("src/test/resources/yaml/swagger_petstore.yaml")).build()
                .toFolder(outputDirectory);

        //Then
        String[] files = outputDirectory.toFile().list();
        assertThat(files).hasSize(4).containsAll(expectedFiles);
    }

    @Test
    public void testFromURL() throws IOException, URISyntaxException {
        //Given
        Path outputDirectory = Paths.get("build/test/asciidoc/fromUrl");
        FileUtils.deleteQuietly(outputDirectory.toFile());

        //When
        Swagger2MarkupConverter.from(new URL("http://petstore.swagger.io/v2/swagger.json")).build()
                .toFolder(outputDirectory);

        //Then
        String[] files = outputDirectory.toFile().list();
        assertThat(files).hasSize(4).containsAll(expectedFiles);
    }

}


text:
<?xml version='1.0' encoding='UTF-8'?>
<para xmlns="http://docbook.org/ns/docbook" version="5.0">

Description of upgrades configuration options

    <col width="50%"/>
    <col width="50%"/>

        Configuration option = Default value
        Description

        [upgrade_levels]

        <option>conductor</option> = <replaceable>icehouse</replaceable>
        (StrOpt) Set a version cap for messages sent to conductor services

        <option>guestagent</option> = <replaceable>icehouse</replaceable>
        (StrOpt) Set a version cap for messages sent to guestagent services

        <option>taskmanager</option> = <replaceable>icehouse</replaceable>
        (StrOpt) Set a version cap for messages sent to taskmanager services

</para>


text:
<?php

namespace Zend\Db\Sql;

use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\Driver\StatementInterface;

/**
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Sql
 */
interface PreparableSqlInterface
{

    /**
     * @abstract
     * @param Adapter $adapter
     * @return StatementInterface
     */
    public function prepareStatement(Adapter $adapter, StatementInterface $statement);
}


text:
namespace QI4N.Framework.Runtime
{
    using System;
    using System.Reflection;

    public class ProxyReferenceInvocationHandler : InvocationHandler
    {
        public object Proxy { get; set; }

        //[DebuggerStepThrough]
        ////[DebuggerHidden]
        public void ClearProxy()
        {
            this.Proxy = null;
        }

        public object Invoke(object proxy, MethodInfo method, object[] args)
        {
            try
            {
                InvocationHandler invocationHandler = JavaProxy.Proxy.GetInvocationHandler(this.Proxy);
                return invocationHandler.Invoke(this.Proxy, method, args);
            }
            catch (InvocationTargetException e)
            {
                throw e.TargetException;
            }
            catch (UndeclaredThrowableException e)
            {
                throw e.UndeclaredThrowable;
            }
        }
    }

    internal class UndeclaredThrowableException : Exception
    {
        public Exception UndeclaredThrowable;
    }
}


text:
const float kMaxAngle = 120.0f;
const float kScalingFactor = 4.0f;

@interface THControlKnob ()

@property (nonatomic) float angle;
@property (nonatomic) CGPoint touchOrigin;
@property (strong, nonatomic) THIndicatorLight *indicatorView;

@end

@implementation THControlKnob

- (id)initWithFrame:(CGRect)frame {
	self = [super initWithFrame:frame];
	if (self) {
		[self setupView];
	}
	return self;
}

- (id)initWithCoder:(NSCoder *)coder {
	self = [super initWithCoder:coder];
	if (self) {
		[self setupView];
	}
	return self;
}

- (void)setupView {

    self.backgroundColor = [UIColor clearColor];

	_angle = 0.0f;

	_defaultValue = 0.0f;
	_minimumValue = -1.0f;
	_maximumValue = 1.0f;
	_value = _defaultValue;

	_indicatorView = [[THIndicatorLight alloc] initWithFrame:self.bounds];
    _indicatorView.lightColor = [self indicatorLightColor];
	[self addSubview:_indicatorView];

	[self valueDidChangeFrom:_defaultValue to:_defaultValue animated:NO];
}

- (UIColor *)indicatorLightColor {
    return [UIColor whiteColor];
}

#pragma mark - Data Model

- (float)clampAngle:(float)angle {
	if (angle < -kMaxAngle) {
		angle = -kMaxAngle;
	} else if (angle > kMaxAngle) {
		angle = kMaxAngle;
	}
	return angle;
}

- (float)angleForValue:(float)value {
	return ((value - self.minimumValue) / (self.maximumValue - self.minimumValue) - 0.5f) * (kMaxAngle * 2.0f);
}

- (float)valueForAngle:(float)angle {
	return (angle / (kMaxAngle * 2.0f) + 0.5f) * (self.maximumValue - self.minimumValue) + self.minimumValue;
}

- (float)valueForPosition:(CGPoint)point {
	float delta = self.touchOrigin.y - point.y;
	float newAngle = [self clampAngle:delta * kScalingFactor + self.angle];
	return [self valueForAngle:newAngle];
}

- (void)setValue:(float)newValue {
	[self setValue:newValue animated:NO];
}

- (void)setValue:(float)newValue animated:(BOOL)animated {
	float oldValue = _value;

	if (newValue < self.minimumValue) {
		_value = self.minimumValue;
	} else if (newValue > self.maximumValue) {
		_value = self.maximumValue;
	} else {
		_value = newValue;
	}

	[self valueDidChangeFrom:(float)oldValue to:(float)_value animated:animated];
}

- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
	CGPoint point = [touch locationInView:self];
	self.touchOrigin = point;
	self.angle = [self angleForValue:self.value];
    self.highlighted = YES;
    [self setNeedsDisplay];
	return YES;
}

- (BOOL)handleTouch:(UITouch *)touch {
	if (touch.tapCount > 1) {
		[self setValue:self.defaultValue animated:YES];
		return NO;
	}
	CGPoint point = [touch locationInView:self];
	self.value = [self valueForPosition:point];
	return YES;
}

- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
	if ([self handleTouch:touch]) {
		[self sendActionsForControlEvents:UIControlEventValueChanged];
	}
	return YES;
}

- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
	[self handleTouch:touch];
	[self sendActionsForControlEvents:UIControlEventValueChanged];
    self.highlighted = NO;
    [self setNeedsDisplay];
}

- (void)valueDidChangeFrom:(float)oldValue to:(float)newValue animated:(BOOL)animated {

	float newAngle = [self angleForValue:newValue];

	if (animated) {

		float oldAngle = [self angleForValue:oldValue];

		CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
		animation.duration = 0.2f;

		animation.values = @[@(oldAngle * M_PI/ 180.0f),
							 @((newAngle + oldAngle) / 2.0f * M_PI/ 180.0f),
							 @(newAngle * M_PI/ 180.0f)];

		animation.keyTimes = @[@0.0f,
							   @0.5f,
							   @1.0f];

		animation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn],
									  [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];

		[self.indicatorView.layer addAnimation:animation forKey:nil];
	}

	self.indicatorView.transform = CGAffineTransformMakeRotation(newAngle * M_PI/ 180.0f);
}

- (void)drawRect:(CGRect)rect {

	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
	CGContextRef context = UIGraphicsGetCurrentContext();

	// Set up Colors
	UIColor *strokeColor = [UIColor colorWithWhite:0.06 alpha:1.0f];
	UIColor *gradientLightColor = [UIColor colorWithRed:0.101 green:0.100 blue:0.103 alpha:1.000];
	UIColor *gradientDarkColor = [UIColor colorWithRed:0.237 green:0.242 blue:0.242 alpha:1.000];

    if (self.highlighted) {
        gradientLightColor = [gradientLightColor darkerColor];
        gradientDarkColor = [gradientDarkColor darkerColor];
    }

	NSArray *gradientColors = @[(id)gradientLightColor.CGColor, (id)gradientDarkColor.CGColor];
	CGFloat locations[] = {0, 1};
	CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, locations);

	CGRect insetRect = CGRectInset(rect, 2.0f, 2.0f);

	// Draw Bezel
	CGContextSetFillColorWithColor(context, strokeColor.CGColor);
	CGContextFillEllipseInRect(context, insetRect);

	CGFloat midX = CGRectGetMidX(insetRect);
	CGFloat midY = CGRectGetMidY(insetRect);

	// Draw Bezel Light Shadow Layer
	CGContextAddArc(context, midX, midY, CGRectGetWidth(insetRect) / 2, 0, M_PI * 2, 1);
	CGContextSetShadowWithColor(context, CGSizeMake(0.0f, 0.5f), 2.0f, [UIColor darkGrayColor].CGColor);
	CGContextFillPath(context);

	// Add Clipping Region for Knob Background
	CGContextAddArc(context, midX, midY, (CGRectGetWidth(insetRect) - 6) / 2, 0, M_PI * 2, 1);
	CGContextClip(context);

	CGPoint startPoint = CGPointMake(midX, CGRectGetMaxY(insetRect));
	CGPoint endPoint = CGPointMake(midX, CGRectGetMinY(insetRect));

	CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);

	CGGradientRelease(gradient);
	CGColorSpaceRelease(colorSpace);
}

@end

@implementation THGreenControlKnob

- (UIColor *)indicatorLightColor {
    return [UIColor colorWithRed:0.226 green:1.000 blue:0.226 alpha:1.000];
}

@end

@implementation THOrangeControlKnob

- (UIColor *)indicatorLightColor {
    return [UIColor colorWithRed:1.000 green:0.718 blue:0.000 alpha:1.000];
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2014 - 2022 Blazebit.

  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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.blazebit</groupId>
        <artifactId>blaze-persistence-archetype</artifactId>
        <version>1.6.9-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>blaze-persistence-archetype-entity-view-sample-jakarta</artifactId>
    <packaging>jar</packaging>

    <name>Blazebit Persistence Archetype Entity-View Sample Jakarta</name>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <configuration>
                        <escapeString>\</escapeString>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>archetype-resources/pom.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
                <excludes>
                    <exclude>archetype-resources/pom.xml</exclude>
                </excludes>
            </resource>
        </resources>
    </build>
</project>