text:
using System;
using System.Collections.Generic;
using System.Linq;
using CRP.Core.Domain;
using CRP.Tests.Core;
using CRP.Tests.Core.Extensions;
using CRP.Tests.Core.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UCDArch.Core.PersistanceSupport;
using UCDArch.Data.NHibernate;
using UCDArch.Testing.Extensions;

namespace CRP.Tests.Repositories
{
    [TestClass]
    public class QuestionRepositoryTests :AbstractRepositoryTests<Question, int >
    {
        private IRepository<Question> QuestionRepository { get; set; }

        #region Init and Overrides
        /// <summary>
        /// Initializes a new instance of the <see cref="QuestionRepositoryTests"/> class.
        /// </summary>
        public QuestionRepositoryTests()
        {
            QuestionRepository = new Repository<Question>();
        }
        /// <summary>
        /// Gets the valid entity of type T
        /// </summary>
        /// <param name="counter">The counter.</param>
        /// <returns>A valid entity of type T</returns>
        protected override Question GetValid(int? counter)
        {
            var rtValue = CreateValidEntities.Question(counter);
            rtValue.QuestionSet = Repository.OfType<QuestionSet>().GetById(1);
            var questionType = Repository.OfType<QuestionType>().GetById(1);
            rtValue.QuestionType = questionType;

            return rtValue;
        }

        /// <summary>
        /// A Query which will return a single record
        /// </summary>
        /// <param name="numberAtEnd"></param>
        /// <returns></returns>
        protected override IQueryable<Question> GetQuery(int numberAtEnd)
        {
            return Repository.OfType<Question>().Queryable.Where(a => a.Name.EndsWith(numberAtEnd.ToString()));
        }

        /// <summary>
        /// A way to compare the entities that were read.
        /// For example, this would have the assert.AreEqual("Comment" + counter, entity.Comment);
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="counter"></param>
        protected override void FoundEntityComparison(Question entity, int counter)
        {
            Assert.AreEqual("Name" + counter, entity.Name);
        }

        /// <summary>
        /// Updates , compares, restores.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="action">The action.</param>
        protected override void UpdateUtility(Question entity, ARTAction action)
        {
            const string updateValue = "Updated";
            switch (action)
            {
                case ARTAction.Compare:
                    Assert.AreEqual(updateValue, entity.Name);
                    break;
                case ARTAction.Restore:
                    entity.Name = RestoreValue;
                    break;
                case ARTAction.Update:
                    RestoreValue = entity.Name;
                    entity.Name = updateValue;
                    break;
            }
        }

        /// <summary>
        /// Loads the data.
        /// Question requires QuestionSet
        /// Question requires QuestionType
        /// </summary>
        protected override void LoadData()
        {
            Repository.OfType<Question>().DbContext.BeginTransaction();
            LoadQuestionSets(1);
            LoadQuestionTypes(1);
            LoadRecords(5);
            Repository.OfType<Question>().DbContext.CommitTransaction();
        }

        #endregion Init and Overrides

        #region Name Tests
        #region Invalid Tests

        /// <summary>
        /// Tests the name with null value does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestNameWithNullValueDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                question = GetValid(9);
                question.Name = null;
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("Name: may not be null or empty");
                Assert.IsTrue(question.IsTransient());
                Assert.IsFalse(question.IsValid());
                throw;
            }
        }

        /// <summary>
        /// Tests the name with empty string does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestNameWithEmptyStringDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                question = GetValid(9);
                question.Name = string.Empty;
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("Name: may not be null or empty");
                Assert.IsTrue(question.IsTransient());
                Assert.IsFalse(question.IsValid());
                throw;
            }
        }

        /// <summary>
        /// Tests the name with spaces only does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestNameWithSpacesOnlyDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                question = GetValid(9);
                question.Name = " ";
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("Name: may not be null or empty");
                Assert.IsTrue(question.IsTransient());
                Assert.IsFalse(question.IsValid());
                throw;
            }
        }

        /// <summary>
        /// Tests the name with too long value does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestNameWithTooLongValueDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                question = GetValid(9);
                question.Name = "x".RepeatTimes(201);
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(question);
                Assert.AreEqual(201, question.Name.Length);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("Name: length must be between 0 and 200");
                Assert.IsTrue(question.IsTransient());
                Assert.IsFalse(question.IsValid());
                throw;
            }
        }
        #endregion Invalid Tests

        #region Valid Tests

        /// <summary>
        /// Tests the name with one character saves.
        /// </summary>
        [TestMethod]
        public void TestNameWithOneCharacterSaves()
        {
            #region Arrange
            var question = GetValid(9);
            question.Name = "x";
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }

        /// <summary>
        /// Tests the name with long value saves.
        /// </summary>
        [TestMethod]
        public void TestNameWithLongValueSaves()
        {
            #region Arrange
            var question = GetValid(9);
            question.Name = "x".RepeatTimes(200);
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(200, question.Name.Length);
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }

        #endregion Valid Tests
        #endregion Name Tests

        #region QuestionType Tests
        #region Invalid Tests
        /// <summary>
        /// Tests the question type with null value does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestQuestionTypeWithNullValueDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                question = GetValid(9);
                question.QuestionType = null;
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                #region Assert
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("QuestionType: may not be null");
                Assert.IsFalse(question.IsValid());
                Assert.IsTrue(question.IsTransient());
                #endregion Assert

                throw;
            }
        }
        /// <summary>
        /// Tests the question type with new value does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(NHibernate.PropertyValueException))]
        public void TestQuestionTypeWithNewValueDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                question = GetValid(9);
                question.QuestionType = new QuestionType();
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception ex)
            {
                #region Assert
                Assert.IsNotNull(question);
                Assert.IsNotNull(ex);
                Assert.AreEqual("not-null property references a null or transient valueCRP.Core.Domain.Question.QuestionType", ex.Message);
                #endregion Assert

                throw;
            }
        }
        #endregion Invalid Tests

        #region Valid Tests
        /// <summary>
        /// Tests the question type with valid value saves.
        /// </summary>
        [TestMethod]
        public void TestQuestionTypeWithValidValueSaves()
        {
            #region Arrange
            Repository.OfType<QuestionType>().DbContext.BeginTransaction();
            LoadQuestionTypes(3);
            Repository.OfType<QuestionType>().DbContext.CommitTransaction();
            var question = GetValid(9);
            var questionType = Repository.OfType<QuestionType>().GetNullableById(3);
            question.QuestionType = questionType;
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        #endregion Valid Tests

        #region CRUD Test
        /// <summary>
        /// Tests the type of the delete question does not cascade to question.
        /// </summary>
        [TestMethod]
        public void TestDeleteQuestionDoesNotCascadeToQuestionType()
        {
            #region Arrange
            Repository.OfType<QuestionType>().DbContext.BeginTransaction();
            LoadQuestionTypes(3);
            Repository.OfType<QuestionType>().DbContext.CommitTransaction();
            var question = GetValid(9);
            var questionType = Repository.OfType<QuestionType>().GetNullableById(3);
            question.QuestionType = questionType;

            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();

            Assert.AreEqual(4, Repository.OfType<QuestionType>().GetAll().Count); //because we load 1 in init
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.Remove(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(4, Repository.OfType<QuestionType>().GetAll().Count); //because we load 1 in init
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        #endregion CRUD Test
        #endregion QuestionType Tests
        #region QuestionSet Tests
        #region Invalid Tests
        /// <summary>
        /// Tests the QuestionSet with null value does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestQuestionSetWithNullValueDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                question = GetValid(9);
                question.QuestionSet = null;
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                #region Assert
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("QuestionSet: may not be null");
                Assert.IsFalse(question.IsValid());
                Assert.IsTrue(question.IsTransient());
                #endregion Assert

                throw;
            }
        }
        /// <summary>
        /// Tests the QuestionSet with new value does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(NHibernate.TransientObjectException))]
        public void TestQuestionSetWithNewValueDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                question = GetValid(9);
                question.QuestionSet = new QuestionSet();
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception ex)
            {
                #region Assert
                Assert.IsNotNull(question);
                Assert.IsNotNull(ex);
                Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing. Type: CRP.Core.Domain.QuestionSet, Entity: CRP.Core.Domain.QuestionSet", ex.Message);
                #endregion Assert

                throw;
            }
        }
        #endregion Invalid Tests

        #region Valid Tests
        /// <summary>
        /// Tests the QuestionSet with valid value saves.
        /// </summary>
        [TestMethod]
        public void TestQuestionSetWithValidValueSaves()
        {
            #region Arrange
            Repository.OfType<QuestionSet>().DbContext.BeginTransaction();
            LoadQuestionSets(3);
            Repository.OfType<QuestionSet>().DbContext.CommitTransaction();
            var question = GetValid(9);
            var questionSet = Repository.OfType<QuestionSet>().GetNullableById(3);
            question.QuestionSet = questionSet;
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        #endregion Valid Tests

        #region CRUD Test
        /// <summary>
        /// Tests the type of the delete question does not cascade to QuestionSet.
        /// </summary>
        [TestMethod]
        public void TestDeleteQuestionDoesNotCascadeToQuestionSet()
        {
            #region Arrange
            Repository.OfType<QuestionSet>().DbContext.BeginTransaction();
            LoadQuestionSets(3);
            Repository.OfType<QuestionSet>().DbContext.CommitTransaction();
            var question = GetValid(9);
            var questionSet = Repository.OfType<QuestionSet>().GetNullableById(3);
            question.QuestionSet = questionSet;

            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();

            Assert.AreEqual(4, Repository.OfType<QuestionSet>().GetAll().Count); //because we load 1 in init
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.Remove(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(4, Repository.OfType<QuestionSet>().GetAll().Count); //because we load 1 in init
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        #endregion CRUD Test
        #endregion QuestionSet Tests

        #region Options Collection Tests

        #region Invalid Tests
        /// <summary>
        /// Tests the options with null value does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestOptionsWithNullValueDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                question = GetValid(9);
                question.Options = null;
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("Options: may not be null");
                Assert.IsTrue(question.IsTransient());
                Assert.IsFalse(question.IsValid());
                throw;
            }
        }
        #endregion Invalid Tests

        #region Valid Tests
        /// <summary>
        /// Tests the options with empty list saves.
        /// </summary>
        [TestMethod]
        public void TestOptionsWithEmptyListSaves()
        {
            #region Arrange
            var question = GetValid(9);
            question.Options = new List<QuestionOption>();
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        /// <summary>
        /// Tests the options for mapping problem.
        /// </summary>
        [TestMethod]
        public void TestOptionsForMappingProblem()
        {
            #region Arrange
            SetOptions(true);
            var questionOption = CreateValidEntities.QuestionOption(1);
            Assert.AreEqual(0, Repository.OfType<QuestionOption>().GetAll().Count);

            var question = GetValid(null);
            question.Options = new List<QuestionOption>();
            question.AddOption(questionOption);
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(1, Repository.OfType<QuestionOption>().GetAll().Count);
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        #endregion Valid Tests

        #region CRUD Tests
        /// <summary>
        /// Tests the new options are saved.
        /// </summary>
        [TestMethod]
        public void TestNewOptionsAreSaved()
        {
            #region Arrange
            SetOptions(true);
            var question = GetValid(null);
            question.AddOption(CreateValidEntities.QuestionOption(1));
            question.AddOption(CreateValidEntities.QuestionOption(2));
            Assert.AreEqual(0, Repository.OfType<QuestionOption>().GetAll().Count);
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(2, Repository.OfType<QuestionOption>().GetAll().Count);
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }

        /// <summary>
        /// Tests the remove option cascades to question option.
        /// </summary>
        [TestMethod]
        public void TestRemoveOptionCascadesToQuestionOption()
        {
            #region Arrange
            SetOptions(true);
            var question = GetValid(null);
            question.AddOption(CreateValidEntities.QuestionOption(1));
            question.AddOption(CreateValidEntities.QuestionOption(2));
            question.AddOption(CreateValidEntities.QuestionOption(3));

            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            Assert.AreEqual(3, Repository.OfType<QuestionOption>().GetAll().Count);
            Assert.AreEqual(3, question.Options.Count);
            #endregion Arrange

            #region Act
            question.RemoveOptions(question.Options.ElementAt(1));
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(2, question.Options.Count);
            Assert.AreEqual(2, Repository.OfType<QuestionOption>().GetAll().Count);
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        /// <summary>
        /// Tests the remove question cascades to question option.
        /// </summary>
        [TestMethod]
        public void TestRemoveQuestionCascadesToQuestionOption()
        {
            #region Arrange
            SetOptions(true);
            var question = GetValid(null);
            question.AddOption(CreateValidEntities.QuestionOption(1));
            question.AddOption(CreateValidEntities.QuestionOption(2));
            question.AddOption(CreateValidEntities.QuestionOption(3));

            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            Assert.AreEqual(3, Repository.OfType<QuestionOption>().GetAll().Count);
            Assert.AreEqual(3, question.Options.Count);
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.Remove(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(0, Repository.OfType<QuestionOption>().GetAll().Count);
            #endregion Assert
        }
        /// <summary>
        /// Tests the update option cascades to question option.
        /// </summary>
        [TestMethod]
        public void TestUpdateOptionCascadesToQuestionOption()
        {
            #region Arrange
            var question = GetValid(null);
            SetOptions(true);
            question.AddOption(CreateValidEntities.QuestionOption(1));
            question.AddOption(CreateValidEntities.QuestionOption(2));
            question.AddOption(CreateValidEntities.QuestionOption(3));

            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            Assert.AreEqual("Name2", Repository.OfType<QuestionOption>().GetById(2).Name);
            #endregion Arrange

            #region Act
            question.Options.ElementAt(1).Name = "Updated";
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert

            Assert.AreEqual("Updated", Repository.OfType<QuestionOption>().GetById(2).Name);
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        #endregion CRUD Tests

        #endregion Options Collection Tests

        #region Validators Collection Tests

        #region Invalid Tests
        /// <summary>
        /// Tests the Validators with null value does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestValidatorsWithNullValueDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                question = GetValid(9);
                question.Validators = null;
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("Validators: may not be null");
                Assert.IsTrue(question.IsTransient());
                Assert.IsFalse(question.IsValid());
                throw;
            }
        }
        #endregion Invalid Tests

        #region Valid Tests
        /// <summary>
        /// Tests the Validators with empty list saves.
        /// </summary>
        [TestMethod]
        public void TestValidatorsWithEmptyListSaves()
        {
            #region Arrange
            var question = GetValid(9);
            question.Validators = new List<Validator>();
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        /// <summary>
        /// Tests the Validators for mapping problem.
        /// </summary>
        [TestMethod]
        public void TestValidatorsForMappingProblem()
        {
            #region Arrange
            Repository.OfType<Validator>().DbContext.BeginTransaction();
            LoadValidators(3);
            Repository.OfType<Validator>().DbContext.CommitTransaction();
            Assert.AreEqual(3, Repository.OfType<Validator>().GetAll().Count);

            var question = GetValid(null);
            question.Validators = new List<Validator>();
            question.Validators.Add(Repository.OfType<Validator>().GetNullableById(2));
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(3, Repository.OfType<Validator>().GetAll().Count);
            Assert.AreEqual(1, question.Validators.Count());
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        #endregion Valid Tests

        #region CRUD Tests
        /// <summary>
        /// Tests the new Validators are saved.
        /// Validators has a cross table
        /// </summary>
        [TestMethod]
        public void TestNewValidatorsAreNotSaved()
        {
            #region Arrange
            Repository.OfType<Validator>().DbContext.BeginTransaction();
            LoadValidators(3);
            Repository.OfType<Validator>().DbContext.CommitTransaction();
            Assert.AreEqual(3, Repository.OfType<Validator>().GetAll().Count);

            var question = GetValid(null);
            question.Validators = new List<Validator>();
            question.Validators.Add(Repository.OfType<Validator>().GetNullableById(2));
            question.Validators.Add(Repository.OfType<Validator>().GetNullableById(1));
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(3, Repository.OfType<Validator>().GetAll().Count);
            Assert.AreEqual(2, question.Validators.Count());
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }

        /// <summary>
        /// Tests the remove Validators does not cascade to Validators.
        /// </summary>
        [TestMethod]
        public void TestRemoveValidatorsDoesNotCascadeToValidators()
        {
            #region Arrange
            Repository.OfType<Validator>().DbContext.BeginTransaction();
            LoadValidators(3);
            Repository.OfType<Validator>().DbContext.CommitTransaction();
            Assert.AreEqual(3, Repository.OfType<Validator>().GetAll().Count);

            var question = GetValid(null);
            question.Validators = new List<Validator>();
            question.Validators.Add(Repository.OfType<Validator>().GetNullableById(2));
            question.Validators.Add(Repository.OfType<Validator>().GetNullableById(1));

            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            Assert.AreEqual(3, Repository.OfType<Validator>().GetAll().Count);
            Assert.AreEqual(2, question.Validators.Count());
            #endregion Arrange

            #region Act
            question.Validators.Remove(question.Validators.ElementAt(0));
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(3, Repository.OfType<Validator>().GetAll().Count);
            Assert.AreEqual(1, question.Validators.Count());
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        #endregion CRUD Tests

        #endregion Validators Collection Tests

        #region ValidationClasses Tests

        /// <summary>
        /// Tests the validation classes joins as expected.
        /// </summary>
        [TestMethod]
        public void TestValidationClassesJoinsAsExpected()
        {
            #region Arrange
            Repository.OfType<Validator>().DbContext.BeginTransaction();
            LoadValidators(3);
            Repository.OfType<Validator>().DbContext.CommitTransaction();

            var question = GetValid(null);
            question.Validators = new List<Validator>();
            question.Validators.Add(Repository.OfType<Validator>().GetNullableById(2));
            question.Validators.Add(Repository.OfType<Validator>().GetNullableById(1));
            #endregion Arrange

            #region Act
            var result = question.ValidationClasses;
            #endregion Act

            #region Assert
            Assert.AreEqual("Class2 Class1", result);
            #endregion Assert
        }

        [TestMethod]
        public void TestValidationClassesJoinsAsExpected2()
        {
            #region Arrange
            //Repository.OfType<Validator>().DbContext.BeginTransaction();
            //LoadValidators(3);
            //Repository.OfType<Validator>().DbContext.CommitTransaction();

            var question = GetValid(null);
            question.Validators = new List<Validator>();
            //question.Validators.Add(Repository.OfType<Validator>().GetNullableById(2));
            //question.Validators.Add(Repository.OfType<Validator>().GetNullableById(1));
            #endregion Arrange

            #region Act
            var result = question.ValidationClasses;
            #endregion Act

            #region Assert
            Assert.AreEqual("", result);
            #endregion Assert
        }

        [TestMethod]
        public void TestValidationClassesJoinsAsExpected3()
        {
            #region Arrange
            //Repository.OfType<Validator>().DbContext.BeginTransaction();
            //LoadValidators(3);
            //Repository.OfType<Validator>().DbContext.CommitTransaction();
            var validators = new List<Validator>();
            for (int i = 0; i < 3; i++)
            {
                validators.Add(CreateValidEntities.Validator(i+1));
            }
            validators[1].Class = null;

            var question = GetValid(null);
            question.Validators = new List<Validator>();
            question.Validators.Add(validators[0]);
            question.Validators.Add(validators[1]);
            question.Validators.Add(validators[2]);

            #endregion Arrange

            #region Act
            var result = question.ValidationClasses;
            #endregion Act

            #region Assert
            Assert.AreEqual("Class1  Class3", result); //Two spaces
            #endregion Assert
        }
        #endregion ValidationClasses Tests

        #region Order Tests

        /// <summary>
        /// Tests the order value of zero saves.
        /// </summary>
        [TestMethod]
        public void TestOrderValueOfZeroSaves()
        {
            #region Arrange
            var question = GetValid(9);
            question.Order = 0;
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        /// <summary>
        /// Tests the order with small value saves.
        /// </summary>
        [TestMethod]
        public void TestOrderWithSmallValueSaves()
        {
            #region Arrange
            var question = GetValid(9);
            question.Order = int.MinValue;
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }
        /// <summary>
        /// Tests the order with large value saves.
        /// </summary>
        [TestMethod]
        public void TestOrderWithLargeValueSaves()
        {
            #region Arrange
            var question = GetValid(9);
            question.Order = int.MaxValue;
            #endregion Arrange

            #region Act
            QuestionRepository.DbContext.BeginTransaction();
            QuestionRepository.EnsurePersistent(question);
            QuestionRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.IsFalse(question.IsTransient());
            Assert.IsTrue(question.IsValid());
            #endregion Assert
        }

        #endregion Order Tests

        #region OptionsNames Tests
        /// <summary>
        /// Tests the options names with invalid value does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestOptionsNamesWithNameWithSpacesOnlyDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                SetOptions(true);
                question = GetValid(9);
                question.AddOption(CreateValidEntities.QuestionOption(1));
                question.AddOption(CreateValidEntities.QuestionOption(2));
                question.AddOption(CreateValidEntities.QuestionOption(3));
                question.Options.ElementAt(1).Name = " ";
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("OptionsNames: One or more options is invalid");
                Assert.IsTrue(question.IsTransient());
                Assert.IsFalse(question.IsValid());
                throw;
            }
        }

        /// <summary>
        /// Tests the options names with name with empty string does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestOptionsNamesWithNameWithEmptyStringDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                SetOptions(true);
                question = GetValid(9);
                question.AddOption(CreateValidEntities.QuestionOption(1));
                question.AddOption(CreateValidEntities.QuestionOption(2));
                question.AddOption(CreateValidEntities.QuestionOption(3));
                question.Options.ElementAt(1).Name = string.Empty;
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("OptionsNames: One or more options is invalid");
                Assert.IsTrue(question.IsTransient());
                Assert.IsFalse(question.IsValid());
                throw;
            }
        }
        /// <summary>
        /// Tests the options names with name with null value does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestOptionsNamesWithNameWithNullValueDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                SetOptions(true);
                question = GetValid(9);
                question.AddOption(CreateValidEntities.QuestionOption(1));
                question.AddOption(CreateValidEntities.QuestionOption(2));
                question.AddOption(CreateValidEntities.QuestionOption(3));
                question.Options.ElementAt(1).Name = null;
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("OptionsNames: One or more options is invalid");
                Assert.IsTrue(question.IsTransient());
                Assert.IsFalse(question.IsValid());
                throw;
            }
        }

        #endregion OptionsNames Tests

        #region OptionsRequired Tests
        /// <summary>
        /// Tests the options required with no options does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestOptionsRequiredWithNoOptionsDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                SetOptions(true);
                question = GetValid(9);
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("OptionsRequired: The question type requires at least one option.");
                Assert.IsTrue(question.IsTransient());
                Assert.IsFalse(question.IsValid());
                throw;
            }
        }

        #endregion OptionsRequired Tests

        #region OptionsNotAllowed Tests
        /// <summary>
        /// Tests the options not allowed with options does not save.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(ApplicationException))]
        public void TestOptionsNotAllowedWithOptionsDoesNotSave()
        {
            Question question = null;
            try
            {
                #region Arrange
                SetOptions(true);
                question = GetValid(9);
                question.AddOption(CreateValidEntities.QuestionOption(1));
                SetOptions(false);
                #endregion Arrange

                #region Act
                QuestionRepository.DbContext.BeginTransaction();
                QuestionRepository.EnsurePersistent(question);
                QuestionRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(question);
                var results = question.ValidationResults().AsMessageList();
                results.AssertErrorsAre("OptionsNotAllowed: Options not allowed");
                Assert.IsTrue(question.IsTransient());
                Assert.IsFalse(question.IsValid());
                throw;
            }
        }

        #endregion OptionsNotAllowed Tests

        #region AddOption Test

        /// <summary>
        /// Tests the does not add option when has options is false.
        /// </summary>
        [TestMethod]
        public void TestDoesNotAddOptionWhenHasOptionsIsFalse()
        {
            #region Arrange
            SetOptions(false);
            var question = GetValid(9);
            #endregion Arrange

            #region Act
            question.AddOption(CreateValidEntities.QuestionOption(1));
            #endregion Act

            #region Assert
            Assert.AreEqual(0, question.Options.Count);
            #endregion Assert
        }

        #endregion AddOption Test

        #region Reflection of Database

        /// <summary>
        /// Tests all fields in the database have been tested.
        /// If this fails and no other tests, it means that a field has been added which has not been tested above.
        /// </summary>
        [TestMethod]
        public void TestAllFieldsInTheDatabaseHaveBeenTested()
        {
            #region Arrange

            var expectedFields = new List<NameAndType>();

            expectedFields.Add(new NameAndType("Id", "System.Int32", new List<string>
            {
                 "[Newtonsoft.Json.JsonPropertyAttribute()]",
                 "[System.Xml.Serialization.XmlIgnoreAttribute()]"
            }));
            expectedFields.Add(new NameAndType("Name", "System.String", new List<string>
            {
                 "[NHibernate.Validator.Constraints.LengthAttribute((Int32)200)]",
                 "[UCDArch.Core.NHibernateValidator.Extensions.RequiredAttribute()]"
            }));
            expectedFields.Add(new NameAndType("Options", "System.Collections.Generic.ICollection`1[CRP.Core.Domain.QuestionOption]", new List<string>
            {
                "[NHibernate.Validator.Constraints.NotNullAttribute()]"
            }));
            expectedFields.Add(new NameAndType("OptionsNames", "System.Boolean", new List<string>
            {
                "[NHibernate.Validator.Constraints.AssertTrueAttribute(Message = \"One or more options is invalid\")]"
            }));
            expectedFields.Add(new NameAndType("OptionsNotAllowed", "System.Boolean", new List<string>
            {
                "[NHibernate.Validator.Constraints.AssertTrueAttribute(Message = \"Options not allowed\")]"
            }));
            expectedFields.Add(new NameAndType("OptionsRequired", "System.Boolean", new List<string>
            {
                "[NHibernate.Validator.Constraints.AssertTrueAttribute(Message = \"The question type requires at least one option.\")]"
            }));
            expectedFields.Add(new NameAndType("Order", "System.Int32", new List<string>()));
            expectedFields.Add(new NameAndType("QuestionSet", "CRP.Core.Domain.QuestionSet", new List<string>
            {
                "[NHibernate.Validator.Constraints.NotNullAttribute()]"
            }));
            expectedFields.Add(new NameAndType("QuestionType", "CRP.Core.Domain.QuestionType", new List<string>
            {
                "[NHibernate.Validator.Constraints.NotNullAttribute()]"
            }));
            expectedFields.Add(new NameAndType("ValidationClasses", "System.String", new List<string>()));
            expectedFields.Add(new NameAndType("Validators", "System.Collections.Generic.ICollection`1[CRP.Core.Domain.Validator]", new List<string>
            {
                "[NHibernate.Validator.Constraints.NotNullAttribute()]"
            }));
            #endregion Arrange

            AttributeAndFieldValidation.ValidateFieldsAndAttributes(expectedFields, typeof(Question));

        }

        #endregion Reflection of Database

        /// <summary>
        /// Turns the on options.
        /// </summary>
        private void SetOptions(bool hasOptions)
        {
            Repository.OfType<QuestionType>().DbContext.BeginTransaction();
            var questionType = Repository.OfType<QuestionType>().GetById(1);
            questionType.HasOptions = hasOptions;
            Repository.OfType<QuestionType>().EnsurePersistent(questionType);
            Repository.OfType<QuestionType>().DbContext.CommitTransaction();
        }
    }
}


text:
package becta.viewer.framework;

import iwb.IWBBridge;

import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.HashSet;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.EventListenerList;

import becta.viewer.accessibility.AccessibilityColor;
import becta.viewer.controls.FloatChangeListener;
import becta.viewer.controls.SelectionModeListener;
import becta.viewer.drawing.BaseElement;
import becta.viewer.filemanagement.Document;
import becta.viewer.filemanagement.Page;
import becta.viewer.selection.SelectionManager;
import becta.viewer.selection.SelectionMode;

/**
 * This class implements the canvas for drawing various elements
 */
public class Canvas extends JPanel{

	/**
	 * Field that hold the back colour of viewer
	 */
	private static final Color BACKCOLOUR = AccessibilityColor.window;
	/**
	 * the offscreen image of the canvas
	 */
	private BufferedImage canvasOffscreenImage;

	/**
	 * the document
	 */
	private Document document;
	/**
	 * Holds the paint listeners
	 */
	private Set<CanvasPainter> paintListeners;
	/**
	 * Holds the zoommanager instance
	 */
	private ZoomManager zoomManager;
	/**
	 * Holds the scroll pane in which this canvas is placed
	 */
	private ScrollPane scrollPane;

	/**
	 * Holds the selection mode
	 */
	private static SelectionMode selectionMode = SelectionMode.NONE;

	/**
	 * List of listeners interested in selection mode changes
	 */
	private static EventListenerList listenerList = new EventListenerList();

	/**
	 * Gets the selection mode
	 * @return current selection mode
	 */
	public static SelectionMode getSelectionMode() {

		return selectionMode;
	}

	/**
	 * Sets the selection mode
	 * @param mode new selection mode
	 */
	public void setSelectionMode(SelectionMode mode){

		selectionMode = mode;
		this.setCursor(getDefaultCursor());

		// Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i = listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==SelectionModeListener.class) {

                ((SelectionModeListener)listeners[i+1]).selectionModeChanged(mode);
            }
        }
	}

	public static void addSelectionModeListener(SelectionModeListener l){

		listenerList.add(SelectionModeListener.class, l);
	}

	/**
	 * The constructor for this class
	 */
	public Canvas(ScrollPane scrollPane){

		setLayout(null);
		//setBorder(BorderFactory.createLineBorder(AccessibilityColor.controlText, 2));
		this.setBackground(BACKCOLOUR);

		paintListeners = new HashSet<CanvasPainter>();

		zoomManager = new ZoomManager(this);
		this.scrollPane = scrollPane;

	}

	public void checkHeavyComponent(Rectangle bounds){

		//TODO: implement the logic for replacing place holder with actual component
		for (BaseElement element : document.getCurrentPage().getElements()) {

			element.updateHeavyControl(bounds,getDocument().getViewbox());
		}
	}

	/**
	 * @return the document of the canvas
	 */
	public Document getDocument(){

		return document;
	}

	/**
	 * this method used for setting the document
	 * @param document
	 */
	public void setDocument(Document document){

		this.document = document;
		Rectangle2D viewport = document.getViewport();
		setCanvasSize(new Dimension((int)viewport.getWidth(), (int)viewport.getHeight()));
	}

	/**
	 * setting the new canvas size
	 * @param newSize
	 */
	public void setCanvasSize(Dimension newSize){

		// set canvas size and refresh canvas content
		this.setPreferredSize(newSize);
		scrollPane.updateSize();
		refreshCanvasContent(true);
	}

	/**
	 * Adds paint listener to canvas
	 * @param painter
	 */
	public void addPaintListener(CanvasPainter painter) {

		paintListeners.add(painter);
	}

	/**
	 * Remove paint listener from canvas
	 * @param painter
	 */
	public void removePaintListener(CanvasPainter painter){

		paintListeners.remove(painter);
	}

	/**
	 * Gets the zoom manager for the canvas
	 * @return ZoomManager
	 */
	public ZoomManager getZoomManager(){

		return zoomManager;
	}

	/**
	 * Get the scrollpane in which canvas is placed
	 * @return ScrollPane
	 */
	public ScrollPane getScrollPane() {
		return scrollPane;
	}

	/**
	 * Overrides paintComponent for handling drawing in canvas
	 */
	public void paintComponent(Graphics g) {

		//super.paintComponent(g);

		if(canvasOffscreenImage!=null) {

			//draw buffered image
			g.drawImage(canvasOffscreenImage, getVisibleRect().x, getVisibleRect().y, null);
		}

		drawPainters((Graphics2D)g);
	}

	/**
	 * This method is used for updating the mouse cursor based on the mode
	 */
	public static Cursor getDefaultCursor(){

		if(getSelectionMode() == SelectionMode.NONE ||  getSelectionMode() == SelectionMode.REGULAR){
			return Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
		}
		else{
			//set cursor for drawing mode
			return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
		}
	}

	/**
	 * Refresh the canvas contents
	 */
	public void refreshCanvasContent(boolean doRepaint){

		BufferedImage tempCanvasOffscreenImage = canvasOffscreenImage;

		Rectangle viewportBounds = scrollPane.getViewportBounds();
		int width = getPreferredSize().width < viewportBounds.width || viewportBounds.width == 0 ? getPreferredSize().width : viewportBounds.width;
		int height = getPreferredSize().height < viewportBounds.height || viewportBounds.height == 0 ? getPreferredSize().height : viewportBounds.height;

		Rectangle visibleRect =  new Rectangle(0,0,width, height);

		//if canvas can be shown
		if(visibleRect.width > 0 && visibleRect.height > 0){

			//BufferedImage is created only when it is null or the size of canvas is changed
			if(tempCanvasOffscreenImage == null || tempCanvasOffscreenImage.getWidth() != visibleRect.width || tempCanvasOffscreenImage.getHeight() != visibleRect.height){

				//tempCanvasOffscreenImage = new BufferedImage(getPreferredSize().width, getPreferredSize().height,BufferedImage.TYPE_INT_ARGB);
				tempCanvasOffscreenImage = new BufferedImage(visibleRect.width, visibleRect.height,BufferedImage.TYPE_INT_ARGB);
			}

			if(tempCanvasOffscreenImage!=null){

				// creates Graphics instance from buffered image
				Graphics2D g2d = tempCanvasOffscreenImage.createGraphics();
				g2d.setClip(0, 0, visibleRect.width, visibleRect.height);
				setRenderingHints(g2d);

				Color oldColor = g2d.getColor();
				Stroke oldStroke = g2d.getStroke();

				Page page = document.getCurrentPage();

				//draw background colour and image
				if(page.getBackgroundColour()!=null)
					g2d.setColor(page.getBackgroundColour());
				else
					//clears canvas
					g2d.setColor(BACKCOLOUR);

				g2d.fillRect(0, 0, tempCanvasOffscreenImage.getWidth(), tempCanvasOffscreenImage.getHeight());

				// set scale transform for having zooming
				g2d.setTransform(zoomManager.getScaleTransform());

				g2d.translate(-(scrollPane.getScrollValues().width/ zoomManager.getCurrentScale()), -(scrollPane.getScrollValues().height/ zoomManager.getCurrentScale()));

				if(page.getBackgroundImage()!=null){

					switch(page.getBackgroundImagePosture()){
						case IWBBridge.IWB_POSTURE_UNDEFINED:
						case IWBBridge.IWB_POSTURE_BY_POSITION:
							page.getBackgroundImage().draw(g2d);
							break;
						case IWBBridge.IWB_POSTURE_STRETCHED_TO_FILL:
						{
							Image img =  page.getBackgroundImage().getImage();
							g2d.drawImage(img, 0, 0, width, height, 0, 0, img.getWidth(null), img.getHeight(null), null);
							break;
						}
						case IWBBridge.IWB_POSTURE_SCALED_TO_FIT:
						{
							Image img =  page.getBackgroundImage().getImage();

					        double xScale = (double)width/img.getWidth(null);
					        double yScale = (double)height/img.getHeight(null);
					        double scale = Math.min(xScale, yScale);    // scale to fit
					        int w = (int)(scale*img.getWidth(null));
					        int h = (int)(scale*img.getHeight(null));
					        int x = (width - width)/2;
					        int y = (height - height)/2;
					        g2d.drawImage(img, x, y, w, h, this);

							break;
						}
						case IWBBridge.IWB_POSTURE_REPEATED:
						{
							Image img =  page.getBackgroundImage().getImage();

							if(width > 0 && height > 0)
							{

								for(int x = 0; x < width ; x += img.getWidth(null))
								{
									for(int y = 0; y < height ; y += img.getHeight(null))
									{
										g2d.drawImage(img,x,y,null);
									}
								}
							}

							break;
						}

					}
				}

				// draw elements to buffered image
				for (BaseElement element : page.getElements()) {

					g2d.setColor(oldColor);
					g2d.setStroke(oldStroke);

					element.draw(g2d);
				}

				// draw elements to buffered image
				for (BaseElement element : page.getAnnotations()) {

					g2d.setColor(oldColor);
					g2d.setStroke(oldStroke);

					element.draw(g2d);
				}
				// dispose graphics object after use
				g2d.dispose();
			}

			canvasOffscreenImage = tempCanvasOffscreenImage;

			// repaints canvas
			if(doRepaint)
				repaint();

		}
	}

	/**
	 * Set rendering hints
	 * @param g
	 */
	private void setRenderingHints(Graphics2D g) {

		//setting the rendering hints
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
	}

	/**
	 * This method will invoke the paintToBeDone method of all paint listeners added
	 * @param g
	 */
	private void drawPainters(Graphics2D g){

		g = (Graphics2D)g.create();

		setRenderingHints(g);
		AffineTransform oldTransformation = g.getTransform();
		oldTransformation.concatenate(zoomManager.getScaleTransform());
		g.setTransform(oldTransformation);

		for (CanvasPainter painter : paintListeners) {

			painter.paintToBeDone(g);
		}

		g.dispose();

	}
}

redpajama_set_name: RedPajamaGithub


text:
package clock

import (
	"time"
)

type mockTicker struct {
	c    chan time.Time
	stop chan bool

	clock    Clock
	interval time.Duration
	start    time.Time
}

var _ Ticker = new(mockTicker)

// note: this probably does not function the same way as the time.Timer
// in the event that the clock skips more than the timer interval. I've
// not yet dug deep into the runtimeTimer to see how that works.
// PRs are appreciated!
func (m *mockTicker) wait(ready chan<- struct{}) {
	for i := time.Duration(1); true; i++ {
		delta := m.start.Add(m.interval * i).Sub(m.clock.Now())
		afterChan := m.clock.After(delta)

		if i == time.Duration(1) {
			ready <- struct{}{}
		}

		select {
		case <-m.stop:
			return
		case <-afterChan:
			select {
			case m.c <- m.clock.Now():
			case <-m.stop:
				return
			}
		}
	}
}

func (m *mockTicker) Chan() <-chan time.Time {
	return m.c
}

func (m *mockTicker) Stop() {
	m.stop <- true
}

// NewMockTicker creates a new Ticker using the provided Clock. You should not use this
// directly outside of unit tests; use Clock.NewTicker().
func NewMockTicker(c Clock, interval time.Duration) Ticker {
	t := &mockTicker{
		c:        make(chan time.Time),
		stop:     make(chan bool),
		interval: interval,
		start:    c.Now(),
		clock:    c,
	}

	ready := make(chan struct{})
	go t.wait(ready)
	<-ready
	return t
}


text:
package org.apache.geode.internal.protocol.protobuf.utilities;

import com.google.protobuf.ByteString;
import org.apache.geode.internal.protocol.protobuf.BasicTypes;
import org.apache.geode.internal.protocol.protobuf.utilities.exception.UnknownProtobufPrimitiveType;
import org.apache.geode.test.junit.categories.UnitTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.nio.charset.Charset;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

@Category(UnitTest.class)
public class ProtobufUtilitiesJUnitTest {
  @Test
  public void getIntPrimitiveFromEncodedValue() throws UnknownProtobufPrimitiveType {
    BasicTypes.EncodedValue.Builder builder = BasicTypes.EncodedValue.newBuilder();
    BasicTypes.EncodedValue encodedValue = builder.setIntResult(1).build();
    assertEquals(1, ProtobufUtilities.getPrimitiveValueFromEncodedValue(encodedValue));
  }

  @Test
  public void getLongPrimitiveFromEncodedValue() throws UnknownProtobufPrimitiveType {
    BasicTypes.EncodedValue encodedValue =
        BasicTypes.EncodedValue.newBuilder().setLongResult(1).build();
    assertEquals(1l, ProtobufUtilities.getPrimitiveValueFromEncodedValue(encodedValue));
  }

  @Test
  public void getShortPrimitiveFromEncodedValue() throws UnknownProtobufPrimitiveType {
    BasicTypes.EncodedValue encodedValue =
        BasicTypes.EncodedValue.newBuilder().setShortResult(1).build();
    assertEquals((short) 1, ProtobufUtilities.getPrimitiveValueFromEncodedValue(encodedValue));
  }

  @Test
  public void getBytePrimitiveFromEncodedValue() throws UnknownProtobufPrimitiveType {
    BasicTypes.EncodedValue encodedValue =
        BasicTypes.EncodedValue.newBuilder().setByteResult(1).build();
    assertEquals((byte) 1, ProtobufUtilities.getPrimitiveValueFromEncodedValue(encodedValue));
  }

  @Test
  public void getBooleanPrimitiveFromEncodedValue() throws UnknownProtobufPrimitiveType {
    BasicTypes.EncodedValue encodedValue =
        BasicTypes.EncodedValue.newBuilder().setBooleanResult(true).build();
    assertEquals(true, ProtobufUtilities.getPrimitiveValueFromEncodedValue(encodedValue));
  }

  @Test
  public void getDoublePrimitiveFromEncodedValue() throws UnknownProtobufPrimitiveType {
    BasicTypes.EncodedValue encodedValue =
        BasicTypes.EncodedValue.newBuilder().setDoubleResult(1.0).build();
    assertEquals(1.0, ProtobufUtilities.getPrimitiveValueFromEncodedValue(encodedValue));
  }

  @Test
  public void getFloatPrimitiveFromEncodedValue() throws UnknownProtobufPrimitiveType {
    BasicTypes.EncodedValue encodedValue =
        BasicTypes.EncodedValue.newBuilder().setFloatResult(1).build();
    assertEquals(1f, ProtobufUtilities.getPrimitiveValueFromEncodedValue(encodedValue));
  }

  @Test
  public void getByteArrayPrimitiveFromEncodedValue() throws UnknownProtobufPrimitiveType {
    BasicTypes.EncodedValue encodedValue = BasicTypes.EncodedValue.newBuilder()
        .setBinaryResult(ByteString.copyFrom("SomeBinary".getBytes())).build();
    assertArrayEquals("SomeBinary".getBytes(Charset.forName("UTF-8")),
        (byte[]) ProtobufUtilities.getPrimitiveValueFromEncodedValue(encodedValue));
  }

  @Test
  public void getStringPrimitiveFromEncodedValue() throws UnknownProtobufPrimitiveType {
    BasicTypes.EncodedValue encodedValue =
        BasicTypes.EncodedValue.newBuilder().setStringResult("SomeString").build();
    assertEquals("SomeString", ProtobufUtilities.getPrimitiveValueFromEncodedValue(encodedValue));
  }

  @Test
  public void doesAIntValueSuccessfullyEncodeIntoPrimitiveEncodedValues()
      throws UnknownProtobufPrimitiveType {
    createAndVerifyEncodedValue(1);
  }

  @Test
  public void doesALongValueSuccessfullyEncodeIntoPrimitiveEncodedValues()
      throws UnknownProtobufPrimitiveType {
    createAndVerifyEncodedValue(1l);
  }

  @Test
  public void doesAShortValueSuccessfullyEncodeIntoPrimitiveEncodedValues()
      throws UnknownProtobufPrimitiveType {
    createAndVerifyEncodedValue((short) 1);
  }

  @Test
  public void doesAByteValueSuccessfullyEncodeIntoPrimitiveEncodedValues()
      throws UnknownProtobufPrimitiveType {
    createAndVerifyEncodedValue((byte) 1);
  }

  @Test
  public void doesABooleanValueSuccessfullyEncodeIntoPrimitiveEncodedValues()
      throws UnknownProtobufPrimitiveType {
    createAndVerifyEncodedValue(true);
  }

  @Test
  public void doesADoubleValueSuccessfullyEncodeIntoPrimitiveEncodedValues()
      throws UnknownProtobufPrimitiveType {
    createAndVerifyEncodedValue((double) 1);
  }

  @Test
  public void doesAFloatValueSuccessfullyEncodeIntoPrimitiveEncodedValues()
      throws UnknownProtobufPrimitiveType {
    createAndVerifyEncodedValue((float) 1);
  }

  @Test
  public void doesABinaryValueSuccessfullyEncodeIntoPrimitiveEncodedValues()
      throws UnknownProtobufPrimitiveType {
    createAndVerifyEncodedValue("Some Text to Binary".getBytes());
  }

  @Test
  public void doesAStringValueSuccessfullyEncodeIntoPrimitiveEncodedValues()
      throws UnknownProtobufPrimitiveType {
    createAndVerifyEncodedValue("Some String text to test");
  }

  private <T> void createAndVerifyEncodedValue(T testObj) throws UnknownProtobufPrimitiveType {
    BasicTypes.EncodedValue encodedValue = ProtobufUtilities.createPrimitiveEncodedValue(testObj);
    if (testObj instanceof byte[]) {
      assertArrayEquals((byte[]) testObj,
          (byte[]) ProtobufUtilities.getPrimitiveValueFromEncodedValue(encodedValue));
    } else {
      assertEquals(testObj, ProtobufUtilities.getPrimitiveValueFromEncodedValue(encodedValue));
    }
  }
}


text:
package json

import (
	"encoding/json"
	"errors"
	"net/http"

	"github.com/jackmanlabs/rpc"
)

var null = json.RawMessage([]byte("null"))

// ----------------------------------------------------------------------------
// Request and Response
// ----------------------------------------------------------------------------

// serverRequest represents a JSON-RPC request received by the server.
type serverRequest struct {
	// A String containing the name of the method to be invoked.
	Method string `json:"method"`
	// An Array of objects to pass as arguments to the method.
	Params *json.RawMessage `json:"params"`
	// The request id. This can be of any type. It is used to match the
	// response with the request that it is replying to.
	Id *json.RawMessage `json:"id"`
}

// serverResponse represents a JSON-RPC response returned by the server.
type serverResponse struct {
	// The Object that was returned by the invoked method. This must be null
	// in case there was an error invoking the method.
	Result interface{} `json:"result"`
	// An Error object if there was an error invoking the method. It must be
	// null if there was no error.
	Error interface{} `json:"error"`
	// This must be the same id as the request it is responding to.
	Id *json.RawMessage `json:"id"`
}

// ----------------------------------------------------------------------------
// Codec
// ----------------------------------------------------------------------------

// NewCodec returns a new JSON Codec.
func NewCodec() *Codec {
	return &Codec{}
}

// Codec creates a CodecRequest to process each request.
type Codec struct {
}

// NewRequest returns a CodecRequest.
func (c *Codec) NewRequest(r *http.Request) rpc.CodecRequest {
	return newCodecRequest(r)
}

// ----------------------------------------------------------------------------
// CodecRequest
// ----------------------------------------------------------------------------

// newCodecRequest returns a new CodecRequest.
func newCodecRequest(r *http.Request) rpc.CodecRequest {
	// Decode the request body and check if RPC method is valid.
	req := new(serverRequest)
	err := json.NewDecoder(r.Body).Decode(req)
	r.Body.Close()
	return &CodecRequest{request: req, err: err}
}

// CodecRequest decodes and encodes a single request.
type CodecRequest struct {
	request *serverRequest
	err     error
}

// Method returns the RPC method for the current request.
//
// The method uses a dotted notation as in "Service.Method".
func (c *CodecRequest) Method() (string, error) {
	if c.err == nil {
		return c.request.Method, nil
	}
	return "", c.err
}

// ReadRequest fills the request object for the RPC method.
func (c *CodecRequest) ReadRequest(args interface{}) error {
	if c.err == nil {
		if c.request.Params != nil {
			// JSON params is array value. RPC params is struct.
			// Unmarshal into array containing the request struct.
			params := [1]interface{}{args}
			c.err = json.Unmarshal(*c.request.Params, &params)
		} else {
			c.err = errors.New("rpc: method request ill-formed: missing params field")
		}
	}
	return c.err
}

// WriteResponse encodes the response and writes it to the ResponseWriter.
//
// The err parameter is the error resulted from calling the RPC method,
// or nil if there was no error.
func (c *CodecRequest) WriteResponse(w http.ResponseWriter, reply interface{}, methodErr error) error {
	if c.err != nil {
		return c.err
	}
	res := &serverResponse{
		Result: reply,
		Error:  &null,
		Id:     c.request.Id,
	}
	if methodErr != nil {
		// Propagate error message as string.
		res.Error = methodErr.Error()
		// Result must be null if there was an error invoking the method.
		// http://json-rpc.org/wiki/specification#a1.2Response
		res.Result = &null
	}
	if c.request.Id == nil {
		// Id is null for notifications and they don't have a response.
		res.Id = &null
	} else {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		encoder := json.NewEncoder(w)
		encoder.Encode(res)
	}
	return nil
}


text:
@interface LUAlertView : UIAlertView

@property (nonatomic, strong) NSArray<LUAlertAction *> *actions;

-(instancetype)initWithTitle:(NSString *)title message:(NSString *)message actions:(NSArray<LUAlertAction *> *)actions;

@end

@implementation LUAlertView

- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message actions:(NSArray<LUAlertAction *> *)actions
{
	self = [super initWithTitle:title message:message delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
	if (self) {
		_actions = actions;
		for (LUAlertAction *action in actions) {
			[self addButtonWithTitle:action.title];
		}
	}
	return self;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (_actions[buttonIndex].handler) {
		_actions[buttonIndex].handler(_actions[buttonIndex]);
	}
}

@end

#pragma clang diagnostic pop

@implementation LUAlertAction

- (instancetype)initWithTitle:(NSString *)title handler:(void (^)(LUAlertAction * _Nonnull))handler
{
	self = [super init];
	if (self) {
		_title = title;
		_handler = handler;
	}
	return self;
}

@end

@implementation LUUIHelper

+ (void)showAlertViewWithTitle:(NSString *)title message:(NSString *)message
{
	NSArray *actions = @[[[LUAlertAction alloc] initWithTitle:title handler:nil]];
	[self showAlertViewWithTitle:title message:message actions:actions];
}

+ (void)showAlertViewWithTitle:(NSString *)title message:(NSString *)message actions:(NSArray<LUAlertAction *> *)actions
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
	LUAlertView *alertView = [[LUAlertView alloc] initWithTitle:title
														message:message
														actions:actions];
	[alertView show];
#pragma clang diagnostic pop
}

+ (void)view:(UIView *)view centerInParent:(UIView *)parent
{
	view.translatesAutoresizingMaskIntoConstraints = NO;
	NSArray *constraints = @[
		[NSLayoutConstraint constraintWithItem:view
									 attribute:NSLayoutAttributeLeading
									 relatedBy:NSLayoutRelationEqual
										toItem:parent
									 attribute:NSLayoutAttributeLeading
									multiplier:1.0
									  constant:0],
		[NSLayoutConstraint constraintWithItem:view
									 attribute:NSLayoutAttributeTrailing
									 relatedBy:NSLayoutRelationEqual
										toItem:parent
									 attribute:NSLayoutAttributeTrailing
									multiplier:1.0
									  constant:0],
        [NSLayoutConstraint constraintWithItem:view
									 attribute:NSLayoutAttributeTop
									 relatedBy:NSLayoutRelationEqual
										toItem:parent
									 attribute:NSLayoutAttributeTop
									multiplier:1.0
									  constant:0],
		[NSLayoutConstraint constraintWithItem:view
									 attribute:NSLayoutAttributeBottom
									 relatedBy:NSLayoutRelationEqual
										toItem:parent
									 attribute:NSLayoutAttributeBottom
									multiplier:1.0
									  constant:0]
	];
	[NSLayoutConstraint activateConstraints:constraints];
}

+ (CGRect)safeAreaRect
{
	if (@available(iOS 11.0, *)) {
		return [UIApplication sharedApplication].keyWindow.safeAreaLayoutGuide.layoutFrame;
	}

	return [UIScreen mainScreen].bounds;
}

@end


text:
/*==================[inlcusiones]============================================*/

#include "programa.h"   // <= su propio archivo de cabecera
#include "sapi.h"       // <= Biblioteca sAPI

/*==================[definiciones y macros]==================================*/

/*==================[definiciones de datos internos]=========================*/

/*==================[definiciones de datos externos]=========================*/

/*==================[declaraciones de funciones internas]====================*/

/*==================[declaraciones de funciones externas]====================*/

/*==================[funcion principal]======================================*/

// FUNCION PRINCIPAL, PUNTO DE ENTRADA AL PROGRAMA LUEGO DE ENCENDIDO O RESET.
int main( void ){

   // ---------- CONFIGURACIONES ------------------------------
   // Inicializar y configurar la plataforma
   boardConfig();

   gpioConfig( T_COL2, GPIO_INPUT ); // Tiene R de pullup en protoboard

   gpioConfig( T_FIL1, GPIO_INPUT_PULLUP ); // Le configuro una R de pullup interna, entonces no pongo R en el protoboard

   // ---------- REPETIR POR SIEMPRE --------------------------
   while( TRUE )
   {
      // Si se presiona el boton conectado a T_FIL1, enciende el LEDR
      gpioWrite( LEDR, !(gpioRead(T_FIL1)) );
      // Si se presiona el boton conectado a T_COL2, enciende el LED3
      gpioWrite( LED3, !(gpioRead(T_COL2)) );

   }

   // NO DEBE LLEGAR NUNCA AQUI, debido a que a este programa se ejecuta
   // directamenteno sobre un microcontroladore y no es llamado/ por ningun
   // Sistema Operativo, como en el caso de un programa para PC.
   return 0;
}

/*==================[definiciones de funciones internas]=====================*/

/*==================[definiciones de funciones externas]=====================*/

/*==================[fin del archivo]========================================*/


text:
from django import forms
from django.conf import settings
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

from oscar.core.loading import get_model
from oscar.forms import widgets

ConditionalOffer = get_model('offer', 'ConditionalOffer')
Condition = get_model('offer', 'Condition')
Benefit = get_model('offer', 'Benefit')

def get_offer_type_choices():
    return (("", "---------"),) + tuple(choice for choice in ConditionalOffer.TYPE_CHOICES
                                        if choice[0] in [getattr(ConditionalOffer, const_name)
                                                         for const_name in settings.OSCAR_OFFERS_IMPLEMENTED_TYPES])

class MetaDataForm(forms.ModelForm):

    offer_type = forms.ChoiceField(label=_("Type"), choices=get_offer_type_choices)

    class Meta:
        model = ConditionalOffer
        fields = ('name', 'description', 'offer_type')

    def clean_offer_type(self):
        data = self.cleaned_data['offer_type']
        if (self.instance.pk is not None) and (self.instance.offer_type == ConditionalOffer.VOUCHER) and \
           ('offer_type' in self.changed_data) and self.instance.vouchers.exists():
            raise forms.ValidationError(_("This can only be changed if it has no vouchers attached to it"))
        return data

class RestrictionsForm(forms.ModelForm):

    start_datetime = forms.DateTimeField(
        widget=widgets.DateTimePickerInput(),
        label=_("Start date"), required=False)
    end_datetime = forms.DateTimeField(
        widget=widgets.DateTimePickerInput(),
        label=_("End date"), required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['start_datetime'].initial = timezone.now()

    class Meta:
        model = ConditionalOffer
        fields = ('start_datetime', 'end_datetime',
                  'max_basket_applications', 'max_user_applications',
                  'max_global_applications', 'max_discount',
                  'priority', 'exclusive', 'combinations')

    def clean(self):
        cleaned_data = super().clean()
        start = cleaned_data['start_datetime']
        end = cleaned_data['end_datetime']
        if start and end and end < start:
            raise forms.ValidationError(_(
                "The end date must be after the start date"))
        exclusive = cleaned_data['exclusive']
        combinations = cleaned_data['combinations']
        if exclusive and combinations:
            raise forms.ValidationError(_('Exclusive offers cannot be combined'))
        return cleaned_data

    def save(self, *args, **kwargs):
        """Store the offer combinations.

        Also, and make sure the combinations are stored on the combine-able
        offers as well.
        """
        instance = super().save(*args, **kwargs)
        if instance.id:
            instance.combinations.clear()
            for offer in self.cleaned_data['combinations']:
                if offer != instance:
                    instance.combinations.add(offer)

            combined_offers = instance.combined_offers
            for offer in combined_offers:
                if offer == instance:
                    continue
                for otheroffer in combined_offers:
                    if offer == otheroffer:
                        continue
                    offer.combinations.add(otheroffer)
        return instance

class ConditionForm(forms.ModelForm):
    custom_condition = forms.ChoiceField(
        required=False,
        label=_("Custom condition"), choices=())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        custom_conditions = Condition.objects.all().exclude(
            proxy_class=None)
        if len(custom_conditions) > 0:
            # Initialise custom_condition field
            choices = [(c.id, str(c)) for c in custom_conditions]
            choices.insert(0, ('', ' --------- '))
            self.fields['custom_condition'].choices = choices
            condition = kwargs.get('instance')
            if condition:
                self.fields['custom_condition'].initial = condition.id
        else:
            # No custom conditions and so the type/range/value fields
            # are no longer optional
            for field in ('type', 'range', 'value'):
                self.fields[field].required = True

    class Meta:
        model = Condition
        fields = ['range', 'type', 'value']

    def clean(self):
        data = super().clean()

        # Check that either a condition has been entered or a custom condition
        # has been chosen
        if not any(data.values()):
            raise forms.ValidationError(
                _("Please either choose a range, type and value OR "
                  "select a custom condition"))

        if data['custom_condition']:
            if data.get('range') or data.get('type') or data.get('value'):
                raise forms.ValidationError(
                    _("No other options can be set if you are using a "
                      "custom condition"))
        elif not data.get('type'):
            raise forms.ValidationError(
                _("Please either choose a range, type and value OR "
                  "select a custom condition"))

        return data

    def save(self, *args, **kwargs):
        # We don't save a new model if a custom condition has been chosen,
        # we simply return the instance that has been chosen
        if self.cleaned_data['custom_condition']:
            return Condition.objects.get(
                id=self.cleaned_data['custom_condition'])
        return super().save(*args, **kwargs)

class BenefitForm(forms.ModelForm):
    custom_benefit = forms.ChoiceField(
        required=False,
        label=_("Custom incentive"), choices=())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        custom_benefits = Benefit.objects.all().exclude(
            proxy_class=None)
        if len(custom_benefits) > 0:
            # Initialise custom_benefit field
            choices = [(c.id, str(c)) for c in custom_benefits]
            choices.insert(0, ('', ' --------- '))
            self.fields['custom_benefit'].choices = choices
            benefit = kwargs.get('instance')
            if benefit:
                self.fields['custom_benefit'].initial = benefit.id
        else:
            # No custom benefit and so the type fields
            # are no longer optional
            self.fields['type'].required = True

    class Meta:
        model = Benefit
        fields = ['range', 'type', 'value', 'max_affected_items']

    def clean(self):
        data = super().clean()

        # Check that either a benefit has been entered or a custom benfit
        # has been chosen
        if not any(data.values()):
            raise forms.ValidationError(
                _("Please either choose a range, type and value OR "
                  "select a custom incentive"))

        if data['custom_benefit']:
            if data.get('range') or data.get('type') or data.get('value'):
                raise forms.ValidationError(
                    _("No other options can be set if you are using a "
                      "custom incentive"))
        elif not data.get('type'):
            raise forms.ValidationError(
                _("Please either choose a range, type and value OR "
                  "select a custom incentive"))

        return data

    def save(self, *args, **kwargs):
        # We don't save a new model if a custom benefit has been chosen,
        # we simply return the instance that has been chosen
        if self.cleaned_data['custom_benefit']:
            return Benefit.objects.get(
                id=self.cleaned_data['custom_benefit'])
        return super().save(*args, **kwargs)

class OfferSearchForm(forms.Form):
    name = forms.CharField(required=False, label=_("Offer name"))
    is_active = forms.NullBooleanField(required=False, label=_("Is active?"), widget=widgets.NullBooleanSelect)
    offer_type = forms.ChoiceField(required=False, label=_("Offer type"), choices=get_offer_type_choices)
    has_vouchers = forms.NullBooleanField(required=False, label=_("Has vouchers?"), widget=widgets.NullBooleanSelect)
    voucher_code = forms.CharField(required=False, label=_("Voucher code"))

    basic_fields = [
        'name',
        'is_active',
    ]

    @property
    def is_voucher_offer_type(self):
        return self.is_bound and (self.cleaned_data['offer_type'] == ConditionalOffer.VOUCHER)


text:
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider

class AngelListAccount(ProviderAccount):
    def get_profile_url(self):
        return self.account.extra_data.get('angellist_url')

    def get_avatar_url(self):
        return self.account.extra_data.get('image')

    def to_str(self):
        dflt = super(AngelListAccount, self).to_str()
        return self.account.extra_data.get('name', dflt)

class AngelListProvider(OAuth2Provider):
    id = 'angellist'
    name = 'AngelList'
    account_class = AngelListAccount

    def extract_uid(self, data):
        return str(data['id'])

    def extract_common_fields(self, data):
        return dict(email=data.get('email'),
                    username=data.get('angellist_url').split('/')[-1],
                    name=data.get('name'))

provider_classes = [AngelListProvider]


text:
import frappe

def execute():
	frappe.db.change_column_type("__Auth", column="password", type="TEXT")


text:
import * as express from 'express';

// Logger
import { log } from '../inc/log';

// Modules
import LabelsModules from '../modules/labels';

// Interfaces
import { RequestInterface } from '../routing-interfaces';

// Define router
const router: express.Router = express.Router();

router.get('/public/labels', async (req: RequestInterface, res: express.Response): Promise<void> => {
    const attributes = {
        siteId: req.siteId
    };

    const labelsModules = new LabelsModules();
    const labels = await labelsModules.getPublicLabels(attributes);

    // Passing session token to the user
    res.status(200).json({
        data: labels
    });
});

router.get('/labels', async (req: RequestInterface, res: express.Response): Promise<boolean> => {
    if (!req.isLogged) {
        res.status(401).json({ message: 'Authorization error' });

        return false;
    }

    const attributes = {
        siteId: req.siteId
    };

    const labelsModules = new LabelsModules();
    const labels = await labelsModules.getLabels(attributes);

    // Passing session token to the user
    res.status(200).json({
        data: labels
    });
});

router.get('/label/:id', async (req: RequestInterface, res: express.Response): Promise<boolean> => {
    if (!req.isLogged) {
        res.status(401).json({ message: 'Authorization error' });

        return false;
    }

    const attributes = {
        siteId: req.siteId,
        id: parseInt(req.params.id)
    };

    const labelsModules = new LabelsModules();
    const label = await labelsModules.getLabel(attributes);

    // Passing session token to the user
    res.status(200).json({
        data: label
    });
});

router.post('/label', async (req: RequestInterface, res: express.Response): Promise<boolean> => {
    if (!req.isLogged) {
        res.status(401).json({ message: 'Authorization error' });

        return false;
    }

    // Gathering attributes
    const attributes = {
        siteId: req.siteId,
        name: req.body.name.toString(),
        output: req.body.output.toString()
    };

    const labelsModules = new LabelsModules();
    // Trying to add label
    const label = await labelsModules.addLabel(attributes);

    // If there is an error, sending fields and message and logging error
    if (!label) {
        res.status(400).json({
            state: 'error',
            message: labelsModules.getMessage(),
            fields: labelsModules.getFields()
        });

        // Log fail
        await log({
            userId: req.user.id,
            module: 'labels',
            type: 'add',
            info: `Label creation failed <b>${labelsModules.getMessage()}</b>`
        });

        return false;
    }

    // Log success
    await log({
        userId: req.user.id,
        module: 'labels',
        type: 'add',
        info: `Label added <b>${attributes.name}</b>`
    });

    // Passing state
    res.status(200).json({
        state: 'success',
        message: 'Success! New label added.'
    });
});

router.put('/label', async (req: RequestInterface, res: express.Response): Promise<boolean> => {
    if (!req.isLogged) {
        res.status(401).json({ message: 'Authorization error' });

        return false;
    }

    // Gathering attributes
    const attributes = {
        siteId: req.siteId,
        id: parseInt(req.body.id),
        name: req.body.name.toString(),
        output: req.body.output.toString()
    };

    const labelsModules = new LabelsModules();
    // Trying to update label
    const label = await labelsModules.editLabel(attributes);

    // If there is an error, sending fields and message and logging error
    if (!label) {
        res.status(400).json({
            state: 'error',
            message: labelsModules.getMessage(),
            fields: labelsModules.getFields()
        });

        // Log fail
        await log({
            userId: req.user.id,
            module: 'labels',
            type: 'edit',
            info: `Label update failed <b>${labelsModules.getMessage()}</b>`
        });

        return false;
    }

    // Log success
    await log({
        userId: req.user.id,
        module: 'labels',
        type: 'edit',
        info: `Label updated <b>${attributes.name}</b>`
    });

    // Passing state
    res.status(200).json({
        state: 'success',
        message: 'Label updated.'
    });
});

router.delete('/label/:id', async (req: RequestInterface, res: express.Response): Promise<boolean> => {
    if (!req.isLogged) {
        res.status(401).json({ message: 'Authorization error' });

        return false;
    }

    const attributes = {
        id: parseInt(req.params.id)
    };

    const labelsModules = new LabelsModules();
    // Trying to delete label
    const label = await labelsModules.deleteLabel(attributes.id);

    // If there is an error, sending fields and message and logging error
    if (!label) {
        res.status(400).json({
            state: 'error',
            message: labelsModules.getMessage()
        });

        // Log fail
        await log({
            userId: req.user.id,
            module: 'labels',
            type: 'delete',
            info: `Label removal failed [<b>${attributes.id}</b>] <b>${labelsModules.getMessage()}</b>`
        });

        return false;
    }

    // Log success
    await log({
        userId: req.user.id,
        module: 'labels',
        type: 'delete',
        info: `Label removed [<b>${attributes.id}</b>]`
    });

    // Passing state
    res.status(200).json({
        state: 'success',
        message: 'Label removed'
    });
});

export default router;


text:
package hu.petabyte.redflags.engine.gear;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import hu.petabyte.redflags.engine.model.Notice;
import hu.petabyte.redflags.engine.model.NoticeID;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Zsolt Jurányi
 */
public class GearTrain implements Callable<Void> {

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

	private Notice notice;
	private final List<? extends AbstractGear> gears;

	public GearTrain(Notice notice, List<? extends AbstractGear> gears) {
		this.notice = checkNotNull(notice, "notice should not be null.");
		this.gears = checkNotNull(gears, "gears should not be null.");
		checkArgument(!gears.isEmpty(), "gears should not be empty.");
	}

	@Override
	public Void call() throws Exception {
		LOG.info("Processing notice {} (HEAP: {}M)", notice.getId(), Runtime
				.getRuntime().totalMemory() / 1024 / 1024);
		for (Iterator<? extends AbstractGear> iterator = gears.iterator(); iterator
				.hasNext() && null != notice;) {
			AbstractGear gear = iterator.next();
			LOG.trace("Notice {} is at gear {}", notice.getId(), gear
					.getClass().getSimpleName());
			NoticeID id = notice.getId();
			try {
				notice = gear.process(notice);
			} catch (Exception e) {
				String s = String.format(
						"%s gear on notice %s threw exception: %s: %s", gear
								.getClass().getSimpleName(), id.toString(), e
								.getClass().getSimpleName(), e.getMessage());
				LOG.debug(s);
				LOG.trace(s, e);
			}
			if (null == notice) {
				LOG.debug("Notice {} dropped by {}", id, gear.getClass()
						.getSimpleName());
			}
		}
		if (null != notice) {
			LOG.debug("Processing of notice {} finished", notice.getId());
		}
		return null;
	}

	public List<? extends AbstractGear> getGears() {
		return gears;
	}

	public Notice getNotice() {
		return notice;
	}

}


text:
using CsvHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using jaytwo.Common.Extensions;
using jaytwo.Common;

namespace jaytwo.TimeZones.CodeGen.GeoNames
{
	public static class GeoNamesCountryParser
	{
        // http://download.geonames.org/export/dump/countryInfo.txt
        // download and paste contents into countryInfo.txt emvedded resource

        public static IList<GeoNamesCountry> GetGeoNamesCountries()
        {
            var rawData = EmbeddedResourceUtility.GetEmbeddedResourceAsString(
                typeof(GeoNamesCountryParser).Assembly,
				"jaytwo.TimeZones.CodeGen.GeoNames.countryInfo.txt");

            return GetGeoNamesCountriesFromCsvData(rawData);
        }

        private static IList<GeoNamesCountry> GetGeoNamesCountriesFromCsvData(string csvData)
		{
			using (var reader = new StringReader(csvData))
			{
				return GetGeoNamesCountriesFromCsvData(reader).ToList();
			}
		}

        private static IEnumerable<GeoNamesCountry> GetGeoNamesCountriesFromCsvData(TextReader reader)
		{
			using (var parser = new CsvParser(reader))
			{
				parser.Configuration.Comment = '#';
				parser.Configuration.Delimiter = "\t";

				string[] csvValues;
				while ((csvValues = parser.Read()) != null)
				{
                    yield return FromCsvValues(csvValues);
				}
			}
		}

		private static GeoNamesCountry FromCsvValues(string[] csvValues)
		{
           var result = new GeoNamesCountry();
			result.ISO = csvValues[GeoNamesCountryColumnIndexes.ISO];
			result.ISO3 = csvValues[GeoNamesCountryColumnIndexes.ISO3];
			result.ISO_Numeric = csvValues[GeoNamesCountryColumnIndexes.ISO_Numeric];
			result.fips = csvValues[GeoNamesCountryColumnIndexes.fips];
			result.Country = csvValues[GeoNamesCountryColumnIndexes.Country];
			result.Capital = csvValues[GeoNamesCountryColumnIndexes.Capital];
			result.Area_in_sq_km = csvValues[GeoNamesCountryColumnIndexes.Area_in_sq_km];
			result.Population = csvValues[GeoNamesCountryColumnIndexes.Population];
			result.Continent = csvValues[GeoNamesCountryColumnIndexes.Continent];
			result.tld = csvValues[GeoNamesCountryColumnIndexes.tld];
			result.CurrencyCode = csvValues[GeoNamesCountryColumnIndexes.CurrencyCode];
			result.CurrencyName = csvValues[GeoNamesCountryColumnIndexes.CurrencyName];
			result.Phone = csvValues[GeoNamesCountryColumnIndexes.Phone];
			result.Postal_Code_Format = csvValues[GeoNamesCountryColumnIndexes.Postal_Code_Format];
			result.Postal_Code_Regex = csvValues[GeoNamesCountryColumnIndexes.Postal_Code_Regex];
			result.Languages = csvValues[GeoNamesCountryColumnIndexes.Languages];
			result.geonameid = csvValues[GeoNamesCountryColumnIndexes.geonameid];
			result.neighbours = csvValues[GeoNamesCountryColumnIndexes.neighbours];
			result.EquivalentFipsCode = csvValues[GeoNamesCountryColumnIndexes.EquivalentFipsCode];

			return result;
		}
	}

}