text:
using AutoMapper;
using fortune_api.App_Start;
using fortune_api.Dtos.LoadBoard;
using fortune_api.Exceptions;
using fortune_api.Models.LoadBoard;
using fortune_api.Persistence;
using fortune_api.Services.LoadBoard;
using fortune_api.Tests.Test_Start;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace fortune_api.Tests.Services.LoadBoard
{
    [TestClass]
    public class TrailerServiceTest
    {
        #region Get Trailer

        [TestMethod]
        public void GetTrailer()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailer
            Trailer testTrailer = new Trailer
            {
                Id = 111111,
                Deleted = false,
                LocationId = testLocation.Id
            };
            TrailerDto testDto = Mapper.Map<TrailerDto>(testTrailer);
            testDto.Location = Mapper.Map<LocationDto>(testLocation);

            //Mock call
            mockTrailerRepo.Setup(x => x.Get(testTrailer.Id)).Returns(testTrailer);
            mockLocationRepo.Setup(x => x.Get(It.Is<Guid>(y => y == testLocation.Id))).Returns(testLocation);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            TrailerDto dto = trailerService.Get(testTrailer.Id);
            TestUtil.Compare(testDto, dto);
        }

        [TestMethod]
        [ExpectedException(typeof(DoesNotExistException))]
        public void GetNonexistentTrailer()
        {
            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test id
            int testId = 111111;

            //Mock call
            mockTrailerRepo.Setup(x => x.Get(testId)).Returns<Trailer>(null);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            TrailerDto dto = trailerService.Get(testId);
        }

        #endregion

        #region Get Trailers

        [TestMethod]
        public void GetTrailers()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailers
            IEnumerable<Trailer> testTrailers = new List<Trailer>
            {
                new Trailer {
                    Id = 111111,
                    Deleted = false,
                    LocationId = testLocation.Id
                },
                new Trailer {
                    Id = 222222,
                    Deleted = false,
                    LocationId = testLocation.Id
                }
            };
            TrailerDto[] testDtos = Mapper.Map<TrailerDto[]>(testTrailers);
            foreach (TrailerDto testDto in testDtos)
            {
                testDto.Location = Mapper.Map<LocationDto>(testLocation);
            }

            //Mock call
            mockTrailerRepo.Setup(x => x.Get(
                It.IsAny<Expression<Func<Trailer, bool>>>(),
                -1,
                -1,
                It.IsAny<Func<IQueryable<Trailer>, IOrderedQueryable<Trailer>>>(),
                ""
            )).Returns(testTrailers);
            mockLocationRepo.Setup(x => x.Get(It.Is<Guid>(y => y == testLocation.Id))).Returns(testLocation);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            TrailerDto[] dtos = trailerService.Get(false);
            TestUtil.Compare(testDtos, dtos);
        }

        [TestMethod]
        public void GetTrailersWithDeleted()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailers
            IEnumerable<Trailer> testTrailers = new List<Trailer>
            {
                new Trailer {
                    Id = 111111,
                    Deleted = false,
                    LocationId = testLocation.Id
                },
                new Trailer {
                    Id = 222222,
                    Deleted = true,
                    LocationId = testLocation.Id
                }
            };
            TrailerDto[] testDtos = Mapper.Map<TrailerDto[]>(testTrailers);
            foreach (TrailerDto testDto in testDtos)
            {
                testDto.Location = Mapper.Map<LocationDto>(testLocation);
            }

            //Mock call
            mockTrailerRepo.Setup(x => x.Get(
                It.IsAny<Expression<Func<Trailer, bool>>>(),
                -1,
                -1,
                It.IsAny<Func<IQueryable<Trailer>, IOrderedQueryable<Trailer>>>(),
                ""
            )).Returns(testTrailers);
            mockLocationRepo.Setup(x => x.Get(It.Is<Guid>(y => y == testLocation.Id))).Returns(testLocation);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            TrailerDto[] dtos = trailerService.Get(true);
            TestUtil.Compare(testDtos, dtos);
        }

        #endregion

        #region Add Trailer

        [TestMethod]
        public void AddTrailer()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailer
            Trailer testTrailer = new Trailer
            {
                Id = 111111,
                Deleted = false,
                LocationId = testLocation.Id
            };
            TrailerDto testDto = Mapper.Map<TrailerDto>(testTrailer);
            testDto.Location = Mapper.Map<LocationDto>(testLocation);

            //Mock calls
            mockLocationRepo.Setup(x => x.Exists(It.Is<Guid>(y => y == testLocation.Id))).Returns(true);
            mockLocationRepo.Setup(x => x.Get(It.Is<Guid>(y => y == testLocation.Id))).Returns(testLocation);
            mockTrailerRepo.Setup(x => x.Get(testTrailer.Id)).Returns<Trailer>(null);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            TrailerDto dto = trailerService.Add(testDto);
            TestUtil.Compare(testDto, dto);
        }

        [TestMethod]
        public void AddSoftDeletedTrailer()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailer
            Trailer testTrailer = new Trailer
            {
                Id = 111111,
                Deleted = true,
                LocationId = testLocation.Id
            };
            TrailerDto testDto = Mapper.Map<TrailerDto>(testTrailer);
            testDto.Location = Mapper.Map<LocationDto>(testLocation);

            //Mock calls
            mockLocationRepo.Setup(x => x.Exists(It.Is<Guid>(y => y == testLocation.Id))).Returns(true);
            mockLocationRepo.Setup(x => x.Get(It.Is<Guid>(y => y == testLocation.Id))).Returns(testLocation);
            mockTrailerRepo.Setup(x => x.Get(testTrailer.Id)).Returns(testTrailer);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            TrailerDto dto = trailerService.Add(testDto);
            TestUtil.Compare(testDto, dto, deletedEqual: false);
        }

        [TestMethod]
        public void AddTrailerWithSoftDeletedLocation()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = true,
                Name = "TEST"
            };

            //Test trailer
            Trailer testTrailer = new Trailer
            {
                Id = 111111,
                Deleted = false,
                LocationId = testLocation.Id
            };
            TrailerDto testDto = Mapper.Map<TrailerDto>(testTrailer);
            testDto.Location = Mapper.Map<LocationDto>(testLocation);

            //Mock calls
            mockLocationRepo.Setup(x => x.Exists(It.Is<Guid>(y => y == testLocation.Id))).Returns(true);
            mockLocationRepo.Setup(x => x.Get(It.Is<Guid>(y => y == testLocation.Id))).Returns(testLocation);
            mockTrailerRepo.Setup(x => x.Get(testTrailer.Id)).Returns<Trailer>(null);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            TrailerDto dto = trailerService.Add(testDto);
            TestUtil.Compare(testDto, dto);
        }

        [TestMethod]
        [ExpectedException(typeof(AlreadyExistsException))]
        public void AddExistingTrailer()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailer
            Trailer testTrailer = new Trailer
            {
                Id = 111111,
                Deleted = false,
                LocationId = testLocation.Id
            };
            TrailerDto testDto = Mapper.Map<TrailerDto>(testTrailer);
            testDto.Location = Mapper.Map<LocationDto>(testLocation);

            //Mock calls
            mockLocationRepo.Setup(x => x.Get(It.Is<Guid>(y => y == testLocation.Id))).Returns(testLocation);
            mockTrailerRepo.Setup(x => x.Get(testTrailer.Id)).Returns(testTrailer);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            trailerService.Add(testDto);
        }

        [TestMethod]
        [ExpectedException(typeof(DoesNotExistException))]
        public void AddTrailerWithNonexistingLocation()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailer
            Trailer testTrailer = new Trailer
            {
                Id = 111111,
                Deleted = false,
                LocationId = testLocation.Id
            };
            TrailerDto testDto = Mapper.Map<TrailerDto>(testTrailer);
            testDto.Location = Mapper.Map<LocationDto>(testLocation);

            //Mock calls
            mockLocationRepo.Setup(x => x.Get(It.Is<Guid>(y => y == testLocation.Id))).Returns<Location>(null);
            mockTrailerRepo.Setup(x => x.Get(testTrailer.Id)).Returns<Trailer>(null);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            trailerService.Add(testDto);
        }

        #endregion

        #region Update Trailer

        [TestMethod]
        public void UpdateTrailer()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailer
            Trailer testTrailer = new Trailer
            {
                Id = 111111,
                Deleted = false,
                LocationId = testLocation.Id
            };
            TrailerDto testDto = Mapper.Map<TrailerDto>(testTrailer);
            testDto.Location = Mapper.Map<LocationDto>(testLocation);

            //Mock calls
            mockLocationRepo.Setup(x => x.Exists(It.Is<Guid>(y => y == testLocation.Id))).Returns(true);
            mockLocationRepo.Setup(x => x.Get(It.Is<Guid>(y => y == testLocation.Id))).Returns(testLocation);
            mockTrailerRepo.Setup(x => x.Get(testTrailer.Id)).Returns(testTrailer);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            TrailerDto dto = trailerService.Update(testDto);
            TestUtil.Compare(testDto, dto);
        }

        [TestMethod]
        [ExpectedException(typeof(DoesNotExistException))]
        public void UpdateNonexistentTrailer()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailer
            Trailer testTrailer = new Trailer
            {
                Id = 111111,
                Deleted = false,
                LocationId = testLocation.Id
            };
            TrailerDto testDto = Mapper.Map<TrailerDto>(testTrailer);
            testDto.Location = Mapper.Map<LocationDto>(testLocation);

            //Mock calls
            mockLocationRepo.Setup(x => x.Get(It.Is<Guid>(y => y == testLocation.Id))).Returns(testLocation);
            mockTrailerRepo.Setup(x => x.Get(testTrailer.Id)).Returns<Trailer>(null);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            trailerService.Update(testDto);
        }

        [TestMethod]
        [ExpectedException(typeof(DoesNotExistException))]
        public void UpdateTrailerWithNonexistentTrailer()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailer
            Trailer testTrailer = new Trailer
            {
                Id = 111111,
                Deleted = false,
                LocationId = testLocation.Id
            };
            TrailerDto testDto = Mapper.Map<TrailerDto>(testTrailer);
            testDto.Location = Mapper.Map<LocationDto>(testLocation);

            //Mock calls
            mockLocationRepo.Setup(x => x.Get(It.Is<Guid>(y => y == testLocation.Id))).Returns(testLocation);
            mockTrailerRepo.Setup(x => x.Get(testTrailer.Id)).Returns<Trailer>(null);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            TrailerDto dto = trailerService.Update(testDto);
            TestUtil.Compare(testDto, dto);
        }

        #endregion

        #region Delete Trailer

        [TestMethod]
        public void DeleteTrailer()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailer
            Trailer testTrailer = new Trailer
            {
                Id = 111111,
                Deleted = false,
                LocationId = testLocation.Id
            };
            TrailerDto testDto = Mapper.Map<TrailerDto>(testTrailer);

            //Mock call
            mockTrailerRepo.Setup(x => x.Get(testTrailer.Id)).Returns(testTrailer);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            trailerService.Delete(testTrailer.Id);
        }

        [TestMethod]
        public void DeleteNonexistentTrailer()
        {
            //Automapper
            AutoMapperConfig.RegisterMappings();

            //Mock context
            Mock<FortuneDbContext> mockContext = new Mock<FortuneDbContext>();

            //Mock repos
            Mock<IRepo<Location>> mockLocationRepo = new Mock<IRepo<Location>>();
            Mock<IRepo<Trailer>> mockTrailerRepo = new Mock<IRepo<Trailer>>();
            Mock<IRepo<Load>> mockLoadRepo = new Mock<IRepo<Load>>();

            //Test location
            Location testLocation = new Location
            {
                Id = Guid.NewGuid(),
                Deleted = false,
                Name = "TEST"
            };

            //Test trailer
            Trailer testTrailer = new Trailer
            {
                Id = 111111,
                Deleted = false,
                LocationId = testLocation.Id
            };
            TrailerDto testDto = Mapper.Map<TrailerDto>(testTrailer);

            //Mock call
            mockTrailerRepo.Setup(x => x.Get(testTrailer.Id)).Returns<Trailer>(null);

            //Unit of work
            Mock<IUnitOfWork> mockUnitOfWork = new Mock<IUnitOfWork>();
            mockUnitOfWork.SetupGet(x => x.LocationRepo).Returns(mockLocationRepo.Object);
            mockUnitOfWork.SetupGet(x => x.TrailerRepo).Returns(mockTrailerRepo.Object);

            //Trailer service
            ITrailerService trailerService = new TrailerService(mockUnitOfWork.Object);

            //Test
            trailerService.Delete(testTrailer.Id);
        }

        #endregion
    }
}


text:
/**
 * @author richt / http://richt.me
 * @author WestLangley / http://github.com/WestLangley
 *
 * W3C Device Orientation control (http://w3c.github.io/deviceorientation/spec-source-orientation.html)
 */

THREE.DeviceOrientationControls = function ( object ) {

	var scope = this;

	this.object = object;
	this.object.rotation.reorder( "YXZ" );

	this.enabled = true;

	this.deviceOrientation = {};
	this.screenOrientation = 0;

	var onDeviceOrientationChangeEvent = function ( event ) {

		scope.deviceOrientation = event;

	};

	var onScreenOrientationChangeEvent = function () {

		scope.screenOrientation = window.orientation || 0;

	};

	// The angles alpha, beta and gamma form a set of intrinsic Tait-Bryan angles of type Z-X'-Y''

	var setObjectQuaternion = function () {

		var zee = new THREE.Vector3( 0, 0, 1 );

		var euler = new THREE.Euler();

		var q0 = new THREE.Quaternion();

		var q1 = new THREE.Quaternion( - Math.sqrt( 0.5 ), 0, 0, Math.sqrt( 0.5 ) ); // - PI/2 around the x-axis

		return function ( quaternion, alpha, beta, gamma, orient ) {

			euler.set( beta, alpha, - gamma, 'YXZ' );                       // 'ZXY' for the device, but 'YXZ' for us

			quaternion.setFromEuler( euler );                               // orient the device

			quaternion.multiply( q1 );                                      // camera looks out the back of the device, not the top

			quaternion.multiply( q0.setFromAxisAngle( zee, - orient ) );    // adjust for screen orientation

		}

	}();

	this.connect = function() {

		onScreenOrientationChangeEvent(); // run once on load

		window.addEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
		window.addEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );

		scope.enabled = true;

	};

	this.disconnect = function() {

		window.removeEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
		window.removeEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );

		scope.enabled = false;

	};

	this.update = function () {

		if ( scope.enabled === false ) return;

		var alpha  = scope.deviceOrientation.alpha ? THREE.Math.degToRad( scope.deviceOrientation.alpha ) : 0; // Z
		var beta   = scope.deviceOrientation.beta  ? THREE.Math.degToRad( scope.deviceOrientation.beta  ) : 0; // X'
		var gamma  = scope.deviceOrientation.gamma ? THREE.Math.degToRad( scope.deviceOrientation.gamma ) : 0; // Y''
		var orient = scope.screenOrientation       ? THREE.Math.degToRad( scope.screenOrientation       ) : 0; // O

		setObjectQuaternion( scope.object.quaternion, alpha, beta, gamma, orient );

	};

	this.connect();

};

redpajama_set_name: RedPajamaGithub


text:
local C = ccn2.C

local SpatialMaxPooling, parent = torch.class('ccn2.SpatialMaxPooling', 'nn.Module')

function SpatialMaxPooling:__init(kW, dW)
  parent.__init(self)

  self.kW = kW
  self.dW = dW or kW

  self.output = torch.Tensor()
  self.gradInput = torch.Tensor()

  self:cuda()
end

function SpatialMaxPooling:updateOutput(input)
  ccn2.typecheck(input)
  ccn2.inputcheck(input)
  local nBatch = input:size(4)
  local inputC = input:view(input:size(1) * input:size(2) * input:size(3), input:size(4))
  local outputX = math.ceil((input:size(2) - self.kW)/self.dW + 1)

  C['convLocalMaxPool'](inputC:cdata(), self.output:cdata(), input:size(1), self.kW, 0, self.dW, outputX)

  local ims = math.sqrt(self.output:size(1)/input:size(1))
  self.output = self.output:view(input:size(1), ims, ims, nBatch)
  return self.output
end

function SpatialMaxPooling:updateGradInput(input, gradOutput)
  ccn2.typecheck(input); ccn2.typecheck(gradOutput);
  ccn2.inputcheck(input); ccn2.inputcheck(gradOutput);
  local inputC = input:view(input:size(1) * input:size(2) * input:size(3), input:size(4))
  local gradOutputC = gradOutput:view(gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4))
  local outputC = self.output:view(gradOutput:size(1) * gradOutput:size(2) * gradOutput:size(3), gradOutput:size(4))

  self.gradInput:resize(inputC:size())
  local outputX = math.ceil((input:size(2) - self.kW)/self.dW + 1)

  C['convLocalMaxUndo'](inputC:cdata(), gradOutputC:cdata(), outputC:cdata(), self.gradInput:cdata(), self.kW, 0, self.dW, outputX)
  self.gradInput = self.gradInput:view(input:size(1), input:size(2), input:size(3), input:size(4))
  return self.gradInput
end


text:
package seedu.watodo.logic.parser;

import static seedu.watodo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;

import java.util.Optional;

import seedu.watodo.logic.commands.Command;
import seedu.watodo.logic.commands.IncorrectCommand;
import seedu.watodo.logic.commands.SelectCommand;

/**
 * Parses input arguments and creates a new SelectCommand object
 */
public class SelectCommandParser {

    /**
     * Parses the given {@code String} of arguments in the context of the SelectCommand
     * and returns an SelectCommand object for execution.
     */
    public Command parse(String args) {
        Optional<Integer> index = ParserUtil.parseIndex(args);
        if (!index.isPresent()) {
            return new IncorrectCommand(
                    String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
        }

        return new SelectCommand(index.get());
    }

}


text:
package org.jtheque.utils.tests;

import org.jtheque.utils.collections.CollectionUtils;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

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

/**
 * A JUnit test class to test the CollectionUtils class.
 *
 * @author Baptiste Wicht
 */
public class CollectionUtilsTest {
    /**
     * Test the copyOf method.
     */
    @Test
    public void testCopyOf() {
        Collection<String> strings = new ArrayList<String>(2);

        strings.add("Test 1");
        strings.add("Test 2");

        Collection<String> copyStrings = CollectionUtils.copyOf(strings);

        assertEquals(strings.size(), copyStrings.size());
        assertEquals(strings, copyStrings);

        copyStrings.clear();

        assertEquals(2, strings.size());
    }

    @Test
    public void testReverse() {
        List<String> strings = new ArrayList<String>(2);

        strings.add("Test 1");
        strings.add("Test 2");

        CollectionUtils.reverse(strings);

        assertEquals("Test 2", strings.get(0));
        assertEquals("Test 1", strings.get(1));
    }

    @Test
    public void testEmptyList() {
        List<String> emptyList = CollectionUtils.emptyList();

        assertTrue(emptyList.isEmpty());
    }

    @Test(expected = UnsupportedOperationException.class)
    public void testEmptyListModification() {
        List<String> emptyList = CollectionUtils.emptyList();

        emptyList.add("Test");
    }

    @Test
    public void first() {
        Collection<String> list = Arrays.asList("asdf", "bsadf", "rtert");

        assertEquals("asdf", CollectionUtils.first(list));
    }
}


text:
  function Cliente(id,nombre,correo,direccion_envio,telefono) {
    this.Cliente(id,nombre,correo,direccion_envio,telefono);
  }

  Cliente.prototype={
	Cliente: function(id,nombre,correo,direccion_envio,telefono){
		this.id=id;
		this.nombre=nombre;
                this.correo=correo;
		this.direccion_envio=direccion_envio;
		this.telefono=telefono;
	},
	toString:function(){
	  return this.id;
	}
  }


text:
@interface ViewController () <SDCycleScrollViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:0.99];
    NSArray *images = @[[UIImage imageNamed:@"h1.jpg"],
                        [UIImage imageNamed:@"h2.jpg"],
                        [UIImage imageNamed:@"h3.jpg"],
                        [UIImage imageNamed:@"h4.jpg"]
                        ];

    NSArray *titles = @[@"感谢您的支持,如果下载的",
                        @"如果代码在使用过程中出现问题",
                        @"您可以发邮件到gsdios@126.com",
                        @"感谢您的支持"
                        ];

    CGFloat w = self.view.bounds.size.width;

    // 创建不带标题的图片轮播器
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 60, w, 180) imagesGroup:images];
    cycleScrollView.delegate = self;
    //cycleScrollView.autoScrollTimeInterval = 2.0;
    [self.view addSubview:cycleScrollView];

    // 创建带标题的图片轮播器
    SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 280, w, 180) imagesGroup:images];
    cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    cycleScrollView2.delegate = self;
    cycleScrollView2.titlesGroup = titles;
    [self.view addSubview:cycleScrollView2];

}

#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", index);
}

@end


text:
( function( $ ) {
	"use strict" // set strict mode

	var widget = $.extend( {}, $.ui.bootTwipsy.prototype, {
		/**
		 * The name of the widget.
		 * @type String
		 */
		name: 'popover',
		/**
		 * The value of the tooltip id attribute.
		 * @type String
		 */
		tooltipId: 'popover',
		/**
		 * Widget options.
		 * - placement: The placement of the tooltip. Valid values are: "above", "right", "below" and "left".
		 * - showEvent: The event for showing the tooltip.
		 * - hideEvent: The event for hiding the tooltip.
		 * - offset: Pixel offset of the tooltip.
		 * - live: Indicates whether to use jQuery.live or jQuery.bind.
		 * @type Object
		 */
		options: {
			placement: 'above',
			showEvent: 'mouseenter',
			hideEvent: 'mouseleave',
			offset: 0,
			live: false
		},
		/**
		 * Shows the tooltip.
		 */
		show: function() {
			if ( !this.visible ) {
				var tooltip = this._getTooltip(),
					position;

				tooltip.find( '.title' ).html( this.element.attr( 'data-title' ) );
				tooltip.find( '.content p' ).html( this.element.attr( 'data-content' ) );
				position = this._pos();
				tooltip.css( {
					top: position.top,
					left: position.left
				} ).show(); // todo: implement support for effects.

				this.visible = true;
			}
		},
		/**
		 * Creates the tooltip element and appends it to the body element.
		 * @returns {HTMLElement} The element.
		 */
		_createTooltip: function() {
			var tooltip = $( '
' )
				.attr( 'id', this.tooltipId )
				.addClass( this.options.placement )
				.appendTo( 'body' )
				.hide();

			$( '
' )
				.appendTo( tooltip );

			$( '

' )
				.appendTo( tooltip );

			return tooltip;
		}
	} );

	/**
	 * BootPopover jQuery UI widget.
	 */
	$.widget( 'ui.bootPopover', widget );

} )( jQuery );


text:
package rhel7

import (
	log "github.com/Sirupsen/logrus"
	xplatform "github.com/dvonthenen/goxplatform"

	mgr "github.com/codedellemc/scaleio-framework/scaleio-executor/executor/pkgmgr/mgr"
	types "github.com/codedellemc/scaleio-framework/scaleio-scheduler/types"
)

//NodeRpmRhel7Mgr implementation for NodeRpmRhel7Mgr
type NodeRpmRhel7Mgr struct {
	*mgr.NodeManager
}

//EnvironmentSetup for setting up the environment for ScaleIO
func (npm *NodeRpmRhel7Mgr) EnvironmentSetup(state *types.ScaleIOFramework) (bool, error) {
	log.Infoln("EnvironmentSetup ENTER")

	aioErr := xplatform.GetInstance().Inst.IsInstalled("libaio")
	zipErr := xplatform.GetInstance().Inst.IsInstalled("zip")
	unzipErr := xplatform.GetInstance().Inst.IsInstalled("unzip")
	javaErr := xplatform.GetInstance().Inst.IsInstalled("java-1.8.0-openjdk")
	if aioErr != nil || zipErr != nil || unzipErr != nil || javaErr != nil {
		log.Infoln("Installing libaio1, zip, and java-1.8.0-openjdk")

		miscCmdline := "yum -y install zip unzip libaio java-1.8.0-openjdk"
		err := xplatform.GetInstance().Run.Command(miscCmdline, aiozipCheck, "")
		if err != nil {
			log.Errorln("Install Prerequisites Failed:", err)
			log.Infoln("EnvironmentSetup LEAVE")
			return false, err
		}
	} else {
		log.Infoln("libaio1, zip, and java-1.8.0-openjdk are already installed")
	}

	log.Infoln("EnvironmentSetup LEAVE")

	return false, nil
}

//NewNodeRpmRhel7Mgr generates a NodeRpmRhel7Mgr object
func NewNodeRpmRhel7Mgr(state *types.ScaleIOFramework) *NodeRpmRhel7Mgr {
	myNodeMgr := &mgr.NodeManager{}
	myNodeRpmRhel7Mgr := &NodeRpmRhel7Mgr{myNodeMgr}

	//ScaleIO node
	myNodeRpmRhel7Mgr.NodeManager.SdsPackageName = types.Rhel7SdsPackageName
	myNodeRpmRhel7Mgr.NodeManager.SdsPackageDownload = state.ScaleIO.Rhel7.Sds
	myNodeRpmRhel7Mgr.NodeManager.SdsInstallCmd = "rpm -Uvh {LocalSds}"
	myNodeRpmRhel7Mgr.NodeManager.SdsInstallCheck = sdsInstallCheck
	myNodeRpmRhel7Mgr.NodeManager.SdcPackageName = types.Rhel7SdcPackageName
	myNodeRpmRhel7Mgr.NodeManager.SdcPackageDownload = state.ScaleIO.Rhel7.Sdc
	myNodeRpmRhel7Mgr.NodeManager.SdcInstallCmd = "MDM_IP={MdmPair} rpm -Uvh {LocalSdc}"
	myNodeRpmRhel7Mgr.NodeManager.SdcInstallCheck = sdcInstallCheck

	//REX-Ray
	myNodeRpmRhel7Mgr.NodeManager.RexrayInstallCheck = rexrayInstallCheck

	//Isolator
	myNodeRpmRhel7Mgr.NodeManager.DvdcliInstallCheck = dvdcliInstallCheck

	return myNodeRpmRhel7Mgr
}


text:
package com.zapateus.util;

import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

@Component
public class MessageUtil {

	@Autowired
	private MessageSource message;

	public String getMessage(String key) {
		Locale locale = LocaleContextHolder.getLocale();
		return message.getMessage(key, null, locale);
	}

	public String getMessageWithParams(String key,String... parameters) {
		Locale locale = LocaleContextHolder.getLocale();
		return message.getMessage(key, parameters, locale);
	}
}


text:
namespace views {

ImageView::ImageView()
    : image_size_set_(false),
      horiz_alignment_(CENTER),
      vert_alignment_(CENTER) {
}

ImageView::~ImageView() {
}

void ImageView::SetImage(const SkBitmap& bm) {
  image_ = bm;
  SchedulePaint();
}

void ImageView::SetImage(SkBitmap* bm) {
  if (bm) {
    SetImage(*bm);
  } else {
    SkBitmap t;
    SetImage(t);
  }
}

const SkBitmap& ImageView::GetImage() {
  return image_;
}

void ImageView::SetImageSize(const gfx::Size& image_size) {
  image_size_set_ = true;
  image_size_ = image_size;
}

bool ImageView::GetImageSize(gfx::Size* image_size) {
  DCHECK(image_size);
  if (image_size_set_)
    *image_size = image_size_;
  return image_size_set_;
}

void ImageView::ResetImageSize() {
  image_size_set_ = false;
}

gfx::Size ImageView::GetPreferredSize() {
  gfx::Insets insets = GetInsets();
  if (image_size_set_) {
    gfx::Size image_size;
    GetImageSize(&image_size);
    image_size.Enlarge(insets.width(), insets.height());
    return image_size;
  }
  return gfx::Size(image_.width() + insets.width(),
                   image_.height() + insets.height());
}

void ImageView::ComputeImageOrigin(int image_width, int image_height,
                                   int *x, int *y) {
  // In order to properly handle alignment of images in RTL locales, we need
  // to flip the meaning of trailing and leading. For example, if the
  // horizontal alignment is set to trailing, then we'll use left alignment for
  // the image instead of right alignment if the UI layout is RTL.
  Alignment actual_horiz_alignment = horiz_alignment_;
  if (UILayoutIsRightToLeft()) {
    if (horiz_alignment_ == TRAILING)
      actual_horiz_alignment = LEADING;
    if (horiz_alignment_ == LEADING)
      actual_horiz_alignment = TRAILING;
  }

  gfx::Insets insets = GetInsets();

  switch(actual_horiz_alignment) {
    case LEADING:
      *x = insets.left();
      break;
    case TRAILING:
      *x = width() - insets.right() - image_width;
      break;
    case CENTER:
      *x = (width() - image_width) / 2;
      break;
    default:
      NOTREACHED();
  }

  switch (vert_alignment_) {
    case LEADING:
      *y = insets.top();
      break;
    case TRAILING:
      *y = height() - insets.bottom() - image_height;
      break;
    case CENTER:
      *y = (height() - image_height) / 2;
      break;
    default:
      NOTREACHED();
  }
}

void ImageView::Paint(gfx::Canvas* canvas) {
  View::Paint(canvas);
  int image_width = image_.width();
  int image_height = image_.height();

  if (image_width == 0 || image_height == 0)
    return;

  int x, y;
  if (image_size_set_ &&
      (image_size_.width() != image_width ||
       image_size_.width() != image_height)) {
    // Resize case
    image_.buildMipMap(false);
    ComputeImageOrigin(image_size_.width(), image_size_.height(), &x, &y);
    SkPaint paint;
    paint.setFilterBitmap(true);
    canvas->DrawBitmapInt(image_, 0, 0, image_width, image_height,
                          x, y, image_size_.width(), image_size_.height(),
                          true, paint);
  } else {
    ComputeImageOrigin(image_width, image_height, &x, &y);
    canvas->DrawBitmapInt(image_, x, y);
  }
}

bool ImageView::GetAccessibleName(std::wstring* name) {
  if (!name || tooltip_text_.empty())
    return false;

  *name = tooltip_text_;
  return true;
}

bool ImageView::GetAccessibleRole(AccessibilityTypes::Role* role) {
  if (!role)
    return false;

  *role = AccessibilityTypes::ROLE_GRAPHIC;
  return true;
}

void ImageView::SetHorizontalAlignment(Alignment ha) {
  if (ha != horiz_alignment_) {
    horiz_alignment_ = ha;
    SchedulePaint();
  }
}

ImageView::Alignment ImageView::GetHorizontalAlignment() {
  return horiz_alignment_;
}

void ImageView::SetVerticalAlignment(Alignment va) {
  if (va != vert_alignment_) {
    vert_alignment_ = va;
    SchedulePaint();
  }
}

ImageView::Alignment ImageView::GetVerticalAlignment() {
  return vert_alignment_;
}

void ImageView::SetTooltipText(const std::wstring& tooltip) {
  tooltip_text_ = tooltip;
}

std::wstring ImageView::GetTooltipText() {
  return tooltip_text_;
}

bool ImageView::GetTooltipText(int x, int y, std::wstring* tooltip) {
  if (tooltip_text_.empty()) {
    return false;
  } else {
    *tooltip = GetTooltipText();
    return true;
  }
}

}  // namespace views


text:
package org.apache.flink.runtime.checkpoint.hooks;

import org.apache.flink.core.io.SimpleVersionedSerializer;
import org.apache.flink.runtime.checkpoint.CheckpointCoordinatorTestingUtils;
import org.apache.flink.runtime.checkpoint.MasterTriggerRestoreHook;

import javax.annotation.Nullable;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * A {@link MasterTriggerRestoreHook} implementation for testing.
 */
public class TestMasterHook implements MasterTriggerRestoreHook<String> {

	private static final String DEFAULT_STATE = "default";

	private final String id;

	private int restoreCount = 0;

	private boolean failOnRestore = false;

	private TestMasterHook(String id) {
		this.id = checkNotNull(id);
	}

	public static TestMasterHook fromId(String id) {
		return new TestMasterHook(id);
	}

	@Override
	public String getIdentifier() {
		return id;
	}

	@Override
	public CompletableFuture<String> triggerCheckpoint(
			final long checkpointId,
			final long timestamp,
			final Executor executor) {

		return CompletableFuture.completedFuture(DEFAULT_STATE);
	}

	@Override
	public void restoreCheckpoint(final long checkpointId, @Nullable final String checkpointData) throws Exception {
		restoreCount++;
		if (failOnRestore) {
			throw new Exception("Failing mast hook state restore on purpose.");
		}
	}

	@Override
	public SimpleVersionedSerializer<String> createCheckpointDataSerializer() {
		return new CheckpointCoordinatorTestingUtils.StringSerializer();
	}

	public int getRestoreCount() {
		return restoreCount;
	}

	public void enableFailOnRestore() {
		this.failOnRestore = true;
	}

	public void disableFailOnRestore() {
		this.failOnRestore = false;
	}
}


text:
class Input {
    enum class Action {
        None,
        Pressed,
        Released
    };

public:
    static Input& GetInstance();

    void resetActions() {
        keyAction = Action::None;
        buttonAction = Action::None;
    }

    void registerEvent(const sf::Event& event);

    bool getKey(sf::Keyboard::Key key);
    bool getKeyDown(sf::Keyboard::Key key);
    bool getKeyUp(sf::Keyboard::Key key);

    bool getMouseButton(sf::Mouse::Button button);
    bool getMouseButtonDown(sf::Mouse::Button button);
    bool getMouseButtonUp(sf::Mouse::Button button);

private:
    Input() = default;

    Action keyAction;
    Action buttonAction;

    sf::Keyboard::Key clickedKey;
    sf::Mouse::Button clickedButton;
};


text:
<?php
/**
 *
 */

namespace Mvc5\Resolver;

use ArrayAccess;
use Iterator;
use Mvc5\Event\Event;
use Mvc5\Event\Generator as EventGenerator;
use Mvc5\Iterator as Mvc5Iterator;
use Throwable;

use function is_string;
use function get_class;

trait Generator
{
    /**
     *
     */
    use EventGenerator;

    /**
     * @var ArrayAccess
     */
    protected ArrayAccess $events;

    /**
     * @param array|Iterator|object|string $event
     * @param array $args
     * @param callable|null $callback
     * @return mixed
     * @throws Throwable
     */
    protected function event($event, array $args = [], callable $callback = null)
    {
        return $this->generate($event, $args, $callback ?? $this);
    }

    /**
     * @param Event|object|string $event
     * @return string
     */
    protected function eventName($event) : string
    {
        return is_string($event) ? $event : ($event instanceof Event ? $event->name() : get_class($event));
    }

    /**
     * @param Event|object|string $event
     * @param array $args
     * @return Iterator
     * @throws Throwable
     */
    protected function iterator($event, array $args = []) : Iterator
    {
        return iterator($event, fn($event) => $event instanceof Iterator ? $event :
            $this->listeners($this->eventName($event), $args));
    }

    /**
     * @param Event|mixed $plugin
     * @return callable|null
     */
    protected function listener($plugin)
    {
        return !$plugin instanceof Event ? $plugin : fn(...$argv) => $this->event($plugin, $this->variadic($argv));
    }

    /**
     * @param string $name
     * @param array $args
     * @return Iterator
     * @throws Throwable
     */
    protected function listeners(string $name, array $args = []) : Iterator
    {
        return iterator($this->resolve($this->events[$name] ?? Unresolvable::plugin($name), $args));
    }

    /**
     * @param array|Iterator|Event|object|string $event
     * @param array $args
     * @param callable|null $callback
     * @return mixed
     * @throws Throwable
     */
    function trigger($event, array $args = [], callable $callback = null)
    {
        return $this->event($event instanceof Event ? $event : $this($event) ?? $event, $args, $callback);
    }

    /**
     * @param string|mixed $plugin
     * @param array $args
     * @return mixed
     */
    abstract function __invoke($plugin, array $args = []);
}

/**
 * @param $iterable
 * @param callable|null $resolver
 * @return Iterator
 */
function iterator($iterable, callable $resolver = null) : Iterator
{
    return is_array($iterable) ? new Mvc5Iterator($iterable) : ($resolver ? $resolver($iterable) : $iterable);
}


text:
package mmarquee.automation.controls;

import mmarquee.automation.Element;
import mmarquee.automation.UIAutomation;
import mmarquee.automation.pattern.Toggle;
import mmarquee.uiautomation.IUIAutomation;
import mmarquee.uiautomation.ToggleState;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;

/**
 * @author Mark Humphreys
 * Date 30/11/2016.
 *
 * Tests of the CheckBox class.
 */
public class CheckBoxTest {

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testName_Gets_Value_From_Element() throws Exception {
        Element element = Mockito.mock(Element.class);
        Toggle pattern = Mockito.mock(Toggle.class);
        when(pattern.isAvailable()).thenReturn(true);

        when(element.getName()).thenReturn("NAME");

        IUIAutomation mocked_automation = Mockito.mock(IUIAutomation.class);

        UIAutomation instance = new UIAutomation(mocked_automation);

        CheckBox checkbox = new CheckBox(
                new ElementBuilder(element).addPattern(pattern).automation(instance));

        String name = checkbox.getName();

        assertTrue(name.equals("NAME"));
    }

    @Test
    public void test_getToggleState_Gets_Value_From_Pattern() throws Exception {
        Element element = Mockito.mock(Element.class);
        Toggle pattern = Mockito.mock(Toggle.class);
        when(pattern.isAvailable()).thenReturn(true);

        when(pattern.currentToggleState()).thenReturn(ToggleState.ON);

        IUIAutomation mocked_automation = Mockito.mock(IUIAutomation.class);

        UIAutomation instance = new UIAutomation(mocked_automation);

        CheckBox checkbox = new CheckBox(
                new ElementBuilder(element).addPattern(pattern).automation(instance));

        ToggleState state = checkbox.getToggleState();

        assertTrue(state == ToggleState.ON);
    }

    @Test
    public void testToggle() throws Exception {
        Element element = Mockito.mock(Element.class);
        Toggle pattern = Mockito.mock(Toggle.class);
        when(pattern.isAvailable()).thenReturn(true);

        IUIAutomation mocked_automation = Mockito.mock(IUIAutomation.class);

        UIAutomation instance = new UIAutomation(mocked_automation);

        CheckBox checkbox = new CheckBox(
                new ElementBuilder(element).addPattern(pattern).automation(instance));

        checkbox.toggle();
    }
}


text:
/**
 *
 */
package org.minnal.security.filter;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.minnal.security.auth.JaxrsWebContext;
import org.minnal.security.auth.User;
import org.minnal.security.config.SecurityConfiguration;
import org.minnal.security.session.Session;
import org.minnal.security.session.SessionStore;
import org.pac4j.core.client.Clients;
import org.pac4j.core.exception.RequiresHttpAction;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.http.client.BasicAuthClient;
import org.pac4j.http.profile.HttpProfile;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * @author ganeshs
 *
 */
public class AuthenticationFilterTest {

	private AuthenticationFilter filter;

	private Clients clients;

	private SecurityConfiguration configuration;

	private ContainerRequestContext context;

	private UriInfo uriInfo;

	private SessionStore sessionStore;

	private BasicAuthClient basicClient;

	@BeforeMethod
	public void setup() {
		basicClient = mock(BasicAuthClient.class);
		when(basicClient.getName()).thenReturn("client1");
		clients = new Clients("/callback", basicClient);
		sessionStore = mock(SessionStore.class);
		configuration = mock(SecurityConfiguration.class);
		when(configuration.getSessionStore()).thenReturn(sessionStore);
		filter = spy(new AuthenticationFilter(clients, configuration));
		context = mock(ContainerRequestContext.class);
		uriInfo = mock(UriInfo.class);
		when(uriInfo.getPath()).thenReturn("/dummy");
		when(context.getUriInfo()).thenReturn(uriInfo);
	}

	@Test
	public void shouldReturnTrueIfWhiteListedUrl() {
		when(configuration.getWhiteListedUrls()).thenReturn(Lists.newArrayList("/dummy", "/dummy1"));
		assertTrue(filter.isWhiteListed(context));
	}

	@Test
	public void shouldReturnFalseIfWhiteNotListedUrl() {
		when(configuration.getWhiteListedUrls()).thenReturn(Lists.newArrayList("/dummy2", "/dummy1"));
		assertFalse(filter.isWhiteListed(context));
	}

	@Test
	public void shouldReturnTrueForWhiteListedUrlWithParams() {
		when(configuration.getWhiteListedUrls()).thenReturn(Lists.newArrayList("/dummy", "/dummy1"));
		when(uriInfo.getPath()).thenReturn("/dummy?key=value");
		assertTrue(filter.isWhiteListed(context));
	}

	@Test
	public void shouldCreateSessionIfAuthCookieIsNotFound() {
		when(context.getCookies()).thenReturn(Maps.<String, Cookie>newHashMap());
		Session session = mock(Session.class);
		when(sessionStore.createSession(any(String.class))).thenReturn(session);
		assertEquals(filter.getSession(context, true), session);
	}

	@Test
	public void shouldNotCreateSessionIfAuthCookieIsNotFoundAndCreateIsFalse() {
		when(context.getCookies()).thenReturn(Maps.<String, Cookie>newHashMap());
		Session session = mock(Session.class);
		when(sessionStore.createSession(any(String.class))).thenReturn(session);
		assertNull(filter.getSession(context, false));
	}

	@Test
	public void shouldCreateSessionIfAuthCookieIsFoundButSessionNotFound() {
		Map<String, Cookie> cookies = new HashMap<String, Cookie>();
		String sessionId = UUID.randomUUID().toString();
		cookies.put(AuthenticationFilter.AUTH_COOKIE, new Cookie(AuthenticationFilter.AUTH_COOKIE, sessionId));
		when(context.getCookies()).thenReturn(cookies);
		Session session = mock(Session.class);
		when(sessionStore.getSession(sessionId)).thenReturn(null);
		when(sessionStore.createSession(any(String.class))).thenReturn(session);
		assertEquals(filter.getSession(context, true), session);
		verify(sessionStore).getSession(sessionId);
	}

	@Test
	public void shouldCreateSessionIfAuthCookieIsFoundButSessionHasExpired() {
		when(configuration.getSessionExpiryTimeInSecs()).thenReturn(100L);
		Map<String, Cookie> cookies = new HashMap<String, Cookie>();
		String sessionId = UUID.randomUUID().toString();
		cookies.put(AuthenticationFilter.AUTH_COOKIE, new Cookie(AuthenticationFilter.AUTH_COOKIE, sessionId));
		when(context.getCookies()).thenReturn(cookies);
		Session expiredSession = mock(Session.class);
		Session session = mock(Session.class);
		when(expiredSession.hasExpired(100)).thenReturn(true);
		when(sessionStore.getSession(sessionId)).thenReturn(expiredSession);

		when(sessionStore.createSession(any(String.class))).thenReturn(session);
		assertEquals(filter.getSession(context, true), session);
		verify(sessionStore).getSession(sessionId);
	}

	@Test
    public void shouldReturnSessionIfAlreadySetToRequestProperty() {
        Session session = mock(Session.class);
        when(context.getProperty(AuthenticationFilter.SESSION)).thenReturn(session);
        assertEquals(filter.getSession(context, true), session);
        verify(sessionStore, never()).createSession(any(String.class));
    }

	@Test
	public void shouldReturnSessionIfAuthCookieIsFoundAndSessionHasNotExpired() {
		when(configuration.getSessionExpiryTimeInSecs()).thenReturn(100L);
		Map<String, Cookie> cookies = new HashMap<String, Cookie>();
		String sessionId = UUID.randomUUID().toString();
		cookies.put(AuthenticationFilter.AUTH_COOKIE, new Cookie(AuthenticationFilter.AUTH_COOKIE, sessionId));
		when(context.getCookies()).thenReturn(cookies);
		Session session = mock(Session.class);
		when(session.hasExpired(100)).thenReturn(false);
		when(sessionStore.getSession(sessionId)).thenReturn(session);
		assertEquals(filter.getSession(context, true), session);
		verify(sessionStore, never()).createSession(any(String.class));
	}

	@Test
	public void shouldReturnNullFromRequestContextIfClientNameAttributeIsNotSet() {
		JaxrsWebContext context = mock(JaxrsWebContext.class);
		when(context.getRequestParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn(null);
		assertNull(filter.getClient(context));
	}

	@Test
	public void shouldThrowExceptionIfClientNameIsNotFoundInRequestContext() {
		JaxrsWebContext context = mock(JaxrsWebContext.class);
		when(context.getRequestParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("unknownClient");
		assertNull(filter.getClient(context));
	}

	@Test
	public void shouldGetClientFromRequestContextIfClientNameAttributeIsSet() {
		JaxrsWebContext context = mock(JaxrsWebContext.class);
		when(context.getRequestParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("client1");
		assertEquals(filter.getClient(context), basicClient);
	}

	@Test
	public void shouldGetClientFromSessionIfClientNameAttributeIsSet() {
		Session session = mock(Session.class);
		when(session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("client1");
		assertEquals(filter.getClient(session), basicClient);
	}

	@Test
	public void shouldReturnNullClientFromSessionIfClientNameAttributeIsNotSet() {
		Session session = mock(Session.class);
		when(session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn(null);
		assertNull(filter.getClient(session));
	}

	@Test(expectedExceptions=TechnicalException.class)
	public void shouldThrowExceptionIfClientNameIsNotFoundInSession() {
		Session session = mock(Session.class);
		when(session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("unknownClient");
		filter.getClient(session);
	}

	@Test
	public void shouldReturnNullProfileIfNotFoundInSession() {
		Session session = mock(Session.class);
		when(session.getAttribute(AuthenticationFilter.PRINCIPAL)).thenReturn(null);
		assertNull(filter.retrieveProfile(session));
	}

	@Test
	public void shouldReturnProfileIfFoundInSession() {
		Session session = mock(Session.class);
		HttpProfile profile = mock(HttpProfile.class);
		when(session.getAttribute(AuthenticationFilter.PRINCIPAL)).thenReturn(profile);
		doReturn(basicClient).when(filter).getClient(session);

		User user = filter.retrieveProfile(session);
		assertEquals(user.getProfile(), profile);
	}

	@Test
	public void shouldDeserializeProfileIfFoundInSessionAsMap() {
		Session session = mock(Session.class);
		Map<String, Object> profile = new HashMap<String, Object>();
		profile.put("id", "dummy");
		when(session.getAttribute(AuthenticationFilter.PRINCIPAL)).thenReturn(profile);
		doReturn(basicClient).when(filter).getClient(session);
		User user = filter.retrieveProfile(session);
		assertEquals(user.getProfile().getId(), "dummy");
	}

	@Test
	public void shouldReturnTrueIfAlreadyAuthenticated() {
		Session session = mock(Session.class);
		doReturn(mock(User.class)).when(filter).retrieveProfile(session);
		assertTrue(filter.isAuthenticated(session));
	}

	@Test
	public void shouldReturnFalseIfNotAlreadyAuthenticated() {
		Session session = mock(Session.class);
		doReturn(null).when(filter).retrieveProfile(session);
		assertFalse(filter.isAuthenticated(session));
	}

	@Test
	public void shouldNotFilterWhiteListedUrls() {
		doReturn(true).when(filter).isWhiteListed(context);
		filter.filter(context);
		verify(filter).getSession(context, true);
		verify(filter, never()).getContext(eq(context), any(Session.class));
	}

	@Test
	public void shouldFilterIfAlreadyAuthenticated() {
		Session session = mock(Session.class);
		doReturn(true).when(filter).isAuthenticated(session);
		doReturn(session).when(filter).getSession(context, true);
		filter.filter(context);
		verify(context, never()).abortWith(any(Response.class));
	}

	@Test
	public void shouldReturnUnauthorizedIfClientNameIsNotSet() {
		Session session = mock(Session.class);
		Response response = mock(Response.class);
		JaxrsWebContext webContext = mock(JaxrsWebContext.class);
		when(webContext.getResponse()).thenReturn(response);
		doReturn(false).when(filter).isAuthenticated(session);
		doReturn(session).when(filter).getSession(context, true);
		doReturn(webContext).when(filter).getContext(context, session);
		filter.filter(context);
		verify(webContext).setResponseStatus(Response.Status.UNAUTHORIZED.getStatusCode());
		verify(context).abortWith(response);
	}

	@Test
	public void shouldSetClientNameParamInSessionIfNotAuthenticated() throws RequiresHttpAction {
		Session session = mock(Session.class);
		Response response = mock(Response.class);
		JaxrsWebContext webContext = mock(JaxrsWebContext.class);
		when(webContext.getResponse()).thenReturn(response);
		doReturn(basicClient).when(filter).getClient(webContext);
		doReturn(false).when(filter).isAuthenticated(session);
		doReturn(session).when(filter).getSession(context, true);
		doReturn(webContext).when(filter).getContext(context, session);
		filter.filter(context);
		verify(session).addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "client1");
		verify(sessionStore).save(session);
	}

	@Test
	public void shouldRedirectIfClientNameIsSet() throws RequiresHttpAction {
		Session session = mock(Session.class);
		when(session.getId()).thenReturn(UUID.randomUUID().toString());
		Response response = mock(Response.class);
		JaxrsWebContext webContext = mock(JaxrsWebContext.class);
		when(webContext.getResponse()).thenReturn(response);
		doNothing().when(basicClient).redirect(webContext, false, false);
		doReturn(basicClient).when(filter).getClient(webContext);
		doReturn(false).when(filter).isAuthenticated(session);
		doReturn(session).when(filter).getSession(context, true);
		doReturn(webContext).when(filter).getContext(context, session);
		filter.filter(context);
		verify(basicClient).redirect(webContext, false, false);
		verify(webContext, atLeast(1)).setResponseHeader(eq(HttpHeaders.LOCATION), any(String.class));
		verify(webContext).setResponseHeader(HttpHeaders.SET_COOKIE, new NewCookie(AuthenticationFilter.AUTH_COOKIE, session.getId(), "/", null, null, NewCookie.DEFAULT_MAX_AGE, false).toString());
		verify(context).abortWith(response);
	}
}


text:
using System;
#if NETFX_CORE
using Windows.System.Threading;
#endif

namespace MarkerMetro.Unity.WinLegacy.Timers
{
    public delegate void ElapsedEventHandler(Object sender,	ElapsedEventArgs e);

    /// <summary>
    /// MSDN reference: http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx.
    /// </summary>
    public class Timer
    {
#if NETFX_CORE
        private ThreadPoolTimer timer;
        private bool running;
#endif
        private bool timeSpanSet = false;
        private TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, 100);
        private bool enabled;

        /**
         * The time, in milliseconds, between Elapsed events. The value must be greater
         * than zero, and less than or equal to Int32.MaxValue. The default is 100 milliseconds.
         *
         * This implementation casts the interval from double to int.
         *
         * TODO: implement this condition:
         * The interval is greater than Int32.MaxValue, and the timer is currently enabled.
         * (If the timer is not currently enabled, no exception is thrown until it becomes enabled.)
         */
        public double Interval
        {
            get { return timeSpan.Milliseconds; }
            set
            {
                if (value <= 0 || value > Int32.MaxValue)
                {
                    throw new ArgumentException("The value of the interval parameter is" +
                        " less than or equal to zero, or greater than Int32.MaxValue.");
                }

                if (!timeSpanSet)
                {
                    timeSpan = new TimeSpan(0, 0, 0, 0, (int)value);
                    timeSpanSet = true;
                }
                else
                {
                    throw new NotImplementedException(
                        "Trying to set interval for the second time is not implemented.");
                }
            }
        }

        /**
         * Gets or sets a value indicating whether the Timer should raise the Elapsed event each
         * time the specified interval elapses or only after the first time it elapses.
         */
        public bool AutoReset { get; set; }

        /**
         * Gets or sets a value indicating whether the Timer should raise the Elapsed event.
         *
         * Setting Enabled to true is the same as calling Start, while setting Enabled to
         * false is the same as calling Stop.
         *
         * TODO:
         * ObjectDisposedException - This property cannot be set because the timer has been disposed.
         * ArgumentException - The Interval property was set to a value greater than Int32.MaxValue
         * before the timer was enabled.
         */
        public bool Enabled
        {
            get { return enabled; }
            set
            {
                if (value)
                {
                    Start();
                }
                else
                {
                    Stop();
                }
            }
        }

#pragma warning disable
        public event ElapsedEventHandler Elapsed;
#pragma warning restore

        public Timer()
        {
#if !NETFX_CORE
            throw new PlatformNotSupportedException();
#endif
        }
        public Timer(double interval) : this()
        {
            Interval = interval;
        }

        /**
         * Starts raising the Elapsed event by setting Enabled to true.
         * You can also start timing by setting Enabled to true.
         */
        public void Start()
        {
#if NETFX_CORE
            enabled = true;

            if (!running)
            {
                TimerElapsedHandler handler = (t) =>
                {
                    if (AutoReset)
                    {
                        throw new NotImplementedException("If autoreset == true and enabled == true," +
                            " the timer is supposed to restart.");
                    }
                    if (Enabled)
                    {
                        Elapsed(null, new ElapsedEventArgs());
                    }
                };

                timer = ThreadPoolTimer.CreatePeriodicTimer(handler, timeSpan);
                running = true;
            }
#else
            throw new PlatformNotSupportedException();
#endif
        }

        public void Stop()
        {
            enabled = false;
        }

    }

    /// <summary>
    /// MSDN reference: http://msdn.microsoft.com/en-us/library/system.timers.elapsedeventargs.aspx.
    /// </summary>
    public class ElapsedEventArgs : EventArgs
    {
        public DateTime SignalTime { get { throw new NotImplementedException(); } }
    }
}


text:
{% extends 'base.html' %}
{% load i18n %}
{% block title %}{% trans "Change Volume Type" %}{% endblock %}

{% block page_header %}
  {% include "horizon/common/_page_header.html" with title=_("Change Volume Type") %}
{% endblock page_header %}

{% block main %}
    {% include 'project/volumes/volumes/_retype.html' %}
{% endblock %}


text:
"""

"""
from retinasdk.model.fingerprint import Fingerprint

class Context(object):
    def __init__(self, fingerprint=None, context_label=None, context_id=None):
        #The semantic fingerprint representation of a context
        self.fingerprint = Fingerprint(**fingerprint) if isinstance(fingerprint, dict) else fingerprint # Fingerprint
        #The descriptive label of a context.
        self.context_label = context_label # str
        #The id of a context.
        self.context_id = context_id # int

    def __repr__(self):
        return "%s(%s)" % (self.__class__.__name__, ", ".join(["%s=%s" % (tup[0], repr(tup[1])) for tup in vars(self).items()]))


text:
using System;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace MarkupConverter
{
    public static class HtmlToRtfConverter
    {

        public static string ConvertHtmlToRtf(string htmlText)
        {
            var xamlText = HtmlToXamlConverter.ConvertHtmlToXaml(htmlText, false);

            return ConvertXamlToRtf(xamlText);
        }

        private static string ConvertXamlToRtf(string xamlText)
        {
            var richTextBox = new RichTextBox();
            if (string.IsNullOrEmpty(xamlText)) return "";

            var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);

            //Create a MemoryStream of the xaml content

            using (var xamlMemoryStream = new MemoryStream())
            {
                using (var xamlStreamWriter = new StreamWriter(xamlMemoryStream))
                {
                    xamlStreamWriter.Write(xamlText);
                    xamlStreamWriter.Flush();
                    xamlMemoryStream.Seek(0, SeekOrigin.Begin);

                    //Load the MemoryStream into TextRange ranging from start to end of RichTextBox.
                    textRange.Load(xamlMemoryStream, DataFormats.Xaml);
                }
            }

            using (var rtfMemoryStream = new MemoryStream())
            {

                textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
                textRange.Save(rtfMemoryStream, DataFormats.Rtf);
                rtfMemoryStream.Seek(0, SeekOrigin.Begin);
                using (var rtfStreamReader = new StreamReader(rtfMemoryStream))
                {
                    return rtfStreamReader.ReadToEnd();
                }
            }

        }

    }
}


text:
package main.java.com.rakesh.suffixtree;

import java.util.Collection;
import java.util.Scanner;

public class GeneralizedSuffixTree {
	private char[] text;

	private int position = -1;
	private Node needSuffixLink;

	private int remainder;
	private int activeLength, activeEdge;
	private Node activeNode;
	private final Node root;

	public GeneralizedSuffixTree() {
		root = activeNode = newNode();
	}

	private Node newNode() {
		return new Node();
	}

	public void put(String inp, int dataIndex) {
		if (inp == null || inp.isEmpty()) {
			return;
		}
		inp += "#";
		reset(inp.length());
		for (int i = 0; i < inp.length(); i++) {
			addChar(i, inp, dataIndex);
		}
	}

	private void reset(int length) {
		text = new char[length];
		remainder = 0;
		position = 0;
		activeNode = root;
		position = -1;
		activeLength = 0;
		activeEdge = 0;
	}

	private void addChar(int idx, String string, int dataIndex) {
		text[++position] = string.charAt(idx);
		needSuffixLink = null;
		remainder++;
		Node ret = null;
		while (remainder > 0) {
			if (activeLength == 0) {
				activeEdge = position;
			}
			if (!activeNode.next.containsKey(text[activeEdge])) {
				Edge newEdge = new Edge(string.substring(position).intern());
				Node newNode = new Node();
				newNode.setData(dataIndex);
				newEdge.setDest(newNode);
				activeNode.next.put(text[activeEdge], newEdge);
				addSuffixLink(activeNode);
			} else {
				Edge edge = activeNode.next.get(text[activeEdge]);
				if (walkDown(edge)) continue;
				if (edge.getLabel().charAt(activeLength) == string.charAt(idx)) {
					activeLength++;
					addSuffixLink(activeNode);
					break;
				}
				Node split = newNode();
				Edge newEdge = new Edge(edge.getLabel().substring(0, activeLength).intern());
				newEdge.setDest(split);
				activeNode.next.put(text[activeEdge], newEdge);
				Edge leaf = new Edge(string.substring(position).intern());
				Node leafNode = newNode();
				leafNode.setData(dataIndex);
				leaf.setDest(leafNode);
				split.next.put(string.charAt(idx), leaf);
				edge.setLabel(edge.getLabel().substring(activeLength).intern());
				split.next.put(edge.getLabel().charAt(0), edge);
				addSuffixLink(split);
			}
			remainder--;
			if (activeNode == root && activeLength > 0) {
				activeLength--;
				activeEdge = position - remainder + 1;
			} else {
				activeNode = activeNode.getSuffixLink() != null ? activeNode.getSuffixLink() : root;
			}
		}
	}

	private boolean walkDown(Edge edge) {
		if (activeLength >= edge.getLength()) {
			activeEdge += edge.getLength();
			activeLength -= edge.getLength();
			activeNode = edge.getDest();
			return true;
		}
		return false;
	}

	private void addSuffixLink(Node activeLink) {
		if (needSuffixLink != null) {
			needSuffixLink.setSuffixLink(activeLink);
		}
		needSuffixLink = activeLink;
	}

	public Collection<Integer> search(String word) {
		return search(word, Integer.MAX_VALUE);
	}

	public Collection<Integer> search(String word, int limit) {
		Node dataNode = findNode(word);
		if (dataNode != null) {
			return dataNode.getData(limit);
		}
		return null;
	}

	private Node findNode(String word) {
		Node it = root;
		for (int i = 0; i < word.length(); ) {
			if (it.next.containsKey(word.charAt(i))) {
				Edge edge = it.next.get(word.charAt(i));
				i += edge.getLength();
				it = edge.getDest();
			}
		}
		return it;
	}

}


text:
package uk.ac.ncl.openlab.intake24.client.survey.portionsize;

import org.pcollections.PMap;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class WeightPortionScriptLoader implements PortionSizeScriptLoader {
	@Override
	public void loadResources(final PMap<String, String> data, final AsyncCallback<PortionSizeScript> onComplete) {
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			public void execute() {
				onComplete.onSuccess(new WeightPortionScript());
			}
		});
	}
}


text:
<?php
function initSession() {
	ini_set('session.use_cookies', 1);
	ini_set('session.use_only_cookies', 1);
	ini_set('session.use_trans_sid', 0);

	session_cache_limiter('nocache');
	session_name('SID');
	session_set_cookie_params(0); // invalidate session-cookie on browser-close
	session_start();
}

function updateSession() {
	if (isset($_SERVER['SOLAR_CONFIG']['AUTH']['TIMEOUT'])) {
		$timeout = (int)$_SERVER['SOLAR_CONFIG']['AUTH']['TIMEOUT'];
		if ($timeout > 0) {
			$_SESSION['EXPIRE'] = time() + $timeout;
		}
	}
}

function requiresAuth() {
	return ( isset($_SERVER['SOLAR_CONFIG']['AUTH'])
		  && isset($_SERVER['SOLAR_CONFIG']['AUTH']['PASSWORD'])
		  && strlen($_SERVER['SOLAR_CONFIG']['AUTH']['PASSWORD']) > 0 );
}

function checkAuth() {
	if (!requiresAuth())
		return true;

	if (!isset($_SESSION['AUTH']) || !$_SESSION['AUTH'])
		return false;

	if ($_SESSION['IP'] != $_SERVER['REMOTE_ADDR'])
		return false;

	if ($_SESSION['UA'] != $_SERVER['HTTP_USER_AGENT'])
		return false;

	if ($_SESSION['EXPIRE'] > 0 && $_SESSION['EXPIRE'] < time())
		return false;

	return true;
}

function generateChallenge() {
	$prefix = '';
	return sha1( uniqid($prefix, true) );
}

function generateExpectedResponse($challenge) {
	return sha1( $challenge . $_SERVER['SOLAR_CONFIG']['AUTH']['PASSWORD'] );
}

function isLogin(&$retChallenge, &$retResponse) {
	if (!isset($_REQUEST['auth']) || !isset($_REQUEST['c']) || !isset($_REQUEST['r']))
		return false;

	if (strlen($_REQUEST['c']) == 0 || strlen($_REQUEST['r']) == 0)
		return false;

	$retChallenge = $_REQUEST['c'];
	$retResponse  = $_REQUEST['r'];
	return true;
}

function checkLogin($challenge, $response) {
	$exp = generateExpectedResponse($challenge);
	return ($response == $exp);
}

function doLogin() {
	session_regenerate_id();
	$_SESSION['AUTH']   = true;
	$_SESSION['IP']     = $_SERVER['REMOTE_ADDR'];
	$_SESSION['UA']     = $_SERVER['HTTP_USER_AGENT'];
	$_SESSION['EXPIRE'] = -1; // will be properly set by updateSession()
}

function isLogout() {
	return isset($_REQUEST['logout']);
}

function doLogout() {
	$_SESSION = array();
	session_destroy();
}

function getLoginForm($header) {
	$self      = $_SERVER['PHP_SELF'];
	$challenge = generateChallenge();

	$o = <<<EOC

${header}

	<form name="auth" action="${self}" method="GET">
		<input name="c" type="hidden" value="${challenge}" />
		<input name="r" type="hidden" value="" />
		<input name="p" type="password" value="" autofocus="autofocus" />
		<input name="auth" type="submit" value="Login" />
	</form>

EOC;

	return $o;
}