text:
package org.kie.workbench.common.widgets.decoratedgrid.data;

import org.junit.Test;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.CellValue;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.data.Coordinate;

import static junit.framework.Assert.assertEquals;

/**
 * Tests for DynamicData
 */
public class DynamicDataTestsWithoutMergingRowAdditions extends BaseDynamicDataTests {

    @Test
    public void testIndexing_DataCoordinates() {

        Coordinate c;
        c = data.get( 0 ).get( 0 ).getCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 0 ).get( 1 ).getCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 0 ).get( 2 ).getCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 1 ).get( 0 ).getCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 1 ).get( 1 ).getCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 1 ).get( 2 ).getCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 2 ).get( 0 ).getCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 2 ).get( 1 ).getCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 2 ).get( 2 ).getCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      2 );

        data.addRow( 1,
                     makeRow() );
        assertEquals( data.size(),
                      4 );

        c = data.get( 0 ).get( 0 ).getCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 0 ).get( 1 ).getCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 0 ).get( 2 ).getCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 1 ).get( 0 ).getCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 1 ).get( 1 ).getCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 1 ).get( 2 ).getCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 2 ).get( 0 ).getCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 2 ).get( 1 ).getCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 2 ).get( 2 ).getCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 3 ).get( 0 ).getCoordinate();
        assertEquals( c.getRow(),
                      3 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 3 ).get( 1 ).getCoordinate();
        assertEquals( c.getRow(),
                      3 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 3 ).get( 2 ).getCoordinate();
        assertEquals( c.getRow(),
                      3 );
        assertEquals( c.getCol(),
                      2 );

    }

    @Test
    public void testIndexing_HtmlCoordinates() {

        Coordinate c;
        c = data.get( 0 ).get( 0 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 0 ).get( 1 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 0 ).get( 2 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 1 ).get( 0 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 1 ).get( 1 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 1 ).get( 2 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 2 ).get( 0 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 2 ).get( 1 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 2 ).get( 2 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      2 );

        data.addRow( 1,
                     makeRow() );
        assertEquals( data.size(),
                      4 );

        c = data.get( 0 ).get( 0 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 0 ).get( 1 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 0 ).get( 2 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 1 ).get( 0 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 1 ).get( 1 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 1 ).get( 2 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 2 ).get( 0 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 2 ).get( 1 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 2 ).get( 2 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 3 ).get( 0 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      3 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 3 ).get( 1 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      3 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 3 ).get( 2 ).getHtmlCoordinate();
        assertEquals( c.getRow(),
                      3 );
        assertEquals( c.getCol(),
                      2 );

    }

    @Test
    public void testIndexing_PhysicalCoordinates() {

        Coordinate c;
        c = data.get( 0 ).get( 0 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 0 ).get( 1 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 0 ).get( 2 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 1 ).get( 0 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 1 ).get( 1 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 1 ).get( 2 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 2 ).get( 0 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 2 ).get( 1 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 2 ).get( 2 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      2 );

        data.addRow( 1,
                     makeRow() );
        assertEquals( data.size(),
                      4 );

        c = data.get( 0 ).get( 0 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 0 ).get( 1 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 0 ).get( 2 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      0 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 1 ).get( 0 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 1 ).get( 1 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 1 ).get( 2 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      1 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 2 ).get( 0 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 2 ).get( 1 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 2 ).get( 2 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      2 );
        assertEquals( c.getCol(),
                      2 );

        c = data.get( 3 ).get( 0 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      3 );
        assertEquals( c.getCol(),
                      0 );
        c = data.get( 3 ).get( 1 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      3 );
        assertEquals( c.getCol(),
                      1 );
        c = data.get( 3 ).get( 2 ).getPhysicalCoordinate();
        assertEquals( c.getRow(),
                      3 );
        assertEquals( c.getCol(),
                      2 );
    }

    @Test
    public void testIndexing_RowSpans() {

        CellValue<? extends Comparable<?>> cv;
        cv = data.get( 0 ).get( 0 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 0 ).get( 1 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 0 ).get( 2 );
        assertEquals( cv.getRowSpan(),
                      1 );

        cv = data.get( 1 ).get( 0 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 1 ).get( 1 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 1 ).get( 2 );
        assertEquals( cv.getRowSpan(),
                      1 );

        cv = data.get( 2 ).get( 0 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 2 ).get( 1 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 2 ).get( 2 );
        assertEquals( cv.getRowSpan(),
                      1 );

        data.addRow( 1,
                     makeRow() );
        assertEquals( data.size(),
                      4 );

        cv = data.get( 0 ).get( 0 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 0 ).get( 1 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 0 ).get( 2 );
        assertEquals( cv.getRowSpan(),
                      1 );

        cv = data.get( 1 ).get( 0 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 1 ).get( 1 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 1 ).get( 2 );
        assertEquals( cv.getRowSpan(),
                      1 );

        cv = data.get( 2 ).get( 0 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 2 ).get( 1 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 2 ).get( 2 );
        assertEquals( cv.getRowSpan(),
                      1 );

        cv = data.get( 3 ).get( 0 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 3 ).get( 1 );
        assertEquals( cv.getRowSpan(),
                      1 );
        cv = data.get( 3 ).get( 2 );
        assertEquals( cv.getRowSpan(),
                      1 );

    }

}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FluentValidation;
using FluentValidation.Results;
using NUnit.Framework;
using SharperArchitecture.Common.Internationalization;
using SharperArchitecture.Tests.Common;
using SharperArchitecture.Tests.Validation.Models;
using SharperArchitecture.Validation;

namespace SharperArchitecture.Tests.Validation
{
    [TestFixture]
    public class ValidationTests : BaseTest
    {
        public ValidationTests()
        {
            I18N.Initialize();
            TestAssemblies.Add(typeof(Validator<>).Assembly);
            TestAssemblies.Add(typeof(ValidationTests).Assembly);
        }

        [Test]
        public void ValidateWithBusinessRule()
        {
            TestModelBusinessRule.ValidateCount = 0;
            TestModelBusinessRule.ValidatBeforeValidationCount = 0;
            var validator = Container.GetInstance<IValidator<TestModel>>();

            for (var i = 0; i < 5; i++)
            {
                var model = new TestModel();
                var valResult = validator.Validate(model);
                Assert.IsTrue(valResult.IsValid);
                Assert.AreEqual(i + 1, TestModelBusinessRule.ValidateCount);
                Assert.AreEqual(i + 1, TestModelBusinessRule.CanValidateCount);
                Assert.AreEqual(i + 1, TestModelBusinessRule.ValidatBeforeValidationCount);
            }
        }

        [Test]
        public void ValidateNestedModelWithBusinessRule()
        {
            var valFuns = new List<Func<IValidator<Parent>, Parent, ValidationResult>>
            {
                (v, m) => v.Validate(m),
                (v, m) => v.Validate((object) m),
                (v, m) => v.Validate(new ValidationContext(m)),
                (v, m) => v.Validate(new ValidationContext<Parent>(m)),
                (v, m) => v.Validate(m, ruleSet: ValidationRuleSet.Default),
                (v, m) => v.Validate(m, ruleSets: new[] {ValidationRuleSet.Default})
            };

            foreach (var valFun in valFuns)
            {
                for (var i = 0; i < 5; i++)
                {
                    ParentBusinessRule.Clear();
                    ParentChildBusinessRule.Clear();
                    ParentChild2BusinessRule.Clear();
                    ChildSubChildBusinessRule.Clear();
                    ParentSubChildBusinessRule.Clear();
                    SubChildBusinessRule.Clear();

                    var validator = Container.GetInstance<IValidator<Parent>>();
                    var model = new Parent
                    {
                        Children = new List<Child>
                        {
                            new Child
                            {
                                Name = "Child",
                                Children = new List<SubChild>
                                {
                                    new SubChild {Name = "SubChild1"},
                                    new SubChild()
                                }
                            },
                            new Child
                            {
                                Children = new List<SubChild>
                                {
                                    new SubChild {Name = "SubChild1"}
                                }
                            }
                        }
                    };
                    var result = valFun(validator, model);

                    Assert.IsTrue(result.IsValid);

                    Assert.AreEqual(1, ParentBusinessRule.Instances.Count);
                    Assert.AreEqual(1, ParentBusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model, ParentBusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(1, ParentBusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model, ParentBusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(1, ParentBusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model, ParentBusinessRule.BeforeValidationModels[0].Item1);

                    Assert.AreEqual(1, ParentChildBusinessRule.Instances.Count);
                    Assert.AreEqual(2, ParentChildBusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model.Children[0], ParentChildBusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[1], ParentChildBusinessRule.ValidateModels[1].Item1);
                    Assert.AreEqual(2, ParentChildBusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model.Children[0], ParentChildBusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[1], ParentChildBusinessRule.CanValidateModels[1].Item1);
                    Assert.AreEqual(1, ParentChildBusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model, ParentChildBusinessRule.BeforeValidationModels[0].Item1);

                    Assert.AreEqual(1, ParentChild2BusinessRule.Instances.Count);
                    Assert.AreEqual(2, ParentChild2BusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model.Children[0], ParentChild2BusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[1], ParentChild2BusinessRule.ValidateModels[1].Item1);
                    Assert.AreEqual(2, ParentChild2BusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model.Children[0], ParentChild2BusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[1], ParentChild2BusinessRule.CanValidateModels[1].Item1);
                    Assert.AreEqual(1, ParentChild2BusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model, ParentChild2BusinessRule.BeforeValidationModels[0].Item1);

                    Assert.AreEqual(1, ParentSubChildBusinessRule.Instances.Count);
                    Assert.AreEqual(3, ParentSubChildBusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], ParentSubChildBusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], ParentSubChildBusinessRule.ValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], ParentSubChildBusinessRule.ValidateModels[2].Item1);
                    Assert.AreEqual(3, ParentSubChildBusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], ParentSubChildBusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], ParentSubChildBusinessRule.CanValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], ParentSubChildBusinessRule.CanValidateModels[2].Item1);
                    Assert.AreEqual(1, ParentSubChildBusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model, ParentSubChildBusinessRule.BeforeValidationModels[0].Item1);

                    Assert.AreEqual(2, ChildSubChildBusinessRule.Instances.Count);
                    Assert.AreEqual(3, ChildSubChildBusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], ChildSubChildBusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], ChildSubChildBusinessRule.ValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], ChildSubChildBusinessRule.ValidateModels[2].Item1);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[0], ChildSubChildBusinessRule.ValidateModels[0].Item2);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[0], ChildSubChildBusinessRule.ValidateModels[1].Item2);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[1], ChildSubChildBusinessRule.ValidateModels[2].Item2);
                    Assert.AreEqual(3, ChildSubChildBusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], ChildSubChildBusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], ChildSubChildBusinessRule.CanValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], ChildSubChildBusinessRule.CanValidateModels[2].Item1);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[0], ChildSubChildBusinessRule.CanValidateModels[0].Item2);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[0], ChildSubChildBusinessRule.CanValidateModels[1].Item2);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[1], ChildSubChildBusinessRule.CanValidateModels[2].Item2);
                    Assert.AreEqual(2, ChildSubChildBusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model.Children[0], ChildSubChildBusinessRule.BeforeValidationModels[0].Item1);
                    Assert.AreEqual(model.Children[1], ChildSubChildBusinessRule.BeforeValidationModels[1].Item1);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[0], ChildSubChildBusinessRule.BeforeValidationModels[0].Item2);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[1], ChildSubChildBusinessRule.BeforeValidationModels[1].Item2);

                    Assert.AreEqual(3, SubChildBusinessRule.Instances.Count);
                    Assert.AreEqual(3, SubChildBusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], SubChildBusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], SubChildBusinessRule.ValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], SubChildBusinessRule.ValidateModels[2].Item1);
                    Assert.AreEqual(SubChildBusinessRule.Instances[0], SubChildBusinessRule.ValidateModels[0].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[1], SubChildBusinessRule.ValidateModels[1].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[2], SubChildBusinessRule.ValidateModels[2].Item2);
                    Assert.AreEqual(3, SubChildBusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], SubChildBusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], SubChildBusinessRule.CanValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], SubChildBusinessRule.CanValidateModels[2].Item1);
                    Assert.AreEqual(SubChildBusinessRule.Instances[0], SubChildBusinessRule.CanValidateModels[0].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[1], SubChildBusinessRule.CanValidateModels[1].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[2], SubChildBusinessRule.CanValidateModels[2].Item2);
                    Assert.AreEqual(3, SubChildBusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], SubChildBusinessRule.BeforeValidationModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], SubChildBusinessRule.BeforeValidationModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], SubChildBusinessRule.BeforeValidationModels[2].Item1);
                    Assert.AreEqual(SubChildBusinessRule.Instances[0], SubChildBusinessRule.BeforeValidationModels[0].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[1], SubChildBusinessRule.BeforeValidationModels[1].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[2], SubChildBusinessRule.BeforeValidationModels[2].Item2);
                }
            }
        }

        [Test]
        public async Task ValidateNestedModelWithBusinessRuleAsync()
        {
            var valFuns = new List<Func<IValidator<Parent>, Parent, Task<ValidationResult>>>
            {
                (v, m) => v.ValidateAsync(m),
                (v, m) => v.ValidateAsync((object) m),
                (v, m) => v.ValidateAsync(new ValidationContext(m)),
                (v, m) => v.ValidateAsync(new ValidationContext<Parent>(m)),
                (v, m) => v.ValidateAsync(m, ruleSet: ValidationRuleSet.Default),
                (v, m) => v.ValidateAsync(m, ruleSets: new[] {ValidationRuleSet.Default})
            };

            foreach (var valFun in valFuns)
            {
                for (var i = 0; i < 5; i++)
                {
                    ParentBusinessRule.Clear();
                    ParentChildBusinessRule.Clear();
                    ParentChild2BusinessRule.Clear();
                    ChildSubChildBusinessRule.Clear();
                    ParentSubChildBusinessRule.Clear();
                    SubChildBusinessRule.Clear();

                    var validator = Container.GetInstance<IValidator<Parent>>();
                    var model = new Parent
                    {
                        Children = new List<Child>
                        {
                            new Child
                            {
                                Name = "Child",
                                Children = new List<SubChild>
                                {
                                    new SubChild {Name = "SubChild1"},
                                    new SubChild()
                                }
                            },
                            new Child
                            {
                                Children = new List<SubChild>
                                {
                                    new SubChild {Name = "SubChild1"}
                                }
                            }
                        }
                    };
                    var result = await valFun(validator, model);

                    Assert.IsTrue(result.IsValid);

                    Assert.AreEqual(1, ParentBusinessRule.Instances.Count);
                    Assert.AreEqual(1, ParentBusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model, ParentBusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(1, ParentBusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model, ParentBusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(1, ParentBusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model, ParentBusinessRule.BeforeValidationModels[0].Item1);

                    Assert.AreEqual(1, ParentChildBusinessRule.Instances.Count);
                    Assert.AreEqual(2, ParentChildBusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model.Children[0], ParentChildBusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[1], ParentChildBusinessRule.ValidateModels[1].Item1);
                    Assert.AreEqual(2, ParentChildBusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model.Children[0], ParentChildBusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[1], ParentChildBusinessRule.CanValidateModels[1].Item1);
                    Assert.AreEqual(1, ParentChildBusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model, ParentChildBusinessRule.BeforeValidationModels[0].Item1);

                    Assert.AreEqual(1, ParentChild2BusinessRule.Instances.Count);
                    Assert.AreEqual(2, ParentChild2BusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model.Children[0], ParentChild2BusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[1], ParentChild2BusinessRule.ValidateModels[1].Item1);
                    Assert.AreEqual(2, ParentChild2BusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model.Children[0], ParentChild2BusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[1], ParentChild2BusinessRule.CanValidateModels[1].Item1);
                    Assert.AreEqual(1, ParentChild2BusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model, ParentChild2BusinessRule.BeforeValidationModels[0].Item1);

                    Assert.AreEqual(1, ParentSubChildBusinessRule.Instances.Count);
                    Assert.AreEqual(3, ParentSubChildBusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], ParentSubChildBusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], ParentSubChildBusinessRule.ValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], ParentSubChildBusinessRule.ValidateModels[2].Item1);
                    Assert.AreEqual(3, ParentSubChildBusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], ParentSubChildBusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], ParentSubChildBusinessRule.CanValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], ParentSubChildBusinessRule.CanValidateModels[2].Item1);
                    Assert.AreEqual(1, ParentSubChildBusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model, ParentSubChildBusinessRule.BeforeValidationModels[0].Item1);

                    Assert.AreEqual(2, ChildSubChildBusinessRule.Instances.Count);
                    Assert.AreEqual(3, ChildSubChildBusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], ChildSubChildBusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], ChildSubChildBusinessRule.ValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], ChildSubChildBusinessRule.ValidateModels[2].Item1);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[0], ChildSubChildBusinessRule.ValidateModels[0].Item2);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[0], ChildSubChildBusinessRule.ValidateModels[1].Item2);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[1], ChildSubChildBusinessRule.ValidateModels[2].Item2);
                    Assert.AreEqual(3, ChildSubChildBusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], ChildSubChildBusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], ChildSubChildBusinessRule.CanValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], ChildSubChildBusinessRule.CanValidateModels[2].Item1);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[0], ChildSubChildBusinessRule.CanValidateModels[0].Item2);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[0], ChildSubChildBusinessRule.CanValidateModels[1].Item2);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[1], ChildSubChildBusinessRule.CanValidateModels[2].Item2);
                    Assert.AreEqual(2, ChildSubChildBusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model.Children[0], ChildSubChildBusinessRule.BeforeValidationModels[0].Item1);
                    Assert.AreEqual(model.Children[1], ChildSubChildBusinessRule.BeforeValidationModels[1].Item1);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[0], ChildSubChildBusinessRule.BeforeValidationModels[0].Item2);
                    Assert.AreEqual(ChildSubChildBusinessRule.Instances[1], ChildSubChildBusinessRule.BeforeValidationModels[1].Item2);

                    Assert.AreEqual(3, SubChildBusinessRule.Instances.Count);
                    Assert.AreEqual(3, SubChildBusinessRule.ValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], SubChildBusinessRule.ValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], SubChildBusinessRule.ValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], SubChildBusinessRule.ValidateModels[2].Item1);
                    Assert.AreEqual(SubChildBusinessRule.Instances[0], SubChildBusinessRule.ValidateModels[0].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[1], SubChildBusinessRule.ValidateModels[1].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[2], SubChildBusinessRule.ValidateModels[2].Item2);
                    Assert.AreEqual(3, SubChildBusinessRule.CanValidateModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], SubChildBusinessRule.CanValidateModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], SubChildBusinessRule.CanValidateModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], SubChildBusinessRule.CanValidateModels[2].Item1);
                    Assert.AreEqual(SubChildBusinessRule.Instances[0], SubChildBusinessRule.CanValidateModels[0].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[1], SubChildBusinessRule.CanValidateModels[1].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[2], SubChildBusinessRule.CanValidateModels[2].Item2);
                    Assert.AreEqual(3, SubChildBusinessRule.BeforeValidationModels.Count);
                    Assert.AreEqual(model.Children[0].Children[0], SubChildBusinessRule.BeforeValidationModels[0].Item1);
                    Assert.AreEqual(model.Children[0].Children[1], SubChildBusinessRule.BeforeValidationModels[1].Item1);
                    Assert.AreEqual(model.Children[1].Children[0], SubChildBusinessRule.BeforeValidationModels[2].Item1);
                    Assert.AreEqual(SubChildBusinessRule.Instances[0], SubChildBusinessRule.BeforeValidationModels[0].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[1], SubChildBusinessRule.BeforeValidationModels[1].Item2);
                    Assert.AreEqual(SubChildBusinessRule.Instances[2], SubChildBusinessRule.BeforeValidationModels[2].Item2);
                }
            }
        }

        [Test]
        public void GenericChildBusinessRuleShouldWork()
        {
            var child1 = new ConcreteGenericChildChild();
            var child2 = new ConcreteGenericChildChild2();
            var child3 = new ConcreteGenericChildChild {Name = "Test"};
            var child4 = new ConcreteGenericChildChild2();
            var model = new GenericChildParent
            {
                Children = new List<GenericChildChild>
                {
                    child1,
                    child2,
                    child3
                },
                Relation = child4
            };
            var validator = Container.GetInstance<IValidator<GenericChildParent>>();

            var valResult = validator.Validate(model);
            Assert.IsFalse(valResult.IsValid);
            Assert.AreEqual(3, valResult.Errors.Count);
            Assert.AreEqual(valResult.Errors[0].ErrorMessage, "Name should not be empty");
            Assert.AreEqual(valResult.Errors[0].PropertyName, "Children[0]");
            Assert.AreEqual(valResult.Errors[0].AttemptedValue, child1);
            Assert.AreEqual(valResult.Errors[1].ErrorMessage, "Name should not be empty");
            Assert.AreEqual(valResult.Errors[1].PropertyName, "Children[1]");
            Assert.AreEqual(valResult.Errors[1].AttemptedValue, child2);
            Assert.AreEqual(valResult.Errors[2].ErrorMessage, "Name should not be empty");
            Assert.AreEqual(valResult.Errors[2].PropertyName, "Relation");
            Assert.AreEqual(valResult.Errors[2].AttemptedValue, child4);

            var childValidator = Container.GetInstance<IValidator<GenericChildChild>>();
            valResult = childValidator.Validate(child1);
            Assert.IsTrue(valResult.IsValid);
        }

        [Test]
        public void GenericRootChildBusinessRuleShouldWork()
        {
            var child1 = new ConcreteGenericRootChildChild();
            var child2 = new ConcreteGenericRootChildChild2();
            var child3 = new ConcreteGenericRootChildChild { Name = "Test" };
            var child4 = new ConcreteGenericRootChildChild2();
            var model = new GenericRootChildParent
            {
                Children = new List<GenericRootChildChild>
                {
                    child1,
                    child2,
                    child3
                },
                Relation = child4
            };
            var validator = Container.GetInstance<IValidator<GenericRootChildParent>>();

            var valResult = validator.Validate(model);
            Assert.IsFalse(valResult.IsValid);
            Assert.AreEqual(3, valResult.Errors.Count);
            Assert.AreEqual(valResult.Errors[0].ErrorMessage, "Name should not be empty");
            Assert.AreEqual(valResult.Errors[0].PropertyName, "Children[0]");
            Assert.AreEqual(valResult.Errors[0].AttemptedValue, child1);
            Assert.AreEqual(valResult.Errors[1].ErrorMessage, "Name should not be empty");
            Assert.AreEqual(valResult.Errors[1].PropertyName, "Children[1]");
            Assert.AreEqual(valResult.Errors[1].AttemptedValue, child2);
            Assert.AreEqual(valResult.Errors[2].ErrorMessage, "Name should not be empty");
            Assert.AreEqual(valResult.Errors[2].PropertyName, "Relation");
            Assert.AreEqual(valResult.Errors[2].AttemptedValue, child4);

            var childValidator = Container.GetInstance<IValidator<GenericRootChildChild>>();
            valResult = childValidator.Validate(child1);
            Assert.IsTrue(valResult.IsValid);
        }

        [Test]
        public void GenericRootBusinessRuleShouldWork()
        {
            var child1 = new GenericRootModel();
            var child2 = new GenericRootModel();
            var child3 = new GenericRootModel { Name = "Test" };
            var child4 = new GenericRootModel();
            var model = new GenericRootModel
            {
                Children = new List<GenericRootModel>
                {
                    child1,
                    child2,
                    child3
                },
                Relation = child4
            };
            var validator = Container.GetInstance<IValidator<GenericRootModel>>();

            var valResult = validator.Validate(model);
            Assert.IsFalse(valResult.IsValid);
            Assert.AreEqual(4, valResult.Errors.Count);
            Assert.AreEqual(valResult.Errors[0].ErrorMessage, "Name should not be empty");
            Assert.AreEqual(valResult.Errors[0].PropertyName, "Children[0]");
            Assert.AreEqual(valResult.Errors[0].AttemptedValue, child1);
            Assert.AreEqual(valResult.Errors[1].ErrorMessage, "Name should not be empty");
            Assert.AreEqual(valResult.Errors[1].PropertyName, "Children[1]");
            Assert.AreEqual(valResult.Errors[1].AttemptedValue, child2);
            Assert.AreEqual(valResult.Errors[2].ErrorMessage, "Name should not be empty");
            Assert.AreEqual(valResult.Errors[2].PropertyName, "Relation");
            Assert.AreEqual(valResult.Errors[2].AttemptedValue, child4);
            Assert.AreEqual(valResult.Errors[3].ErrorMessage, "Name should not be empty");
            Assert.AreEqual(valResult.Errors[3].PropertyName, "");
            Assert.AreEqual(valResult.Errors[3].AttemptedValue, model);

            var childValidator = Container.GetInstance<IValidator<GenericRootModel>>();
            valResult = childValidator.Validate(child1);
            Assert.IsFalse(valResult.IsValid);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text: Apicacion web de ingles activo


text:
"""
jsonq.core

Contains the core processing functions.

"""

from .utils import isArr, isDict
from itertools import imap
from operator import itemgetter
import string
import re

__all__ = ('jsonq')
_orderfn = ('filter',
            'sort',
            'min',
            'max',
            'decr',
            'incr',
            'select')
_min = min
_max = max
operators = {'<' : -1,
             '==' : 0,
             '>' : 1}
parseOpRe = re.compile(r'(<|==|>)')

def _(_str):
    """Remove the white space."""
    return ''.join(_str.strip().split())

def select(iterable, args):
    if len(args) == 1:
        for obj in iterable:
            yield obj[args[0]]
    else:
        for obj in iterable:
             yield [v for k, v in obj.iteritems() if k in args]

def filter(iterable, args):
    _it = iterable
    parse_op = imap(parseOpRe.split, imap(_, args))
    for (k, op, v) in parse_op:
        op_cmp = operators[op]
        v = int(v)
        _it = (obj for obj in _it if obj[k].__cmp__(v) == op_cmp)
    return _it

def sort(iterable, key):
    return iter(sorted(iterable, key=itemgetter(key)))

def min(iterable, key):
    yield _min(iterable, key=itemgetter(key))

def max(iterable, key):
    yield _max(iterable, key=itemgetter(key))

def decr(iterable, args):
    for obj in iterable:
        for k in args:
            obj[k] -= 1
        yield obj

def incr(iterable, args):
    for obj in iterable:
        for k in args:
            obj[k] += 1
        yield obj

def jsonq(json_obj, options):
    functions = globals()
    # get an ordered chain of functions to be processed
    chain = [(functions[fn], options[fn]) for fn in _orderfn if fn in options]
    _it = json_obj
    if isDict(_it):
        _it = [_it]
    for fn, args in chain:
        _it = fn(_it, args)
    return _it


text:
/**
 * Created by adelmo.pereira on 11/11/2016.
 */
(function() {
    'use strict';

    angular
        .module('pandora')
        .factory('stateHandler', stateHandler);

    stateHandler.$inject = ['$rootScope', '$state', '$window', 'Auth', 'Principal'];

    function stateHandler($rootScope, $state,  $window,
                          Auth, Principal) {
        return {
            initialize: initialize
        };

        function initialize() {
            var stateChangeStart = $rootScope.$on('$stateChangeStart', function (event, toState, toStateParams, fromState) {
                $rootScope.toState = toState;
                $rootScope.toStateParams = toStateParams;
                $rootScope.fromState = fromState;

                if (toState.external) {
                    event.preventDefault();
                    $window.open(toState.url, '_self');
                }

                Auth.authorize(true);
            });

            var stateChangeSuccess = $rootScope.$on('$stateChangeSuccess',  function(event, toState, toParams, fromState, fromParams) {
                var titleKey = 'atacama' ;

                // Set the page title key to the one configured in state or use default one
                if (toState.data != null && toState.data.pageTitle) {
                    titleKey = toState.data.pageTitle;
                }
                $window.document.title =  $window.document.title + ' - ' + titleKey;
            });

            $rootScope.$on('$destroy', function () {
                if(angular.isDefined(stateChangeStart) && stateChangeStart !== null){
                    stateChangeStart();
                }
                if(angular.isDefined(stateChangeSuccess) && stateChangeSuccess !== null){
                    stateChangeSuccess();
                }
            });
        }
    }
})();


text:
@class YR_ArtCircleListModel,YR_ArtCircleOutUserModel,YR_ArtCircleLikedModel,YR_ArtCircleInUserModel,YR_ArtCirclePicsModel;

@interface YR_ArtCircleModel : YR_BaseModel

@property (nonatomic, strong) NSNumber *code;

@property (nonatomic, strong) NSArray<YR_ArtCircleListModel *> *list;

@property (nonatomic, strong) NSNumber *last_id;

@property (nonatomic, copy) NSString *time;

@end


text:
#include "dart/collision/fcl/FCLCollisionObject.hpp"

#include <fcl/BVH/BVH_model.h>

#include "dart/collision/fcl/FCLTypes.hpp"
#include "dart/dynamics/SoftMeshShape.hpp"
#include "dart/dynamics/ShapeFrame.hpp"

namespace dart {
namespace collision {

//==============================================================================
FCLCollisionObject::UserData::UserData(CollisionObject* collisionObject)
  : mCollisionObject(collisionObject)
{
  // Do nothing
}

//==============================================================================
fcl::CollisionObject* FCLCollisionObject::getFCLCollisionObject()
{
  return mFCLCollisionObject.get();
}

//==============================================================================
const fcl::CollisionObject* FCLCollisionObject::getFCLCollisionObject() const
{
  return mFCLCollisionObject.get();
}

//==============================================================================
FCLCollisionObject::FCLCollisionObject(
    CollisionDetector* collisionDetector,
    const dynamics::ShapeFrame* shapeFrame,
    const fcl_shared_ptr<fcl::CollisionGeometry>& fclCollGeom)
  : CollisionObject(collisionDetector, shapeFrame),
    mFCLCollisionObjectUserData(new UserData(this)),
    mFCLCollisionObject(new fcl::CollisionObject(fclCollGeom))
{
  mFCLCollisionObject->setUserData(mFCLCollisionObjectUserData.get());
}

//==============================================================================
void FCLCollisionObject::updateEngineData()
{
  using dart::dynamics::BodyNode;
  using dart::dynamics::Shape;
  using dart::dynamics::SoftMeshShape;

  auto shape = mShapeFrame->getShape().get();

  // Update soft-body's vertices
  if (shape->getType() == dynamics::SoftMeshShape::getStaticType())
  {
    assert(dynamic_cast<const SoftMeshShape*>(shape));
    auto softMeshShape = static_cast<const SoftMeshShape*>(shape);

    const aiMesh* mesh = softMeshShape->getAssimpMesh();
    const_cast<SoftMeshShape*>(softMeshShape)->update();
    // TODO(JS): update function be called by somewhere out of here.

#if FCL_VERSION_AT_LEAST(0,3,0)
    auto collGeom = const_cast<fcl::CollisionGeometry*>(
          mFCLCollisionObject->collisionGeometry().get());
#else
    fcl::CollisionGeometry* collGeom
        = const_cast<fcl::CollisionGeometry*>(
          mFCLCollisionObject->getCollisionGeometry());
#endif
    assert(dynamic_cast<fcl::BVHModel<fcl::OBBRSS>*>(collGeom));
    auto bvhModel = static_cast<fcl::BVHModel<fcl::OBBRSS>*>(collGeom);

    bvhModel->beginUpdateModel();
    for (auto i = 0u; i < mesh->mNumFaces; ++i)
    {
      fcl::Vec3f vertices[3];
      for (auto j = 0u; j < 3; ++j)
      {
        const auto& vertex = mesh->mVertices[mesh->mFaces[i].mIndices[j]];
        vertices[j] = fcl::Vec3f(vertex.x, vertex.y, vertex.z);
      }
      bvhModel->updateTriangle(vertices[0], vertices[1], vertices[2]);
    }
    bvhModel->endUpdateModel();
  }

  mFCLCollisionObject->setTransform(FCLTypes::convertTransform(getTransform()));
  mFCLCollisionObject->computeAABB();
}

}  // namespace collision
}  // namespace dart


text:
<?php

namespace AlexeyKuperhstokh\LocationBundle;

use AlexeyKuperhstokh\LocationBundle\DependencyInjection\LocationBundleExtension;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class LocationBundle extends Bundle
{
    public function getContainerExtension()
    {
        return new LocationBundleExtension();
    }
}


text:
import json

import pytest

from indy import did, error

@pytest.mark.asyncio
async def test_replace_keys_start_works(wallet_handle):
    (_did, ver_key) = await did.create_and_store_my_did(wallet_handle, "{}")
    new_ver_key = await did.replace_keys_start(wallet_handle, _did, "{}")
    assert new_ver_key != _did

@pytest.mark.asyncio
async def test_replace_keys_start_works_for_seed(wallet_handle, seed_my1, verkey_my1):
    (_did, ver_key) = await did.create_and_store_my_did(wallet_handle, "{}")
    new_ver_key = await did.replace_keys_start(wallet_handle, _did, json.dumps({'seed': seed_my1}))
    assert new_ver_key != _did
    assert verkey_my1 == new_ver_key

@pytest.mark.asyncio
async def test_replace_keys_start_works_for_not_exists_did(wallet_handle, did_my1):
    with pytest.raises(error.WalletItemNotFound):
        await did.replace_keys_start(wallet_handle, did_my1, "{}")


text:
package webhook

import (
	admissionregistration "k8s.io/api/admissionregistration/v1"
	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

type WebhookConfig struct {
	Type          webhookType
	Name          string
	Path          string
	Handler       admission.Handler
	FailurePolicy admissionregistration.FailurePolicyType
	Rules         []admissionregistration.RuleWithOperations
	SideEffects   admissionregistration.SideEffectClass
}

type webhookType string

const (
	Mutating   webhookType = "Mutating"
	Validating webhookType = "Validating"
)


text:
package org.wso2.carbon.identity.user.endpoint;

import org.wso2.carbon.identity.user.endpoint.*;
import org.wso2.carbon.identity.user.endpoint.dto.*;

import org.wso2.carbon.identity.user.endpoint.dto.ExportedUserDTO;
import org.wso2.carbon.identity.user.endpoint.dto.SelfUserRegistrationRequestDTO;
import org.wso2.carbon.identity.user.endpoint.dto.SuccessfulUserCreationDTO;
import org.wso2.carbon.identity.user.endpoint.dto.ErrorDTO;

import java.util.List;

import java.io.InputStream;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;

import javax.ws.rs.core.Response;

public abstract class MeApiService {
    public abstract Response getMe();
    public abstract Response mePost(SelfUserRegistrationRequestDTO user);
}


text:
import argparse
import codecs
import datetime
import json
import logging
import os.path
import subprocess
import tempfile

import inseven.finance

PDF_TABLE_COLUMNS = ["Date", "Payment ", "type ", "and ", "details", "Paid ", "out", "Paid ", "in", "Balance"]
PDF_TABLE_START = ["BALANCE ", "BROUGHT ", "FORWARD"]
PDF_TABLE_END = ["BALANCE ", "CARRIED ", "FORWARD"]
PDF_POSITION_THRESHOLD = 20

def pdf2json(path):
    with tempfile.NamedTemporaryFile(delete=False) as temp:
        subprocess.check_output(["/usr/local/bin/pdf2json", path, temp.name])
        with codecs.open(temp.name, "r", "ISO-8859-1") as f:
            return json.loads(f.read())

def line_matches_offset(line, strings, offset):
    try:
        for i, data in enumerate(strings):
            if line[i + offset]["data"] != data:
                return False
    except IndexError:
        return False
    return True

def line_matches(line, strings):
    if len(line) < len(strings):
        return False
    else:
        for i in xrange(0, len(line) - len(strings) + 1):
            if line_matches_offset(line, strings, i):
                return True
    return False

def lines_between(lines, start, end):
    result = []
    active = False
    for line in lines:
        if line_matches(line, start):
            active = True
            result.append(line)
        elif line_matches(line, end):
            active = False
        else:
            if active:
                result.append(line)
    return result

def format_number(text):
    return float(text.replace(",", ""))

def parse_page(page, date=None):
    nodes = sorted(page["text"], key=lambda x: x["top"])

    # Group the individual nodes into lines.
    lines = []
    top = 0
    line = []
    for node in nodes:
        if node["top"] != top:
            line = []
            lines.append(line)
            top = node["top"]
        line.append(node)

    # Determine the column offsets.
    details = None
    for line in lines:
        if line_matches(line, PDF_TABLE_COLUMNS):
                details = [line[0]["left"], line[1]["left"], line[5]["left"], line[7]["left"], line[9]["left"]]

    # Filter out the lines we're interested in.
    statements = lines_between(lines, PDF_TABLE_START, PDF_TABLE_END)

    record = None
    results = []
    for line in statements:

        # Check to see if the row has changed.
        line = sorted(line, key=lambda x: x["left"])
        if line[0]["left"] == details[0] or line[0]["left"] == details[1] or record is None:
            record = inseven.finance.Record()
            results.append(record)

        # Process nodes for the current row.
        for node in line:
            logging.debug(line)
            left = node["left"]
            data = node["data"]
            if left >= details[4] - PDF_POSITION_THRESHOLD:
                logging.debug("Parsing '%s'..." % data)
                if data == "D":
                    record.balance = -1 * record.balance
                else:
                    record.balance = format_number(data)
            elif left >= details[3] - PDF_POSITION_THRESHOLD:
                # Paid in.
                record.value = format_number(data)
            elif left >= details[2] - PDF_POSITION_THRESHOLD:
                # Paid out.
                record.value = (format_number(data) * -1)
            elif left >= details[1]:
                record.description = (record.description + " " + data).strip()
            elif left > details[0]:
                date = (date + " " + data).strip()
            elif left == details[0]:
                date = data.strip()

            # Keep attempting to parse the date until we have a valid date.
            try:
                record.date = datetime.datetime.strptime(date, "%d %b %y")
            except ValueError:
                pass

    if not len(results):
        return (results, date, None)

    # Check and retrieve the starting balance.
    balance = results.pop(0)
    assert balance.description == "BALANCE BROUGHT FORWARD", "Unable to determine starting balance."

    return (results, date, balance.balance)

def parse_pdf(path):

    contents = pdf2json(path)

    results = []
    date = None
    starting_balance = None
    for page in contents:
        (records, date, balance) = parse_page(page, date)
        if starting_balance is None:
            starting_balance = balance
        results.extend(records)

    total = starting_balance
    for result in results:
        logging.debug("%s", result)
        total = total + result.value
        if result.balance is not None:
            assert abs(total - result.balance) < 0.0001, "Unable to reconcile balances"

    return results


text:
from django.conf.urls import url, include
from rest_framework import routers
from task_manager.task_manager import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'employees', views.EmployeeViewSet)
router.register(r'projects', views.ProjectViewSet)
router.register(r'tasks', views.TaskViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]


text:
package io.redlink.smarti.services;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Locale;

/**
 */
@Service
public class SpeakService {

    @Value("${message.locale:de_DE}")
    private Locale messageLocale = Locale.GERMANY;

    @Value("${message.source:#{null}}")
    private String externalResourceBundle = null;

    private ReloadableResourceBundleMessageSource messageSource;

    @PostConstruct
    protected void initMessageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages/conversation");
        messageSource.setDefaultEncoding("utf-8");
        messageSource.setCacheSeconds(3600);

        if (externalResourceBundle != null) {
            ReloadableResourceBundleMessageSource external = new ReloadableResourceBundleMessageSource();
            external.setBasename(externalResourceBundle);
            external.setDefaultEncoding("utf-8");
            external.setCacheSeconds(500);
            external.setParentMessageSource(messageSource);

            this.messageSource = external;
        } else {
            this.messageSource = messageSource;
        }
    }

    public String getMessage(String code, String defaultMessage) {
        return messageSource.getMessage(code, null, defaultMessage, messageLocale);
    }

    public String getMessage(String code, String defaultMessage, Object... args) {
        return messageSource.getMessage(code, args, defaultMessage, messageLocale);
    }

    public String getMessage(String code) throws NoSuchMessageException {
        return messageSource.getMessage(code, null, messageLocale);
    }

    public String getMessage(String code, Object... args) throws NoSuchMessageException {
        return messageSource.getMessage(code, args, messageLocale);
    }

    public String getMessage(MessageSourceResolvable resolvable) throws NoSuchMessageException {
        return messageSource.getMessage(resolvable, messageLocale);
    }
}


text:
module Imagery
  module Missing
    # Allows you to set the current filename of your photo.
    # Much of Imagery::Missing is hinged on this.
    #
    # @example
    #
    #   Photo = Class.new(Struct.new(:id))
    #   i = Imagery::Model.new(Photo.new(1001))
    #   i.extend Imagery::Missing
    #   i.url == "/photo/1001/original.png"
    #   # => true
    #
    #   i.existing = "Filename"
    #   i.url == "/missing/photo/original.png"
    #   # => true
    #
    # @see Imagery::Missing#url
    #
    attr_accessor :existing

    def url(size = self.default_size)
      if existing.to_s.empty?
        return ['', 'missing', namespace, filename(size)].join('/')
      else
        super
      end
    end
  end
end


text:
<resources>
    <!-- 1/2 Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">8dp</dimen>
    <dimen name="activity_vertical_margin">8dp</dimen>
    <dimen name="output_text_size">16sp</dimen>
</resources>


text:
package kubernetes

import (
	"context"
	"fmt"

	"github.com/go-kit/kit/log"
	"github.com/pkg/errors"
	"github.com/ryanuber/go-glob"
	apiv1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"github.com/fluxcd/flux/pkg/image"
	"github.com/fluxcd/flux/pkg/registry"
	"github.com/fluxcd/flux/pkg/resource"
)

func mergeCredentials(log func(...interface{}) error,
	includeImage func(imageName string) bool,
	client ExtendedClient,
	namespace string, podTemplate apiv1.PodTemplateSpec,
	imageCreds registry.ImageCreds,
	seenCreds map[string]registry.Credentials) {
	var images []image.Name
	for _, container := range podTemplate.Spec.InitContainers {
		r, err := image.ParseRef(container.Image)
		if err != nil {
			log("err", err.Error())
			continue
		}
		if includeImage(r.CanonicalName().Name.String()) {
			images = append(images, r.Name)
		}
	}

	for _, container := range podTemplate.Spec.Containers {
		r, err := image.ParseRef(container.Image)
		if err != nil {
			log("err", err.Error())
			continue
		}
		if includeImage(r.CanonicalName().Name.String()) {
			images = append(images, r.Name)
		}
	}

	if len(images) < 1 {
		return
	}

	creds := registry.NoCredentials()
	var imagePullSecrets []string
	saName := podTemplate.Spec.ServiceAccountName
	if saName == "" {
		saName = "default"
	}

	sa, err := client.CoreV1().ServiceAccounts(namespace).Get(saName, meta_v1.GetOptions{})
	if err == nil {
		for _, ips := range sa.ImagePullSecrets {
			imagePullSecrets = append(imagePullSecrets, ips.Name)
		}
	}

	for _, imagePullSecret := range podTemplate.Spec.ImagePullSecrets {
		imagePullSecrets = append(imagePullSecrets, imagePullSecret.Name)
	}

	for _, name := range imagePullSecrets {
		if seen, ok := seenCreds[name]; ok {
			creds.Merge(seen)
			continue
		}

		secret, err := client.CoreV1().Secrets(namespace).Get(name, meta_v1.GetOptions{})
		if err != nil {
			log("err", errors.Wrapf(err, "getting secret %q from namespace %q", name, namespace))
			seenCreds[name] = registry.NoCredentials()
			continue
		}

		var decoded []byte
		var ok bool
		// These differ in format; but, ParseCredentials will
		// handle either.
		switch apiv1.SecretType(secret.Type) {
		case apiv1.SecretTypeDockercfg:
			decoded, ok = secret.Data[apiv1.DockerConfigKey]
		case apiv1.SecretTypeDockerConfigJson:
			decoded, ok = secret.Data[apiv1.DockerConfigJsonKey]
		default:
			log("skip", "unknown type", "secret", namespace+"/"+secret.Name, "type", secret.Type)
			seenCreds[name] = registry.NoCredentials()
			continue
		}

		if !ok {
			log("err", errors.Wrapf(err, "retrieving pod secret %q", secret.Name))
			seenCreds[name] = registry.NoCredentials()
			continue
		}

		// Parse secret
		crd, err := registry.ParseCredentials(fmt.Sprintf("%s:secret/%s", namespace, name), decoded)
		if err != nil {
			log("err", err.Error())
			seenCreds[name] = registry.NoCredentials()
			continue
		}
		seenCreds[name] = crd

		// Merge into the credentials for this PodSpec
		creds.Merge(crd)
	}

	// Now create the service and attach the credentials
	for _, image := range images {
		imageCreds[image] = creds
	}
}

// ImagesToFetch is a k8s specific method to get a list of images to update along with their credentials
func (c *Cluster) ImagesToFetch() registry.ImageCreds {
	allImageCreds := make(registry.ImageCreds)
	ctx := context.Background()

	namespaces, err := c.getAllowedAndExistingNamespaces(ctx)
	if err != nil {
		c.logger.Log("err", errors.Wrap(err, "getting namespaces"))
		return allImageCreds
	}

	for _, ns := range namespaces {
		seenCreds := make(map[string]registry.Credentials)
		for kind, resourceKind := range resourceKinds {
			workloads, err := resourceKind.getWorkloads(ctx, c, ns)
			if err != nil {
				if apierrors.IsNotFound(err) || apierrors.IsForbidden(err) {
					// Skip unsupported or forbidden resource kinds
					continue
				}
				c.logger.Log("err", errors.Wrapf(err, "getting kind %s for namespace %s", kind, ns))
			}

			imageCreds := make(registry.ImageCreds)
			for _, workload := range workloads {
				logger := log.With(c.logger, "resource", resource.MakeID(workload.GetNamespace(), kind, workload.GetName()))
				mergeCredentials(logger.Log, c.includeImage, c.client, ns, workload.podTemplate, imageCreds, seenCreds)
			}

			// Merge creds
			for imageID, creds := range imageCreds {
				existingCreds, ok := allImageCreds[imageID]
				if ok {
					mergedCreds := registry.NoCredentials()
					mergedCreds.Merge(existingCreds)
					mergedCreds.Merge(creds)
					allImageCreds[imageID] = mergedCreds
				} else {
					allImageCreds[imageID] = creds
				}
			}
		}
	}

	return allImageCreds
}

func (c *Cluster) includeImage(imageName string) bool {
	for _, exp := range c.imageExcludeList {
		if glob.Glob(exp, imageName) {
			return false
		}
	}
	return true
}


text:
namespace Nancy.Routing.Trie.Nodes
{
    using System.Text.RegularExpressions;

    /// <summary>
    /// A regular expression capture node e.g. (?<foo>\d{2,4})
    /// </summary>
    public class RegExNode : TrieNode
    {
        private Regex expression;

        private string[] groupNames;

        /// <summary>
        /// Score for this node
        /// </summary>
        public override int Score
        {
            get { return 1000; }
        }

        public RegExNode(TrieNode parent, string segment, ITrieNodeFactory nodeFactory)
            : base(parent, segment, nodeFactory)
        {
            this.BuildRegEx();
        }

        /// <summary>
        /// Matches the segment for a requested route
        /// </summary>
        /// <param name="segment">Segment string</param>
        /// <returns>A <see cref="SegmentMatch"/> instance representing the result of the match</returns>
        public override SegmentMatch Match(string segment)
        {
            var match = this.expression.Match(segment);

            if (!match.Success)
            {
                return SegmentMatch.NoMatch;
            }

            var result = new SegmentMatch(true);
            foreach (var groupName in this.groupNames)
            {
                var group = match.Groups[groupName];
                if (group.Success)
                {
                    result.CapturedParameters[groupName] = group.Value;
                }
            }

            return result;
        }

        private void BuildRegEx()
        {
            this.expression = new Regex(this.RouteDefinitionSegment, RegexOptions.Compiled);
            this.groupNames = this.expression.GetGroupNames();
        }
    }
}


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  New template code for TAMU Theses and Dissertations starting Fall 2012.
%  For more info about this template or the
%  TAMU LaTeX User's Group, see http://www.howdy.me/.
%
%  Author: Wendy Lynn Turner
%	 Version 1.4
%  Last updated 1/27/2013
%	Modified by Jacob Hedrick
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%       TABLE OF CONTENTS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% single-space sections in Table of Contents
\renewcommand{\cftsecafterpnum}{\vskip0.5\baselineskip}
\renewcommand{\cftsubsecafterpnum}{\vskip0.5\baselineskip}
\renewcommand{\cftsubsubsecafterpnum}{\vskip0.5\baselineskip}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\phantomsection
\addcontentsline{toc}{chapter}{TABLE OF CONTENTS}

\begin{singlespace}
\renewcommand\contentsname{\normalfont} {\centerline{TABLE OF CONTENTS}}

%\setcounter{tocdepth}{4} % This puts \subsubsection[]{×} in your List of Tables.  The default is 3.

%%%%%%%%%%%%%  Adds Page above the page number in TOC
\setlength{\cftaftertoctitleskip}{1em}
\renewcommand{\cftaftertoctitle}{%
\hfill{\normalfont {Page}\par}}

\tableofcontents

\end{singlespace}

\pagebreak{}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                           LIST OF FIGURES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\phantomsection
\addcontentsline{toc}{chapter}{LIST OF FIGURES}

\renewcommand{\cftloftitlefont}{\center\normalfont\MakeUppercase}

\setlength{\cftbeforeloftitleskip}{-12pt} %% Positions the LOF title vertically to match the chapter titles
\renewcommand{\cftafterloftitleskip}{12pt}

\renewcommand{\cftafterloftitle}{%
\\[4em]\mbox{}\hspace{2pt}FIGURE\hfill{\normalfont Page}\vskip\baselineskip}

\begingroup

\begin{center}
\begin{singlespace}
%% These values make the lof table entries appear double spaced between.
\setlength{\cftbeforechapskip}{0.4cm}
\setlength{\cftbeforesecskip}{0.30cm}
\setlength{\cftbeforesubsecskip}{0.30cm}
\setlength{\cftbeforefigskip}{0.4cm}
\setlength{\cftbeforetabskip}{0.4cm}

\listoffigures

\end{singlespace}
\end{center}

\pagebreak{}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                           lIST OF TABLES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
\phantomsection
\addcontentsline{toc}{chapter}{LIST OF TABLES}

\renewcommand{\cftlottitlefont}{\center\normalfont\MakeUppercase}

\setlength{\cftbeforelottitleskip}{-12pt} %% Positions the LOT title vertically to match the chapter titles

\renewcommand{\cftafterlottitleskip}{12pt}

\renewcommand{\cftafterlottitle}{%
\\[4em]\mbox{}\hspace{4pt}TABLE\hfill{\normalfont Page}\vskip\baselineskip}

\begin{center}
\begin{singlespace}

%% These values make the lot table entries appear double spaced between.
\setlength{\cftbeforechapskip}{0.4cm}
\setlength{\cftbeforesecskip}{0.30cm}
\setlength{\cftbeforesubsecskip}{0.30cm}
\setlength{\cftbeforefigskip}{0.4cm}
\setlength{\cftbeforetabskip}{0.4cm}

\listoftables

\end{singlespace}
\end{center}
\endgroup
\pagebreak{}  % Need this for the pagenumbering to be correct.


text:
---
title: ESLint v4.2.0 released
tags:
  - release
  - minor
---

We just pushed ESLint v4.2.0, which is a minor release upgrade of ESLint. This release adds some new features and fixes several bugs found in the previous release.

## Highlights

* `linter.verifyAndFix` can now accept a filter function for fixes

    When using the Node.js API to autofix code, it's sometimes undesirable to autofix every problem at once. For example, a user might want to avoid fixing problems reported by particular rule, or a tool might want to only fix one problem at a time. You can now pass an object like `{ fix: message => /* ... */ }` to the third argument of `linter.verifyAndFix`, or to the `CLIEngine` constructor. If the `fix` function returns `true`, a fix is applied -- otherwise, a fix is not applied. [`eslint-nibble`](https://github.com/IanVS/eslint-nibble) uses this feature to autofix individual rules, or only autofix errors rather than warnings.

    Also see: [documentation](/docs/developer-guide/nodejs-api#cliengine)

* The [`getter-return`](/docs/rules/getter-return) rule has been added.
* The [`no-sync`](/docs/rules/no-sync) rule now has a boolean `allowAtRootLevel` option to allow sync function calls at the top level of a file.
* The [`multiline-ternary`](/docs/rules/multiline-ternary) rule now has an `always-multiline` option.

## Features

* [c693be5](https://github.com/eslint/eslint/commit/c693be5) New: Allow passing a function as `fix` option (fixes [#8039](https://github.com/eslint/eslint/issues/8039)) ([#8730](https://github.com/eslint/eslint/issues/8730)) (Ian VanSchooten)
* [8698a92](https://github.com/eslint/eslint/commit/8698a92) New: [getter-return](/docs/rules/getter-return) rule (fixes [#8449](https://github.com/eslint/eslint/issues/8449)) ([#8460](https://github.com/eslint/eslint/issues/8460)) (薛定谔的猫)

## Enhancements

* [e0f0101](https://github.com/eslint/eslint/commit/e0f0101) Update: fix indentation of nested function parameters (fixes [#8892](https://github.com/eslint/eslint/issues/8892)) ([#8900](https://github.com/eslint/eslint/issues/8900)) (Teddy Katz)
* [975dacf](https://github.com/eslint/eslint/commit/975dacf) Update: fix indentation of EmptyStatements (fixes [#8882](https://github.com/eslint/eslint/issues/8882)) ([#8885](https://github.com/eslint/eslint/issues/8885)) (Teddy Katz)
* [3767cda](https://github.com/eslint/eslint/commit/3767cda) Update: add [no-sync](/docs/rules/no-sync) option to allow at root level (fixes [#7985](https://github.com/eslint/eslint/issues/7985)) ([#8859](https://github.com/eslint/eslint/issues/8859)) (Victor Hom)
* [1f5bfc2](https://github.com/eslint/eslint/commit/1f5bfc2) Update: Add always-multiline option to [multiline-ternary](/docs/rules/multiline-ternary) (fixes [#8770](https://github.com/eslint/eslint/issues/8770)) ([#8841](https://github.com/eslint/eslint/issues/8841)) (Nathan Woltman)
* [676af9e](https://github.com/eslint/eslint/commit/676af9e) Update: fix indentation of JSXExpressionContainer contents (fixes [#8832](https://github.com/eslint/eslint/issues/8832)) ([#8850](https://github.com/eslint/eslint/issues/8850)) (Teddy Katz)
* [85c9327](https://github.com/eslint/eslint/commit/85c9327) Update: fix parenthesized CallExpression indentation (fixes [#8790](https://github.com/eslint/eslint/issues/8790)) ([#8802](https://github.com/eslint/eslint/issues/8802)) (Teddy Katz)
* [be8d354](https://github.com/eslint/eslint/commit/be8d354) Update: simplify variable declarator [indent](/docs/rules/indent) handling (fixes [#8785](https://github.com/eslint/eslint/issues/8785)) ([#8801](https://github.com/eslint/eslint/issues/8801)) (Teddy Katz)

## Bug Fixes

* [11ffe6b](https://github.com/eslint/eslint/commit/11ffe6b) Fix: [no-regex-spaces](/docs/rules/no-regex-spaces) rule incorrectly fixes quantified spaces ([#8773](https://github.com/eslint/eslint/issues/8773)) (Keri Warr)
* [931a9f1](https://github.com/eslint/eslint/commit/931a9f1) Fix: [indent](/docs/rules/indent) false positive with multi-line await expression ([#8837](https://github.com/eslint/eslint/issues/8837)) (薛定谔的猫)
* [f00854e](https://github.com/eslint/eslint/commit/f00854e) Fix: --quiet no longer fixes warnings (fixes [#8675](https://github.com/eslint/eslint/issues/8675)) ([#8858](https://github.com/eslint/eslint/issues/8858)) (Kevin Partington)
* [22116f2](https://github.com/eslint/eslint/commit/22116f2) Fix: correct [comma-dangle](/docs/rules/comma-dangle) JSON schema ([#8864](https://github.com/eslint/eslint/issues/8864)) (Evgeny Poberezkin)
* [5c3ac8e](https://github.com/eslint/eslint/commit/5c3ac8e) Fix: [arrow-parens](/docs/rules/arrow-parens) fixer gets tripped up with trailing comma in args ([#8838](https://github.com/eslint/eslint/issues/8838)) (薛定谔的猫)
* [9417818](https://github.com/eslint/eslint/commit/9417818) Fix: [no-debugger](/docs/rules/no-debugger) autofixer produced invalid syntax ([#8806](https://github.com/eslint/eslint/issues/8806)) (Teddy Katz)
* [eac06f2](https://github.com/eslint/eslint/commit/eac06f2) Fix: [no-extra-parens](/docs/rules/no-extra-parens) false positives for variables called "let" ([#8808](https://github.com/eslint/eslint/issues/8808)) (Teddy Katz)
* [616587f](https://github.com/eslint/eslint/commit/616587f) Fix: [dot-notation](/docs/rules/dot-notation) autofix produces syntax errors for object called "let" ([#8807](https://github.com/eslint/eslint/issues/8807)) (Teddy Katz)
* [a53ef7e](https://github.com/eslint/eslint/commit/a53ef7e) Fix: don't require a third argument in linter.verifyAndFix (fixes [#8805](https://github.com/eslint/eslint/issues/8805)) ([#8809](https://github.com/eslint/eslint/issues/8809)) (Teddy Katz)

## Documentation

* [7c8de92](https://github.com/eslint/eslint/commit/7c8de92) Docs: Clarified PR guidelines in maintainer guide ([#8876](https://github.com/eslint/eslint/issues/8876)) (Kevin Partington)
* [d1fc408](https://github.com/eslint/eslint/commit/d1fc408) Docs: Update CLA link in Contributing docs ([#8883](https://github.com/eslint/eslint/issues/8883)) (Calvin Freitas)
* [1ce553d](https://github.com/eslint/eslint/commit/1ce553d) Docs: Fix wording of minProperties in [object-curly-newline](/docs/rules/object-curly-newline) (fixes [#8874](https://github.com/eslint/eslint/issues/8874)) ([#8878](https://github.com/eslint/eslint/issues/8878)) (solmsted)
* [8796d55](https://github.com/eslint/eslint/commit/8796d55) Docs: add missing item to 4.0 migration guide table of contents ([#8835](https://github.com/eslint/eslint/issues/8835)) (薛定谔的猫)
* [ce969f9](https://github.com/eslint/eslint/commit/ce969f9) Docs: add guidelines for patch release communication (fixes [#7277](https://github.com/eslint/eslint/issues/7277)) ([#8823](https://github.com/eslint/eslint/issues/8823)) (Teddy Katz)
* [5c83c99](https://github.com/eslint/eslint/commit/5c83c99) Docs: Clarify arrow function parens in [no-extra-parens](/docs/rules/no-extra-parens) (fixes [#8741](https://github.com/eslint/eslint/issues/8741)) ([#8822](https://github.com/eslint/eslint/issues/8822)) (Kevin Partington)
* [84d921d](https://github.com/eslint/eslint/commit/84d921d) Docs: Added note about Node/CJS scoping to [no-redeclare](/docs/rules/no-redeclare) (fixes [#8814](https://github.com/eslint/eslint/issues/8814)) ([#8820](https://github.com/eslint/eslint/issues/8820)) (Kevin Partington)
* [5ad8b70](https://github.com/eslint/eslint/commit/5ad8b70) Docs: add minor formatting improvement to paragraph about parsers ([#8816](https://github.com/eslint/eslint/issues/8816)) (Teddy Katz)

## Build Related

* [88ed041](https://github.com/eslint/eslint/commit/88ed041) Build: Turnoff CI branch build (fixes [#8804](https://github.com/eslint/eslint/issues/8804)) ([#8873](https://github.com/eslint/eslint/issues/8873)) (Gyandeep Singh)
* [c4f2e29](https://github.com/eslint/eslint/commit/c4f2e29) Build: fix race condition in demo ([#8827](https://github.com/eslint/eslint/issues/8827)) (Teddy Katz)

## Chores

* [9f95a3e](https://github.com/eslint/eslint/commit/9f95a3e) Chore: remove unused helper method from [`indent`](/docs/rules/indent) ([#8901](https://github.com/eslint/eslint/issues/8901)) (Teddy Katz)
* [72f22eb](https://github.com/eslint/eslint/commit/72f22eb) Chore: replace is-my-json-valid with Ajv ([#8852](https://github.com/eslint/eslint/issues/8852)) (Gajus Kuizinas)
* [b678535](https://github.com/eslint/eslint/commit/b678535) Chore: Add collapsible block for config in ISSUE_TEMPLATE ([#8872](https://github.com/eslint/eslint/issues/8872)) (Gyandeep Singh)
* [330dd58](https://github.com/eslint/eslint/commit/330dd58) Chore: fix title of linter test suite ([#8861](https://github.com/eslint/eslint/issues/8861)) (Teddy Katz)
* [60099ed](https://github.com/eslint/eslint/commit/60099ed) Chore: enable [for-direction](/docs/rules/for-direction) rule on ESLint codebase ([#8853](https://github.com/eslint/eslint/issues/8853)) (薛定谔的猫)
* [e0d1a84](https://github.com/eslint/eslint/commit/e0d1a84) Chore: upgrade eslint-plugin-eslint-plugin & eslint-plugin-node ([#8856](https://github.com/eslint/eslint/issues/8856)) (薛定谔的猫)
* [0780d86](https://github.com/eslint/eslint/commit/0780d86) Chore: remove identical tests ([#8851](https://github.com/eslint/eslint/issues/8851)) (Teddy Katz)


text:
main.lua
Copyright (c) 2017 andynines
MIT License
]]

local simulation = require("bugevo")

local FIELD_X = simulation.FIELD_X
local FIELD_Y = simulation.FIELD_Y
local CODES = simulation.CODES
local initialize = simulation.initialize
local iterate = simulation.iterate

local function rgb(r, g, b)
    return {r=r, g=g, b=b}
end

local WINDOW_TITLE = "BugEvo"
local RUN_PROMPT = "Press [SPACE] to begin a new simulation"
local WORD_WRAP = 500

local TEXT_COLOR = rgb(255, 255, 153)
local BACKGROUND_COLOR = rgb(0, 0, 0)
local BUG_COLOR = rgb(153, 255, 0)
local BACTERIA_COLOR = rgb(76, 0, 153)

--Keyboard control
local RUN_CONTROL = " "
local QUIT_CONTROL = "q"

local STATES = {INITIAL=1,
                ACTIVE=2}

--Stretch simulation space to fit display window
local X_STRETCH = love.graphics.getWidth() / FIELD_X
local Y_STRETCH = love.graphics.getHeight() / FIELD_Y

--Initialize display window
love.graphics.setCaption(WINDOW_TITLE)
love.graphics.setBackgroundColor(BACKGROUND_COLOR.r, BACKGROUND_COLOR.g, BACKGROUND_COLOR.b)

local state

local function initial()
    --Wait for user input and initialize a new simulation
    love.graphics.setColor(TEXT_COLOR.r, TEXT_COLOR.g, TEXT_COLOR.b)
    love.graphics.printf(RUN_PROMPT, 0, 0, WORD_WRAP)
    if love.keyboard.isDown(RUN_CONTROL) then
        initialize()
        state = STATES.ACTIVE
    end
end

local function active()
    --Iterate over the current simulation
    local data = iterate()
    if not data then
        --Simulation returns nil when ended; return to start screen
        state = STATES.INITIAL
    else
        local field = data.field
        local iteration = data.iteration
        local population = data.population
        for x = 1, #field do
            for y = 1, #field[x] do
                if field[x][y] ~= CODES.EMPTY then
                    if field[x][y] == CODES.BUG then
                        love.graphics.setColor(BUG_COLOR.r, BUG_COLOR.g, BUG_COLOR.b)
                    elseif field[x][y] == CODES.BACTERIA then
                        love.graphics.setColor(BACTERIA_COLOR.r, BACTERIA_COLOR.g, BACTERIA_COLOR.b)
                    end
                    --[[Adjustments are made here to transition between "simulation" and "LOVE2D" space.
                        1. LOVE2D coordinates begin counting from 0; the simulation counts from 1
                        2. LOVE2D draws in the foruth quadrant of the cartesian plane; the simulation uses the first]]
                    love.graphics.rectangle("fill", X_STRETCH * x - X_STRETCH, (FIELD_Y - y) * Y_STRETCH, X_STRETCH, Y_STRETCH)
                end
            end
        end
        love.graphics.setColor(TEXT_COLOR.r, TEXT_COLOR.g, TEXT_COLOR.b)
        love.graphics.printf("iter ".. iteration.. "\npop ".. population, 0, 0, WORD_WRAP)
    end
end

local STATE_FUNCTIONS = {initial, active}

state = STATES.INITIAL

function love.draw()
    --Check for quit command, else do according to the state of the program
    if love.keyboard.isDown(QUIT_CONTROL) then
        love.event.quit()
    end
    STATE_FUNCTIONS[state]()
end