text:
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PrtgAPI.Parameters;
using PrtgAPI.Tests.IntegrationTests.ObjectData.Query;
using PrtgAPI.Tests.UnitTests.Support;

namespace PrtgAPI.Tests.IntegrationTests.ObjectData
{
    [TestClass]
    public class StreamTests : BasePrtgClientTest
    {
        #region Serial

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_WithStartOffset_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            StreamLogsSerial(parameters, expected);
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_WithStartOffset_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.PageSize = 50;

            StreamLogsSerial(parameters, expected);
        }

        #region Start

        //todo: what to do about count being 0 when requesting page count?

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Start_SinglePage()
        {
            var sensors = client.GetSensors();

            var start = 3;

            //Count (30) > (Total (30) - Start (3))
            //Result: request 27 instead
            StreamSerial(new SensorParameters
            {
                Start = start
            }, sensors.Skip(start).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Start_MultiplePages()
        {
            var sensors = client.GetSensors();

            var start = 8;

            //Count (30) > (Total (30) - Start (8))
            //Result: false. Request 500 as normal

            //Increment page: want 500, but can only get 2
            StreamSerial(
                new SensorParameters
                {
                    Start = start,
                    PageSize = 5
                },
                sensors.Skip(start).ToList()
            );
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Start_AndStartOffset_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var start = 3;

            parameters.Start = start;

            StreamLogsSerial(parameters, expected.Skip(start - 1).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Start_AndStartOffset_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var start = 13;

            parameters.Start = start;
            parameters.PageSize = 5;

            StreamLogsSerial(parameters, expected.Skip(start - 1).ToList());
        }

        #endregion
        #region Count

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_SinglePage()
        {
            var sensors = client.GetSensors();

            var count = 10;

            Assert.IsTrue(count < Settings.SensorsInTestServer);

            //Total Objects is not known, so we ask for Count many
            StreamSerial(new SensorParameters
            {
                Count = count
            }, sensors.Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_MultiplePages()
        {
            var sensors = client.GetSensors();

            var count = 13;

            Assert.IsTrue(count < Settings.SensorsInTestServer);

            //Total Objects is not known, so we ask for Count many
            StreamSerial(new SensorParameters
            {
                Count = count,
                PageSize = 5
            }, sensors.Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_LessThanAvailable_SinglePage()
        {
            var sensors = client.GetSensors();

            var count = 10;

            Assert.IsTrue(count < sensors.Count);

            StreamSerial(new SensorParameters
            {
                Count = count
            }, sensors.Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_LessThanAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            var count = 17;

            Assert.IsTrue(count < sensors.Count);

            StreamSerial(new SensorParameters
            {
                Count = count,
                PageSize = 4
            }, sensors.Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_EqualsAvailable_SinglePage()
        {
            var sensors = client.GetSensors();

            StreamSerial(new SensorParameters
            {
                Count = Settings.SensorsInTestServer
            }, sensors);
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_EqualsAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            StreamSerial(new SensorParameters
            {
                Count = Settings.SensorsInTestServer,
                PageSize = 7
            }, sensors);
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_MoreThanAvailable_SinglePage()
        {
            var sensors = client.GetSensors();

            StreamSerial(new SensorParameters
            {
                Count = Settings.SensorsInTestServer * 2,
            }, sensors);
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_MoreThanAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            StreamSerial(new SensorParameters
            {
                Count = Settings.SensorsInTestServer * 2,
                PageSize = 5
            }, sensors);
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_AndStartOffset_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.Count = 10;

            StreamLogsSerial(parameters, expected.Take(10).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_AndStartOffset_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.PageSize = 5;
            parameters.Count = 10;

            StreamLogsSerial(parameters, expected.Take(10).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_AndStartOffset_LessThanAvailable_SinglePage()
        {
            FilterTests.Retry(retry =>
            {
                var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

                var expected = client.GetLogs(parameters);

                var count = 100;

                AssertEx.IsTrue(count < expected.Count, $"Expected {count} to be less than {expected.Count}");

                parameters.Count = count;

                StreamLogsSerial(parameters, expected.Take(count).ToList());
            });
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_AndStartOffset_LessThanAvailable_MultiplePages()
        {
            FilterTests.Retry(retry =>
            {
                var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

                var expected = client.GetLogs(parameters);

                var count = 100;

                Assert.IsTrue(count < expected.Count);

                parameters.Count = count;
                parameters.PageSize = 30;

                StreamLogsSerial(parameters, expected.Take(count).ToList());
            });
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_AndStartOffset_EqualsAvailable_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.Count = expected.Count;

            StreamLogsSerial(parameters, expected.ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_AndStartOffset_EqualsAvailable_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.Count = expected.Count;
            parameters.PageSize = 507;

            StreamLogsSerial(parameters, expected.ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_AndStartOffset_MoreThanAvailable_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.Count = expected.Count * 2;

            StreamLogsSerial(parameters, expected.ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_Count_AndStartOffset_MoreThanAvailable_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.Count = expected.Count;
            parameters.PageSize = 507;

            StreamLogsSerial(parameters, expected.ToList());
        }

        #endregion
        #region StartAndCount

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_SinglePage()
        {
            var sensors = client.GetSensors();

            var start = 3;
            var count = 10;

            StreamSerial(new SensorParameters
            {
                Start = start,
                Count = count
            }, sensors.Skip(start).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_MultiplePages()
        {
            var sensors = client.GetSensors();

            var start = 3;
            var count = 10;

            StreamSerial(new SensorParameters
            {
                Start = start,
                Count = count,
                PageSize = 3
            }, sensors.Skip(start).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_CountLessThanAvailable_SinglePage()
        {
            var sensors = client.GetSensors();

            var start = 3;
            var count = 10;

            Assert.IsTrue(count < sensors.Count);

            StreamSerial(new SensorParameters
            {
                Start = start,
                Count = count
            }, sensors.Skip(start).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_CountLessThanAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            var start = 3;
            var count = 10;

            Assert.IsTrue(count < sensors.Count);

            StreamSerial(new SensorParameters
            {
                Start = start,
                Count = count,
                PageSize = 3
            }, sensors.Skip(start).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_CountEqualsAvailable_SinglePage()
        {
            var sensors = client.GetSensors();

            var start = 3;
            var count = sensors.Count;

            StreamSerial(new SensorParameters
            {
                Start = start,
                Count = count
            }, sensors.Skip(start).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_CountEqualsAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            var start = 7;
            var count = sensors.Count;

            StreamSerial(new SensorParameters
            {
                Start = start,
                Count = count,
                PageSize = 5
            }, sensors.Skip(start).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_CountMoreThanAvailable_SinglePage()
        {
            var sensors = client.GetSensors();

            var start = 3;
            var count = sensors.Count * 2;

            StreamSerial(new SensorParameters
            {
                Start = start,
                Count = count
            }, sensors.Skip(start).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_CountMoreThanAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            var start = 7;
            var count = sensors.Count * 2;

            StreamSerial(new SensorParameters
            {
                Start = start,
                Count = count,
                PageSize = 5
            }, sensors.Skip(start).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_AndStartOffset_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var count = 10;
            var start = 4;

            parameters.Count = count;
            parameters.Start = start;

            StreamLogsSerial(parameters, expected.Skip(start - 1).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_AndStartOffset_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var count = 10;
            var start = 8;

            parameters.Count = count;
            parameters.Start = start;
            parameters.PageSize = 5;

            StreamLogsSerial(parameters, expected.Skip(start - 1).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_AndStartOffset_CountLessThanAvailable_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var count = 10;
            var start = 4;

            parameters.Count = count;
            parameters.Start = start;

            Assert.IsTrue(parameters.Count < expected.Count);

            StreamLogsSerial(parameters, expected.Skip(start - 1).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_AndStartOffset_CountLessThanAvailable_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var count = 10;
            var start = 8;

            parameters.Count = count;
            parameters.Start = start;
            parameters.PageSize = 5;

            Assert.IsTrue(parameters.Count < expected.Count);

            StreamLogsSerial(parameters, expected.Skip(start - 1).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_AndStartOffset_CountEqualsAvailable_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var start = 4;

            parameters.Count = expected.Count;
            parameters.Start = start;

            StreamLogsSerial(parameters, expected.Skip(start - 1).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_AndStartOffset_CountEqualsAvailable_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var start = 8;

            parameters.Count = expected.Count;
            parameters.Start = start;
            parameters.PageSize = 50;

            StreamLogsSerial(parameters, expected.Skip(start - 1).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_AndStartOffset_CountMoreThanAvailable_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var start = 4;

            parameters.Count = expected.Count * 2;
            parameters.Start = start;

            StreamLogsSerial(parameters, expected.Skip(start - 1).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Serially_StartAndCount_AndStartOffset_CountMoreThanAvailable_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var start = 8;

            parameters.Count = expected.Count * 2;
            parameters.Start = start;
            parameters.PageSize = 50;

            StreamLogsSerial(parameters, expected.Skip(start - 1).ToList());
        }

        #endregion
        #endregion
        #region Parallel

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_WithStartOffset_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            StreamLogs(parameters, expected);
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_WithStartOffset_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.PageSize = 50;

            StreamLogs(parameters, expected);
        }

        #region Start

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Start_SinglePage()
        {
            var sensors = client.GetSensors();

            var start = 3;

            Stream(new SensorParameters
            {
                Start = start
            }, sensors.Skip(start).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Start_MultiplePages()
        {
            var sensors = client.GetSensors();

            var start = 7;

            Stream(new SensorParameters
            {
                Start = start,
                PageSize = 5
            }, sensors.Skip(start).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Start_AndStartOffset_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.Today, null);

            var expected = client.GetLogs(parameters);

            var start = 3;

            parameters.Start = start;

            StreamLogs(parameters, expected.Skip(start - 1).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Start_AndStartOffset_MultiplePages()
        {
            FilterTests.Retry(retry =>
            {
                var parameters = new LogParameters(Settings.UpSensor, RecordAge.Today, null);

                var expected = client.GetLogs(parameters);

                var start = 130;

                parameters.Start = start;
                parameters.PageSize = 50;

                StreamLogs(parameters, expected.Skip(start - 1).ToList(), retry);
            });
        }

        #endregion
        #region Count

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_SinglePage()
        {
            var sensors = client.GetSensors();

            var count = 900;

            //Total Objects is retrieved, which is lower than Count so Count is ignored
            Stream(new SensorParameters
            {
                Count = count
            }, sensors.Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_MultiplePages()
        {
            var sensors = client.GetSensors();

            var count = 900;

            Stream(new SensorParameters
            {
                Count = count,
                PageSize = 5
            }, sensors.Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_LessThanAvailable_SinglePage()
        {
            var sensors = client.GetSensors();

            var count = 3;

            Stream(new SensorParameters
            {
                Count = count
            }, sensors.Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_LessThanAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            var count = 13;

            Stream(
                new SensorParameters
                {
                    Count = count,
                    PageSize = 5
                },
                sensors.Take(count).ToList()
            );
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_EqualsAvailable_SinglePage()
        {
            var sensors = client.GetSensors();

            Stream(new SensorParameters
            {
                Count = Settings.SensorsInTestServer
            }, sensors);
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_EqualsAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            Stream(
                new SensorParameters
                {
                    Count = sensors.Count,
                    PageSize = 5
                },
                sensors
            );
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_MoreThanAvailable_SinglePage()
        {
            var sensors = client.GetSensors();

            var count = 900;

            Stream(new SensorParameters
            {
                Count = count
            }, sensors);
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_MoreThanAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            var count = 900;

            Stream(new SensorParameters
            {
                Count = count,
                PageSize = 5
            }, sensors);
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_AndStartOffset_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.Count = 10;

            StreamLogs(parameters, expected.Take(10).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_AndStartOffset_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.PageSize = 5;
            parameters.Count = 10;

            StreamLogs(parameters, expected.Take(10).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_AndStartOffset_LessThanAvailable_SinglePage()
        {
            FilterTests.Retry(retry =>
            {
                var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

                var expected = client.GetLogs(parameters);

                var count = 100;

                AssertEx.IsTrue(count < expected.Count, $"Expected {count} to be less than {expected.Count}");

                parameters.Count = count;

                StreamLogs(parameters, expected.Take(count).ToList());
            });
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_AndStartOffset_LessThanAvailable_MultiplePages()
        {
            FilterTests.Retry(retry =>
            {
                var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

                var expected = client.GetLogs(parameters);

                var count = 100;

                AssertEx.IsTrue(count < expected.Count, $"Expected {count} to be less than {expected.Count}");

                parameters.Count = count;
                parameters.PageSize = 30;

                StreamLogs(parameters, expected.Take(count).ToList());
            });
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_AndStartOffset_EqualsAvailable_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.Count = expected.Count;

            StreamLogs(parameters, expected.ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_AndStartOffset_EqualsAvailable_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.Count = expected.Count;
            parameters.PageSize = 507;

            StreamLogs(parameters, expected.ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_AndStartOffset_MoreThanAvailable_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.Count = expected.Count * 2;

            StreamLogsSerial(parameters, expected.ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_Count_AndStartOffset_MoreThanAvailable_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            parameters.Count = expected.Count;
            parameters.PageSize = 507;

            StreamLogsSerial(parameters, expected.ToList());
        }

        #endregion
        #region StartAndCount

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_SinglePage()
        {
            var sensors = client.GetSensors();

            var start = 3;
            var count = 10;

            Stream(new SensorParameters
            {
                Start = start,
                Count = count
            }, sensors.Skip(start).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_MultiplePages()
        {
            var sensors = client.GetSensors();

            var start = 3;
            var count = 10;

            Stream(new SensorParameters
            {
                Start = start,
                Count = count,
                PageSize = 3
            }, sensors.Skip(start).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_CountLessThanAvailable_SinglePage()
        {
            var sensors = client.GetSensors();

            var count = 5;
            var start = 2;

            Stream(new SensorParameters
            {
                Count = count,
                Start = start
            }, sensors.Skip(start).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_CountLessThanAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            var count = 16;
            var start = 10;

            Stream(
                new SensorParameters
                {
                    Count = count,
                    Start = start,
                    PageSize = 3
                },
                sensors.Skip(start).Take(count).ToList()
            );
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_CountEqualsAvailable_SinglePage()
        {
            var sensors = client.GetSensors();

            var start = 2;

            Stream(new SensorParameters
            {
                Count = sensors.Count,
                Start = start
            }, sensors.Skip(start).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_CountEqualsAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            var count = Settings.SensorsInTestServer;
            var start = 7;

            Stream(
                new SensorParameters
                {
                    Count = count,
                    Start = start,
                    PageSize = 5
                },
                sensors.Skip(start).ToList()
            );
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_CountMoreThanAvailable_SinglePage()
        {
            var sensors = client.GetSensors();
            var start = 1;

            Stream(new SensorParameters
            {
                Count = 900,
                Start = start
            }, sensors.Skip(start).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_CountMoreThanAvailable_MultiplePages()
        {
            var sensors = client.GetSensors();

            var start = 7;
            var count = sensors.Count * 2;

            Stream(new SensorParameters
            {
                Start = start,
                Count = count,
                PageSize = 5
            }, sensors.Skip(start).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_AndStartOffset_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var start = 4;

            parameters.Count = expected.Count;
            parameters.Start = start;

            StreamLogs(parameters, expected.Skip(start - 1).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_AndStartOffset_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var count = 10;
            var start = 8;

            parameters.Count = count;
            parameters.Start = start;
            parameters.PageSize = 5;

            StreamLogs(parameters, expected.Skip(start - 1).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_AndStartOffset_CountLessThanAvailable_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var count = 10;
            var start = 4;

            parameters.Count = count;
            parameters.Start = start;

            Assert.IsTrue(parameters.Count < expected.Count);

            StreamLogs(parameters, expected.Skip(start - 1).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_AndStartOffset_CountLessThanAvailable_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var count = 10;
            var start = 8;

            parameters.Count = count;
            parameters.Start = start;
            parameters.PageSize = 5;

            Assert.IsTrue(parameters.Count < expected.Count);

            StreamLogs(parameters, expected.Skip(start - 1).Take(count).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_AndStartOffset_CountEqualsAvailable_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var start = 4;

            parameters.Count = expected.Count;
            parameters.Start = start;

            StreamLogs(parameters, expected.Skip(start - 1).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_AndStartOffset_CountEqualsAvailable_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var start = 8;

            parameters.Count = expected.Count;
            parameters.Start = start;
            parameters.PageSize = 50;

            StreamLogs(parameters, expected.Skip(start - 1).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_AndStartOffset_CountMoreThanAvailable_SinglePage()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var start = 4;

            parameters.Count = expected.Count * 2;
            parameters.Start = start;

            StreamLogs(parameters, expected.Skip(start - 1).ToList());
        }

        [TestMethod]
        [IntegrationTest]
        public void Data_Stream_Parallel_StartAndCount_AndStartOffset_CountMoreThanAvailable_MultiplePages()
        {
            var parameters = new LogParameters(Settings.UpSensor, RecordAge.All, null);

            var expected = client.GetLogs(parameters);

            var start = 8;

            parameters.Count = expected.Count * 2;
            parameters.Start = start;
            parameters.PageSize = 50;

            StreamLogs(parameters, expected.Skip(start - 1).ToList());
        }

        #endregion
        #endregion

        [TestMethod]
        [IntegrationTest]
        public void Data_HasAllStreamTests()
        {
            var expected = TestHelpers.GetTests(typeof(UnitTests.ObjectData.StreamTests)).Where(m => m.Name != "Stream_HasAllTests").Select(m => $"Data_{m.Name}").ToList();

            TestHelpers.Assert_TestClassHasMethods(GetType(), expected);
        }

        private void Stream(SensorParameters parameters, List<Sensor> expected)
        {
            var result = client.StreamSensors(parameters).OrderBy(s => s.Id).ToList();

            AssertEx.AreEqualLists(expected, result, new PrtgObjectComparer(), "Lists were not the same");
        }

        private void StreamSerial(SensorParameters parameters, List<Sensor> expected)
        {
            var result = client.StreamSensors(parameters, true).ToList();

            AssertEx.AreEqualLists(expected, result, new PrtgObjectComparer(), "Lists were not the same");
        }

        private void StreamLogs(LogParameters parameters, List<Log> expected, bool retry = false)
        {
            var result = client.StreamLogs(parameters).ToList().OrderBy(d => d.DateTime).ThenBy(d => d.Status).ToList();
            expected = expected.OrderBy(d => d.DateTime).ThenBy(d => d.Status).ToList();

            AssertEx.AreEqualLists(expected, result, PrtgAPIHelpers.LogEqualityComparer(), "Lists were not the same");
        }

        private void StreamLogsSerial(LogParameters parameters, List<Log> expected)
        {
            var result = client.StreamLogs(parameters, true).ToList();

            AssertEx.AreEqualLists(expected, result, PrtgAPIHelpers.LogEqualityComparer(), "Lists were not the same");
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.google.zxing.qrcode.detector.FinderPattern (ZXing 3.3.0 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.google.zxing.qrcode.detector.FinderPattern

Packages that use FinderPattern

Package
Description

com.google.zxing.qrcode.detector

Uses of FinderPattern in com.google.zxing.qrcode.detector

Methods in com.google.zxing.qrcode.detector that return FinderPattern

Modifier and Type
Method and Description

FinderPattern
FinderPatternInfo.getBottomLeft()

FinderPattern
FinderPatternInfo.getTopLeft()

FinderPattern
FinderPatternInfo.getTopRight()

Methods in com.google.zxing.qrcode.detector that return types with arguments of type FinderPattern

Modifier and Type
Method and Description

protected List<FinderPattern>
FinderPatternFinder.getPossibleCenters()

Constructors in com.google.zxing.qrcode.detector with parameters of type FinderPattern

Constructor and Description

FinderPatternInfo(FinderPattern[] patternCenters)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2007–2016. All rights reserved.

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  Beanshell Maven Plugin
  %%
  Copyright (C) 2014 - 2017 Günther Enthaler
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.github.genthaler</groupId>
	<artifactId>@project.artifactId@-test</artifactId>
	<version>@project.version@</version>
	<packaging>pom</packaging>
	<name>@project.name@ POM Test</name>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<build>
		<plugins>
			<plugin>
				<groupId>@project.groupId@</groupId>
				<artifactId>@project.artifactId@</artifactId>
				<version>@project.version@</version>
				<executions>
					<execution>
						<id>default-cli</id>
						<goals>
							<goal>run</goal>
						</goals>
						<inherited>false</inherited>
						<configuration>
							<file>touch.bsh</file>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
package org.sourcepit.osgifier.core.bundle;

import static com.google.common.base.Strings.isNullOrEmpty;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import org.eclipse.emf.ecore.util.EcoreUtil;
import org.sourcepit.common.constraints.NotNull;
import org.sourcepit.common.manifest.osgi.BundleManifest;
import org.sourcepit.common.manifest.osgi.BundleRequirement;
import org.sourcepit.common.manifest.osgi.PackageImport;
import org.sourcepit.common.utils.path.PathMatcher;
import org.sourcepit.common.utils.props.PropertiesSource;
import org.sourcepit.osgifier.core.ee.ExecutionEnvironment;
import org.sourcepit.osgifier.core.ee.ExecutionEnvironmentImplementation;
import org.sourcepit.osgifier.core.ee.ExecutionEnvironmentService;
import org.sourcepit.osgifier.core.model.context.BundleCandidate;
import org.sourcepit.osgifier.core.model.context.BundleReference;
import org.sourcepit.osgifier.core.util.OptionsUtils;

/**
 * @author Bernd Vogt <bernd.vogt@sourcepit.org>
 */
@Named
public class PackageImportAppender {
   private final PackageResolver packageResolver;

   private final ExecutionEnvironmentService environmentService;

   private final PackageImportFactory packageImportFactory;

   @Inject
   public PackageImportAppender(PackageResolver packageResolver, ExecutionEnvironmentService environmentService,
      PackageImportFactory packageImportFactory) {
      this.packageResolver = packageResolver;
      this.environmentService = environmentService;
      this.packageImportFactory = packageImportFactory;
   }

   private static final class RequireBundleInfo {
      AccessRestriction accessRestriction;

      boolean optional;

      void updateAccessRestriction(AccessRestriction accessRestriction) {
         if (this.accessRestriction == null || this.accessRestriction == AccessRestriction.NONE
            && accessRestriction == AccessRestriction.DISCOURAGED) {
            this.accessRestriction = accessRestriction;
         }
      }

      void updateOptional(boolean optional) {
         if (!this.optional && optional) {
            this.optional = optional;
         }
      }
   }

   public void append(@NotNull BundleCandidate bundle, PropertiesSource options) {
      final Map<BundleCandidate, RequireBundleInfo> bundleToRequireBundleInfo = new HashMap<BundleCandidate, RequireBundleInfo>();
      final Map<String, PackageImport> packageToImport = new HashMap<String, PackageImport>();
      collectRequirements(bundleToRequireBundleInfo, packageToImport, bundle, options);

      final Map<String, BundleRequirement> symbolicNameToBundleRequirement = new HashMap<String, BundleRequirement>(
         bundleToRequireBundleInfo.size());

      for (Entry<BundleCandidate, RequireBundleInfo> entry : bundleToRequireBundleInfo.entrySet()) {
         final RequireBundleInfo info = entry.getValue();
         final BundleCandidate requiredBundle = entry.getKey();
         final BundleRequirement bundleRequirement = packageImportFactory.newRequireBundle(bundle, requiredBundle,
            info.optional, info.accessRestriction, options);
         if (bundleRequirement != null) {
            symbolicNameToBundleRequirement.put(requiredBundle.getSymbolicName(), bundleRequirement);
         }
      }

      collectRequirementsOfEmbeddedBundles(packageToImport, symbolicNameToBundleRequirement, bundle);

      if (!symbolicNameToBundleRequirement.isEmpty()) {
         final List<String> symbolicNames = new ArrayList<String>(symbolicNameToBundleRequirement.keySet());
         Collections.sort(symbolicNames);

         final List<BundleRequirement> requireBundle = bundle.getManifest().getRequireBundle(true);
         for (String symbolicName : symbolicNames) {
            requireBundle.add(symbolicNameToBundleRequirement.get(symbolicName));
         }
      }

      if (!packageToImport.isEmpty()) {
         final List<String> requiredPackages = new ArrayList<String>(packageToImport.keySet());
         Collections.sort(requiredPackages);

         final List<PackageImport> importPackage = bundle.getManifest().getImportPackage(true);
         for (String packageName : requiredPackages) {
            importPackage.add(packageToImport.get(packageName));
         }

         // erase ee and vendor package versions
         if (importPackage != null) {
            final Set<String> eePackages = new HashSet<String>();

            for (ExecutionEnvironment executionEnvironment : environmentService.getExecutionEnvironments()) {
               eePackages.addAll(executionEnvironment.getPackages());
            }

            for (ExecutionEnvironmentImplementation vendors : environmentService.getExecutionEnvironmentImplementations()) {
               eePackages.addAll(vendors.getVendorPackages());
            }

            for (PackageImport packageImport : importPackage) {
               for (String packageName : packageImport.getPackageNames()) {
                  if (eePackages.contains(packageName)) {
                     packageImport.setVersion(null);
                     break;
                  }
               }
            }
         }
      }
   }

   private void collectRequirementsOfEmbeddedBundles(final Map<String, PackageImport> packageToImport,
      final Map<String, BundleRequirement> bundleToRequirement, BundleCandidate bundle) {
      for (BundleCandidate embeddedBundle : BundleUtils.getEmbeddedBundles(bundle)) {
         final BundleManifest manifest = embeddedBundle.getManifest();

         final List<BundleRequirement> requireBundle = manifest.getRequireBundle();
         if (requireBundle != null) {
            for (BundleRequirement bundleRequirement : requireBundle) {
               for (String symbolicName : bundleRequirement.getSymbolicNames()) {
                  if (!bundleToRequirement.containsKey(symbolicName)) {
                     final BundleRequirement copy = EcoreUtil.copy(bundleRequirement);
                     copy.getSymbolicNames().clear();
                     copy.getSymbolicNames().add(symbolicName);
                     bundleToRequirement.put(symbolicName, copy);
                  }
               }
            }
         }

         final List<PackageImport> importPackage = manifest.getImportPackage();
         if (importPackage != null) {
            for (PackageImport packageImport : importPackage) {
               for (String packageName : packageImport.getPackageNames()) {
                  if (!packageToImport.containsKey(packageName)) {
                     final PackageImport copy = EcoreUtil.copy(packageImport);
                     copy.getPackageNames().clear();
                     copy.getPackageNames().add(packageName);
                     packageToImport.put(packageName, copy);
                  }
               }
            }
         }
      }
   }

   private void collectRequirements(final Map<BundleCandidate, RequireBundleInfo> bundleToRequireBundleInfo,
      final Map<String, PackageImport> packageToImport, BundleCandidate bundle, PropertiesSource options) {
      final boolean treatInheritedPackagesAsInternal = options.getBoolean("osgifier.treatInheritedPackagesAsInternal",
         false);
      for (PackageResolutionResult result : packageResolver.resolveRequiredPackages(bundle,
         treatInheritedPackagesAsInternal)) {
         final BundleCandidate exportingBundle = getExportingBundle(result);
         if (exportingBundle != null && bundle != exportingBundle && isRequireBundle(exportingBundle, options)) {
            processRequireBundle(bundleToRequireBundleInfo, bundle, result.getSelectedExporter().getBundleReference(),
               result.getAccessRestriction(), options);
         }
         else {
            processPackageImport(packageToImport, bundle, result, options);
         }
      }
   }

   private void processRequireBundle(Map<BundleCandidate, RequireBundleInfo> requiredBundleToAccessRestriction,
      BundleCandidate bundle, BundleReference reference, AccessRestriction accessRestriction, PropertiesSource options) {
      final BundleCandidate requiredBundle = reference.getTarget();
      RequireBundleInfo info = requiredBundleToAccessRestriction.get(requiredBundle);
      if (info == null) {
         info = new RequireBundleInfo();
         requiredBundleToAccessRestriction.put(requiredBundle, info);
      }
      info.updateAccessRestriction(accessRestriction);
      info.updateOptional(reference.isOptional());
   }

   private void processPackageImport(final Map<String, PackageImport> packageToImport, BundleCandidate bundle,
      PackageResolutionResult result, PropertiesSource options) {
      final PackageImport packageImport = packageImportFactory.newPackageImport(bundle, result, options);
      if (packageImport != null) {
         packageToImport.put(result.getRequiredPackage(), packageImport);
      }
   }

   private static boolean isRequireBundle(BundleCandidate bundle, PropertiesSource options) {
      final String string = options.get("osgifier.requireBundle");
      if (isNullOrEmpty(string)) {
         return false;
      }

      final String symbolicName = bundle.getManifest().getBundleSymbolicName().getSymbolicName();

      final List<String> list = OptionsUtils.parseListValue(string);
      if (list.contains(symbolicName)) {
         return true;
      }
      for (String pattern : list) {
         if (PathMatcher.parsePackagePatterns(pattern).isMatch(symbolicName)) {
            return true;
         }
      }

      return false;
   }

   private static BundleCandidate getExportingBundle(PackageResolutionResult result) {
      final PackageExportDescription exporter = result.getSelectedExporter();
      if (exporter == null) {
         return null;
      }
      return exporter.getBundle();
   }

}


text:
"""
Unit tests for input_pipeline_dask
"""
import sys
import os
sys.path.append(os.path.abspath('codes/'))
from shutil import copyfile
import unittest
from trainer import input_pipeline_dask as test
import dask
import pandas as pd
import tensorflow as tf

CSV_PATH = os.path.abspath('data/iris_formatted.csv')
TASK_TYPE = 'classification'
TARGET_VAR = 'label'
COLUMN_TO_DROP = ['Cluster_indices']
TASK_NAME = 'classification'
NUM_EPOCHS = 1
BATCH_SIZE = 4
BUFFER_SIZE = 4
NAME = 'train'
MODE = 23
COLUMN_NAMES = os.path.abspath('data/iris_names.txt')
NA_VALUES = None
DATA_TYPE = {'id': 'int',
             'a': 'float',
             'b': 'float',
             'c': 'float',
             'd': 'float',
             'label': 'int',
             'Cluster_indices': 'int'}

class BasicInput(unittest.TestCase):
    """Class which will perform unittests"""

    def is_not_used(self):
        """Function to remove warning"""
        pass

    def init_inputreader(self):
        """
        Initialise class InputReader
        """
        self.is_not_used()
        return test.InputReader(
            csv_path=CSV_PATH,
            task_type=TASK_TYPE,
            target_var=TARGET_VAR,
            gcs_path=False,
            na_values=NA_VALUES)

    def init_basicstats(self):
        """
        Initialise class BasicStats
        """
        self.is_not_used()
        return test.BasicStats()

    def init_dataset(self):
        """
        Initialise class Dataset
        """
        iread = self.init_inputreader()
        stats = self.init_basicstats()
        ddf, _ = iread._parse_csv()
        copyfile(CSV_PATH, '/tmp/data.csv')
        ddf, _, _, csv_defaults = stats.clean_data(
            df=ddf,
            target_var=TARGET_VAR,
            task_type=TASK_TYPE,
            name=TASK_NAME
        )
        return test.DatasetInput(
            num_epochs=NUM_EPOCHS,
            batch_size=BATCH_SIZE,
            buffer_size=BUFFER_SIZE,
            csv_defaults=csv_defaults,
            csv_cols=ddf.columns,
            target_var=TARGET_VAR,
            task_type=TASK_TYPE
        )

    def test__parse_csv(self):
        """
        Testing function parse_csv
        """
        iread = self.init_inputreader()
        data = iread._parse_csv()
        self.assertEqual(type(data[0]), dask.dataframe.core.DataFrame)
        self.assertEqual(len(data[0]), 150)
        self.assertIsInstance(data[1], list)
        self.assertListEqual(
            data[1], ['id', 'a', 'b', 'c', 'd', 'label', 'Cluster_indices'])

    def test_drop_cols(self):
        """
        Testing function drop_cols
        """
        iread = self.init_inputreader()
        ddf, _ = iread._parse_csv()
        data = iread.drop_cols(
            df=ddf,
            col_names=COLUMN_TO_DROP
        )
        self.assertFalse(set(data.columns) <= set(COLUMN_TO_DROP))

    def test_dropping_zero_var_cols(self):
        """
        Testing function drop_cols
        """
        copyfile(CSV_PATH, '/tmp/data.csv')
        iread = self.init_inputreader()
        stats = self.init_basicstats()
        ddf, _ = iread._parse_csv()
        ddf, _, std_dev, _ = stats.clean_data(
            df=ddf,
            task_type=TASK_TYPE,
            target_var=TARGET_VAR,
            name=TASK_NAME
        )
        stats.dropping_zero_var_cols(
            df=ddf,
            target_var=TARGET_VAR,
            stddev_list=std_dev
        )
        std_list = ddf.std(axis=0, skipna=True)
        std = dask.compute(std_list)
        for i in range(len(std[0])):
            self.assertNotEqual(std[0][i], 0)

    def test_clean_data(self):
        """
        Testing function clean_csv
        """
        copyfile(CSV_PATH, '/tmp/data.csv')
        iread = self.init_inputreader()
        stats = self.init_basicstats()
        ddf, _ = iread._parse_csv()
        data, mean, std_dev, csv_defaults = stats.clean_data(
            df=ddf,
            task_type=TASK_TYPE,
            target_var=TARGET_VAR,
            name=NAME
        )

        self_computed_mean = dask.compute(ddf.mean())
        self.assertListEqual(list(mean), list(self_computed_mean[0]))
        self_computed_std_dev = dask.compute(ddf.std(axis=0, skipna=True))
        self.assertListEqual(list(std_dev), list(self_computed_std_dev[0]))
        self.assertIsInstance(data, dask.dataframe.core.DataFrame)
        self.assertIsInstance(mean, pd.core.series.Series)
        self.assertIsInstance(std_dev, pd.core.series.Series)
        self.assertIsInstance(csv_defaults, list)

    def test_creating_lime_explainer(self):
        copyfile(CSV_PATH, '/tmp/data.csv')
        iread = self.init_inputreader()
        stats = self.init_basicstats()
        ddf, _ = iread._parse_csv()
        stats.creating_explainer_lime(
            df=ddf,
            target_var=TARGET_VAR
        )
        self.assertTrue(os.path.isfile('/tmp/lime_explainer'))

    def test_normalize(self):
        """
        Testing function normalise
        """
        iread = self.init_inputreader()
        stats = self.init_basicstats()
        ddf, _ = iread._parse_csv()
        copyfile(CSV_PATH, '/tmp/data.csv')
        ddf, mean, std_dev, _ = stats.clean_data(
            df=ddf,
            task_type=TASK_TYPE,
            target_var=TARGET_VAR,
            name=NAME)
        data = stats.normalize(
            df=ddf,
            target_var=TARGET_VAR,
            mean_list=mean,
            stddev_list=std_dev
        )
        dataframe = dask.compute(data)[0]
        rows = dataframe.columns
        for row in rows:
            if row != 'label':
                col = dask.compute(data)[0][row]
                self.assertAlmostEqual(col.std(), 1)
        self.assertIsInstance(data, dask.dataframe.core.DataFrame)

    def test_calculate_stats(self):
        """
        Testing function calculate_stats
        """
        iread = self.init_inputreader()
        stats = self.init_basicstats()
        ddf, _ = iread._parse_csv()
        mean, median, mode_dict, std_dev = stats.calculate_stats(
            df=ddf,
            target_var=TARGET_VAR
        )
        self_computed_mean = dask.compute(ddf.mean())
        self.assertListEqual(list(mean), list(self_computed_mean[0]))
        self_computed_std_dev = dask.compute(ddf.std(axis=0, skipna=True))
        self.assertListEqual(list(std_dev), list(self_computed_std_dev[0]))
        self_computed_median = dask.compute(ddf.quantile(0.5))
        self.assertListEqual(list(median), list(self_computed_median[0]))
        self.assertIsInstance(mean, pd.core.series.Series)
        self.assertIsInstance(std_dev, pd.core.series.Series)
        self.assertIsInstance(median, pd.core.series.Series)
        self.assertIsInstance(mode_dict, dict)

    def test_impute(self):
        """
        Testing function impute
        """
        iread = self.init_inputreader()
        stats = self.init_basicstats()
        ddf, _ = iread._parse_csv()
        _, median, _, _ = stats.calculate_stats(
            df=ddf,
            target_var=TARGET_VAR
        )
        data = stats.impute(
            df=ddf,
            target_var=TARGET_VAR,
            median=median,
            mode=MODE
        )
        imputed_data = dask.compute(data.isnull().sum())
        rows = ddf.columns
        for row in rows:
            col = imputed_data[0][row]
            self.assertEqual(col, 0)
        self.assertIsInstance(data, dask.dataframe.core.DataFrame)

    def test_find_vocab(self):
        """
        Testing function find_vocab
        """
        iread = self.init_inputreader()
        stats = self.init_basicstats()
        ddf, _ = iread._parse_csv()
        col_mapping = stats.find_vocab(
            df=ddf
        )
        test_col_mapping = {'a': 0, 'c': 0, 'b': 0, 'd': 0,
                            'label': 0, 'Cluster_indices': 0, 'id': 0}
        self.assertIsInstance(col_mapping, dict)
        self.assertDictEqual(col_mapping, test_col_mapping)

    def test_kmeans_input_fn(self):
        """
        Testing function kmeans_input_fn
        """
        copyfile(CSV_PATH, '/tmp/clean_1_train.csv')
        data = self.init_dataset()
        inp_fn = data.kmeans_input_fn(
            name=NAME
        )
        self.assertIsInstance(inp_fn, tf.Tensor)

    def test_creating_feature_cols(self):
        """
        Testing function of _create_feature_columns function
        """
        iread = self.init_inputreader()
        stats = self.init_basicstats()
        data = self.init_dataset()
        ddf, _ = iread._parse_csv()
        mean, _, _, std_dev = stats.calculate_stats(
            df=ddf,
            target_var=TARGET_VAR
        )
        vocab = stats.find_vocab(ddf)
        feat_cols = data._create_feature_columns(
            dictionary=vocab,
            mean=mean,
            std_dev=std_dev
        )
        test_vocab = {'a': 0, 'c': 0, 'b': 0, 'd': 0,
                      'label': 0, 'Cluster_indices': 0, 'id': 0}
        self.assertIsInstance(vocab, dict)
        self.assertIsInstance(feat_cols, list)
        self.assertDictEqual(vocab, test_vocab)

    def test_input_fn(self):
        """
        Testing function input_csv
        """
        data = self.init_dataset()
        inp_fn = data.input_fn(
            name=NAME
        )
        for _, v in inp_fn[0].items():
            self.assertIsInstance(v, tf.Tensor)

if __name__ == "__main__":
    unittest.main()


text:
/*
 * Description:
 *     What is this file about?
 *
 * Revision history:
 *     xxxx-xx-xx, author, first version
 *     xxxx-xx-xx, author, fix bug about xxx
 */

#include "asio_net_provider.h"
#include "asio_rpc_session.h"

# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "asio.net.provider"

namespace dsn {
    namespace tools{

        asio_network_provider::asio_network_provider(rpc_engine* srv, network* inner_provider)
            : connection_oriented_network(srv, inner_provider)
        {
            _acceptor = nullptr;
        }

        error_code asio_network_provider::start(rpc_channel channel, int port, bool client_only, io_modifer& ctx)
        {
            if (_acceptor != nullptr)
                return ERR_SERVICE_ALREADY_RUNNING;

            int io_service_worker_count = config()->get_value<int>("network", "io_service_worker_count", 1,
                "thread number for io service (timer and boost network)");
            for (int i = 0; i < io_service_worker_count; i++)
            {
                _workers.push_back(std::shared_ptr<std::thread>(new std::thread([this, ctx, i]()
                {
                    task::set_tls_dsn_context(node(), nullptr, ctx.queue);

                    const char* name = ::dsn::tools::get_service_node_name(node());
                    char buffer[128];
                    sprintf(buffer, "%s.asio.%d", name, i);
                    task_worker::set_name(buffer);

                    boost::asio::io_service::work work(_io_service);
                    _io_service.run();
                })));
            }

            _acceptor = nullptr;

            dassert(channel == RPC_CHANNEL_TCP || channel == RPC_CHANNEL_UDP, "invalid given channel %s", channel.to_string());

            _address.assign_ipv4(get_local_ipv4(), port);

            if (!client_only)
            {
                auto v4_addr = boost::asio::ip::address_v4::any(); //(ntohl(_address.ip));
                ::boost::asio::ip::tcp::endpoint ep(v4_addr, _address.port());

                try
                {
                    _acceptor.reset(new boost::asio::ip::tcp::acceptor(_io_service, ep, true));
                    do_accept();
                }
                catch (boost::system::system_error& err)
                {
                    printf("boost asio listen on port %u failed, err: %s\n", port, err.what());
                    return ERR_ADDRESS_ALREADY_USED;
                }
            }

            return ERR_OK;
        }

        rpc_session_ptr asio_network_provider::create_client_session(::dsn::rpc_address server_addr)
        {
            auto sock = std::shared_ptr<boost::asio::ip::tcp::socket>(new boost::asio::ip::tcp::socket(_io_service));
            return rpc_session_ptr(new asio_rpc_session(*this, server_addr, sock, new_message_parser(), true));
        }

        void asio_network_provider::do_accept()
        {
            auto socket = std::shared_ptr<boost::asio::ip::tcp::socket>(
                new boost::asio::ip::tcp::socket(_io_service));

            _acceptor->async_accept(*socket,
                [this, socket](boost::system::error_code ec)
            {
                if (!ec)
                {
                    auto ip = socket->remote_endpoint().address().to_v4().to_ulong();
                    auto port = socket->remote_endpoint().port();
                    ::dsn::rpc_address client_addr(ip, port);

                    rpc_session_ptr s = new asio_rpc_session(*this, client_addr,
                        (std::shared_ptr<boost::asio::ip::tcp::socket>&)socket,
                        new_message_parser(), false);
                    this->on_server_session_accepted(s);
                }

                do_accept();
            });
        }

        void asio_udp_provider::send_message(message_ex* request)
        {
            // prepare parser as there will be concurrent send-message-s
            auto pr = get_message_parser_info();
            auto parser_place = alloca(pr.second);
            auto parser = pr.first(parser_place, _message_buffer_block_size, true);

            auto count = parser->get_send_buffers_count(request);
            std::unique_ptr<message_parser::send_buf[]> bufs(new message_parser::send_buf[count]);
            parser->prepare_buffers_on_send(request, 0, bufs.get());
            // end using parser
            parser->~message_parser();
            size_t tlen = 0, offset = 0;
            for (int i = 0; i < count; i ++)
            {
                tlen += bufs[i].sz;
            }
            dassert(tlen < max_udp_packet_size, "the message is too large to send via a udp channel");
            std::unique_ptr<char[]> packet_buffer(new char[tlen]);
            for (int i = 0; i < count; i ++)
            {
                memcpy(&packet_buffer[offset], bufs[i].buf, bufs[i].sz);
                offset += bufs[i].sz;
            };
            ::boost::asio::ip::udp::endpoint ep(::boost::asio::ip::address_v4(request->to_address.ip()), request->to_address.port());
            _socket->async_send_to(::boost::asio::buffer(packet_buffer.get(), tlen), ep,
                [=](const boost::system::error_code& error, std::size_t bytes_transferred)
                {
                    if (error) {
                        dwarn("send udp packet to ep %s:%d failed, message = %s", ep.address().to_string().c_str(), ep.port(), error.message().c_str());
                        //we do not handle failure here, rpc matcher would handle timeouts
                    }
                });
        }

        void asio_udp_provider::do_receive()
        {
            std::shared_ptr< ::boost::asio::ip::udp::endpoint> send_endpoint(new ::boost::asio::ip::udp::endpoint);

            _recv_parser->truncate_read();
            auto buffer_ptr = _recv_parser->read_buffer_ptr(max_udp_packet_size);
            dassert(_recv_parser->read_buffer_capacity() >= max_udp_packet_size, "failed to load enough buffer in parser");

            _socket->async_receive_from(
                ::boost::asio::buffer(buffer_ptr, max_udp_packet_size),
                *send_endpoint,
                [this, send_endpoint](const boost::system::error_code& error, std::size_t bytes_transferred)
                {
                    if (!error)
                    {
                        int read_next;
                        auto message = _recv_parser->get_message_on_receive(bytes_transferred, read_next);

                        if (message == nullptr)
                        {
                            derror("invalid udp packet");
                        }
                        else
                        {
                            message->to_address = address();
                            if (message->header->context.u.is_request)
                            {
                                on_recv_request(message, 0);
                            }
                            else
                            {
                                on_recv_reply(message->header->id, message, 0);
                            }
                        }
                    }

                    do_receive();
                }
            );
        }

        error_code asio_udp_provider::start(rpc_channel channel, int port, bool client_only, io_modifer& ctx)
        {
            _is_client = client_only;
            int io_service_worker_count = config()->get_value<int>("network", "io_service_worker_count", 1,
                                                                   "thread number for io service (timer and boost network)");

            dassert(channel == RPC_CHANNEL_UDP, "invalid given channel %s", channel.to_string());

            if (client_only)
            {
                do
                {
                    //FIXME: we actually do not need to set a random port for clinet if the rpc_engine is refactored
                    _address.assign_ipv4(get_local_ipv4(), std::numeric_limits<uint16_t>::max() -
                        dsn_random64(std::numeric_limits<uint64_t>::min(),
                                     std::numeric_limits<uint64_t>::max()) % 5000);
                    ::boost::asio::ip::udp::endpoint ep(boost::asio::ip::address_v4::any(), _address.port());
                    try
                    {
                        _socket.reset(new ::boost::asio::ip::udp::socket(_io_service, ep));
                        break;
                    }
                    catch (boost::system::system_error& err)
                    {
                        derror("boost asio listen on port %u failed, err: %s\n", port, err.what());
                    }
                } while (true);
            }
            else
            {
                _address.assign_ipv4(get_local_ipv4(), port);
                ::boost::asio::ip::udp::endpoint ep(boost::asio::ip::address_v4::any(), _address.port());
                try
                {
                    _socket.reset(new ::boost::asio::ip::udp::socket(_io_service, ep));
                }
                catch (boost::system::system_error& err)
                {
                    derror("boost asio listen on port %u failed, err: %s\n", port, err.what());
                    return ERR_ADDRESS_ALREADY_USED;
                }
            }

            for (int i = 0; i < io_service_worker_count; i++)
            {
                _workers.push_back(std::shared_ptr<std::thread>(new std::thread([this, ctx, i]()
                {
                    task::set_tls_dsn_context(node(), nullptr, ctx.queue);

                    const char* name = ::dsn::tools::get_service_node_name(node());
                    char buffer[128];
                    sprintf(buffer, "%s.asio.udp.%d.%d", name, (int)(this->address().port()), i);
                    task_worker::set_name(buffer);

                    boost::asio::io_service::work work(_io_service);
                    _io_service.run();
                })));
            }

            do_receive();
            return ERR_OK;
        }
    }
}


text:
import React, { Component } from 'react'
import { gql, graphql } from 'react-apollo';

class PeopleList extends Component {
	render() {
		const { data: {loading, error, people } } = this.props

		if (loading) {
			return
Loading ...

		}
	   if (error) {
	     return
{error.message}
;
	   }

		return (

				{ people.map( person =>
				(

				   {person.name}

)
				)}

		)
	}
}

export const peopleListQuery = gql`
	query PeopleListQuery {
		people {
			id
			name
			interests
		}
	}
`

export default graphql(peopleListQuery, {
  options: { pollInterval: 5000 },
})(PeopleList);


text:
class String
 def to_quoted_printable(*args)
   [self].pack("M").gsub(/\n/, "\r\n")
 end
 def from_quoted_printable
   self.gsub(/\r\n/, "\n").unpack("M").first
 end
end

if __FILE__ == $0
  require 'optparse'

  # Look, James, I'm opt-parsing! :)
  decode_mode = false
  xml_mode = false
  opts = OptionParser.new do |opts|
    opts.banner = "Usage: #{File.basename($0)} [OPTIONS]"
    opts.separator ''
    opts.separator 'Specific Options:'

    opts.on('-d', '--decode', 'Convert from quoted-printable to native') do
      decode_mode = true
    end

    opts.on('-x', '--xml', 'Quote XML special characters <, > and &',
                           '(ignored when decoding)') do
      xml_mode = true
    end

    opts.on('-h', '-?', '--help', 'Show this text') do
      puts opts
      exit
    end

    opts.separator 'The default mode encodes STDIN as quoted-printable.'
  end

  opts.parse! ARGV

  operation =
    if decode_mode
      [:from_quoted_printable]
    elsif xml_mode
      [:to_quoted_printable, QuotedPrintable::XML_PRINTABLES]
    else
      [:to_quoted_printable]
    end

  if decode_mode
    ARGF.binmode
  else
    STDOUT.binmode
  end

  ARGF.each { |line| print line.send(*operation) }

end


text:
namespace cpptorch
{
    template<typename T, GPUFlag F = GPU_None>
    class API Storage
    {
    public:
        explicit Storage(typename THTrait<T, F>::Storage *th = nullptr);
        template<class TIterator>
        Storage(TIterator begin, TIterator end) : th_(nullptr) { unserialze(begin, end); }
        template<class TContainer>
        Storage(const TContainer &c) : th_(nullptr) { unserialze(c); }
        Storage(const std::initializer_list<T> &inputs) : th_(nullptr) { unserialze(inputs); }
        Storage(const T *ptr_src, long size, bool take_ownership_of_data = true) : th_(nullptr) { unserialze(ptr_src, size, take_ownership_of_data); }
        Storage(const Storage<T, F> &other) : th_(nullptr) { *this = other; }
        Storage(Storage<T, F> &&other) : th_(nullptr) { *this = std::move(other); }
        ~Storage();

        Storage<T, F>& operator = (const Storage<T, F> &src);
        Storage<T, F>& operator = (Storage<T, F> &&src);
        operator typename THTrait<T, F>::Storage* () const { return th_; }

        // getter
        bool valid() const { return th_ != nullptr; }
        int size() const;
        const T* data() const;
        T* data();

        // creator
        void create();
        // from raw ptr
        void unserialze(const T *ptr_src, long count, bool take_ownership_of_data = true);
        // from stl iterator
        template<class TIterator>
        void unserialze(const TIterator begin, const TIterator end)
        {
            long size = (long)(end - begin);
            T *ptr = (T*)malloc(size * sizeof(T));
            int i = 0;
            for (auto it = begin; it != end; it++, i++)
            {
                ptr[i] = *it;
            }
            unserialze(ptr, size);
        }
        // from stl container
        template<class TContainer>
        void unserialze(const TContainer &c) { return unserialze(c.begin(), c.end()); }
        // from initializer list
        void unserialze(const std::initializer_list<T> &i) { return unserialze(i.begin(), i.end()); }

    protected:
        typename THTrait<T, F>::Storage *th_;
   };
}


text:
package com.google.mu.protobuf.util;

import static com.google.common.truth.Truth.assertThat;
import static com.google.mu.collect.Immutables.list;
import static com.google.mu.collect.Immutables.map;
import static com.google.mu.collect.Immutables.table;
import static com.google.mu.protobuf.util.MoreStructs.struct;
import static com.google.mu.protobuf.util.MoreValues.toListValue;
import static org.junit.Assert.assertThrows;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.primitives.ImmutableDoubleArray;
import com.google.common.primitives.ImmutableIntArray;
import com.google.common.primitives.ImmutableLongArray;
import com.google.common.testing.NullPointerTester;
import com.google.mu.util.stream.BiStream;
import com.google.protobuf.ListValue;
import com.google.protobuf.NullValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.google.protobuf.util.Values;

@RunWith(JUnit4.class)
public class StructorTest {
  private final Structor maker = new Structor();

  @Test public void toValue_fromMap() {
    assertThat(maker.toValue(map("one", 1, "two", 2)))
        .isEqualTo(
            Value.newBuilder()
                .setStructValue(
                    Struct.newBuilder()
                        .putFields("one", Values.of(1))
                        .putFields("two", Values.of(2))
                        .build())
                .build());
  }

  @Test public void toValue_fromMultimap() {
    assertThat(maker.toValue(ImmutableListMultimap.of("1", "uno", "1", "one")))
        .isEqualTo(
            Value.newBuilder()
                .setStructValue(
                    Struct.newBuilder().putFields("1", maker.toValue(list("uno", "one"))).build())
                .build());
  }

  @Test public void toValue_fromTable() {
    assertThat(maker.toValue(table("one", "uno", 1)))
        .isEqualTo(
            Value.newBuilder()
                .setStructValue(
                    Struct.newBuilder()
                        .putFields("one", maker.toValue(map("uno", 1)))
                        .build())
                .build());
  }

  @Test public void toValue_withNullMapKey() {
    Map<?, ?> map = BiStream.of(null, "null").collect(Collectors::toMap);
    assertThrows(NullPointerException.class, () -> maker.toValue(map));
  }

  @Test public void toValue_withNonStringMapKey() {
    Map<?, ?> map = BiStream.of(1, "one").collect(Collectors::toMap);
    assertThrows(IllegalArgumentException.class, () -> maker.toValue(map));
  }

  @Test public void toValue_fromIterable() {
    assertThat(maker.toValue(list(10, 20)))
        .isEqualTo(
            Value.newBuilder()
                .setListValue(ListValue.newBuilder().addValues(Values.of(10)).addValues(Values.of(20)))
                .build());
  }

  @Test public void toValue_fromOptional() {
    assertThat(maker.toValue(Optional.empty())).isEqualTo(Values.ofNull());
    assertThat(maker.toValue(Optional.of("foo"))).isEqualTo(Values.of("foo"));
  }

  @Test public void toValue_fromStruct() {
    Struct struct = maker.struct("foo", 1, "bar", "x");
    assertThat(maker.toValue(struct)).isEqualTo(Value.newBuilder().setStructValue(struct).build());
  }

  @Test public void toValue_fromListValue() {
    ListValue list = Stream.of(1, 2).map(maker::toValue).collect(toListValue());
    assertThat(maker.toValue(list)).isEqualTo(Value.newBuilder().setListValue(list).build());
  }

  @Test public void toValue_fromNullValue() {
    assertThat(maker.toValue(NullValue.NULL_VALUE))
        .isEqualTo(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build());
  }

  @Test public void toValue_fromNumber() {
    assertThat(maker.toValue(10L)).isEqualTo(Values.of(10));
    assertThat(maker.toValue(10)).isEqualTo(Values.of(10));
    assertThat(maker.toValue(10F)).isEqualTo(Values.of(10));
    assertThat(maker.toValue(10D)).isEqualTo(Values.of(10));
  }

  @Test public void toValue_fromString() {
    assertThat(maker.toValue("42")).isEqualTo(Value.newBuilder().setStringValue("42").build());
  }

  @Test public void toValue_fromBoolean() {
    assertThat(maker.toValue(true)).isEqualTo(Value.newBuilder().setBoolValue(true).build());
    assertThat(maker.toValue(false)).isEqualTo(Value.newBuilder().setBoolValue(false).build());
    assertThat(maker.toValue(true)).isSameAs(maker.toValue(true));
    assertThat(maker.toValue(false)).isSameAs(maker.toValue(false));
  }

  @Test public void toValue_fromNull() {
    assertThat(maker.toValue(null))
        .isEqualTo(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build());
    assertThat(maker.toValue(null)).isSameAs(maker.toValue(null));
  }

  @Test public void toValue_fromEmptyOptional() {
    assertThat(maker.toValue(Optional.empty())).isEqualTo(Values.ofNull());
  }

  @Test public void toValue_fromNonEmptyOptional() {
    assertThat(maker.toValue(Optional.of(123))).isEqualTo(Values.of(123));
  }

  @Test public void toValue_fromValue() {
    Value value = Value.newBuilder().setBoolValue(false).build();
    assertThat(maker.toValue(value).getBoolValue()).isFalse();
  }

  @Test public void toValue_fromUnsupportedType() {
    IllegalArgumentException thrown =
        assertThrows(IllegalArgumentException.class, () -> maker.toValue(this));
    assertThat(thrown).hasMessageThat().contains(getClass().getName());
  }

  @Test public void toValue_cyclic() {
    List<Object> list = new ArrayList<>();
    list.add(list);
    assertThrows(StackOverflowError.class, () -> maker.toValue(list));
  }

  @Test public void toValue_fromIntArray() {
    assertThat(maker.toValue(new int[] {10}))
        .isEqualTo(Values.of(ImmutableList.of(Values.of(10))));
  }

  @Test public void toValue_fromImmutableIntArray() {
    assertThat(maker.toValue(ImmutableIntArray.of(10)))
        .isEqualTo(Values.of(ImmutableList.of(Values.of(10))));
  }

  @Test public void toValue_fromLongArray() {
    assertThat(maker.toValue(new long[] {10}))
        .isEqualTo(Values.of(ImmutableList.of(Values.of(10))));
  }

  @Test public void toValue_fromImmutableLongArray() {
    assertThat(maker.toValue(ImmutableLongArray.of(10)))
        .isEqualTo(Values.of(ImmutableList.of(Values.of(10))));
  }

  @Test public void toValue_fromDoubleArray() {
    assertThat(maker.toValue(new double[] {10}))
        .isEqualTo(Values.of(ImmutableList.of(Values.of(10))));
  }

  @Test public void toValue_fromImmutableDoubleArray() {
    assertThat(maker.toValue(ImmutableDoubleArray.of(10)))
        .isEqualTo(Values.of(ImmutableList.of(Values.of(10))));
  }

  @Test public void toValue_fromByteArray() {
    assertThat(maker.toValue(new byte[] {10, 20}))
        .isEqualTo(Values.of(ImmutableList.of(Values.of(10), Values.of(20))));
  }

  @Test public void toValue_fromShortArray() {
    assertThat(maker.toValue(new short[] {10, 20}))
        .isEqualTo(Values.of(ImmutableList.of(Values.of(10), Values.of(20))));
  }

  @Test public void toValue_fromArray() {
    assertThat(maker.toValue(new String[] {"foo", "bar"}))
        .isEqualTo(Values.of(ImmutableList.of(Values.of("foo"), Values.of("bar"))));
  }

  @Test public void toValue_fromEnum() {
    assertThat(maker.toValue(Cast.values()))
        .isEqualTo(Values.of(ImmutableList.of(Values.of("VILLAIN"), Values.of("HERO"))));
  }

  @Test public void customConversion() {
    Structor custom = new Structor() {
      @Override public Value toValue(Object obj) {
        if (obj instanceof Hero) {
          Hero hero = (Hero) obj;
          return toValue(map("name", hero.name, "titles", hero.titles, "friends", hero.friends));
        }
        return super.toValue(obj);
      }
    };
    Hero ironMan = new Hero("Tony Stark", "Iron Man", "Robert Downey");
    Hero scarletWitch = new Hero("Wanda", "Scarlet Witch");
    ironMan.friends.add(scarletWitch);
    scarletWitch.friends.add(new Hero("Vision"));
    assertThat(custom.toValue(Optional.of(ironMan)))
        .isEqualTo(Values.of(custom.struct(
                "name", "Tony Stark",
                "titles", ImmutableList.of("Iron Man", "Robert Downey"),
                "friends", ImmutableList.of(custom.struct(
                    "name", "Wanda",
                    "titles", ImmutableList.of("Scarlet Witch"),
                    "friends", ImmutableList.of(custom.struct(
                        "name", "Vision",
                        "titles", ImmutableList.of(),
                        "friends", ImmutableList.of())))))));
  }

  @Test public void struct_onePair() {
    assertThat(new Structor().struct("key", 1))
        .isEqualTo(
            Struct.newBuilder()
                .putFields("key", Values.of(1))
                .build());
  }

  @Test public void struct_onePair_nullKey() {
    assertThrows(NullPointerException.class, () -> struct(null, "v"));
  }

  @Test public void struct_onePair_nullValue() {
    assertThat(new Structor().struct("key", null))
        .isEqualTo(
            Struct.newBuilder()
                .putFields("key", Values.ofNull())
                .build());
  }

  @Test public void struct_twoPairs() {
    assertThat(new Structor().struct("int", 1, "string", "two"))
        .isEqualTo(
            Struct.newBuilder()
                .putFields("int", Values.of(1))
                .putFields("string", Values.of("two"))
                .build());
  }

  @Test public void struct_twoPairs_nullKey() {
    Structor maker = new Structor();
    assertThrows(NullPointerException.class, () -> maker.struct(null, "v1", "k2", "v2"));
  }

  @Test public void struct_twoPairs_nullValue() {
    assertThat(new Structor().struct("k1", null, "k2", null))
        .isEqualTo(
            Struct.newBuilder()
                .putFields("k1", Values.ofNull())
                .putFields("k2", Values.ofNull())
                .build());
  }

  @Test public void struct_twoPairs_duplicateKey() {
    Structor maker = new Structor();
    assertThrows(IllegalArgumentException.class, () -> maker.struct("a", 1, "a", 2));
  }

  @Test public void struct_3Pairs() {
    assertThat(new Structor().struct("a", 1, "b", 2, "c", 3))
        .isEqualTo(
            Struct.newBuilder()
                .putFields("a", Values.of(1))
                .putFields("b", Values.of(2))
                .putFields("c", Values.of(3))
                .build());
  }

  @Test public void struct_3Pairs_nullKey() {
    Structor maker = new Structor();
    assertThrows(NullPointerException.class, () -> maker.struct("k1", "v1", "k2", "v2", null, 3));
  }

  @Test public void struct_3Pairs_nullValue() {
    assertThat(new Structor().struct("k1", null, "k2", null, "k3", null))
        .isEqualTo(
            Struct.newBuilder()
                .putFields("k1", Values.ofNull())
                .putFields("k2", Values.ofNull())
                .putFields("k3", Values.ofNull())
                .build());
  }

  @Test public void struct_3Pairs_duplicateKey() {
    Structor maker = new Structor();
    assertThrows(IllegalArgumentException.class, () -> maker.struct("a", 1, "b", 2, "a", 3));
  }

  @Test public void struct_fromMap() {
    assertThat(new Structor().struct(map("int", 1, "string", "two")))
        .isEqualTo(
            Struct.newBuilder()
                .putFields("int", Values.of(1))
                .putFields("string", Values.of("two"))
                .build());
  }

  @Test public void nestedStruct_fromTable() {
    assertThat(new Structor().nestedStruct(table("row", "col", 1)))
        .isEqualTo(struct("row", struct("col", 1)));
  }

  @Test public void toStruct_biCollector() {
    Struct struct = BiStream.of("foo", 1, "bar", map("one", true)).collect(new Structor().toStruct());
    assertThat(struct)
        .isEqualTo(
            Struct.newBuilder()
                .putFields("foo", Values.of(1))
                .putFields(
                    "bar",
                    Value.newBuilder()
                        .setStructValue(Struct.newBuilder().putFields("one", Values.of(true)).build())
                        .build())
                .build());
  }

  @Test public void testNulls() {
    CharSequence key = new CharSequence() {
      private int toStringCalled = 0;
      @Override public String toString() {
        return "string" + (++toStringCalled);
      }
      @Override public int length() {
        throw new UnsupportedOperationException();
      }
      @Override public char charAt(int index) {
        throw new UnsupportedOperationException();
      }
      @Override public CharSequence subSequence(int start, int end) {
        throw new UnsupportedOperationException();
      }
    };
    new NullPointerTester()
        .setDefault(CharSequence.class, key)
        .testAllPublicInstanceMethods(new Structor());
  }

  private static final class Hero {
    final String name;
    final ImmutableList<String> titles;
    final List<Hero> friends = new ArrayList<>();

    Hero(String name, String... titles) {
      this.name = name;
      this.titles = ImmutableList.copyOf(titles);
    }
  }

  private enum Cast {
    VILLAIN, HERO
  }
}


text:
module.exports =  function(_, pg, db, errorCodes){

	function makeid(){
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        for( var i=0; i < 12; i++ )
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        return text;
    }

    function createSession(data, callback){
    	var sessionId = makeid()
    	db.query('insert into session values($1, $2)',
    	[sessionId, data.userId], function(err, result){
			if (err) {
    			callback(err)
    		} else {
                restoreSession(sessionId, function(err, session){
                    if(err){
                        callback(err)
                    }else{
                        callback(null, session.sessionId, session.userPriviledge)
                    }
                })
        	}
    	})
    }

    function restoreSession(sessionId, callback){
    	if(!_.isString(sessionId)){
            callback(null, {
                userId: null,
                sessionId: null,
                userPriviledge: 'guest'
            })
            return
        }
    	db.query(`select public.User.userPriviledge, Session.userId
        from Session inner join public.User on Session.userId = public.User.id
            where Session.token = $1`,
        [sessionId], function(err, result){
    		if (err) {
    			callback(err)
    		} else {
                if (result.rows.length == 0){
                    callback({
                        code: errorCodes.invalidSessionId,
                        message: 'Invalid Session Id'
                    })
                    return
                }
                // console.log(result.rows, sessionId)
    			callback(null, {
                    userId: result.rows[0].userId,
                    sessionId: sessionId,
                    userPriviledge: result.rows[0].userPriviledge
                });
    		}
    	})
    }

	Session = {
		createSession: createSession,
        restoreSession: restoreSession
	}

	return Session;
}


text:
<?php

namespace Ariscratle\Utils;

class UtilsTest extends \PHPUnit_Framework_TestCase
{
	/**
	 * Testes do método upper()
	 */
	public function testUpper()
	{
		$someObject = new Utils;
		$this->assertEquals('TESTE', $someObject->upper('teste'));
	}

	public function testUpperWithTilde()
	{
		$someObject = new Utils;
		$this->assertEquals('SÃO', $someObject->upper('são'));
	}

	public function testUpperWithAcute()
	{
		$someObject = new Utils;
		$this->assertEquals('JOSÉ', $someObject->upper('josé'));
	}
}


text:
	<title>Claire Richards's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Claire Richards's panel show appearances

Claire Richards (born 1977-08-17[ref]) has appeared in 18 episodes between 2001-2014.  Claire Richards on Wikipedia.

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2014-06-23 / Loose Women

2014-06-18 / Loose Women

2014-06-06 / Loose Women

2014-06-02 / Loose Women

2014-05-20 / Loose Women

2014-05-08 / Loose Women

2014-04-16 / Loose Women

2014-04-10 / Loose Women

2014-04-07 / Loose Women

2014-04-01 / Loose Women

2013-09-17 / Loose Women

2012-11-16 / Loose Women

2011-11-03 / Celebrity Juice

2011-10-24 / Loose Women

2011-07-01 / Loose Women

2009-01-13 / Loose Women

2008-09-12 / Loose Women

2001-03-19 / Never Mind The Buzzcocks


text:
using System.Data.Entity.Migrations;

namespace ILK_Protokoll.Migrations
{
	public partial class AttachmentForEP : DbMigration
	{
		public override void Up()
		{
			RenameColumn(table: "dbo.Attachment", name: "EmployeePresentation_ID", newName: "EmployeePresentationID");
			RenameIndex(table: "dbo.Attachment", name: "IX_EmployeePresentation_ID", newName: "IX_EmployeePresentationID");
		}

		public override void Down()
		{
			RenameIndex(table: "dbo.Attachment", name: "IX_EmployeePresentationID", newName: "IX_EmployeePresentation_ID");
			RenameColumn(table: "dbo.Attachment", name: "EmployeePresentationID", newName: "EmployeePresentation_ID");
		}
	}
}