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

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel.Syndication;
using System.Xml;
using System.IO;
using Xunit;

namespace System.ServiceModel.Syndication.Tests
{
    public static class BasicScenarioTests
    {
        [Fact]
        public static void SyndicationFeed_CreateNewFeed()
        {
            string filePath = Path.GetTempFileName();

            try
            {
                // *** SETUP *** \\
                SyndicationFeed sf = new SyndicationFeed("First feed on .net core ever!!", "This is the first feed on .net core ever!", new Uri("https://github.com/dotnet/wcf"));
                Assert.True(sf != null);

                XmlWriter xmlw = XmlWriter.Create(filePath);
                Rss20FeedFormatter rssf = new Rss20FeedFormatter(sf);

                // *** EXECUTE *** \\
                rssf.WriteTo(xmlw);
                xmlw.Close();

                // *** VALIDATE *** \\
                Assert.True(File.Exists(filePath));
            }
            finally
            {
                // *** CLEANUP *** \\
                File.Delete(filePath);
            }
        }

        [Fact]
        public static void SyndicationFeed_Load_Write_RSS_Feed()
        {
            string path = Path.GetTempFileName();

            try
            {
                // *** SETUP *** \\\
                XmlReader xmlr = XmlReader.Create(@"SimpleRssFeed.xml");
                SyndicationFeed sf = SyndicationFeed.Load(xmlr);
                Assert.True(sf != null);

                // *** EXECUTE *** \\
                //Write the same feed that was read.
                XmlWriter xmlw = XmlWriter.Create(path);
                Rss20FeedFormatter atomFeed = new Rss20FeedFormatter(sf);
                atomFeed.WriteTo(xmlw);
                xmlw.Close();

                // *** VALIDATE *** \\
                Assert.True(File.Exists(path));
            }
            finally
            {
                // *** CLEANUP *** \\
                File.Delete(path);
            }
        }

        [Fact]
        public static void SyndicationFeed_Load_Write_RSS_Feed_()
        {
            string path = Path.GetTempFileName();

            try
            {
                // *** SETUP *** \\\
                XmlReaderSettings settingsReader = new XmlReaderSettings();
                XmlReader xmlr = XmlReader.Create(@"rssSpecExample.xml", settingsReader);
                SyndicationFeed sf = SyndicationFeed.Load(xmlr);
                Assert.True(sf != null);

                // *** EXECUTE *** \\
                //Write the same feed that was read.
                XmlWriterSettings settingsWriter = new XmlWriterSettings();
                XmlWriter xmlw = XmlWriter.Create(path, settingsWriter);
                Rss20FeedFormatter atomFeed = new Rss20FeedFormatter(sf);
                atomFeed.WriteTo(xmlw);

                xmlw.Close();

                // *** VALIDATE *** \\
                Assert.True(File.Exists(path));
            }
            finally
            {
                // *** CLEANUP *** \\
                File.Delete(path);
            }
        }

        [Fact]
        public static void SyndicationFeed_Load_Write_Atom_Feed()
        {
            string path = Path.GetTempFileName();

            try
            {
                // *** SETUP *** \\\
                XmlReaderSettings setting = new XmlReaderSettings();
                XmlReader xmlr = XmlReader.Create(@"SimpleAtomFeed.xml", setting);
                SyndicationFeed sf = SyndicationFeed.Load(xmlr);
                Assert.True(sf != null);

                // *** EXECUTE *** \\
                //Write the same feed that was read.
                XmlWriter xmlw = XmlWriter.Create(path);
                Atom10FeedFormatter atomFeed = new Atom10FeedFormatter(sf);
                atomFeed.WriteTo(xmlw);
                xmlw.Close();

                // *** VALIDATE *** \\
                Assert.True(File.Exists(path));
            }
            finally
            {
                // *** CLEANUP *** \\
                File.Delete(path);
            }
        }

        [Fact]
        public static void SyndicationFeed_Load_Write_Atom_Feed_()
        {
            string path = Path.GetTempFileName();

            try
            {
                // *** SETUP *** \\\
                XmlReaderSettings readerSettings = new XmlReaderSettings();
                XmlReader xmlr = XmlReader.Create(@"atom_spec_example.xml", readerSettings);
                SyndicationFeed sf = SyndicationFeed.Load(xmlr);
                Assert.True(sf != null);

                // *** EXECUTE *** \\
                //Write the same feed that was read.
                XmlWriterSettings writerSettings = new XmlWriterSettings();

                XmlWriter xmlw = XmlWriter.Create(path, writerSettings);
                Atom10FeedFormatter atomFeed = new Atom10FeedFormatter(sf);
                atomFeed.WriteTo(xmlw);
                xmlw.Close();

                // *** VALIDATE *** \\
                Assert.True(File.Exists(path));
            }
            finally
            {
                // *** CLEANUP *** \\
                File.Delete(path);
            }
        }

        [Fact]
        public static void SyndicationFeed_Write_RSS_Atom()
        {
            string RssPath = Path.GetTempFileName();
            string AtomPath = Path.GetTempFileName();

            try
            {
                // *** SETUP *** \\
                SyndicationFeed feed = new SyndicationFeed("Contoso News", "
Most recent news from Contoso
", new Uri("http://www.Contoso.com/news"), "123FeedID", DateTime.Now);

                //Add an author
                SyndicationPerson author = new SyndicationPerson("jerry@Contoso.com");
                feed.Authors.Add(author);

                //Create item
                SyndicationItem item1 = new SyndicationItem("SyndicationFeed released for .net Core", "A lot of text describing the release of .net core feature", new Uri("http://Contoso.com/news/path"));

                //Add item to feed
                List<SyndicationItem> feedList = new List<SyndicationItem> { item1 };
                feed.Items = feedList;
                feed.ElementExtensions.Add("CustomElement", "", "asd");

                //add an image
                feed.ImageUrl = new Uri("http://2.bp.blogspot.com/-NA5Jb-64eUg/URx8CSdcj_I/AAAAAAAAAUo/eCx0irI0rq0/s1600/bg_Contoso_logo3-20120824073001907469-620x349.jpg");

                feed.BaseUri = new Uri("http://mypage.com");

                // Write to XML > rss
                XmlWriterSettings settings = new XmlWriterSettings();
                XmlWriter xmlwRss = XmlWriter.Create(RssPath, settings);
                Rss20FeedFormatter rssff = new Rss20FeedFormatter(feed);

                // Write to XML > atom

                XmlWriter xmlwAtom = XmlWriter.Create(AtomPath);
                Atom10FeedFormatter atomf = new Atom10FeedFormatter(feed);

                // *** EXECUTE *** \\
                rssff.WriteTo(xmlwRss);
                xmlwRss.Close();

                atomf.WriteTo(xmlwAtom); ;
                xmlwAtom.Close();

                // *** ASSERT *** \\
                Assert.True(File.Exists(RssPath));
                Assert.True(File.Exists(AtomPath));
            }
            finally
            {
                // *** CLEANUP *** \\
                File.Delete(RssPath);
                File.Delete(AtomPath);
            }
        }

        [Fact]
        public static void SyndicationFeed_Load_Rss()
        {
            XmlReaderSettings setting = new XmlReaderSettings();
            using (XmlReader reader = XmlReader.Create(@"rssSpecExample.xml", setting))
            {
                SyndicationFeed rss = SyndicationFeed.Load(reader);
                Assert.True(rss.Items != null);
            }
        }

        [Fact]
        public static void SyndicationFeed_Load_Atom()
        {
            XmlReaderSettings setting = new XmlReaderSettings();
            using (XmlReader reader = XmlReader.Create(@"atom_spec_example.xml", setting))
            {
                SyndicationFeed atom = SyndicationFeed.Load(reader);
                Assert.True(atom.Items != null);
            }
        }

        [Fact]
        [ActiveIssue(25080)]
        public static void SyndicationFeed_Rss_TestDisjointItems()
        {
            using (XmlReader reader = XmlReader.Create(@"RssDisjointItems.xml"))
            {
                // *** EXECUTE *** \\
                SyndicationFeed sf = SyndicationFeed.Load(reader);

                // *** ASSERT *** \\
                int count = 0;
                foreach (SyndicationItem item in sf.Items)
                {
                    count++;
                }

                Assert.True(count == 2);
            }
        }

        [Fact]
        [ActiveIssue(25080)]
        public static void SyndicationFeed_Atom_TestDisjointItems()
        {
            using (XmlReader reader = XmlReader.Create(@"AtomDisjointItems.xml"))
            {
                // *** EXECUTE *** \\
                SyndicationFeed sf = SyndicationFeed.Load(reader);

                // *** ASSERT *** \\
                int count = 0;
                foreach (SyndicationItem item in sf.Items)
                {
                    count++;
                }

                Assert.True(count == 2);
            }
        }

        [Fact]
        [ActiveIssue(25080)]
        public static void SyndicationFeed_Rss_WrongDateFormat()
        {
            // *** SETUP *** \\
            Rss20FeedFormatter rssformatter = new Rss20FeedFormatter();

            XmlReader reader = XmlReader.Create(@"rssSpecExampleWrongDateFormat.xml");

            // *** EXECUTE *** \\
            SyndicationFeed res = SyndicationFeed.Load(reader);

            // *** ASSERT *** \\
            Assert.True(!res.LastUpdatedTime.Equals(new DateTimeOffset()));
        }

        [Fact]
        public static void AtomEntryPositiveTest()
        {
            string file = @"brief-entry-noerror.xml";
            ReadWriteSyndicationItem(file, (itemObject) => new Atom10ItemFormatter(itemObject));
        }

        [Fact]
        public static void AtomEntryPositiveTest_write()
        {
            string file = @"AtomEntryTest.xml";
            string serializeFilePath = Path.GetTempFileName();
            bool toDeletedFile = true;

            SyndicationItem item = new SyndicationItem("SyndicationFeed released for .net Core", "A lot of text describing the release of .net core feature", new Uri("http://contoso.com/news/path"));
            item.Id = "uuid:43481a10-d881-40d1-adf2-99b438c57e21;id=1";
            item.LastUpdatedTime = new DateTimeOffset(Convert.ToDateTime("2017-10-11T11:25:55Z")).UtcDateTime;

            try
            {
                using (FileStream fileStream = new FileStream(serializeFilePath, FileMode.OpenOrCreate))
                {
                    using (XmlWriter writer = XmlDictionaryWriter.CreateTextWriter(fileStream))
                    {
                        Atom10ItemFormatter f = new Atom10ItemFormatter(item);
                        f.WriteTo(writer);
                    }
                }

                CompareHelper ch = new CompareHelper
                {
                    Diff = new XmlDiff()
                    {
                        Option = XmlDiffOption.IgnoreComments | XmlDiffOption.IgnorePrefix | XmlDiffOption.IgnoreWhitespace | XmlDiffOption.IgnoreChildOrder | XmlDiffOption.IgnoreAttributeOrder
                    }
                };

                string diffNode = string.Empty;
                if (!ch.Compare(file, serializeFilePath, out diffNode))
                {
                    toDeletedFile = false;
                    string errorMessage = $"The generated file was different from the baseline file:{Environment.NewLine}Baseline: {file}{Environment.NewLine}Actual: {serializeFilePath}{Environment.NewLine}Different Nodes:{Environment.NewLine}{diffNode}";
                    Assert.True(false, errorMessage);
                }
            }
            finally
            {
                if (toDeletedFile)
                {
                    File.Delete(serializeFilePath);
                }
            }
        }

        [Fact]
        public static void AtomFeedPositiveTest()
        {
            string dataFile = @"atom_feeds.dat";
            List<string> fileList = GetTestFilesForFeedTest(dataFile);
            List<AllowableDifference> allowableDifferences = GetAtomFeedPositiveTestAllowableDifferences();

            foreach (string file in fileList)
            {
                ReadWriteSyndicationFeed(file, (feedObject) => new Atom10FeedFormatter(feedObject), allowableDifferences);
            }
        }

        [Fact]
        public static void RssEntryPositiveTest()
        {
            string file = @"RssEntry.xml";
            ReadWriteSyndicationItem(file, (itemObject) => new Rss20ItemFormatter(itemObject));
        }

        [Fact]
        public static void RssFeedPositiveTest()
        {
            string dataFile = @"rss_feeds.dat";
            List<string> fileList = GetTestFilesForFeedTest(dataFile);
            List<AllowableDifference> allowableDifferences = GetRssFeedPositiveTestAllowableDifferences();

            foreach (string file in fileList)
            {
                ReadWriteSyndicationFeed(file, (feedObject) => new Rss20FeedFormatter(feedObject), allowableDifferences);
            }
        }

        private static void ReadWriteSyndicationItem(string file, Func<SyndicationItem, SyndicationItemFormatter> itemFormatter)
        {
            string serializeFilePath = Path.GetTempFileName();
            bool toDeletedFile = true;

            try
            {
                SyndicationItem itemObjct = null;
                using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    using (XmlReader reader = XmlDictionaryReader.CreateTextReader(fileStream, XmlDictionaryReaderQuotas.Max))
                    {
                        itemObjct = SyndicationItem.Load(reader);
                    }
                }

                using (FileStream fileStream = new FileStream(serializeFilePath, FileMode.OpenOrCreate))
                {
                    using (XmlWriter writer = XmlDictionaryWriter.CreateTextWriter(fileStream))
                    {
                        SyndicationItemFormatter formatter = itemFormatter(itemObjct);
                        formatter.WriteTo(writer);
                    }
                }

                // compare file filePath and serializeFilePath
                CompareHelper ch = new CompareHelper
                {
                    Diff = new XmlDiff()
                    {
                        Option = XmlDiffOption.IgnoreComments | XmlDiffOption.IgnorePrefix | XmlDiffOption.IgnoreWhitespace | XmlDiffOption.IgnoreChildOrder | XmlDiffOption.IgnoreAttributeOrder
                    }
                };

                string diffNode = string.Empty;
                if (!ch.Compare(file, serializeFilePath, out diffNode))
                {
                    toDeletedFile = false;
                    string errorMessage = $"The generated file was different from the baseline file:{Environment.NewLine}Baseline: {file}{Environment.NewLine}Actual: {serializeFilePath}{Environment.NewLine}Different Nodes:{Environment.NewLine}{diffNode}";
                    Assert.True(false, errorMessage);
                }
            }
            catch (Exception e)
            {
                Exception newEx = new Exception($"Failed File Name: {file}", e);
                throw newEx;
            }
            finally
            {
                if (toDeletedFile)
                {
                    File.Delete(serializeFilePath);
                }
            }
        }

        private static void ReadWriteSyndicationFeed(string file, Func<SyndicationFeed, SyndicationFeedFormatter> feedFormatter, List<AllowableDifference> allowableDifferences = null)
        {
            string serializeFilePath = Path.GetTempFileName();
            bool toDeletedFile = true;

            try
            {
                SyndicationFeed feedObjct;
                using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    using (XmlReader reader = XmlDictionaryReader.CreateTextReader(fileStream, XmlDictionaryReaderQuotas.Max))
                    {
                        feedObjct = SyndicationFeed.Load(reader);
                    }
                }

                using (FileStream fileStream = new FileStream(serializeFilePath, FileMode.OpenOrCreate))
                {
                    using (XmlWriter writer = XmlDictionaryWriter.CreateTextWriter(fileStream))
                    {
                        SyndicationFeedFormatter formatter = feedFormatter(feedObjct);
                        formatter.WriteTo(writer);
                    }
                }

                CompareHelper ch = new CompareHelper
                {
                    Diff = new XmlDiff()
                    {
                        Option = XmlDiffOption.IgnoreComments | XmlDiffOption.IgnorePrefix | XmlDiffOption.IgnoreWhitespace | XmlDiffOption.IgnoreChildOrder | XmlDiffOption.IgnoreAttributeOrder
                    },
                    AllowableDifferences = allowableDifferences
                };

                string diffNode = string.Empty;
                if (!ch.Compare(file, serializeFilePath, out diffNode))
                {
                    toDeletedFile = false;
                    string errorMessage = $"The generated file was different from the baseline file:{Environment.NewLine}Baseline: {file}{Environment.NewLine}Actual: {serializeFilePath}{Environment.NewLine}Different Nodes:{Environment.NewLine}{diffNode}";
                    Assert.True(false, errorMessage);
                }
            }
            catch (Exception e)
            {
                Exception newEx = new Exception($"Failed File Name: {file}", e);
                throw newEx;
            }
            finally
            {
                if (toDeletedFile)
                {
                    File.Delete(serializeFilePath);
                }
            }
        }

        private static List<AllowableDifference> GetAtomFeedPositiveTestAllowableDifferences()
        {
            return new List<AllowableDifference>(new AllowableDifference[]
            {
                new AllowableDifference("<content xmlns=\"http://www.w3.org/2005/Atom\" />","<content type=\"text\" xmlns=\"http://www.w3.org/2005/Atom\" />"),
                new AllowableDifference("<content>","<content type=\"text\">"),
                new AllowableDifference("<content src=\"http://contoso.com/2003/12/13/atom03\" xmlns=\"http://www.w3.org/2005/Atom\" />","<content src=\"http://contoso.com/2003/12/13/atom03\" type=\"text\" xmlns=\"http://www.w3.org/2005/Atom\" />"),
                new AllowableDifference("<content src=\"  http://www.contoso.com/doc.pdf\" type=\"application/pdf\" xmlns=\"http://www.w3.org/2005/Atom\" />","<content src=\"http://www.contoso.com/doc.pdf\" type=\"application/pdf\" xmlns=\"http://www.w3.org/2005/Atom\" />"),
                new AllowableDifference("<title>","<title type=\"text\">"),
                new AllowableDifference("<subtitle>","<subtitle type=\"text\">"),
                new AllowableDifference("<subtitle xmlns=\"http://www.w3.org/2005/Atom\" />","<subtitle type=\"text\" xmlns=\"http://www.w3.org/2005/Atom\" />"),
                new AllowableDifference("<title xmlns=\"http://www.w3.org/2005/Atom\" />","<title type=\"text\" xmlns=\"http://www.w3.org/2005/Atom\" />"),
                new AllowableDifference("<atom:title>","<title type=\"text\">"),
                new AllowableDifference("",""),
                new AllowableDifference("<atom:summary>",""),
                new AllowableDifference("<generator uri=\"http://www.contoso.com/\" version=\"1.0\">", "<generator>"),
                new AllowableDifference("<generator uri=\"/generator\" xmlns=\"http://www.w3.org/2005/Atom\" />", "<generator xmlns=\"http://www.w3.org/2005/Atom\" />"),
                new AllowableDifference("<generator uri=\"/generator\">", "<generator>"),
                new AllowableDifference("<generator uri=\"misc/Colophon\">", "<generator>"),
                new AllowableDifference("<generator uri=\"http://www.contoso.com/ \" version=\"1.0\">", "<generator>"),
                new AllowableDifference("<rights>","<rights type=\"text\">"),
                new AllowableDifference("<link href=\"http://contoso.com\" xmlns=\"http://www.w3.org/2005/Atom\" />","<link href=\"http://contoso.com/\" xmlns=\"http://www.w3.org/2005/Atom\" />"),
                new AllowableDifference("<link href=\"  http://contoso.com/  \" xmlns=\"http://www.w3.org/2005/Atom\" />","<link href=\"http://contoso.com/\" xmlns=\"http://www.w3.org/2005/Atom\" />"),
                new AllowableDifference("<feed xml:lang=\"\" xmlns=\"http://www.w3.org/2005/Atom\">","<feed xmlns=\"http://www.w3.org/2005/Atom\">"),
                new AllowableDifference("<entry xmlns:xh=\"http://www.w3.org/1999/xhtml\">","<entry>"),
                new AllowableDifference("<xh:div>","<xh:div xmlns:xh=\"http://www.w3.org/1999/xhtml\">"),
                new AllowableDifference("",""),
                new AllowableDifference("<xhtml:a href=\"http://contoso.com/\">","<xhtml:a href=\"http://contoso.com/\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">"),
                new AllowableDifference("<feed xmlns:trackback=\"http://contoso.com/public/xml/rss/module/trackback/\" xmlns=\"http://www.w3.org/2005/Atom\">","<feed xmlns=\"http://www.w3.org/2005/Atom\">"),
                new AllowableDifference("<trackback:ping>", "<trackback:ping xmlns:trackback=\"http://contoso.com/public/xml/rss/module/trackback/\">"),
                new AllowableDifference("<feed xmlns:dc=\"http://contoso.com/dc/elements/1.1/\" xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns=\"http://www.w3.org/2005/Atom\">", "<feed xmlns=\"http://www.w3.org/2005/Atom\">"),
                new AllowableDifference("<author rdf:parseType=\"Resource\">", "<author xmlns:a=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" a:parseType=\"Resource\">"),
                new AllowableDifference("<foaf:homepage rdf:resource=\"http://contoso.com/\">", "<foaf:homepage xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" rdf:resource=\"http://contoso.com/\">"),
                new AllowableDifference("<foaf:weblog rdf:resource=\"http://contoso.com/blog/\">", "<foaf:weblog xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" rdf:resource=\"http://contoso.com/blog/\">"),
                new AllowableDifference("<foaf:workplaceHomepage rdf:resource=\"http://DoeCorp.contoso.com/\">", "<foaf:workplaceHomepage xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" rdf:resource=\"http://DoeCorp.contoso.com/\">"),
                new AllowableDifference("<dc:description>", "<dc:description xmlns:dc=\"http://contoso.com/dc/elements/1.1/\">"),
                new AllowableDifference("<entry rdf:parseType=\"Resource\">", "<entry xmlns:a=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" a:parseType=\"Resource\">"),
                new AllowableDifference("<foaf:primaryTopic rdf:parseType=\"Resource\">", "<foaf:primaryTopic xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" rdf:parseType=\"Resource\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">"),
                new AllowableDifference("<link href=\"http://contoso.com/\" rdf:resource=\"http://contoso.com/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns=\"http://www.w3.org/2005/Atom\" />", "<link xmlns:a=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" href=\"http://contoso.com/\" a:resource=\"http://contoso.com/\" xmlns=\"http://www.w3.org/2005/Atom\" />"),
                new AllowableDifference("<feed xmlns:creativeCommons=\"http://contoso.com/creativeCommonsRssModule\" xmlns=\"http://www.w3.org/2005/Atom\">", "<feed xmlns=\"http://www.w3.org/2005/Atom\">"),
                new AllowableDifference("<creativeCommons:license>", "<creativeCommons:license xmlns:creativeCommons=\"http://contoso.com/creativeCommonsRssModule\">"),
                new AllowableDifference("<feed xmlns:a=\"http://www.contoso.com/extension-a\" xmlns:dc=\"http://contoso.com/dc/elements/1.1/\" xmlns=\"http://www.w3.org/2005/Atom\">", "<feed xmlns=\"http://www.w3.org/2005/Atom\">"),
                new AllowableDifference("", ""),
                new AllowableDifference("", ""),
                new AllowableDifference("<dc:title>", "<dc:title xmlns:dc=\"http://contoso.com/dc/elements/1.1/\">"),
                new AllowableDifference("<simple-value>", "<simple-value xmlns=\"\">"),
                new AllowableDifference("<feed xmlns:xhtml=\"http://www.w3.org/1999/xhtml\" xmlns=\"http://www.w3.org/2005/Atom\">", "<feed xmlns=\"http://www.w3.org/2005/Atom\">"),
                new AllowableDifference("<trackback:about>", "<trackback:about xmlns:trackback=\"http://contoso.com/public/xml/rss/module/trackback/\">"),
                new AllowableDifference("<xhtml:img src=\"http://contoso.com/image.jpg\">", "<xhtml:img src=\"http://contoso.com/image.jpg\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">"),
                new AllowableDifference("<feed xml:base=\"http://contoso.com\" xmlns=\"http://www.w3.org/2005/Atom\">", "<feed xml:base=\"http://contoso.com/\" xmlns=\"http://www.w3.org/2005/Atom\">"),
                new AllowableDifference("<link href=\"http://contoso.com/licenses/by-nc/2.5/\" xmlns:lic=\"http://web.resource.org/cc/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" rel=\"http://www.contoso.com/atom/extensions/proposed/license\" rdf:resource=\"http://contoso.com/licenses/by-nc/2.5/\" type=\"text/html\" rdf:type=\"http://web.resource.org/cc/license\">", "<link xmlns:a=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" href=\"http://contoso.com/licenses/by-nc/2.5/\" rel=\"http://www.contoso.com/atom/extensions/proposed/license\" a:resource=\"http://contoso.com/licenses/by-nc/2.5/\" type=\"text/html\" a:type=\"http://web.resource.org/cc/license\">"),
            });
        }

        private static List<AllowableDifference> GetRssFeedPositiveTestAllowableDifferences()
        {
            return new List<AllowableDifference>(new AllowableDifference[]
            {
                new AllowableDifference("<rss version=\"2.0\">","<rss xmlns:a10=\"http://www.w3.org/2005/Atom\" version=\"2.0\">"),
                new AllowableDifference("<content:encoded>", "<content:encoded xmlns:content=\"http://contoso.com/rss/1.0/modules/content/\">"),
                new AllowableDifference("Tue, 31 Dec 2002 14:20:20 GMT", "Tue, 31 Dec 2002 14:20:20 Z"),
            });
        }

        private static List<string> GetTestFilesForFeedTest(string dataFile)
        {
            List<string> fileList = new List<string>();

            string file;
            using (StreamReader sr = new StreamReader(dataFile))
            {
                while (!string.IsNullOrEmpty(file = sr.ReadLine()))
                {
                    if (!file.StartsWith("#"))
                    {
                        file = file.Trim();
                        if (File.Exists(file))
                        {
                            fileList.Add(Path.GetFullPath(file));
                        }
                        else
                        {
                            throw new FileNotFoundException($"File `{file}` was not found!");
                        }
                    }
                }
            }
            return fileList;
        }

    }
}


text:
package com.photon.templatemvp.di.modules;

/**
 * Created by jumbada on 03/05/2017.
 */

import android.content.Context;

import com.photon.templatemvp.BuildConfig;
import com.photon.templatemvp.application.TemplateApp;
import com.photon.templatemvp.data.repository.gallery.GalleryDataRepository;
import com.photon.templatemvp.data.repository.gallery.GalleryRepository;
import com.photon.templatemvp.executor.JobExecutor;
import com.photon.templatemvp.executor.PostExecutionThread;
import com.photon.templatemvp.executor.ThreadExecutor;
import com.photon.templatemvp.executor.UIThread;

import java.io.File;

import javax.inject.Named;
import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

/**
 * Dagger module that provides objects which will live during the application lifecycle.
 */
@Module
public class ApplicationModule {
    private final TemplateApp application;

    public ApplicationModule(TemplateApp application) {
        this.application = application;
    }

    @Provides
    @Singleton
    Context provideApplicationContext() {
        return this.application;
    }

    @Provides @Singleton
    ThreadExecutor provideThreadExecutor(JobExecutor jobExecutor) {
        return jobExecutor;
    }

    @Provides @Singleton
    PostExecutionThread providePostExecutionThread(UIThread uiThread) {
        return uiThread;
    }

    /*
    @Provides @Singleton
    UserCache provideUserCache(UserCacheImpl userCache) {
        return userCache;
    }
    */

    @Provides @Singleton
    GalleryRepository provideGalleryRepository(GalleryDataRepository galleryDataRepository) {
        return galleryDataRepository;
    }

    @Provides
    @Singleton
    @Named("cacheDir")
    File provideCacheDir(Context context) {
        return context.getCacheDir();
    }

    @Provides
    @Singleton
    @Named("isDebug")
    Boolean provideIsDebug() {
        return BuildConfig.DEBUG;
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  Colors.h
//  workShopTutorial
//
//  Created by Fabian Buentello on 9/28/15.
//  Copyright © 2015 Fabian Buentello. All rights reserved.
//

#ifndef Colors_h
#define Colors_h

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]    //hex converter

#define baseColor UIColorFromRGB(0x81d4dc)

#define baseComplementColor UIColorFromRGB(0x46898F)

#define subColor UIColorFromRGB(0xf04943)

#define sideBarBackground UIColorFromRGB(0x3f3f3f)

//Colors
#define whiteColor UIColorFromRGB(0xffffff)

//TWITTER COLORS link: https://about.twitter.com/company/brand-assets
#define twitterColor UIColorFromRGB(0x55acee)
#define twitterDark UIColorFromRGB(0x292f33)
#define twitterGrey UIColorFromRGB(0x66757f)
#define twitterLightGrey UIColorFromRGB(0xccd6dd)

//FACEBOOK COLORS
#define facebookColor UIColorFromRGB(0x3b5998)

//LINKEDIN COLORS
#define linkedInColor UIColorFromRGB(0x0173b2)

#endif /* Colors_h */


text:
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;

public class GotoThemeFile extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        // TODO: insert action logic here
        Project project = e.getData(PlatformDataKeys.PROJECT);

        String txt = Messages.showInputDialog(project, "Theme to use?", "Theme package name", Messages.getQuestionIcon());
        Messages.showMessageDialog(project, "TODO: navigate to the file in theme " + txt + ".", "Navigate", Messages.getInformationIcon());
    }
}


text:
<?php

$aPathInfo = pathinfo(__FILE__);
require_once ($aPathInfo['dirname'] . '/../inc/header.inc.php');

$a = BxDolStudioInstallerUtils::getInstance()->perform('boonex/intercom/', 'install', array('auto_enable' => true));
echo json_encode($a);


text:
Kvpbase is a data storage platform for developers and sysadmins that allows you to quickly deploy an elastic object storage cloud with near-infinite key-value storage on your own machines within minutes.  This SDK is intended to help you quickly integrate Kvpbase into your application.

Kvpbase is a RESTful object storage platform.  This SDK is intended to help application developers integrate object storage using kvpbase into their Javascript applications.

## Help or Feedback
First things first - do you need help or have feedback?  Contact me at joel dot christner at gmail dot com or file an issue here!

## Install with npm
```
npm install kvpbase
```

## Full Example
Refer to ```Test.js``` project for a full example.


text:
package org.springframework.boot.configurationsample.method;

import org.springframework.boot.configurationsample.ConfigurationProperties;

/**
 * Sample for testing deprecated method configuration.
 *
 * @author Stephane Nicoll
 */
public class DeprecatedMethodConfig {

	@ConfigurationProperties(prefix = "foo")
	@Deprecated
	public Foo foo() {
		return new Foo();
	}

	public static class Foo {

		private String name;

		private boolean flag;

		public String getName() {
			return this.name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public boolean isFlag() {
			return this.flag;
		}

		public void setFlag(boolean flag) {
			this.flag = flag;
		}

	}

}


text:
'use strict';

/**
 * General-purpose validator for ngModel.
 * angular.js comes with several built-in validation mechanism for input fields (ngRequired, ngPattern etc.) but using
 * an arbitrary validation function requires creation of a custom formatters and / or parsers.
 * The ui-validate directive makes it easy to use any function(s) defined in scope as a validator function(s).
 * A validator function will trigger validation on both model and input changes.
 *
 * @example <input ui-validate=" 'myValidatorFunction($value)' ">
 * @example <input ui-validate="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }">
 * @example <input ui-validate="{ foo : '$value > anotherModel' }" ui-validate-watch=" 'anotherModel' ">
 * @example <input ui-validate="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }" ui-validate-watch=" { foo : 'anotherModel' } ">
 *
 * @param ui-validate {string|object literal} If strings is passed it should be a scope's function to be used as a validator.
 * If an object literal is passed a key denotes a validation error key while a value should be a validator function.
 * In both cases validator function should take a value to validate as its argument and should return true/false indicating a validation result.
 */
angular.module('ui.validate',[]).directive('uiValidate',
    function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            var validateFn, validators = {},
            validateExpr = scope.$eval(attrs.uiValidate);

            if (!validateExpr) { return; }

            if (angular.isString(validateExpr)) {
                validateExpr = { validator: validateExpr };
            }

            angular.forEach(validateExpr, function (exprssn, key) {
                validateFn = function (valueToValidate) {
                    var expression = scope.$eval(exprssn, { '$value' : valueToValidate });
                    if (angular.isObject(expression) && angular.isFunction(expression.then)) {
                        // expression is a promise
                        expression.then(function() {
                            ctrl.$setValidity(key, true);
                        }, function() {
                            ctrl.$setValidity(key, false);
                        });
                        return valueToValidate;
                    } else if (expression) {
                        // expression is true
                        ctrl.$setValidity(key, true);
                        return valueToValidate;
                    } else {
                        // expression is false
                        ctrl.$setValidity(key, false);
                        return valueToValidate;
                    }
                };
                validators[key] = validateFn;
                ctrl.$formatters.push(validateFn);
                ctrl.$parsers.push(validateFn);
            });

            function apply_watch(watch) {
                //string - update all validators on expression change
                if (angular.isString(watch)) {
                    scope.$watch(watch, function() {
                        angular.forEach(validators, function(validatorFn) {
                            validatorFn(ctrl.$modelValue);
                        });
                    });
                    return;
                }

                //array - update all validators on change of any expression
                if (angular.isArray(watch)) {
                    angular.forEach(watch, function(expression) {
                        scope.$watch(expression, function() {
                            angular.forEach(validators, function(validatorFn) {
                                validatorFn(ctrl.$modelValue);
                            });
                        });
                    });
                    return;
                }

                //object - update appropriate validator
                if (angular.isObject(watch)) {
                    angular.forEach(watch, function(expression, validatorKey) {
                        //value is string - look after one expression
                        if (angular.isString(expression)) {
                            scope.$watch(expression, function() {
                                validators[validatorKey](ctrl.$modelValue);
                            });
                        }

                        //value is array - look after all expressions in array
                        if (angular.isArray(expression)) {
                            angular.forEach(expression, function(intExpression) {
                                scope.$watch(intExpression, function() {
                                    validators[validatorKey](ctrl.$modelValue);
                                });
                            });
                        }
                    });
                }
            }
            // Support for ui-validate-watch
            if (attrs.uiValidateWatch) {
                apply_watch( scope.$eval(attrs.uiValidateWatch));
            }
        }
    };
});


text:
package com.emitrom.lienzo.client.junit;

import com.emitrom.lienzo.client.core.types.DashArray;
import com.emitrom.lienzo.client.core.types.Point2D;
import com.emitrom.lienzo.client.core.types.Point2DArray;
import com.emitrom.lienzo.client.core.types.Transform;
import com.google.gwt.junit.client.GWTTestCase;

public abstract class LienzoTestCase extends GWTTestCase
{
    public String getModuleName()
    {
        return "com.emitrom.lienzo.Lienzo";
    }

    public void assertEqualsJsonString(String expected, String actual)
    {
        //TODO if different implementations serialize the attributes in a different order,
        // we should parse the JSON of each and do pairwise comparisons (recursively)
        assertEquals(expected, actual);
    }

    public static void assertEquals(Point2DArray a, Point2DArray b)
    {
        int na = a.getLength();
        int nb = b.getLength();
        assertEquals(na, nb);
        for (int i = 0; i < na; i++)
        {
            Point2D pa = a.getPoint(i);
            Point2D pb = b.getPoint(i);
            assertEquals(pa, pb);
        }
    }

    public static void assertEquals(Point2D a, Point2D b)
    {
        assertEquals(a.getX(), b.getX());
        assertEquals(a.getY(), b.getY());
    }

    public static void assertEquals(Transform a, Transform b)
    {
        for (int i = 0; i < 6; i++)
        {
            assertEquals(a.get(i), b.get(i));
        }
    }

    public static void assertEquals(DashArray a, DashArray b)
    {
        assertEquals(a.getNormalizedArray(), b.getNormalizedArray());
    }

    public static void assertEquals(double[] a, double[] b)
    {
        assertEquals(a.length, b.length);
        for (int i = 0; i < a.length; i++)
        {
            assertEquals(a[i], b[i]);
        }
    }

    public static String escape(String s)
    {
        if (s == null)
            return "null";

        StringBuilder b = new StringBuilder("\"");
        for (int i = 0, n = s.length(); i < n; i++)
        {
            char c = s.charAt(i);
            switch (c)
            {
                case '"': b.append("\\").append(c); break;
                default: b.append(c); break;
            }
        }
        b.append('"');
        return b.toString();
    }
}


text:
class GoldStandardAnnotationPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve(action)
      return scope.all if user.is_admin?

      public_workflows = Workflow.where("public_gold_standard IS TRUE")
      public_workflow_ids = public_workflows.select(:id)

      scope.where(workflow_id: public_workflow_ids).order(id: :asc)
    end
  end

  scope :index, with: Scope
end


text:
package consulo.dotnet.psi;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNameIdentifierOwner;
import com.intellij.util.ArrayFactory;

import javax.annotation.Nullable;

/**
 * @author VISTALL
 * @since 28.11.13.
 * Index Method
 * Property
 * Event
 */
public interface DotNetXAccessor extends DotNetModifierListOwner, PsiNameIdentifierOwner, DotNetNamedElement, DotNetCodeBlockOwner
{
	DotNetXAccessor[] EMPTY_ARRAY = new DotNetXAccessor[0];

	ArrayFactory<DotNetXAccessor> ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new DotNetXAccessor[count];

	String VALUE = "value";

	enum Kind
	{
		GET,
		SET,
		ADD,
		REMOVE;

		public static final Kind[] VALUES = values();
	}

	@Nullable
	PsiElement getAccessorElement();

	@Nullable
	Kind getAccessorKind();
}


text:
package com.fatuhiva.touch.render.container.toolbar;

import com.fatuhiva.model.container.toolbar.FatuToolbar;
import com.fatuhiva.touch.render.container.JextAbstractContainerRender;

@SuppressWarnings("rawtypes")
public class JextToolbarRender extends JextAbstractContainerRender<FatuToolbar>{

    public JextToolbarRender() {
        super("Ext.toolbar.Toolbar");
        //composite.addRender(new JextUnmodifiablePropertyRender<JextToolbar>("height", 30));
        //composite.addRender(new JextUnmodifiablePropertyRender<JextToolbar>("autoHeight", true));
    }

}


text:
#include <aws/drs/model/DeleteRecoveryInstanceRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::drs::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DeleteRecoveryInstanceRequest::DeleteRecoveryInstanceRequest() :
    m_recoveryInstanceIDHasBeenSet(false)
{
}

Aws::String DeleteRecoveryInstanceRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_recoveryInstanceIDHasBeenSet)
  {
   payload.WithString("recoveryInstanceID", m_recoveryInstanceID);

  }

  return payload.View().WriteReadable();
}


text:
package com.navercorp.pinpoint.plugin.jdbc.jtds;

import com.navercorp.pinpoint.bootstrap.plugin.jdbc.JdbcUrlParserV2;
import com.navercorp.pinpoint.pluginit.jdbc.DataBaseTestCase;
import com.navercorp.pinpoint.pluginit.jdbc.DefaultJDBCApi;
import com.navercorp.pinpoint.pluginit.jdbc.DriverProperties;
import com.navercorp.pinpoint.pluginit.jdbc.JDBCApi;
import com.navercorp.pinpoint.pluginit.jdbc.JDBCDriverClass;
import com.navercorp.pinpoint.pluginit.jdbc.JDBCTestConstants;
import com.navercorp.pinpoint.pluginit.utils.AgentPath;
import com.navercorp.pinpoint.pluginit.utils.TestcontainersOption;
import com.navercorp.pinpoint.test.plugin.Dependency;
import com.navercorp.pinpoint.test.plugin.ImportPlugin;
import com.navercorp.pinpoint.test.plugin.PinpointAgent;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
import com.navercorp.pinpoint.test.plugin.Repository;
import com.navercorp.pinpoint.test.plugin.shared.AfterSharedClass;
import com.navercorp.pinpoint.test.plugin.shared.BeforeSharedClass;

import org.apache.logging.slf4j.Log4jLoggerFactory;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.MSSQLServerContainer;
import org.testcontainers.containers.output.Slf4jLogConsumer;

import java.io.IOException;
import java.util.Properties;

/**
 * @author Jongho Moon
 */
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
@Repository("http://repo.navercorp.com/maven2")
@ImportPlugin("com.navercorp.pinpoint:pinpoint-jtds-plugin")
@Dependency({"net.sourceforge.jtds:jtds:[1.2.8],[1.3.1,)", "com.microsoft.sqlserver:mssql-jdbc:[6.1.0.jre8]",
        "log4j:log4j:1.2.16", "org.slf4j:slf4j-log4j12:1.7.5",
        JDBCTestConstants.VERSION, TestcontainersOption.TEST_CONTAINER, TestcontainersOption.MSSQL})
public class JtdsIT extends DataBaseTestCase {
    private static final String MSSQL = "MSSQL";
    private static final String MSSQL_EXECUTE_QUERY = "MSSQL_EXECUTE_QUERY";

    private static final Logger logger = LoggerFactory.getLogger(JtdsIT.class);

    public static final MSSQLServerContainer mssqlserver = newMSSQLServerContainer(logger.getName());

    public static MSSQLServerContainer newMSSQLServerContainer(String loggerName) {
        final MSSQLServerContainer mssqlServerContainer = new MSSQLServerContainer("mcr.microsoft.com/mssql/server:2019-latest");
        mssqlServerContainer.addEnv("ACCEPT_EULA", "y");
        mssqlServerContainer.withInitScript("sql/init_mssql.sql");
        mssqlServerContainer.withPassword(JtdsITConstants.PASSWORD);

        Log4jLoggerFactory log4jLoggerFactory = new Log4jLoggerFactory();
        org.slf4j.Logger sLogger = log4jLoggerFactory.getLogger(loggerName);
        mssqlServerContainer.withLogConsumer(new Slf4jLogConsumer(sLogger));
        return mssqlServerContainer;
    }

    private static DriverProperties driverProperties;
    private static JDBCDriverClass driverClass;
    private static JDBCApi jdbcApi;

    private static JdbcUrlParserV2 jdbcUrlParser;

    private static String address;

    @BeforeSharedClass
    public static void sharedSetUp() throws Exception {
        mssqlserver.start();
        setAddress(mssqlserver.getJdbcUrl());

    }

    @AfterSharedClass
    public static void sharedTearDown() {
        if (mssqlserver != null) {
            mssqlserver.stop();
        }
    }

    @BeforeClass
    public static void beforeClass() throws IOException, InterruptedException {
        String serverJdbcUrl = getAddress();
        String address = serverJdbcUrl.substring(JtdsITConstants.JDBC_URL_PREFIX.length());
        String jdbcUrl = JtdsITConstants.JTDS_URL_PREFIX + address;

        driverProperties = new DriverProperties(jdbcUrl, JtdsITConstants.USER_NAME, JtdsITConstants.PASSWORD, new Properties());

        driverClass = new JtdsJDBCDriverClass();
        jdbcApi = new DefaultJDBCApi(driverClass);
        // load jdbc driver
        driverClass.getDriver();

        jdbcUrlParser = new JtdsJdbcUrlParser();
    }

    @Override
    protected JDBCDriverClass getJDBCDriverClass() {
        return driverClass;
    }

    @Before
    public void before() {
        setup(MSSQL, MSSQL_EXECUTE_QUERY, driverProperties, jdbcUrlParser, jdbcApi);
    }

    public static String getAddress() {
        return address;
    }

    public static void setAddress(String address) {
        JtdsIT.address = address;
    }

}


text:
require 'spec_helper'

describe HamlLint::Linter::SpaceBeforeScript do
  include_context 'linter'

  context 'when silent script has no separating space' do
    let(:haml) { <<-HAML }
      %span Hello
      -some_code
      %span World
    HAML

    it { should report_lint line: 2 }
  end

  context 'when silent script has a separating space' do
    let(:haml) { <<-HAML }
      %span Hello
      - some_code
      %span World
    HAML

    it { should_not report_lint }
  end

  context 'when script has no separating space' do
    let(:haml) { <<-HAML }
      %span Hello
      =some_code
      %span World
    HAML

    it { should report_lint line: 2 }
  end

  context 'when script has a separating space' do
    let(:haml) { <<-HAML }
      %span Hello
      = some_code
      %span World
    HAML

    it { should_not report_lint }
  end

  context 'when inline script has no separating space' do
    let(:haml) { <<-HAML }
      %span Hello
      %span='there'
      %span World
    HAML

    it { should report_lint line: 2 }
  end

  context 'when inline script has a separating space' do
    let(:haml) { <<-HAML }
      %span Hello
      %span= 'there'
      %span World
    HAML

    it { should_not report_lint }
  end

  context 'when inline script contains string that is the same as the tag' do
    let(:haml) { <<-HAML }
      %tag.count= count
    HAML

    it { should_not report_lint }
  end

  context 'when inline script spreads across multiple lines via comma' do
    context 'and the script has a separating space' do
      let(:haml) { <<-HAML }
        %tag= link_to 'Link',
                      path
      HAML

      it { should_not report_lint }
    end

    context 'and the script does not have a separating space' do
      let(:haml) { <<-HAML }
        %tag=link_to 'Link',
                     path
        %tag
      HAML

      it { should report_lint line: 1 }
    end
  end

  context 'when inline script spreads across multiple lines via vertical pipe' do
    context 'and the script has a separating space' do
      let(:haml) { <<-HAML }
        %tag= link_to 'Click' + |
                      'Here'    |
      HAML

      it { should_not report_lint }
    end

    context 'and the script does not have a separating space' do
      let(:haml) { <<-HAML }
        %tag=link_to 'Click' + |
                     'Here'    |
        %tag
      HAML

      it { should report_lint line: 1 }
    end
  end

  context 'when plain text contains interpolation' do
    let(:haml) { <<-HAML }
      %p
        Some \#{interpolated} text
    HAML

    it { should_not report_lint }
  end

  context 'when inline tag text contains interpolation' do
    let(:haml) { '%p Some #{interpolated} text' }

    it { should_not report_lint }
  end

  context 'when inline tag script contains quotes' do
    context 'and there is no separating space' do
      let(:haml) { '%p="Some #{interpolated} text"' }
      it { should report_lint }
    end

    context 'and there is a separating space' do
      let(:haml) { '%p= "Some #{interpolated} text"' }
      it { should_not report_lint }
    end
  end

  context 'when inline tag is nested in another tag' do
    let(:haml) { <<-HAML }
      %div
        %div
          %div= value
      %div= array[value]
    HAML

    it { should_not report_lint }

    context 'and the tag has siblings' do
      let(:haml) { <<-HAML }
        %div
          %div Hello
          %div= value
        = array[value]
      HAML

      it { should_not report_lint }
    end
  end
end


text:
window.addPerlinNoisePT = function() {
    var pn = new BABYLON.PerlinNoiseProceduralTexture("perlinNoisePT", 512, scene);
    return pn;
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using MixedRealityToolkit.Common;
using MixedRealityToolkit.SpatialMapping;
using MixedRealityToolkit.SpatialMapping.SpatialProcessing;
using System.Collections.Generic;
using UnityEngine;

namespace MixedRealityToolkit.Examples.SpatialMapping
{
    /// <summary>
    /// The SpatialProcessingTest class allows applications to scan the environment for a specified amount of time
    /// and then process the Spatial Mapping Mesh (find planes, remove vertices) after that time has expired.
    /// </summary>
    public class SpatialProcessingTest : Singleton<SpatialProcessingTest>
    {
        [Tooltip("How much time (in seconds) that the SurfaceObserver will run after being started; used when 'Limit Scanning By Time' is checked.")]
        public float scanTime = 30.0f;

        [Tooltip("Material to use when rendering Spatial Mapping meshes while the observer is running.")]
        public Material defaultMaterial;

        [Tooltip("Optional Material to use when rendering Spatial Mapping meshes after the observer has been stopped.")]
        public Material secondaryMaterial;

        [Tooltip("Minimum number of floor planes required in order to exit scanning/processing mode.")]
        public uint minimumFloors = 1;

        /// <summary>
        /// Indicates if processing of the surface meshes is complete.
        /// </summary>
        private bool meshesProcessed = false;

        /// <summary>
        /// GameObject initialization.
        /// </summary>
        private void Start()
        {
            // Update surfaceObserver and storedMeshes to use the same material during scanning.
            SpatialMappingManager.Instance.SetSurfaceMaterial(defaultMaterial);

            // Register for the MakePlanesComplete event.
            SurfaceMeshesToPlanes.Instance.MakePlanesComplete += SurfaceMeshesToPlanes_MakePlanesComplete;
        }

        /// <summary>
        /// Called once per frame.
        /// </summary>
        private void Update()
        {
            // Check to see if the spatial mapping data has been processed yet.
            if (!meshesProcessed)
            {
                // Check to see if enough scanning time has passed
                // since starting the observer.
                if ((Time.unscaledTime - SpatialMappingManager.Instance.StartTime) < scanTime)
                {
                    // If we have a limited scanning time, then we should wait until
                    // enough time has passed before processing the mesh.
                }
                else
                {
                    // The user should be done scanning their environment,
                    // so start processing the spatial mapping data...

                    if (SpatialMappingManager.Instance.IsObserverRunning())
                    {
                        // Stop the observer.
                        SpatialMappingManager.Instance.StopObserver();
                    }

                    // Call CreatePlanes() to generate planes.
                    CreatePlanes();

                    // Set meshesProcessed to true.
                    meshesProcessed = true;
                }
            }
        }

        /// <summary>
        /// Handler for the SurfaceMeshesToPlanes MakePlanesComplete event.
        /// </summary>
        /// <param name="source">Source of the event.</param>
        /// <param name="args">Args for the event.</param>
        private void SurfaceMeshesToPlanes_MakePlanesComplete(object source, System.EventArgs args)
        {
            // Collection of floor planes that we can use to set horizontal items on.
            List<GameObject> floors = new List<GameObject>();
            floors = SurfaceMeshesToPlanes.Instance.GetActivePlanes(PlaneTypes.Floor);

            // Check to see if we have enough floors (minimumFloors) to start processing.
            if (floors.Count >= minimumFloors)
            {
                // Reduce our triangle count by removing any triangles
                // from SpatialMapping meshes that intersect with active planes.
                RemoveVertices(SurfaceMeshesToPlanes.Instance.ActivePlanes);

                // After scanning is over, switch to the secondary (occlusion) material.
                SpatialMappingManager.Instance.SetSurfaceMaterial(secondaryMaterial);
            }
            else
            {
                // Re-enter scanning mode so the user can find more surfaces before processing.
                SpatialMappingManager.Instance.StartObserver();

                // Re-process spatial data after scanning completes.
                meshesProcessed = false;
            }
        }

        /// <summary>
        /// Creates planes from the spatial mapping surfaces.
        /// </summary>
        private void CreatePlanes()
        {
            // Generate planes based on the spatial map.
            SurfaceMeshesToPlanes surfaceToPlanes = SurfaceMeshesToPlanes.Instance;
            if (surfaceToPlanes != null && surfaceToPlanes.enabled)
            {
                surfaceToPlanes.MakePlanes();
            }
        }

        /// <summary>
        /// Removes triangles from the spatial mapping surfaces.
        /// </summary>
        /// <param name="boundingObjects"></param>
        private void RemoveVertices(IEnumerable<GameObject> boundingObjects)
        {
            RemoveSurfaceVertices removeVerts = RemoveSurfaceVertices.Instance;
            if (removeVerts != null && removeVerts.enabled)
            {
                removeVerts.RemoveSurfaceVerticesWithinBounds(boundingObjects);
            }
        }

        /// <summary>
        /// Called when the GameObject is unloaded.
        /// </summary>
        protected override void OnDestroy()
        {
            if (SurfaceMeshesToPlanes.Instance != null)
            {
                SurfaceMeshesToPlanes.Instance.MakePlanesComplete -= SurfaceMeshesToPlanes_MakePlanesComplete;
            }

            base.OnDestroy();
        }
    }
}


text:
namespace RegExpose.Nodes.Anchors
{
    public class EndOfString : ZeroWidthAssertion
    {
        public EndOfString(bool matchesFinalNewLine, int index, string pattern)
            : base(index, pattern)
        {
            MatchesFinalNewLine = matchesFinalNewLine;
        }

        public bool MatchesFinalNewLine { get; private set; }

        public override string NodeType
        {
            get { return "End of String"; }
        }

        protected override bool Matches(State state)
        {
            if (IsAtEndOfInput(state))
            {
                return true;
            }

            if (MatchesFinalNewLine)
            {
                return IsAtFinalNewLine(state);
            }

            return false;
        }

        protected override string AdditionalSettingsString
        {
            get { return string.Format("(MatchesFinalNewLine:{0})", MatchesFinalNewLine); }
        }
    }
}


text:
<!DOCTYPE html>
<title>position:relative should work on table captions</title>
<link rel="match" href="position-relative-table-top-ref.html" />
<link rel="help" href="https://www.w3.org/TR/css-position-3/#rel-pos" />
<meta name="assert" content="This test checks that the position:relative top constraint behaves correctly for <caption> elements">

You should see a green box above. No red should be visible.


text:
namespace Sitecore.FakeDb.Tests.Security.AccessControl
{
  using FluentAssertions;
  using Sitecore.FakeDb.Security.AccessControl;
  using Sitecore.Security.AccessControl;
  using Xunit;

  public class AuthorizationManagerTest
  {
    [Fact]
    public void ShouldResolveDefaultAuthorizationProvider()
    {
      // act & assert
      AuthorizationManager.Provider.Should().BeOfType<FakeAuthorizationProvider>();
    }
  }
}


text:
<?php
namespace Concrete\Controller\Dialog\Block;

use Concrete\Controller\Backend\UserInterface\Block as BackendInterfaceBlockController;
use Concrete\Core\Area\Area;
use Concrete\Core\Block\Block;
use Concrete\Core\Block\Command\AddAliasDefaultsBlockCommand;
use Concrete\Core\Block\Command\ForceDefaultDisplayOrderBlockCommand;
use Concrete\Core\Block\Command\UpdateForkedAliasDefaultsBlockCommand;
use Concrete\Core\Command\Batch\Batch;
use Concrete\Core\Http\ResponseFactoryInterface;
use Concrete\Core\Page\PageList;
use Concrete\Core\Page\Template;
use Concrete\Core\Page\Type\Type;
use Concrete\Core\Permission\Checker;

class Aliasing extends BackendInterfaceBlockController
{
    protected $viewPath = '/dialogs/block/aliasing';

    public function view()
    {
        $ct = Type::getByDefaultsPage($this->page);
        $template = Template::getByID($this->page->getPageTemplateID());

        $pl = new PageList();
        $pl->setSiteTreeToAll();
        $pl->ignorePermissions();
        $pl->filterByPageTypeID($ct->getPageTypeID());
        $pl->filterByPageTemplate($template);

        $this->set('total', $pl->getTotalResults());
    }

    /**
     * @return \Concrete\Core\Http\Response | void
     * @throws \Illuminate\Contracts\Container\BindingResolutionException | \Doctrine\DBAL\Exception
     */
    public function submit()
    {
        if ($this->validateAction() && $this->canAccess()) {
            $a = Area::get($this->page, $this->request->get('arHandle'));
            $c = $this->page;
            if (is_object($a)) {
                $b = Block::getByID($this->request->get('bID'), $c, $a);
                $p = new Checker($b);
                /** @phpstan-ignore-next */
                if ($p->canAdminBlock() && $c->isMasterCollection()) {
                    $blocks = $this->block->queueForDefaultsAliasing($this->request->request->get('addBlock'), $this->request->request->get('updateForkedBlocks'), (bool) $this->request->request->get('forceDisplayOrder' , false));
                    $batch = Batch::create(t('Update Defaults'), function() use ($blocks) {
                        foreach ($blocks as $b) {
                            if ($b['action'] == 'update_forked_alias') {
                                $commandClass = UpdateForkedAliasDefaultsBlockCommand::class;
                            } elseif ($b['action']== 'force_display_order') {
                                $commandClass = ForceDefaultDisplayOrderBlockCommand::class;
                            } else {
                                $commandClass = AddAliasDefaultsBlockCommand::class;
                            }

                            $command = new $commandClass(
                                $this->block->getBlockID(),
                                $this->page->getCollectionID(),
                                $this->page->getVersionID(),
                                $this->area->getAreaHandle(),
                                $b['bID'],
                                $b['cID'],
                                $b['cvID'],
                                $b['arHandle'],
                                (bool) $this->request->request->get('forceDisplayOrder', false)
                            );
                            yield $command;
                        }
                    });
                    return $this->dispatchBatch($batch);
                }
            }
        }

        if ($this->error->has()) {
            return $this->app->make(ResponseFactoryInterface::class)->error($this->error);
        }

        $this->app->shutdown();
    }

    /*
    public function submit()
    {
        if ($this->validateAction() && $this->canAccess()) {
            $a = \Area::get($this->page, $_GET['arHandle']);
            $c = $this->page;
            if (is_object($a)) {
                $b = \Block::getByID($_GET['bID'], $c, $a);
                $p = new \Permissions($b);
                if ($p->canAdminBlock() && $c->isMasterCollection()) {
                    if (is_array($_POST['cIDs'])) {
                        foreach ($_POST['cIDs'] as $cID) {
                            $nc = \Page::getByID($cID);
                            if (!$b->isAlias($nc)) {
                                $bt = $b->getBlockTypeObject();
                                if ($bt->isCopiedWhenPropagated()) {
                                    $b->duplicate($nc, true);
                                } else {
                                    $b->alias($nc);
                                }
                            }
                        }
                    }
                    // now remove any items that WERE checked and now aren't
                    if (is_array($_POST['checkedCIDs'])) {
                        foreach ($_POST['checkedCIDs'] as $cID) {
                            if (!(is_array($_POST['cIDs'])) || (!in_array($cID, $_POST['cIDs']))) {
                                $nc = \Page::getByID($cID, 'RECENT');
                                $nb = \Block::getByID($_GET['bID'], $nc, $a);
                                if (is_object($nb) && (!$nb->isError())) {
                                    $nb->deleteBlock();
                                }
                                $nc->rescanDisplayOrder($_REQUEST['arHandle']);
                            }
                        }
                    }
                    $er = new EditResponse();
                    $er->setPage($this->page);
                    $er->setAdditionalDataAttribute('bID', $b->getBlockID());
                    $er->setAdditionalDataAttribute('aID', $a->getAreaID());
                    $er->setAdditionalDataAttribute('arHandle', $a->getAreaHandle());
                    $er->setMessage(t('Defaults updated.'));
                    $er->outputJSON();
                }
            }
        }
    }
    */

    protected function validateAction()
    {
        if (parent::validateAction()) {
            $r = $this->request->request;
            if (!$r->get('addBlock') && !$r->get('updateForkedBlocks') && !$r->get('forceDisplayOrder')) {
                $this->error->add(t('You need to select at least one action'));
            } else {
                return true;
            }
        }

        return false;
    }

    protected function canAccess()
    {
        return $this->permissions->canAdminBlock();
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>bowl.cli_opts.remove — bowl 0.3.0 documentation</title>

    <link rel="stylesheet" href="../../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />

    <link rel="top" title="bowl 0.3.0 documentation" href="../../../index.html" />
    <link rel="up" title="Module code" href="../../index.html" />

Navigation

          index

          modules |

bowl 0.3.0 documentation »

Module code »

Source code for bowl.cli_opts.remove

"""
This module is the rm command of bowl.

Created on 26 May 2014
@author: Charlie Lewis
"""
import ast
import docker
import os

[docs]class remove(object):
    """
    This class is responsible for the rm command of the cli.
    """
    @classmethod

[docs]    def main(self, args):
        # !! TODO needs to implement login if using that

        # !! TODO make more robust and read from connected hosts
        #         also deal with the possibility of more than one
        #         container having the same name on different hosts
        #         also make it easier to specify the container id
        try:
            directory = args.metadata_path
            directory = os.path.expanduser(directory)
            with open(os.path.join(directory, "containers"), 'r') as f:
                for line in f:
                    container = ast.literal_eval(line.rstrip("\n"))
                    if container['container_id'] == args.CONTAINER:
                        c = docker.Client(base_url='tcp://'+container['host']+':2375', version='1.12',
                                          timeout=10)
                        c.remove_container(args.CONTAINER)
                        if not args.z:
                            print "removed "+container['container_id']+" on "+container['host']
        except:
            if not args.z:
                print "unable to remove ",args.CONTAINER
            return False
        return True

Quick search

    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

bowl 0.3.0 documentation »

Module code »

        © Copyright 2014 Charlie Lewis, All Rights Reserved..
      Created using Sphinx 1.2.2.


text:
    This example shows the accessibility features of Telerik TreeView for ASP.NET MVC.

    You can post selected item to the server with Url property of the item.

    Telerik TreeView for ASP.NET MVC is level A accessible (in compliance
    with the W3C Web Accessibility Guidelines 2.0).


text:
package io.datalayer.data.hash;

import io.datalayer.data.hash.PrimeNumberGenerator;
import io.datalayer.data.hash.SimplePrimeNumberGenerator;

/**
 * Test cases for {@link SimplePrimeNumberGenerator}.
 *
 */
public class SimplePrimeNumberGeneratorTest extends AbstractPrimeNumberGeneratorTestCase {
    protected PrimeNumberGenerator createGenerator() {
        return SimplePrimeNumberGenerator.INSTANCE;
    }
}


text:
using namespace lldb;
using namespace lldb_private;

SBFileSpec::SBFileSpec() : m_opaque_up(new lldb_private::FileSpec()) {
  LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBFileSpec);
}

SBFileSpec::SBFileSpec(const SBFileSpec &rhs) : m_opaque_up() {
  LLDB_RECORD_CONSTRUCTOR(SBFileSpec, (const lldb::SBFileSpec &), rhs);

  m_opaque_up = clone(rhs.m_opaque_up);
}

SBFileSpec::SBFileSpec(const lldb_private::FileSpec &fspec)
    : m_opaque_up(new lldb_private::FileSpec(fspec)) {}

// Deprecated!!!
SBFileSpec::SBFileSpec(const char *path) : m_opaque_up(new FileSpec(path)) {
  LLDB_RECORD_CONSTRUCTOR(SBFileSpec, (const char *), path);

  FileSystem::Instance().Resolve(*m_opaque_up);
}

SBFileSpec::SBFileSpec(const char *path, bool resolve)
    : m_opaque_up(new FileSpec(path)) {
  LLDB_RECORD_CONSTRUCTOR(SBFileSpec, (const char *, bool), path, resolve);

  if (resolve)
    FileSystem::Instance().Resolve(*m_opaque_up);
}

SBFileSpec::~SBFileSpec() = default;

const SBFileSpec &SBFileSpec::operator=(const SBFileSpec &rhs) {
  LLDB_RECORD_METHOD(const lldb::SBFileSpec &,
                     SBFileSpec, operator=,(const lldb::SBFileSpec &), rhs);

  if (this != &rhs)
    m_opaque_up = clone(rhs.m_opaque_up);
  return LLDB_RECORD_RESULT(*this);
}

bool SBFileSpec::operator==(const SBFileSpec &rhs) const {
  LLDB_RECORD_METHOD_CONST(bool, SBFileSpec, operator==,(const SBFileSpec &rhs),
                           rhs);

  return ref() == rhs.ref();
}

bool SBFileSpec::operator!=(const SBFileSpec &rhs) const {
  LLDB_RECORD_METHOD_CONST(bool, SBFileSpec, operator!=,(const SBFileSpec &rhs),
                           rhs);

  return !(*this == rhs);
}

bool SBFileSpec::IsValid() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFileSpec, IsValid);
  return this->operator bool();
}
SBFileSpec::operator bool() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFileSpec, operator bool);

  return m_opaque_up->operator bool();
}

bool SBFileSpec::Exists() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFileSpec, Exists);

  return FileSystem::Instance().Exists(*m_opaque_up);
}

bool SBFileSpec::ResolveExecutableLocation() {
  LLDB_RECORD_METHOD_NO_ARGS(bool, SBFileSpec, ResolveExecutableLocation);

  return FileSystem::Instance().ResolveExecutableLocation(*m_opaque_up);
}

int SBFileSpec::ResolvePath(const char *src_path, char *dst_path,
                            size_t dst_len) {
  LLDB_RECORD_STATIC_METHOD(int, SBFileSpec, ResolvePath,
                            (const char *, char *, size_t), src_path, dst_path,
                            dst_len);

  llvm::SmallString<64> result(src_path);
  FileSystem::Instance().Resolve(result);
  ::snprintf(dst_path, dst_len, "%s", result.c_str());
  return std::min(dst_len - 1, result.size());
}

const char *SBFileSpec::GetFilename() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBFileSpec, GetFilename);

  return m_opaque_up->GetFilename().AsCString();
}

const char *SBFileSpec::GetDirectory() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBFileSpec, GetDirectory);

  FileSpec directory{*m_opaque_up};
  directory.GetFilename().Clear();
  return directory.GetCString();
}

void SBFileSpec::SetFilename(const char *filename) {
  LLDB_RECORD_METHOD(void, SBFileSpec, SetFilename, (const char *), filename);

  if (filename && filename[0])
    m_opaque_up->GetFilename().SetCString(filename);
  else
    m_opaque_up->GetFilename().Clear();
}

void SBFileSpec::SetDirectory(const char *directory) {
  LLDB_RECORD_METHOD(void, SBFileSpec, SetDirectory, (const char *), directory);

  if (directory && directory[0])
    m_opaque_up->GetDirectory().SetCString(directory);
  else
    m_opaque_up->GetDirectory().Clear();
}

uint32_t SBFileSpec::GetPath(char *dst_path, size_t dst_len) const {
  LLDB_RECORD_CHAR_PTR_METHOD_CONST(uint32_t, SBFileSpec, GetPath,
                                    (char *, size_t), dst_path, "", dst_len);

  uint32_t result = m_opaque_up->GetPath(dst_path, dst_len);

  if (result == 0 && dst_path && dst_len > 0)
    *dst_path = '\0';
  return result;
}

const lldb_private::FileSpec *SBFileSpec::operator->() const {
  return m_opaque_up.get();
}

const lldb_private::FileSpec *SBFileSpec::get() const {
  return m_opaque_up.get();
}

const lldb_private::FileSpec &SBFileSpec::operator*() const {
  return *m_opaque_up;
}

const lldb_private::FileSpec &SBFileSpec::ref() const { return *m_opaque_up; }

void SBFileSpec::SetFileSpec(const lldb_private::FileSpec &fs) {
  *m_opaque_up = fs;
}

bool SBFileSpec::GetDescription(SBStream &description) const {
  LLDB_RECORD_METHOD_CONST(bool, SBFileSpec, GetDescription, (lldb::SBStream &),
                           description);

  Stream &strm = description.ref();
  char path[PATH_MAX];
  if (m_opaque_up->GetPath(path, sizeof(path)))
    strm.PutCString(path);
  return true;
}

void SBFileSpec::AppendPathComponent(const char *fn) {
  LLDB_RECORD_METHOD(void, SBFileSpec, AppendPathComponent, (const char *), fn);

  m_opaque_up->AppendPathComponent(fn);
}

namespace lldb_private {
namespace repro {

template <>
void RegisterMethods<SBFileSpec>(Registry &R) {
  LLDB_REGISTER_CONSTRUCTOR(SBFileSpec, ());
  LLDB_REGISTER_CONSTRUCTOR(SBFileSpec, (const lldb::SBFileSpec &));
  LLDB_REGISTER_CONSTRUCTOR(SBFileSpec, (const char *));
  LLDB_REGISTER_CONSTRUCTOR(SBFileSpec, (const char *, bool));
  LLDB_REGISTER_METHOD(const lldb::SBFileSpec &,
                       SBFileSpec, operator=,(const lldb::SBFileSpec &));
  LLDB_REGISTER_METHOD_CONST(bool,
                             SBFileSpec, operator==,(const lldb::SBFileSpec &));
  LLDB_REGISTER_METHOD_CONST(bool,
                             SBFileSpec, operator!=,(const lldb::SBFileSpec &));
  LLDB_REGISTER_METHOD_CONST(bool, SBFileSpec, IsValid, ());
  LLDB_REGISTER_METHOD_CONST(bool, SBFileSpec, operator bool, ());
  LLDB_REGISTER_METHOD_CONST(bool, SBFileSpec, Exists, ());
  LLDB_REGISTER_METHOD(bool, SBFileSpec, ResolveExecutableLocation, ());
  LLDB_REGISTER_STATIC_METHOD(int, SBFileSpec, ResolvePath,
                              (const char *, char *, size_t));
  LLDB_REGISTER_METHOD_CONST(const char *, SBFileSpec, GetFilename, ());
  LLDB_REGISTER_METHOD_CONST(const char *, SBFileSpec, GetDirectory, ());
  LLDB_REGISTER_METHOD(void, SBFileSpec, SetFilename, (const char *));
  LLDB_REGISTER_METHOD(void, SBFileSpec, SetDirectory, (const char *));
  LLDB_REGISTER_METHOD_CONST(bool, SBFileSpec, GetDescription,
                             (lldb::SBStream &));
  LLDB_REGISTER_METHOD(void, SBFileSpec, AppendPathComponent, (const char *));
  LLDB_REGISTER_CHAR_PTR_METHOD_CONST(uint32_t, SBFileSpec, GetPath);
}

}
}


text:
const sql = require("@dataform/sql")();

module.exports = (params) => {

  return publish(params.tablePrefix + "quarterly_overview", {
  ...params.defaultConfig
  }).query(ctx => `
with daily_overview as (

select *
from ${ctx.ref(params.defaultConfig.schema, params.tablePrefix + 'daily_overview')}

)

select
${sql.timestamps.truncate(sql.asTimestamp('date'), 'quarter')} as quarter,
  sum(total_sales) as total_sales,
  sum(total_refunds) as total_refunds,
  sum(total_adjustments) as total_adjustments,
  sum(total_other_transactions) as total_other_transactions,
  sum(total_gross_transaction_amount) as total_gross_transaction_amount,
  sum(total_net_tranactions) as total_net_tranactions,
  sum(total_payout_fees) as total_payout_fees,
  sum(total_gross_payout_amount) as total_gross_payout_amount,
  sum(daily_net_activity) as quarterly_net_activity,
  sum(total_sales_count) as total_sales_count,
  sum(total_payouts_count) as total_payouts_count,
  sum(total_adjustments_count) as total_adjustments_count,
  sum(total_failed_charge_count) as total_failed_charge_count,
  sum(total_failed_charge_amount) as total_failed_charge_amount
from daily_overview
group by 1
order by 1 desc
`)
}


text:
<?php

namespace Symfony\Bridge\Doctrine\Types;

use Symfony\Component\Uid\Ulid;

final class UlidBinaryType extends AbstractBinaryUidType
{
    public function getName(): string
    {
        return 'ulid_binary';
    }

    protected function getUidClass(): string
    {
        return Ulid::class;
    }
}


text:
import * as stringHelpers from "../../lib/stringHelpers";
import ArgumentNullError from "../../lib/argumentNullError";
import "../../lib/zip";

import WordsStatistics from "../wordsStatistics";

//#region Do not open!

export class WordsStatisticsL2 extends WordsStatistics {
    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (stringHelpers.isWhitespace(word)) {
            return;
        }
        this.statistics.set(word.toLowerCase(), 1 + (this.statistics.get(word.toLowerCase()) || 0));
    }
}

export class WordsStatisticsL3 extends WordsStatistics {
    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (stringHelpers.isWhitespace(word)) {
            return;
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        } else if (word.length > 5) {
            word = word.substr(0, word.length - 2);
        }
        this.statistics.set(word.toLowerCase(), 1 + (this.statistics.get(word.toLowerCase()) || 0));
    }
}

export class WordsStatisticsL4 extends WordsStatistics {
    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (stringHelpers.isWhitespace(word)) {
            return;
        }
        if (word.length - 1 > 10) {
            word = word.substr(0, 10);
        }
        this.statistics.set(word.toLowerCase(), 1 + (this.statistics.get(word.toLowerCase()) || 0));
    }
}

export class WordsStatisticsC extends WordsStatistics {
    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (stringHelpers.isWhitespace(word)) {
            return;
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        if (!this.statistics.has(word.toLowerCase())) {
            this.statistics.set(word, 0);
        }
        this.statistics.set(word, 1 + this.statistics.get(word));
    }
}

export class WordsStatisticsE extends WordsStatistics {
    addWord(word) {
        if (!stringHelpers.isDefinedString(word) || stringHelpers.isWhitespace(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        this.statistics.set(word.toLowerCase(), 1 + (this.statistics.get(word.toLowerCase()) || 0));
    }
}

export class WordsStatisticsE2 extends WordsStatistics {
    addWord(word) {
        if (!stringHelpers.isDefinedString(word) || stringHelpers.isWhitespace(word)) {
            return;
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        this.statistics.set(word.toLowerCase(), 1 + (this.statistics.get(word.toLowerCase()) || 0));
    }
}

export class WordsStatisticsE3 extends WordsStatistics {
    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        if (stringHelpers.isWhitespace(word)) {
            return;
        }
        this.statistics.set(word.toLowerCase(), 1 + (this.statistics.get(word.toLowerCase()) || 0));
    }
}

export class WordsStatisticsE4 extends WordsStatistics {
    addWord(word) {
        if (word.length === 0 || stringHelpers.isWhitespace(word)) {
            return;
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        this.statistics.set(word.toLowerCase(), 1 + (this.statistics.get(word.toLowerCase()) || 0));
    }
}

export class WordsStatisticsO1 extends WordsStatistics {
    getStatistics() {
        return Array
            .from(this.statistics)
            .map((keyValue) => ({
                word: keyValue[0],
                count: keyValue[1]
            }))
            .sort((a, b) => a.word.localeCompare(b.word));
    }
}

export class WordsStatisticsO2 extends WordsStatistics {
    getStatistics() {
        return Array
            .from(this.statistics)
            .map((keyValue) => ({
                word: keyValue[0],
                count: keyValue[1]
            }))
            .sort((a, b) => b.count - a.count);
    }
}

export class WordsStatisticsO3 extends WordsStatistics {
    getStatistics() {
        return super.getStatistics().sort((a, b) => a.word.localeCompare(b.word));
    }
}

export class WordsStatisticsO4 extends WordsStatistics {
    getStatistics() {
        return super.getStatistics().sort((a, b) => a.count !== b.count
            ? b.count - a.count
            : -a.word.localeCompare(b.word));
    }
}

export class WordsStatisticsCR {
    constructor() {
        this.statistics = new Map();
    }

    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (stringHelpers.isEmpty(word)) {
            return;
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        word = word.toLowerCase();

        this.statistics.set(word, 1 + (this.statistics.get(word) || 0));
    }

    getStatistics() {
        return Array
            .from(this.statistics)
            .map((keyValue) => ({
                word: keyValue[0],
                count: keyValue[1]
            }))
            .sort((a, b) => a.count !== b.count
                ? b.count - a.count
                : a.word.localeCompare(b.word));
    }
}

const statistics_STA = new Map();

export class WordsStatisticsSTA {
    constructor() {
        statistics_STA.clear();
    }

    get statistics() {
        return statistics_STA;
    }

    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (stringHelpers.isWhitespace(word)) {
            return;
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        this.statistics.set(word.toLowerCase(), 1 + (this.statistics.get(word.toLowerCase()) || 0));
    }

    getStatistics() {
        return Array
            .from(this.statistics)
            .map((keyValue) => ({
                word: keyValue[0],
                count: keyValue[1]
            }))
            .sort((a, b) => a.count !== b.count
                ? b.count - a.count
                : a.word.localeCompare(b.word));
    }
}

export class WordsStatistics123 {
    constructor() {
        this.MAX_SIZE = 1237;

        this.statistics = new Array(this.MAX_SIZE);
        this.words = new Array(this.MAX_SIZE);
    }

    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (stringHelpers.isWhitespace(word)) {
            return;
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        const index = Math.abs(stringHelpers.calculateHash(word.toLowerCase())) % this.MAX_SIZE;
        this.statistics[index] = 1 + (this.statistics[index] || 0);
        this.words[index] = word.toLowerCase();
    }

    getStatistics() {
        return this.statistics
            .zip(this.words, (s, w) => ({ word: w, count: s }))
            .filter(s => s.count > 0)
            .sort((a, b) => a.count !== b.count
                ? b.count - a.count
                : a.word.localeCompare(b.word))
    }
}

export class WordsStatisticsQWE {
    constructor() {
        this.statistics = new Map();
    }

    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (stringHelpers.isWhitespace(word)) {
            return;
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        this.statistics.set(this.toLower(word), 1 + (this.statistics.get(this.toLower(word)) || 0));
    }

    getStatistics() {
        return Array
            .from(this.statistics)
            .map((keyValue) => ({
                word: keyValue[0],
                count: keyValue[1]
            }))
            .sort((a, b) => a.count !== b.count
                ? b.count - a.count
                : a.word.localeCompare(b.word));
    }

    toLower(word) {
        const englishCharsArray = [..."QWERTYUIOPLJKHGFDSAZXCVBNM"];
        const russianCharsArray = [..."ЙЦУКЕНГШЩЗФЫВАПРОЛДЯЧСМИТЬ"];

        const lowerCharacter = character => {
            const charCode = character.charCodeAt(0);
            if (englishCharsArray.includes(character)) {
                return charCode - "D".charCodeAt(0) + "d".charCodeAt(0);
            } else if (russianCharsArray.includes(character)) {
                return charCode - "Я".charCodeAt(0) + "я".charCodeAt(0);
            }
            return charCode;
        };

        return String.fromCharCode(...[...word].map(lowerCharacter));
    };
}

export class WordsStatistics998 {
    constructor() {
        this.statistics = [];
    }

    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (stringHelpers.isWhitespace(word)) {
            return;
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        let lowerCaseWord = word.toLowerCase();
        let wordCount = this.statistics.find(s => s.word === lowerCaseWord) || null;
        if (wordCount !== null) {
            this.statistics = this.statistics.filter(s => s.word !== wordCount.word || s.count !== wordCount.count);
        } else {
            wordCount = { word: lowerCaseWord, count: 0 };
        }
        this.statistics.push({ word: wordCount.word, count: wordCount.count - 1 });
        this.statistics.sort((a, b) => a.count === b.count
            ? a.word.localeCompare(b.word)
            : a.count - b.count);
    }

    getStatistics() {
        return this.statistics.map(s => ({word: s.word, count: -s.count}))
    }
}

export class WordsStatistics999 {
    constructor() {
        this.usedWords = new Set();
        this.statistics = [];
    }

    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (stringHelpers.isWhitespace(word)) {
            return;
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        word = word.toLowerCase();

        if (this.usedWords.has(word)) {
            let wordCount = this.statistics.find(s => s.word === word) || null;
            this.statistics = this.statistics.filter(s => s.word !== wordCount.word || s.count !== wordCount.count);
            this.statistics.push({ word: wordCount.word, count: wordCount.count + 1 });
        } else {
            this.statistics.push({ word: word, count: 1 });
            this.usedWords.add(word);
        }
    }

    getStatistics() {
        return this.statistics.sort((a, b) => a.count !== b.count
            ? b.count - a.count
            : a.word.localeCompare(b.word));
    }
}

export class WordsStatisticsEN1 {
    constructor() {
        this.statistics = new Map();
    }

    addWord(word) {
        if (!stringHelpers.isDefinedString(word)) {
            throw new ArgumentNullError("word should be a defined string");
        }
        if (stringHelpers.isWhitespace(word)) {
            return;
        }
        if (word.length > 10) {
            word = word.substr(0, 10);
        }
        this.statistics.set(word.toLowerCase(), 1 + (this.statistics.get(word.toLowerCase()) || 0));
    }

    getStatistics() {
        const temp = this.statistics;
        this.statistics = new Map();
        return Array
            .from(temp)
            .map((keyValue) => ({
                word: keyValue[0],
                count: keyValue[1]
            }))
            .sort((a, b) => a.count !== b.count
                ? b.count - a.count
                : a.word.localeCompare(b.word));
    }
}

export class WordsStatisticsEN2 extends WordsStatistics {
    constructor() {
        super();
        this.result = null;
    }

    getStatistics() {
        if (this.result) {
            return this.result;
        }
        this.result = super.getStatistics();
        return this.result;
    }
}

//#endregion


text:
package com.deleidos.dp.accumulators;

import static org.junit.Assert.assertTrue;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;
import org.junit.Test;

import com.deleidos.dp.accumulator.BundleProfileAccumulator;
import com.deleidos.dp.accumulator.StringProfileAccumulator;
import com.deleidos.dp.beans.Histogram;
import com.deleidos.dp.beans.Profile;
import com.deleidos.dp.beans.StringDetail;
import com.deleidos.dp.deserializors.SerializationUtility;
import com.deleidos.dp.exceptions.MainTypeException;
import com.deleidos.dp.histogram.AbstractBucket;
import com.deleidos.dp.histogram.AbstractBucketList;

public class StringProfileAccumulatorTest {
	private Logger logger = Logger.getLogger(StringProfileAccumulatorTest.class);
	@Test
	public void testStringMetricsAccumulation() throws SQLException, MainTypeException {
		List<Object> values = Arrays.asList("hello", "hello", "hello world", "greetings");
		StringDetail s = Profile.getStringDetail(BundleProfileAccumulator.generateProfile("test-field", values));
		logger.info(SerializationUtility.serialize(s));
		assertTrue(Double.doubleToLongBits(s.getAverageLength()) == Double.doubleToLongBits(7.5));
		assertTrue(s.getMinLength() == 5);
		assertTrue(s.getMaxLength() == 11);
		assertTrue(Integer.valueOf(s.getNumDistinctValues()) == 3);
		assertTrue((s.getStdDevLength() - 2.59) < .01);
		logger.info("Average, min, max, number of distinct, and standard deviation successfully accumulated.");
		logger.debug(s.getHistogram());

		logger.debug(SerializationUtility.serialize(s));
		assertTrue(noNullValuesInHistogram(s.getHistogram()));

	}

	public boolean noNullValuesInHistogram(Histogram histogram) {
		boolean hasNullValue = false;
		for(String label : histogram.getLabels()) {
			if(label.contains("null")) {
				hasNullValue = true;
			}
		}
		if(hasNullValue) return false;
		else return true;
	}

	@Test
	public void testTermBucketIsNotEmpty() throws SQLException, MainTypeException {
		List<Object> values = Arrays.asList("hello", "hello", "hello world", "greetings");
		/*StringProfileAccumulator str = new StringProfileAccumulator("test-field", "hello");
		str.accumulate("hello");
		str.accumulate("hello world");
		str.accumulate("greetings");
		str.finish();
		StringDetail s = Profile.getStringDetail(str.getState());*/
		StringDetail s = Profile.getStringDetail(BundleProfileAccumulator.generateProfile("test-field", values));

		assertTrue(Double.doubleToLongBits(s.getAverageLength()) == Double.doubleToLongBits(7.5));
		assertTrue(s.getMinLength() == 5);
		assertTrue(s.getMaxLength() == 11);
		assertTrue(Integer.valueOf(s.getNumDistinctValues()) == 3);
		assertTrue((s.getStdDevLength() - 2.59) < .01);
		logger.info("Average, min, max, number of distinct, and standard deviation successfully accumulated.");
		logger.debug(s.getHistogram());

		int size = s.getHistogram().getLabels().size();
		logger.info("Size: " + size);
		assertTrue(size > 0);

	}

}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Searchlight;
using Searchlight.Parsing;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Searchlight.Tests
{
    [TestClass]
    public class TokenizerTests
    {
        [DataTestMethod]
        [DataRow("WHERE field1 = 'value AND Id = 123")]
        public void NonterminatedString(string filter)
        {
            var ex = Assert.ThrowsException<UnterminatedString>(() => Tokenizer.GenerateTokens(filter));
            Assert.AreEqual(filter, ex.OriginalFilter);
        }

        [TestMethod]
        public void CheckStandardFilters()
        {
            // Parse a date time pattern
            string date = DateTime.UtcNow.ToString("yyyy-MM-dd");
            string filters = String.Format("EffectiveDate > '{0}' OR MaintenanceDate > '{0}' OR TotalSalesEffDate > '{0}' OR SalesEffDate > '{0}' OR UseEffDate > '{0}'", date);
            List<string> list = Tokenizer.GenerateTokens(filters).ToList();
            Assert.AreEqual(19, list.Count);
            Assert.AreEqual("EffectiveDate", list[0]);
            Assert.AreEqual(">", list[1]);
            Assert.AreEqual(date, list[2]);
            Assert.AreEqual("OR", list[3]);
            Assert.AreEqual("MaintenanceDate", list[4]);
            Assert.AreEqual(">", list[5]);
            Assert.AreEqual(date, list[6]);
            Assert.AreEqual("OR", list[7]);
            Assert.AreEqual("TotalSalesEffDate", list[8]);
            Assert.AreEqual(">", list[9]);
            Assert.AreEqual(date, list[10]);
            Assert.AreEqual("OR", list[11]);
            Assert.AreEqual("SalesEffDate", list[12]);
            Assert.AreEqual(">", list[13]);
            Assert.AreEqual(date, list[14]);
            Assert.AreEqual("OR", list[15]);
            Assert.AreEqual("UseEffDate", list[16]);
            Assert.AreEqual(">", list[17]);
            Assert.AreEqual(date, list[18]);

            // Parse a string with embedded single quotes
            filters = "TestValue = 'Ted''s Home' AND Possessive = 'Cat''s cradle'";
            list = Tokenizer.GenerateTokens(filters).ToList();
            Assert.AreEqual(7, list.Count);
            Assert.AreEqual("TestValue", list[0]);
            Assert.AreEqual("=", list[1]);
            Assert.AreEqual("Ted's Home", list[2]);
            Assert.AreEqual("AND", list[3]);
            Assert.AreEqual("Possessive", list[4]);
            Assert.AreEqual("=", list[5]);
            Assert.AreEqual("Cat's cradle", list[6]);

            // Parse a filter with parenthesis
            filters = "(TestValue = 'Ted''s Home') AND (Possessive = 'Cat''s cradle' OR test = 1)";
            list = Tokenizer.GenerateTokens(filters).ToList();
            Assert.AreEqual(15, list.Count);
            Assert.AreEqual("(", list[0]);
            Assert.AreEqual("TestValue", list[1]);
            Assert.AreEqual("=", list[2]);
            Assert.AreEqual("Ted's Home", list[3]);
            Assert.AreEqual(")", list[4]);
            Assert.AreEqual("AND", list[5]);
            Assert.AreEqual("(", list[6]);
            Assert.AreEqual("Possessive", list[7]);
            Assert.AreEqual("=", list[8]);
            Assert.AreEqual("Cat's cradle", list[9]);
            Assert.AreEqual("OR", list[10]);
            Assert.AreEqual("test", list[11]);
            Assert.AreEqual("=", list[12]);
            Assert.AreEqual("1", list[13]);
            Assert.AreEqual(")", list[14]);

            // Parse another filter
            filters = "CompanyReturnId=123 and ((FilingYear>2013) or (FilingYear=2013 and FilingMonth>1))";
            list = Tokenizer.GenerateTokens(filters).ToList();
            Assert.AreEqual("CompanyReturnId", list[0]);
            Assert.AreEqual("=", list[1]);
            Assert.AreEqual("123", list[2]);
            Assert.AreEqual("and", list[3]);
            Assert.AreEqual("(", list[4]);
            Assert.AreEqual("(", list[5]);
            Assert.AreEqual("FilingYear", list[6]);
            Assert.AreEqual(">", list[7]);
            Assert.AreEqual("2013", list[8]);
            Assert.AreEqual(")", list[9]);
            Assert.AreEqual("or", list[10]);
            Assert.AreEqual("(", list[11]);
            Assert.AreEqual("FilingYear", list[12]);
            Assert.AreEqual("=", list[13]);
            Assert.AreEqual("2013", list[14]);
            Assert.AreEqual("and", list[15]);
            Assert.AreEqual("FilingMonth", list[16]);
            Assert.AreEqual(">", list[17]);
            Assert.AreEqual("1", list[18]);
            Assert.AreEqual(")", list[19]);
            Assert.AreEqual(")", list[20]);

            // Parse a filter with != or <>
            // Usage: Workflow ScheduleFetch
            filters = "FilingTypeId != 2";
            list = Tokenizer.GenerateTokens(filters).ToList();
            Assert.AreEqual(3, list.Count);
            Assert.AreEqual("FilingTypeId", list[0]);
            Assert.AreEqual("!=", list[1]);
            Assert.AreEqual("2", list[2]);

            filters = "FilingTypeId <> 2";
            list = Tokenizer.GenerateTokens(filters).ToList();
            Assert.AreEqual(3, list.Count);
            Assert.AreEqual("FilingTypeId", list[0]);
            Assert.AreEqual("<>", list[1]);
            Assert.AreEqual("2", list[2]);

            // Test as per Dustin Welden
            filters = "UserName = 'Bob\\'";
            list = Tokenizer.GenerateTokens(filters).ToList();
            Assert.AreEqual(3, list.Count);
            Assert.AreEqual("UserName", list[0]);
            Assert.AreEqual("=", list[1]);
            Assert.AreEqual("Bob\\", list[2]);

            // Test as per Dustin Welden
            filters = "UserName = 'Bob'''";
            list = Tokenizer.GenerateTokens(filters).ToList();
            Assert.AreEqual(3, list.Count);
            Assert.AreEqual("UserName", list[0]);
            Assert.AreEqual("=", list[1]);
            Assert.AreEqual("Bob'", list[2]);
        }
    }
}