text:
//#define TRACEDEBUG
//#define TRACEDEBUGTICKS
//#define TRACELOG

using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.Ccr.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.ServiceModel.DsspServiceBase;
using W3C.Soap;

//for XSLT:
using Microsoft.Dss.Core.DsspHttpUtilities;
using Microsoft.Dss.Core.DsspHttp;
using System.Net;
using System.Collections.Specialized;

using cons = Microsoft.Dss.Services.Constructor;
using submgr = Microsoft.Dss.Services.SubscriptionManager;
using coord = Microsoft.Robotics.Services.Coordination;

using trmotor = TrackRoamer.Robotics.Services.TrackRoamerServices.Motor.Proxy;
using motor = Microsoft.Robotics.Services.Motor.Proxy;

using trencoder = TrackRoamer.Robotics.Services.TrackRoamerServices.Encoder.Proxy;
using encoder = Microsoft.Robotics.Services.Encoder.Proxy;

using drive = Microsoft.Robotics.Services.Drive.Proxy;

using TrackRoamer.Robotics.Utility.LibSystem;

namespace TrackRoamer.Robotics.Services.TrackRoamerDrive
{
    [Contract(Contract.Identifier)]
    [AlternateContract(drive.Contract.Identifier)]
    [DisplayName("(User) TrackRoamer Differential Drive")]
    [Description("Provides access to an TrackRoamer differential motor drive - coordinates two motors that function together.\n(Uses the Generic Differential Drive contract.)\n(Partner with the 'TrackRoamerPowerBrick' service.)")]
    [ActivationSettings(ShareDispatcher = false, ExecutionUnitsPerDispatcher = 6)]      // allow more threads for dispatcher (default is 2 threads, way too low)
    class TrackRoamerDriveService : DsspServiceBase
    {
        /// <summary>
        /// Service state
        /// </summary>
        [ServiceState]
        [InitialStatePartner(Optional = true)]
        private drive.DriveDifferentialTwoWheelState _state = new drive.DriveDifferentialTwoWheelState();

        drive.DriveRequestOperation _internalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified;

        /// <summary>
        /// Main service port
        /// </summary>
        [ServicePort("/TrackRoamerDrive", AllowMultipleInstances = false)]
        drive.DriveOperations _mainPort = new drive.DriveOperations();

        // This is the internal drive port for excuting the drive operations that must wait for encoders ticks reaching preset value:
        //  driveDistance, and rotateDegrees.
        private PortSet<drive.DriveDistance, drive.RotateDegrees> _internalDriveOperationsPort = new PortSet<drive.DriveDistance, drive.RotateDegrees>();

        // Port used for canceling a driveDistance or RotateDegrees operation.
        //private Port<drive.CancelPendingDriveOperation> _internalDriveCancelOperationPort = new Port<drive.CancelPendingDriveOperation>();

        [SubscriptionManagerPartner]
        submgr.SubscriptionManagerPort _subMgrPort = new submgr.SubscriptionManagerPort();

        [Partner(Partners.LeftMotor,
            Contract = motor.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.UsePartnerListEntry)]
        motor.MotorOperations _leftMotorPort = new motor.MotorOperations();

        [Partner(Partners.RightMotor,
            Contract = motor.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.UsePartnerListEntry)]
        motor.MotorOperations _rightMotorPort = new motor.MotorOperations();

        [Partner(Partners.LeftEncoder,
            Optional = false,
            Contract = encoder.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.UsePartnerListEntry)]
        encoder.EncoderOperations _leftEncoderPort = new encoder.EncoderOperations();
        Port<encoder.UpdateTickCount> _leftEncoderTickPort = new Port<encoder.UpdateTickCount>();   // notifications from Left Encoder
        //encoder.EncoderOperations _leftEncoderTickPort = new encoder.EncoderOperations();             // notifications - ticks and state from Left Encoder
        bool _leftEncoderTickEnabled = false;

        [Partner(Partners.RightEncoder,
            Optional = false,
            Contract = encoder.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.UsePartnerListEntry)]
        encoder.EncoderOperations _rightEncoderPort = new encoder.EncoderOperations();
        Port<encoder.UpdateTickCount> _rightEncoderTickPort = new Port<encoder.UpdateTickCount>();   // notifications from Right Encoder
        //encoder.EncoderOperations _rightEncoderTickPort = new encoder.EncoderOperations();             // notifications - ticks and state from Right Encoder
        bool _rightEncoderTickEnabled = false;

        // we are permanently subscribed to encoder ticks, but allow or disallow them to be processed via flags:
        private bool EncoderTicksEnabled
        {
            set
            {
                _rightEncoderTickEnabled = value;
                _leftEncoderTickEnabled = value;
            }
        }

        //For XSLT
        DsspHttpUtilitiesPort _httpUtilities = new DsspHttpUtilitiesPort();
        [EmbeddedResource("TrackRoamer.Robotics.Services.TrackRoamerDrive.TrackRoamerDrive.xslt")]
        string _transform = null;

        /// <summary>
        /// Polling the encoder state
        /// </summary>
        private Port<DateTime> encodersPollingPort = new Port<DateTime>();

        /// <summary>
        /// TrackRoamerDrive Service constructor
        /// </summary>
        public TrackRoamerDriveService(DsspServiceCreationPort creationPort)
            : base(creationPort)
        {
            LogInfo("TrackRoamerDriveService:TrackRoamerDriveService() -- port: " + creationPort.ToString());
        }

        /// <summary>
        /// Service Startup Handler
        /// </summary>
        protected override void Start()
        {
            LogInfo("TrackRoamerDriveService:: Start() ");

            InitState();

            _internalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified;

            // send configuration commands to partner services
            SpawnIterator(ConfigureDrive);

            _state.TimeStamp = DateTime.Now;

            //needed for HttpPost
            _httpUtilities = DsspHttpUtilitiesService.Create(Environment);

            base.Start();

            // Interleave to manage internal drive operations (driveDistance and RotateDegrees)
            Activate(
                new Interleave(
                    new ExclusiveReceiverGroup(
                                    Arbiter.ReceiveWithIterator(true, this.encodersPollingPort, this.PollEncoders),
                                    Arbiter.ReceiveWithIteratorFromPortSet<drive.DriveDistance>(true, _internalDriveOperationsPort, InternalDriveDistanceHandler),
                                    Arbiter.ReceiveWithIteratorFromPortSet<drive.RotateDegrees>(true, _internalDriveOperationsPort, InternalRotateDegreesHandler)
                    ),
                    new ConcurrentReceiverGroup())
                   );
        }

        public int EncodersPollingInterval = 1000;     // milliseconds

        /// <summary>
        /// a slow polling process to keep encoders state in sync. Not the ticks-updating mechanism, which is subscription based
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private IEnumerator<ITask> PollEncoders(DateTime dt)
        {
            try{
                pollEncoderState();
            }
            finally
            {
                // Ensure we haven't been droppped
                if (ServicePhase == ServiceRuntimePhase.Started)
                {
                    // Issue another polling request
                    Activate(TimeoutPort(EncodersPollingInterval).Receive(this.encodersPollingPort.Post));
                }
            }

            yield break;
        }

        #region InitState()

        private void InitState()
        {
            LogInfo("TrackRoamerDriveService:: InitState() _state=" + _state);

            if (_state == null)
            {
                // no partner-supplied initial state found - create default one:

                LogInfo("TrackRoamerDriveService:: InitState()  (null) - creating one");

                //_state = new TrackRoamerDriveState();
                _state = new drive.DriveDifferentialTwoWheelState();

                _state.DistanceBetweenWheels = TrackRoamerDriveParams.DistanceBetweenWheels;

                _state.LeftWheel = new motor.WheeledMotorState();
                _state.LeftWheel.Radius = TrackRoamerDriveParams.WheelRadius;
                _state.LeftWheel.GearRatio = TrackRoamerDriveParams.WheelGearRatio;
                _state.LeftWheel.MotorState = new motor.MotorState();
                _state.LeftWheel.MotorState.HardwareIdentifier = 1;
                _state.LeftWheel.MotorState.Name = "Left Motor";
                _state.LeftWheel.MotorState.PowerScalingFactor = TrackRoamerDriveParams.MotorPowerScalingFactor;
                _state.LeftWheel.MotorState.ReversePolarity = true;

                _state.RightWheel = new motor.WheeledMotorState();
                _state.RightWheel.Radius = TrackRoamerDriveParams.WheelRadius;
                _state.RightWheel.GearRatio = TrackRoamerDriveParams.WheelGearRatio;
                _state.RightWheel.MotorState = new motor.MotorState();
                _state.RightWheel.MotorState.HardwareIdentifier = 2;
                _state.RightWheel.MotorState.Name = "Right Motor";
                _state.RightWheel.MotorState.PowerScalingFactor = TrackRoamerDriveParams.MotorPowerScalingFactor;
                _state.RightWheel.MotorState.ReversePolarity = true;

                _state.LeftWheel.EncoderState = new encoder.EncoderState();
                _state.LeftWheel.EncoderState.HardwareIdentifier = 1;
                _state.LeftWheel.EncoderState.TicksPerRevolution = TrackRoamerDriveParams.EncoderTicksPerWheelRevolution;

                _state.RightWheel.EncoderState = new encoder.EncoderState();
                _state.RightWheel.EncoderState.HardwareIdentifier = 2;
                _state.RightWheel.EncoderState.TicksPerRevolution = TrackRoamerDriveParams.EncoderTicksPerWheelRevolution;

                _state.IsEnabled = true;
                _state.TimeStamp = DateTime.Now;
            	//_state.InternalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified;  -- not available in drive.Proxy

                LogInfo("TrackRoamerDriveService:: InitState(): saving state");

                SaveState(_state);
            }
            else
            {
                LogInfo("TrackRoamerDriveService:: InitState() (not null) _state.DistanceBetweenWheels=" + _state.DistanceBetweenWheels);
                //    + " PowerScalingFactor=" + _state.LeftWheel.MotorState.PowerScalingFactor + "/" + _state.RightWheel.MotorState.PowerScalingFactor);
            	//_state.InternalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified;  -- not available in drive.Proxy
	            _state.TimeStamp = DateTime.Now;
            }
        }
        #endregion // InitState()

        #region ConfigureDrive() iterator

        private IEnumerator<ITask> ConfigureDrive()
        {
            LogInfo("TrackRoamerDriveService:: ConfigureDrive()");

            bool noError = true;

            // Configure motor connections
            motor.Replace configureLeftMotor = new motor.Replace();
            configureLeftMotor.Body = _state.LeftWheel.MotorState;
            _leftMotorPort.Post(configureLeftMotor);

            motor.Replace configureRightMotor = new motor.Replace();
            configureRightMotor.Body = _state.RightWheel.MotorState;
            _rightMotorPort.Post(configureRightMotor);

            yield return Arbiter.Choice(configureLeftMotor.ResponsePort,
                delegate(DefaultReplaceResponseType success) { LogInfo("    Left Motor Configured"); },
                delegate(Fault fault) { LogError(fault); noError = false; });

            yield return Arbiter.Choice(configureRightMotor.ResponsePort,
                delegate(DefaultReplaceResponseType success) { LogInfo("    Right Motor Configured"); },
                delegate(Fault fault) { LogError(fault); noError = false; });

            // Configure encoder connections, and permanently subscribe to the encoders on internal ports.
            if (_leftEncoderPort != null)
            {
                encoder.Replace configureLeftEncoder = new encoder.Replace();
                configureLeftEncoder.Body = _state.LeftWheel.EncoderState;
                _leftEncoderPort.Post(configureLeftEncoder);

                yield return Arbiter.Choice(configureLeftEncoder.ResponsePort,
                    delegate(DefaultReplaceResponseType success) { LogInfo("    Left Encoder Configured"); },
                    delegate(Fault fault) { LogError(fault); noError = false; });

                encoder.Subscribe op = new encoder.Subscribe();
                op.Body = new SubscribeRequestType();
                op.NotificationPort = _leftEncoderTickPort;
                _leftEncoderPort.Post(op);

                yield return (Arbiter.Choice(op.ResponsePort,
                    delegate(SubscribeResponseType response)
                    {
                        //subscription was successful, start listening for encoder replace messages
                        Activate(Arbiter.Receive<encoder.UpdateTickCount>(true, _leftEncoderTickPort,       // "true" here makes listener to subscription permanent
                            delegate(encoder.UpdateTickCount update)
                            {
#if TRACEDEBUGTICKS
                                LogInfo("Drive: left encoder tick: " + update.Body.Count);
#endif // TRACEDEBUGTICKS
                                StopMotorWithEncoderHandler(_leftEncoderTickPort, "left", update, _leftMotorPort);
                            }));
                    },
                    delegate(Fault fault) { LogError(fault); noError = false; }
                ));
            }

            if (_rightEncoderPort != null)
            {
                encoder.Replace configureRightEncoder = new encoder.Replace();
                configureRightEncoder.Body = _state.RightWheel.EncoderState;
                _rightEncoderPort.Post(configureRightEncoder);

                yield return Arbiter.Choice(configureRightEncoder.ResponsePort,
                    delegate(DefaultReplaceResponseType success) { LogInfo("    Right Encoder Configured"); },
                    delegate(Fault fault) { LogError(fault); noError = false; });

                encoder.Subscribe op2 = new encoder.Subscribe();
                op2.Body = new SubscribeRequestType();
                op2.NotificationPort = _rightEncoderTickPort;
                _rightEncoderPort.Post(op2);

                yield return (Arbiter.Choice(op2.ResponsePort,
                    delegate(SubscribeResponseType response)
                    {
                        //subscription was successful, start listening for encoder replace messages
                        Activate(Arbiter.Receive<encoder.UpdateTickCount>(true, _rightEncoderTickPort,       // "true" here makes listener to subscription permanent
                            delegate(encoder.UpdateTickCount update)
                            {
#if TRACEDEBUGTICKS
                                LogInfo("Drive: right encoder tick: " + update.Body.Count);
#endif // TRACEDEBUGTICKS
                                StopMotorWithEncoderHandler(_rightEncoderTickPort, "right", update, _rightMotorPort);
                            }
                        ));
                    },
                    delegate(Fault fault) { LogError(fault); noError = false; }
                ));
            }

            if (noError)
            {
                LogInfo("TrackRoamerDriveService:: ConfigureDrive() - success");
                _state.IsEnabled = true;

                // Start the encoder polling interval
                this.encodersPollingPort.Post(DateTime.Now);
            }
            else
            {
                LogError("TrackRoamerDriveService:: ConfigureDrive() - failure");
                _state.IsEnabled = false;
            }

            yield break;
        }
        #endregion // ConfigureDrive()

        #region Operation Handlers - implementing Microsoft DriveDifferentialTwoWheel

        /// <summary>
        /// Get Handler
        /// </summary>
        /// <param name="get"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent)]
        public IEnumerator<ITask> GetHandler(drive.Get get)
        {
            get.ResponsePort.Post(_state);
            yield break;
        }

        /// <summary>
        /// Update Handler
        /// </summary>
        /// <param name="update"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> UpdateHandler(drive.Update update)
        {
            _state = update.Body;
            _state.TimeStamp = DateTime.Now;
            update.ResponsePort.Post(new DefaultUpdateResponseType());
            yield break;
        }

        /// <summary>
        /// Subscribe Handler
        /// </summary>
        /// <param name="subscribe"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> SubscribeHandler(drive.Subscribe subscribe)
        {
            yield return Arbiter.Choice(
                SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort),
                delegate(SuccessResult success)
                {
                    drive.Update update = new drive.Update(_state);
                    SendNotificationToTarget<drive.Update>(subscribe.Body.Subscriber, _subMgrPort, update);
                },
                delegate(Exception ex)
                {
                    LogError(ex);
                    throw ex;
                }
            );
        }

        /// <summary>
        /// Reliable Subscribe Handler
        /// </summary>
        /// <param name="subscribe"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> ReliableSubscribeHandler(drive.ReliableSubscribe subscribe)
        {
            yield return Arbiter.Choice(
                SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort),
                delegate(SuccessResult success)
                {
                    drive.Update update = new drive.Update(_state);
                    SendNotificationToTarget<drive.Update>(subscribe.Body.Subscriber, _subMgrPort, update);
                },
                delegate(Exception ex)
                {
                    LogError(ex);
                    throw ex;
                }
            );
        }

        [ServiceHandler(ServiceHandlerBehavior.Teardown)]
        public virtual IEnumerator<ITask> DropHandler(DsspDefaultDrop drop)
        {
            LogInfo("TrackRoamerDriveService:DropHandler()");

            base.DefaultDropHandler(drop);

            yield break;
        }

        /// <summary>
        /// Handles EnableDrive requests
        /// </summary>
        /// <param name="enabledrive">request message</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> EnableDriveHandler(drive.EnableDrive enableDrive)
        {

            _state.IsEnabled = enableDrive.Body.Enable;
            _state.TimeStamp = DateTime.Now;

#if TRACELOG
            LogInfo("TrackRoamerDriveService:EnableDriveHandler() - enable=" + _state.IsEnabled);
#endif

            // if we are enabling the drive, validate that the motors are configured.
            if (enableDrive.Body.Enable)
            {
                try
                {
                    ValidateDriveConfiguration(true);   // we must have encoders for the drive to work properly
                }
                catch (InvalidOperationException)
                {
                    // If validation fails,
                    // force the state to not be enabled.
                    _state.IsEnabled = false;

                    // rethrow the fault
                    throw;
                }
            }

            // send notification to subscription manager
            drive.Update update = new drive.Update(_state);
            SendNotification<drive.Update>(_subMgrPort, update);

            enableDrive.ResponsePort.Post(DefaultUpdateResponseType.Instance);
            yield break;
        }

        #region Drive Power Handler

        /// <summary>
        /// Handles SetDrivePower requests
        /// </summary>
        /// <param name="setdrivepower">request message</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> SetDrivePowerHandler(drive.SetDrivePower setDrivePower)
        {
            ValidateDriveConfiguration(false);

#if TRACELOG
            Tracer.Trace("TR Drive: SetDrivePowerHandler()  =============================== TR handler ====================================     left=" + setDrivePower.Body.LeftWheelPower + "   right=" + setDrivePower.Body.RightWheelPower);
#endif
            cancelCurrentOperation();

            _state.TimeStamp = DateTime.Now;

            PortSet<DefaultUpdateResponseType, Fault> responsePort = new PortSet<DefaultUpdateResponseType, Fault>();

            // Add a coordination header to our motor requests
            // so that advanced motor implementations can
            // coordinate the individual motor reqests.
            coord.ActuatorCoordination coordination = new coord.ActuatorCoordination(2);

            motor.SetMotorPower leftPower = new motor.SetMotorPower(new motor.SetMotorPowerRequest() { TargetPower = setDrivePower.Body.LeftWheelPower });
            leftPower.ResponsePort = responsePort;
            leftPower.AddHeader(coordination);
            _leftMotorPort.Post(leftPower);

            motor.SetMotorPower rightPower = new motor.SetMotorPower(new motor.SetMotorPowerRequest() { TargetPower = setDrivePower.Body.RightWheelPower });
            rightPower.ResponsePort = responsePort;
            rightPower.AddHeader(coordination);
            _rightMotorPort.Post(rightPower);

            // send notification to subscription manager
            drive.Update update = new drive.Update(_state);
            SendNotification<drive.Update>(_subMgrPort, update);

            Activate(Arbiter.MultipleItemReceive<DefaultUpdateResponseType, Fault>(responsePort, 2,
                delegate(ICollection<DefaultUpdateResponseType> successList, ICollection<Fault> failureList)
                {
                    if (successList.Count == 2)
                        setDrivePower.ResponsePort.Post(new DefaultUpdateResponseType());

                    foreach (Fault fault in failureList)
                    {
                        setDrivePower.ResponsePort.Post(fault);
                        break;
                    }
                }));

            pollEncoderState();

            yield break;
        }

        #endregion //  Drive Power Handler

        #region Drive Speed Handler

        /// <summary>
        /// Handles SetDriveSpeed requests
        /// </summary>
        /// <param name="setDriveSpeed">request message</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> SetDriveSpeedHandler(drive.SetDriveSpeed setDriveSpeed)
        {
            ValidateDriveConfiguration(true);

            cancelCurrentOperation();

            _state.TimeStamp = DateTime.Now;

            LogError("Drive speed is not implemented");

            throw new NotImplementedException();
        }

        #endregion // Drive Speed Handler

        #region Rotate Degrees Handler

        /// <summary>
        /// Handles RotateDegrees requests (positive degrees turn counterclockwise)
        /// </summary>
        /// <param name="rotatedegrees">request message</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> RotateDegreesHandler(drive.RotateDegrees rotateDegrees)
        {
            ValidateDriveConfiguration(true);
            if (_state.DistanceBetweenWheels <= 0)
            {
                rotateDegrees.ResponsePort.Post(new Fault());
                throw new InvalidOperationException("The wheel encoders are not properly configured");
            }
            else
            {
#if TRACELOG
                Tracer.Trace("^^^^^^^^^^^^^^^^^^^^^ TrackRoamerDriveService:: RotateDegreesHandler(degrees=" + rotateDegrees.Body.Degrees + ")");
#endif
                _state.TimeStamp = DateTime.Now;

                // send immediate response
                rotateDegrees.ResponsePort.Post(DefaultUpdateResponseType.Instance);

                // post request to internal port.
                _internalDriveOperationsPort.Post(rotateDegrees);

            }
            yield break;
        }

        int stopLeftWheelAt;
        int stopRightWheelAt;

        /// <summary>
        /// Rotate the the drive (positive degrees turn counterclockwise)
        /// </summary>
        /// <param name="degrees">(positive degrees turn counterclockwise)</param>
        /// <param name="power">(-1.0 to 1.0)</param>
        IEnumerator<ITask> RotateUntilDegrees(double degrees, double power)
        {
#if TRACELOG
            Tracer.Trace("^^^^^^^^^^^^^^^^^^^^^ TrackRoamerDriveService:: RotateUntilDegrees(degrees=" + degrees + ",  power=" + power + ")");
#endif

            EncoderTicksEnabled = false;

            //reset encoders
            encoder.Reset Lreset = new encoder.Reset();
            _leftEncoderPort.Post(Lreset);
            yield return (Arbiter.Choice(Lreset.ResponsePort,
                delegate(DefaultUpdateResponseType response) { },
                delegate(Fault fault) { LogError(fault); }
            ));

            encoder.Reset Rreset = new encoder.Reset();
            _rightEncoderPort.Post(Rreset);
            yield return (Arbiter.Choice(Rreset.ResponsePort,
                delegate(DefaultUpdateResponseType response) { },
                delegate(Fault fault) { LogError(fault); }
            ));

            double arcDistance = Math.Abs(degrees) * _state.DistanceBetweenWheels * Math.PI / 360.0d;

            //compute tick to stop at
            stopLeftWheelAt = (int)Math.Round(arcDistance / (2.0d * Math.PI * _state.LeftWheel.Radius / _state.LeftWheel.EncoderState.TicksPerRevolution));
            stopRightWheelAt = (int)Math.Round(arcDistance / (2.0d * Math.PI * _state.RightWheel.Radius / _state.RightWheel.EncoderState.TicksPerRevolution));

            EncoderTicksEnabled = true;

            pollEncoderState();     // get starting encoder state

            //start moving

            // start rotate operation
            _state.RotateDegreesStage = drive.DriveStage.Started;

            drive.RotateDegrees rotateUpdate = new drive.RotateDegrees();
            rotateUpdate.Body.RotateDegreesStage = drive.DriveStage.Started;
#if TRACELOG
            Tracer.Trace("++++++++++++++++++ DRIVE: RotateUntilDegrees() DriveStage.Started");
#endif
            _internalDriveOperationsPort.Post(rotateUpdate);

            PortSet<DefaultUpdateResponseType, Fault> responsePort = new PortSet<DefaultUpdateResponseType, Fault>();

            double rightPow;
            double leftPow;

            if (degrees > 0)
            {
                rightPow = power;
                leftPow = -power;
            }
            else
            {
                rightPow = -power;
                leftPow = power;
            }

            motor.SetMotorPower leftPower = new motor.SetMotorPower(new motor.SetMotorPowerRequest() { TargetPower = leftPow });
            leftPower.ResponsePort = responsePort;
            _leftMotorPort.Post(leftPower);

            motor.SetMotorPower rightPower = new motor.SetMotorPower(new motor.SetMotorPowerRequest() { TargetPower = rightPow });
            rightPower.ResponsePort = responsePort;
            _rightMotorPort.Post(rightPower);

#if TRACELOG
            Tracer.Trace("=============== TrackRoamerDriveService:: RotateUntilDegrees() start moving: degrees=" + degrees);
            Tracer.Trace("=============== TrackRoamerDriveService:: RotateUntilDegrees() will stop wheels at:  Left=" + stopLeftWheelAt + " Right=" + stopRightWheelAt);
#endif

            Activate(Arbiter.MultipleItemReceive<DefaultUpdateResponseType, Fault>(responsePort, 2,
                delegate(ICollection<DefaultUpdateResponseType> successList, ICollection<Fault> failureList)
                {
                    foreach (Fault fault in failureList)
                    {
                        LogError(fault);
                    }
                }
            ));

#if TRACELOG
            Tracer.Trace("=============== TrackRoamerDriveService:: RotateUntilDegrees() calling DriveWaitForCompletionDual() - waiting for both sides to complete...");
#endif

            yield return DriveWaitForCompletionDual();

#if TRACELOG
            Tracer.Trace("=============== TrackRoamerDriveService:: RotateUntilDegrees() - both sides completed, send notification of RotateDegrees complete to subscription manager");
#endif

            // send notification of RotateDegrees complete to subscription manager
            rotateUpdate.Body.RotateDegreesStage = drive.DriveStage.Completed;
#if TRACELOG
            Tracer.Trace("++++++++++++++++++ DRIVE: RotateUntilDegrees() DriveStage.Completed");
#endif
            _internalDriveOperationsPort.Post(rotateUpdate);

            _state.RotateDegreesStage = drive.DriveStage.Completed;
        }

        #endregion // Rotate Degrees Handler

        #region Drive Distance Handler

        /// <summary>
        /// Handles DriveDistance requests
        /// </summary>
        /// <param name="drivedistance">request message</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> DriveDistanceHandler(drive.DriveDistance driveDistance)
        {
            // If configuration is invalid, an InvalidException is thrown.
            ValidateDriveConfiguration(true);
            _state.TimeStamp = DateTime.Now;

#if TRACELOG
            Tracer.Trace("==================== TrackRoamerDriveService:: DriveDistanceHandler(distance=" + driveDistance.Body.Distance + ")");
#endif

            // send immediate response
            driveDistance.ResponsePort.Post(DefaultUpdateResponseType.Instance);

            // post request to internal port.
            _internalDriveOperationsPort.Post(driveDistance);

            yield break;
        }

        /// <summary>
        /// drives a specified number of meters
        /// </summary>
        IEnumerator<ITask> DriveUntilDistance(double distance, double power)
        {
#if TRACELOG
            Tracer.Trace("=============== TrackRoamerDriveService:: DriveUntilDistance(distance=" + distance + " meters,  power=" + power + ")");
#endif

            EncoderTicksEnabled = false;

            //reset encoders
            encoder.Reset Lreset = new encoder.Reset();
            _leftEncoderPort.Post(Lreset);
            yield return (Arbiter.Choice(Lreset.ResponsePort,
                delegate(DefaultUpdateResponseType response) { },
                delegate(Fault fault) { LogError(fault); }
            ));

            encoder.Reset Rreset = new encoder.Reset();
            _rightEncoderPort.Post(Rreset);
            yield return (Arbiter.Choice(Rreset.ResponsePort,
                delegate(DefaultUpdateResponseType response) { },
                delegate(Fault fault) { LogError(fault); }
            ));

            //compute tick to stop at
            stopLeftWheelAt = (int)Math.Round(Math.Abs(distance) / (2.0 * 3.14159 * _state.LeftWheel.Radius / _state.LeftWheel.EncoderState.TicksPerRevolution));
            stopRightWheelAt = (int)Math.Round(Math.Abs(distance) / (2.0 * 3.14159 * _state.RightWheel.Radius / _state.RightWheel.EncoderState.TicksPerRevolution));

            EncoderTicksEnabled = true;

            pollEncoderState();     // get starting encoder state

            //start moving

            double Pow;

            if (distance > 0)
                Pow = power;
            else
                Pow = -power;

            PortSet<DefaultUpdateResponseType, Fault> responsePort = new PortSet<DefaultUpdateResponseType, Fault>();

            // send notification of driveDistance start to subscription manager
            _state.DriveDistanceStage = drive.DriveStage.Started;

            drive.DriveDistance driveUpdate = new drive.DriveDistance();
            driveUpdate.Body.DriveDistanceStage = drive.DriveStage.Started;
#if TRACELOG
            Tracer.Trace("++++++++++++++++++ DRIVE: DriveUntilDistance() DriveStage.Started");
#endif
            _internalDriveOperationsPort.Post(driveUpdate);

            motor.SetMotorPower leftPower = new motor.SetMotorPower(new motor.SetMotorPowerRequest() { TargetPower = Pow });
            leftPower.ResponsePort = responsePort;
            _leftMotorPort.Post(leftPower);

            motor.SetMotorPower rightPower = new motor.SetMotorPower(new motor.SetMotorPowerRequest() { TargetPower = Pow });
            rightPower.ResponsePort = responsePort;
            _rightMotorPort.Post(rightPower);

#if TRACELOG
            Tracer.Trace("=============== TrackRoamerDriveService:: DriveUntilDistance() start moving: distance=" + distance + " meters");
            Tracer.Trace("=============== TrackRoamerDriveService:: DriveUntilDistance() will stop wheels at:  Left=" + stopLeftWheelAt + "   Right=" + stopRightWheelAt);
#endif

            Activate(Arbiter.MultipleItemReceive<DefaultUpdateResponseType, Fault>(responsePort, 2,
                delegate(ICollection<DefaultUpdateResponseType> successList, ICollection<Fault> failureList)
                {
                    foreach (Fault fault in failureList)
                    {
                        LogError(fault);
                    }
                }
            ));

#if TRACELOG
            Tracer.Trace("=============== TrackRoamerDriveService:: DriveUntilDistance() calling DriveWaitForCompletionDual() - waiting for both sides to complete...");
#endif

            yield return DriveWaitForCompletionDual();

            // send notification of driveDistance complete to subscription manager
            driveUpdate.Body.DriveDistanceStage = drive.DriveStage.Completed;
#if TRACELOG
            Tracer.Trace("++++++++++++++++++ DRIVE: DriveUntilDistance() DriveStage.Completed");
#endif
            _internalDriveOperationsPort.Post(driveUpdate);

            _state.DriveDistanceStage = drive.DriveStage.Completed;
        }

        #endregion // Drive Distance Handler

        #region AllStop Handler

        /// <summary>
        /// Handles AllStop requests
        /// </summary>
        /// <param name="allstop">request message</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> AllStopHandler(drive.AllStop allStop)
        {
            /*
                from http://social.msdn.microsoft.com/Forums/en-US/roboticssimulation/thread/13fb26c8-75fe-43b9-9e65-6a915e7d2560 :
                In RDS 2008 there is some discussion of the Generic Differential Drive in the Help file.
                AllStop should cause the current operation to be cancelled, as you expect.
                It will then disable the drive and you will have to issue an EnableDrive request before you can get the robot to move again.
                This is by design so that AllStop can act as an Emergency Stop and prevent any further action without an explicit reset.
                There should be a notification from the drive service that the drive power has been set to zero after the AllStop.
             */

#if TRACELOG
            LogInfo("TrackRoamerDriveService:: AllStopHandler()");
#endif

            cancelCurrentOperation();

            drive.SetDrivePower zeroPower = new drive.SetDrivePower();
            zeroPower.Body = new drive.SetDrivePowerRequest(0.0d, 0.0d);
            zeroPower.ResponsePort = allStop.ResponsePort;
            _mainPort.Post(zeroPower);

            pollEncoderState();     // get starting encoder state

            yield break;
        }

        #endregion // AllStop Handler

        /// <summary>
        /// ResetEncoders handler
        /// </summary>
        /// <param name="resetEncoders">ResetEncoders message</param>
        /// <returns>A CCR task enumerator</returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public IEnumerator<ITask> ResetEncodersHandler(drive.ResetEncoders resetEncoders)
        {
            encoder.Reset rightResetRequest = null;
            encoder.Reset leftResetRequest = null;

            if (this._rightEncoderPort != null)
            {
                rightResetRequest = new encoder.Reset();

                this._rightEncoderPort.Post(rightResetRequest);
            }

            if (this._leftEncoderPort != null)
            {
                leftResetRequest = new encoder.Reset();

                this._leftEncoderPort.Post(leftResetRequest);
            }

            if (rightResetRequest != null)
            {
                yield return rightResetRequest.ResponsePort.Choice(EmptyHandler, EmptyHandler);
            }

            if (leftResetRequest != null)
            {
                yield return leftResetRequest.ResponsePort.Choice(EmptyHandler, EmptyHandler);
            }

            this.SendNotification<drive.ResetEncoders>(this._subMgrPort, resetEncoders.Body);

            resetEncoders.ResponsePort.Post(new DefaultUpdateResponseType());

            yield break;
        }

        #endregion // Operation Handlers (implementing MS Generic Drive)

        #region HTTP Get / Post
        /// <summary>
        /// Http Get Handler.  Needed for XSLT transform
        /// </summary>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent)]
        public virtual IEnumerator<ITask> HttpGetHandler(HttpGet httpGet)
        {
            HttpListenerRequest request = httpGet.Body.Context.Request;
            HttpListenerResponse response = httpGet.Body.Context.Response;

            string path = request.Url.AbsolutePath;

            HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transform);
            httpGet.ResponsePort.Post(rsp);
            yield break;

        }

        /// <summary>
        /// Http Post Handler.  Handles http form inputs
        /// </summary>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public void HttpPostHandler(HttpPost httpPost)
        {
            HttpPostRequestData formData = httpPost.GetHeader<HttpPostRequestData>();

            try
            {
                DsspOperation operation = formData.TranslatedOperation;

                if (operation is drive.DriveDistance)
                {
                    _mainPort.Post((drive.DriveDistance)operation);
                }
                else if (operation is drive.SetDrivePower)
                {
                    _mainPort.Post((drive.SetDrivePower)operation);
                }
                else if (operation is drive.RotateDegrees)
                {
                    _mainPort.Post((drive.RotateDegrees)operation);
                }
                else if (operation is drive.EnableDrive)
                {
                    _mainPort.Post((drive.EnableDrive)operation);
                }
                else if (operation is drive.AllStop)
                {
                    _mainPort.Post((drive.AllStop)operation);
                }
                else if (operation is drive.ResetEncoders)
                {
                    _mainPort.Post((drive.ResetEncoders)operation);
                }
                else
                {
                    NameValueCollection parameters = formData.Parameters;

                    if (parameters["StartDashboard"] != null)
                    {
                        string Dashboardcontract = "http://schemas.microsoft.com/robotics/2006/01/simpledashboard.user.html";
                        ServiceInfoType info = new ServiceInfoType(Dashboardcontract);
                        cons.Create create = new cons.Create(info);
                        create.TimeSpan = DsspOperation.DefaultShortTimeSpan;

                        ConstructorPort.Post(create);
                        Activate(Arbiter.Choice(
                            create.ResponsePort,
                            delegate(CreateResponse createResponse) { },
                            delegate(Fault f) { LogError(f); }
                        ));
                    }
                    else if (parameters["DrivePower"] != null)
                    {
                        double power = double.Parse(parameters["Power"]);
                        drive.SetDrivePowerRequest drivepower = new drive.SetDrivePowerRequest();
                        drivepower.LeftWheelPower = power;
                        drivepower.RightWheelPower = power;
                        _mainPort.Post(new drive.SetDrivePower(drivepower));
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }
                }
                HttpPostSuccess(httpPost);
            }
            catch
            {
                HttpPostFailure(httpPost);
            }
        }

        /// <summary>
        /// Send Http Post Success Response
        /// </summary>
        private void HttpPostSuccess(HttpPost httpPost)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.OK, _state, _transform);
            httpPost.ResponsePort.Post(rsp);
        }

        /// <summary>
        /// Send Http Post Failure Response
        /// </summary>
        private void HttpPostFailure(HttpPost httpPost)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.BadRequest, _state, _transform);
            httpPost.ResponsePort.Post(rsp);
        }

        #endregion // HTTP Get / Post

        #region ValidateDriveConfiguration() helper

        /// <summary>
        /// Validate that the motors are configured and the drive is enabled.
        /// <remarks>Throws an exception (converted to fault)
        /// when the service is not properly configured.</remarks>
        /// </summary>
        /// <param name="requireEncoders">validate encoder configuration</param>
        private void ValidateDriveConfiguration(bool requireEncoders)
        {
            if (_leftMotorPort == null || _rightMotorPort == null)
            {
                LogError("The motors are not connected.");
                throw new InvalidOperationException();
            }

            if (!_state.IsEnabled)
            {
                LogError("The differential drive is not enabled.");
                throw new InvalidOperationException();
            }

            if (requireEncoders)
            {
                if (_state.LeftWheel == null
                    || _state.LeftWheel.Radius == 0.0
                    || _state.LeftWheel.EncoderState == null
                    || _state.LeftWheel.EncoderState.TicksPerRevolution == 0
                    || _state.RightWheel == null
                    || _state.RightWheel.Radius == 0.0
                    || _state.RightWheel.EncoderState == null
                    || _state.RightWheel.EncoderState.TicksPerRevolution == 0
                    )
                {
                    LogError("The wheel encoders are not properly configured.");
                    throw new InvalidOperationException();
                }

            }
        }

        #endregion // ValidateDriveConfiguration() helper

        #region Internal Drive Operation Handlers

        // This port is sent a message every time that there is a
        // Canceled or Complete message from the Drive, so it can
        // be used to wait for completion.
        private Port<drive.DriveStage> completionPort = new Port<drive.DriveStage>();

        /// <summary>
        /// DriveWaitForCompletion - Helper function to wait on Completion Port
        /// </summary>
        /// <returns>Receiver suitable for waiting on</returns>
        private Receiver<drive.DriveStage> DriveWaitForCompletion()
        {
            // Note that this method does nothing with the drive status
            return Arbiter.Receive(false, completionPort, EmptyHandler<drive.DriveStage>);
        }

        /// <summary>
        /// DriveWaitForCompletionDual - Helper function to wait on Completion Port for two events
        /// </summary>
        /// <returns>Receiver suitable for waiting on</returns>
        public JoinSinglePortReceiver DriveWaitForCompletionDual()
        {
#if TRACELOG
            //Tracer.Trace(string.Format("++++++++++++++++++  TrackRoamerDrive:: DriveWaitForCompletionDual()"));
#endif

            // Note that this method does nothing with the drive status
            return Arbiter.MultipleItemReceive(false, completionPort, 2, driveCompletionHandler);
        }

        public void driveCompletionHandler(drive.DriveStage[] driveStages)
        {
#if TRACELOG
            //Tracer.Trace("++++++++++++++++++  TrackRoamerDrive:: driveCompletionHandler()");

            //foreach (drive.DriveStage driveStage in driveStages)
            //{
            //    Tracer.Trace("++++++++++++++++++  driveStage=" + driveStage);
            //}
#endif
            pollEncoderState();
        }

        /// <summary>
        /// get both encoders' state and save it in drive state
        /// </summary>
        private void pollEncoderState()
        {
            encoder.Get get = new encoder.Get();

            _leftEncoderPort.Post(get);

            Activate(Arbiter.Receive<encoder.EncoderState>(false, get.ResponsePort,
                delegate(encoder.EncoderState response)
                {
                    _state.LeftWheel.EncoderState = response;
                }
            ));

            get = new encoder.Get();

            _rightEncoderPort.Post(get);

            Activate(Arbiter.Receive<encoder.EncoderState>(false, get.ResponsePort,
                delegate(encoder.EncoderState response)
                {
                    _state.RightWheel.EncoderState = response;
                }
            ));
        }

        void StopMotorWithEncoderHandler(Port<encoder.UpdateTickCount> encoderNotificationPort, string side, encoder.UpdateTickCount update, motor.MotorOperations motorPort)
        {
            int stopWheelAt;
            bool ignore;

            switch (side)
            {
                case "left":
                    stopWheelAt = stopLeftWheelAt;
                    ignore = !_leftEncoderTickEnabled;
                    break;

                default:
                case "right":
                    stopWheelAt = stopRightWheelAt;
                    ignore = !_rightEncoderTickEnabled;
                    break;
            }

            if (!ignore)
            {
#if TRACEDEBUGTICKS
                Tracer.Trace("^^^^^^^^^^^^^^^^^^^^^ TrackRoamerDriveService:: StopMotorWithEncoderHandler() " + side + " encoder at=" + update.Body.Count + "    will stop wheel at=" + stopWheelAt);
#endif // TRACEDEBUGTICKS

                if (update.Body.Count >= stopWheelAt)
                {
                    switch (side)
                    {
                        case "left":
                            _leftEncoderTickEnabled = false;
                            break;

                        default:
                        case "right":
                            _rightEncoderTickEnabled = false;
                            break;
                    }
                    // whatever else got stuck there, we are not interested. Keep the port clear.
                    //Port<encoder.UpdateTickCount> port = (Port<encoder.UpdateTickCount>)encoderNotificationPort[typeof(encoder.UpdateTickCount)];
                    //port.Clear();

                    motor.SetMotorPower stop = new motor.SetMotorPower(new motor.SetMotorPowerRequest() { TargetPower = 0 });
                    motorPort.Post(stop);
                    Activate(Arbiter.Choice(stop.ResponsePort,
                        delegate(DefaultUpdateResponseType resp)
                        {
#if TRACEDEBUGTICKS
                            Tracer.Trace("^^^^^^^^^^^^^^^^^^^^^ TrackRoamerDriveService:: StopMotorWithEncoderHandler() " + side + " - motor stopped by encoder !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
#endif // TRACEDEBUGTICKS
                        },
                        delegate(Fault fault) { LogError(fault); }
                    ));

#if TRACEDEBUGTICKS
                    Tracer.Trace("^^^^^^^^^^^^^^^^^^^^^ TrackRoamerDriveService:: StopMotorWithEncoderHandler() " + side + " - Sending to completionPort: DriveStage.Completed !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
#endif // TRACEDEBUGTICKS
                    completionPort.Post(drive.DriveStage.Completed);
                }
            }
        }

        private drive.DriveDistance pendingDriveDistance = null;
        private drive.RotateDegrees pendingRotateDegrees = null;

        private void cancelCurrentOperation()
        {
            switch (_internalPendingDriveOperation)
            {
                case drive.DriveRequestOperation.DriveDistance:
                    {
#if TRACELOG
                        Tracer.Trace("cancelCurrentOperation() - DriveDistance - completionPort.ItemCount=" + completionPort.ItemCount);
#endif

                        if (pendingDriveDistance != null)
                        {
                            EncoderTicksEnabled = false;
                            // send notification to subscription manager
                            pendingDriveDistance.Body.DriveDistanceStage = drive.DriveStage.Canceled;
                            double distanceTraveled = pendingDriveDistance.Body.Distance / 2.0d;        // TODO: need to compute real distance traveled
                            pendingDriveDistance.Body.Distance = distanceTraveled;
                            SendNotification<drive.DriveDistance>(_subMgrPort, pendingDriveDistance);
                            pendingDriveDistance = null;
                        }
                    }
                    break;

                case drive.DriveRequestOperation.RotateDegrees:
                    {
#if TRACELOG
                        Tracer.Trace("cancelCurrentOperation() - RotateDegrees - completionPort.ItemCount=" + completionPort.ItemCount);
#endif

                        if (pendingRotateDegrees != null)
                        {
                            EncoderTicksEnabled = false;
                            // send notification to subscription manager
                            pendingRotateDegrees.Body.RotateDegreesStage = drive.DriveStage.Canceled;
                            double angleRotated = pendingRotateDegrees.Body.Degrees / 2.0d;             // TODO: need to compute real angle rotated
                            pendingRotateDegrees.Body.Degrees = angleRotated;
                            SendNotification<drive.RotateDegrees>(_subMgrPort, pendingRotateDegrees);
                            pendingRotateDegrees = null;
                        }
                    }
                    break;

                case drive.DriveRequestOperation.NotSpecified:
                    break;

                default:
                    Tracer.Trace("Warning: cancelCurrentOperation() - no pending wait-type operation to cancel - current operation = " + _internalPendingDriveOperation);
                    break;
            }
            _internalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified;
        }

        /// <summary>
        /// Internal drive distance operation handler
        /// </summary>
        /// <param name="driveDistance"></param>
        /// <returns></returns>
        public virtual IEnumerator<ITask> InternalDriveDistanceHandler(drive.DriveDistance driveDistance)
        {
#if TRACELOG
            Tracer.Trace("InternalDriveDistanceHandler() - DriveStage." + driveDistance.Body.DriveDistanceStage);
#endif

            switch (driveDistance.Body.DriveDistanceStage)
            {
                case drive.DriveStage.InitialRequest:
                    cancelCurrentOperation();
                    pendingDriveDistance = driveDistance;   // we will need it for possible cancelation
                    // _state.InternalPendingDriveOperation = drive.DriveRequestOperation.DriveDistance; - not available in Proxy
                    _internalPendingDriveOperation = drive.DriveRequestOperation.DriveDistance;
                    SpawnIterator<double, double>(driveDistance.Body.Distance, driveDistance.Body.Power, DriveUntilDistance);
                    break;

                case drive.DriveStage.Started:
                    SendNotification<drive.DriveDistance>(_subMgrPort, driveDistance.Body);
                    break;

                case drive.DriveStage.Completed:
                    pendingDriveDistance = null;
                    // _state.InternalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified; - not available in Proxy
                    _internalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified;
                    SendNotification<drive.DriveDistance>(_subMgrPort, driveDistance.Body);
                    break;

                case drive.DriveStage.Canceled:
                    pendingDriveDistance = null;
                    // _state.InternalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified; - not available in Proxy
                    _internalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified;
                    SendNotification<drive.DriveDistance>(_subMgrPort, driveDistance.Body);
                    break;
            }

            yield break;
        }

        /// <summary>
        /// Internal rotate degrees handler
        /// </summary>
        /// <param name="rotateDegrees"></param>
        /// <returns></returns>
        public virtual IEnumerator<ITask> InternalRotateDegreesHandler(drive.RotateDegrees rotateDegrees)
        {
#if TRACELOG
            Tracer.Trace("InternalRotateDegreesHandler() - DriveStage." + rotateDegrees.Body.RotateDegreesStage);
#endif

            switch (rotateDegrees.Body.RotateDegreesStage)
            {
                case drive.DriveStage.InitialRequest:
                    cancelCurrentOperation();
                    pendingRotateDegrees = rotateDegrees;
                    // _state.InternalPendingDriveOperation = drive.DriveRequestOperation.RotateDegrees; - not available in Proxy
                    _internalPendingDriveOperation = drive.DriveRequestOperation.RotateDegrees;
                    SpawnIterator<double, double>(rotateDegrees.Body.Degrees, rotateDegrees.Body.Power, RotateUntilDegrees);
                    break;

                case drive.DriveStage.Started:
                    SendNotification<drive.RotateDegrees>(_subMgrPort, rotateDegrees.Body);
                    break;

                case drive.DriveStage.Completed:
                    pendingRotateDegrees = null;
                    // _state.InternalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified; - not available in Proxy
                    _internalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified;
                    SendNotification<drive.RotateDegrees>(_subMgrPort, rotateDegrees.Body);
                    break;

                case drive.DriveStage.Canceled:
                    pendingRotateDegrees = null;
                    // _state.InternalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified; - not available in Proxy
                    _internalPendingDriveOperation = drive.DriveRequestOperation.NotSpecified;
                    SendNotification<drive.RotateDegrees>(_subMgrPort, rotateDegrees.Body);
                    break;
            }

            yield break;
        }

        #endregion // Internal Drive Operation Handlers

#if TRACEDEBUG
        protected new void LogInfo(string str)
        {
            Tracer.Trace(str);
        }
        protected new void LogError(string str)
        {
            Tracer.Error(str);
        }
#endif // TRACEDEBUG
    }
}


text:
<?php

class Setting extends Eloquent {

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'settings';

	public $timestamps = false;

	public function user()
	{
		return $this->belongsTo('User');
	}
}

redpajama_set_name: RedPajamaGithub


text:
package vpp2106

import (
	"fmt"
	"net"

	"github.com/go-errors/errors"
	vpp_dns "go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp2106/dns"
)

// EnableDNS make act VPP as DNS cache server
func (h *DNSVppHandler) EnableDNS() error {
	h.log.Debug("Enabling DNS functionality of VPP")
	if err := h.enableDisableDNS(true); err != nil {
		return err
	}
	h.log.Debug("DNS functionality of VPP enabled.")
	return nil
}

// DisableDNS disables functionality that makes VPP act as DNS cache server
func (h *DNSVppHandler) DisableDNS() error {
	h.log.Debug("Disabling DNS functionality of VPP")
	if err := h.enableDisableDNS(false); err != nil {
		return err
	}
	h.log.Debug("DNS functionality of VPP disabled.")
	return nil
}

func (h *DNSVppHandler) enableDisableDNS(enable bool) error {
	req := &vpp_dns.DNSEnableDisable{}
	if enable {
		req.Enable = 1
	}
	reply := &vpp_dns.DNSEnableDisableReply{}

	if err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil {
		return err
	}
	if reply.Retval != 0 {
		return fmt.Errorf("vpp call %q returned: %d", reply.GetMessageName(), reply.Retval)
	}
	return nil
}

// AddUpstreamDNSServer adds new upstream DNS Server to the upstream DNS server list
func (h *DNSVppHandler) AddUpstreamDNSServer(serverIPAddress net.IP) error {
	h.log.Debug("Adding upstream DNS server with IP %s", serverIPAddress)
	if err := h.addRemoveUpstreamDNSServer(true, serverIPAddress); err != nil {
		return err
	}
	h.log.Debug("Upstream DNS server with IP %s was added", serverIPAddress)
	return nil
}

// DeleteUpstreamDNSServer removes upstream DNS Server from the upstream DNS server list
func (h *DNSVppHandler) DeleteUpstreamDNSServer(serverIPAddress net.IP) error {
	h.log.Debug("Removing upstream DNS server with IP %s", serverIPAddress)
	if err := h.addRemoveUpstreamDNSServer(false, serverIPAddress); err != nil {
		return err
	}
	h.log.Debug("Upstream DNS server with IP %s was removed", serverIPAddress)
	return nil
}

func (h *DNSVppHandler) addRemoveUpstreamDNSServer(addition bool, serverIPAddress net.IP) error {
	if serverIPAddress == nil {
		return errors.New("upstream DNS server IP address can't be nil")
	}
	req := &vpp_dns.DNSNameServerAddDel{
		IsAdd: boolToUint(addition),
	}
	if serverIPAddress.To4() == nil { // IPv6
		req.IsIP6 = 1
		req.ServerAddress = serverIPAddress.To16()
	} else {
		req.ServerAddress = serverIPAddress.To4()
	}
	reply := &vpp_dns.DNSNameServerAddDelReply{}

	if err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil {
		return err
	}
	if reply.Retval != 0 {
		return fmt.Errorf("vpp call %q returned: %d", reply.GetMessageName(), reply.Retval)
	}
	return nil
}

func boolToUint(input bool) uint8 {
	if input {
		return uint8(1)
	}
	return uint8(0)
}


text:
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField, TextAreaField,BooleanField, SelectField, ValidationError
from wtforms.validators import DataRequired, Length, Email, Regexp
from ..models import User, Role
from flask.ext.pagedown.fields import PageDownField

class NameForm(Form):
    name = StringField("还不知道你的名字呢?", validators=[DataRequired()])
    submit = SubmitField('提交')

class EditProfileForm(Form):
    name = StringField('真实姓名', validators=[Length(0, 64)])
    location = StringField('地址', validators=[Length(0, 64)])
    about_me = TextAreaField('关于我')
    submit = SubmitField('提交')

class EditProfileAdminForm(Form):
    email = StringField('邮箱', validators=[DataRequired(), Email(), Length(1, 64)])
    username = StringField('用户名', validators=[
        DataRequired(), Length(1, 64), Regexp('^\w[\w\d_.]*$', 0, 'User name must have only letters, '
                                               'dots, numbers or underscores.')])
    confirmed = BooleanField('已认证')
    role = SelectField('Role', coerce=int)
    name = StringField('真实姓名', validators=[Length(0, 64)])
    location = StringField('地址', validators=[Length(0, 64)])
    about_me = TextAreaField('关于我')
    submit = SubmitField('提交')

    def __init__(self, user, *args, **kwargs):
        super(EditProfileAdminForm, self).__init__(*args, **kwargs)
        self.role.choices = [(role.id, role.name)
                             for role in Role.query.order_by(Role.name).all()]
        self.user = user

    def validate_email(self, field):
        if field.data != self.user.email and \
                User.query.filter_by(emil=field.data).first():
            raise ValidationError('该邮箱已注册')

    def validate_username(self, field):
        if field.data != self.user.username and \
                User.query.filter_by(username=field.data).first():
            raise ValidationError('用户名已注册')

class PostForm(Form):
    body = PageDownField("在想些什么?", validators=[DataRequired()])
    submit = SubmitField('提交')

class CommentForm(Form):
    body = StringField('', validators=[DataRequired()])
    submit = SubmitField('提交')

class SearchForm(Form):
    search = StringField('Search', validators=[DataRequired()])


text:
"""Defines the serializers for source files"""
import rest_framework.fields as fields
import rest_framework.serializers as serializers

from storage.serializers import ScaleFileSerializerV6

class SourceFileBaseSerializer(ScaleFileSerializerV6):
    """Converts source file model fields to REST output"""
    is_parsed = serializers.BooleanField()
    parsed = serializers.DateTimeField()

class SourceFileSerializer(SourceFileBaseSerializer):
    """Converts source file model fields to REST output"""
    pass

class SourceFileDetailsSerializer(SourceFileSerializer):
    """Converts source file model fields to REST output"""
    pass

class SourceFileUpdateField(fields.Field):
    """Field for displaying the update information for a source file"""

    type_name = 'UpdateField'
    type_label = 'update'

    def to_representation(self, value):
        """Converts the model to its update information

        :param value: the source file model
        :type value: :class:`source.models.SourceFile`
        :rtype: dict
        :returns: the dict with the update information
        """

        if value.is_deleted:
            action = 'DELETED'
            when = value.deleted
        elif value.is_parsed:
            action = 'PARSED'
            when = value.parsed
        else:
            action = 'CREATED'
            when = value.created

        return {'action': action, 'when': when}

class SourceFileUpdateSerializer(SourceFileSerializer):
    """Converts source file updates to REST output"""
    update = SourceFileUpdateField(source='*')


text:
\hypertarget{structconfig}{\section{config Struct Reference}
\label{structconfig}\index{config@{config}}
}

{\ttfamily \#include $<$config.\-h$>$}

Collaboration diagram for config\-:
\subsection*{Data Fields}
\begin{DoxyCompactItemize}
\item
\hyperlink{config_8h_a264461903d572c81f91bd5c50c7c4859}{elemento} $\ast$ \hyperlink{structconfig_a2613a654ec9846270b5aa0d63cebee60}{inicio}
\end{DoxyCompactItemize}

\subsection{Detailed Description}

Definition at line 24 of file config.\-h.

\subsection{Field Documentation}
\hypertarget{structconfig_a2613a654ec9846270b5aa0d63cebee60}{\index{config@{config}!inicio@{inicio}}
\index{inicio@{inicio}!config@{config}}
\subsubsection[{inicio}]{\setlength{\rightskip}{0pt plus 5cm}{\bf elemento}$\ast$ inicio}}\label{structconfig_a2613a654ec9846270b5aa0d63cebee60}

Definition at line 25 of file config.\-h.

The documentation for this struct was generated from the following file\-:\begin{DoxyCompactItemize}
\item
J\-:/\-S\-E\-N\-A\-C/\-Logi\-Kid/make/src/\hyperlink{config_8h}{config.\-h}\end{DoxyCompactItemize}


text:
import { StyleSheet } from 'react-native';

export default StyleSheet.create({
  button: {
    flex: 1,
    alignSelf: 'stretch',
    backgroundColor: '#fff',
    borderRadius: 5,
    borderWidth: 1,
    borderColor: '#007aff',
    marginLeft: 5,
    marginRight: 5
  },
  buttonText: {
    alignSelf: 'center',
    color: '#007aff',
    fontSize: 13,
    fontWeight: '600',
    paddingTop: 10,
    paddingBottom: 10
  }
});


text:
require 'helper'
require 'cassanity/operator'

describe Cassanity::Operator do
  subject {
    described_class.new(:<, 5)
  }

  describe "self named helper method" do
    it "returns instance" do
      Cassanity::Operator(:<, 5).should eq(described_class.new(:<, 5))
    end
  end

  describe "#initialize" do
    before do
      @instance = described_class.new('<', 5)
    end

    it "sets symbol" do
      @instance.symbol.should eq('<')
    end

    it "sets value" do
      @instance.value.should be(5)
    end
  end

  shared_examples_for "operator equality" do |method_name|
    it "returns true for same class, symbol and value" do
      instance = described_class.new(:<, 5)
      other = described_class.new(:<, 5)
      instance.send(method_name, other).should be_true
    end

    it "returns false for same class/value and different symbol" do
      instance = described_class.new(:<, 5)
      other = described_class.new(:>, 5)
      instance.send(method_name, other).should be_false
    end

    it "returns false for same class/symbol and different value" do
      instance = described_class.new(:<, 5)
      other = described_class.new(:>, 7)
      instance.send(method_name, other).should be_false
    end

    it "returns false for different class" do
      instance = described_class.new(:<, 5)
      other = Object.new
      instance.send(method_name, other).should be_false
    end
  end

  describe "#eql?" do
    include_examples "operator equality", :eql?
  end

  describe "#==" do
    include_examples "operator equality", :==
  end

  describe "#inspect" do
    it "return representation" do
      subject.inspect.should eq("#<Cassanity::Operator:#{subject.object_id} symbol=:<, value=5>")
    end
  end
end


text:
using EventCentric.Config;
using System;

namespace EventCentric.MicroserviceFactory
{
    internal static class ConfigResolver
    {
        internal static IEventStoreConfig ResolveConfig(IEventStoreConfig providedConfig)
        {
            try
            {
                return providedConfig != null ? providedConfig : EventStoreConfig.GetConfig();
            }
            catch (ArgumentNullException)
            {
                return new HardcodedEventStoreConfig();
            }

        }

        internal static IPollerConfig ResolveConfig(IPollerConfig providedConfig)
        {
            try
            {
                return providedConfig != null ? providedConfig : PollerConfig.GetConfig();
            }
            catch (ArgumentNullException)
            {
                return new HardcodedPollerConfig();
            }
        }
    }
}


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.ikut;

public final class Manifest {
    public static final class permission {
        public static final String C2D_MESSAGE="com.ikut.permission.C2D_MESSAGE";
    }
}


text:
#ifndef __Observable_Defined__
#define __Observable_Defined__

#include "A4_Observer.hh"

#ifndef A4_DotNet
#include "A4_Mutex.hh"
#include "A4_Unordered_Map_T.hh"
#endif // A4_DotNet

namespace A4_Lib
{ // begin

  namespace Observable_Constant
  {
    const Error_Offset   Observer_Map_Error_Offset = 100;
  } // namespace Observable_Constant

  class  Observable_Entry; //  forward declaration of a private implementation

  typedef class Observable
  { // begin
  public: // construction
    Observable(void);
    ~Observable(void);

  public: // methods
    Error_Code	Register_Observer (Observer	      *the_observer_instance); // C pointers
    Error_Code	Register_Observer (Observer::Pointer  the_observer_instance);

    Error_Code	Unregister_Observer (Observer           *the_observer_instance); // C pointers
    Error_Code	Unregister_Observer (Observer::Pointer  the_observer_instance);

    Error_Code	Notify_Observers (std::uint64_t           the_data,
                                  Observer::Hint  the_hint = 0);

    Error_Code	Notify_Observers (Message_Block::Pointer   the_msg_block,
                                  Observer::Hint           the_hint = 0);

  public: // types
    typedef std::shared_ptr <Observable_Entry>  Observable_Entry_Pointer;
    typedef Unordered_Map_T<std::uint64_t, Observable_Entry_Pointer, A4_Observable_Module_ID, Observable_Constant::Observer_Map_Error_Offset>   Map_Type;

  #ifndef A4_DotNet
  private: // data
    Map_Type    observer_map;

    bool        is_initialized;
  #endif // A4_DotNet

  public: // errors
    enum Observable_Errors
    { // begin
      RO_Invalid_Observer_Address       = 0,
      SO_NULL_Instance                  = 1,
      UO_Observer_Not_Found             = 2,
      NCO_Invalid_Observer_Address      = 3,
      UO_Erase_Failed                   = 4,
      NCO_Invalid_Msg_Block             = 5,
      NO_Invalid_Observer_Address2      = 6,
      ROSP_Invalid_Observer_Address     = 7,
      ROSP_Duplicate_Observer           = 8,
      UOSP_Observer_Not_Found           = 9,
      NO_Invalid_Observer_Address       = 10,
      SO_Instance_Is_Shared             = 11,
      SO_Instance_Already_Set           = 12,
      SO_NullPtr_Instance               = 13,
      SO_Instance_Is_Shared2            = 14,
      SO_Instance_Already_Set2          = 15,
      A_Already_Allocated               = 16,
      A_Allocation_Error                = 17,
      ROSP_Duplicate_Observer2          = 18,
      NO_Invalid_Entry_Address2         = 19,
    }; // end Observable_Errors
  } Observable;

} // namespace A4_Lib

#endif // __Observable_Defined__


text:
; (function () {
	'use strict';

	angular.module("umbraco.resources").factory("multipleMediaPickerResource", multipleMediaPickerResource);

	multipleMediaPickerResource.$inject = ["$http", "umbRequestHelper"];

	function multipleMediaPickerResource($http, umbRequestHelper) {
		var resource = {
			saveMedia: saveMedia,
			getMediaProperties: getMediaProperties,
			getUmbracoVersion: getUmbracoVersion
		};

		return resource;

		// Private functions

		function saveMedia(id, properties) {
			return umbRequestHelper.resourcePromise(
                $http.post("/umbraco/backoffice/OP10/MultipleMediaPickerApi/PostMedia", {
                	id: id,
                	properties: properties
                }),
                "Media could not be saved!"
            );
		};

		function getMediaProperties() {
			return umbRequestHelper.resourcePromise(
                $http.get("/umbraco/backoffice/OP10/MultipleMediaPickerApi/GetMediaProperties"),
                "Could not get Media properties!"
            );
		};

		function getUmbracoVersion() {
			return umbRequestHelper.resourcePromise(
                $http.get("/umbraco/backoffice/OP10/MultipleMediaPickerApi/GetUmbracoVersion"),
                "Could not get Umbraco Version!"
            );
		};

	};

}());


text:
package gui.models;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;

import org.mapdb.Fun.Tuple2;

import controller.Controller;
import qora.assets.Asset;
import qora.assets.Trade;
import utils.ObserverMessage;
import database.DBSet;
import database.SortableList;

@SuppressWarnings("serial")
public class TradesTableModel extends QoraTableModel<Tuple2<BigInteger, BigInteger>, Trade> implements Observer
{
	public static final int COLUMN_TIMESTAMP = 0;
	public static final int COLUMN_TYPE = 1;
	public static final int COLUMN_PRICE = 2;
	public static final int COLUMN_AMOUNT = 3;
	public static final int COLUMN_TOTAL = 4;

	private SortableList<Tuple2<BigInteger, BigInteger>, Trade> trades;
	private Asset have;

	private String[] columnNames = {"Timestamp", "Type", "Price", "Amount", "Total"};

	public TradesTableModel(Asset have, Asset want)
	{
		Controller.getInstance().addObserver(this);

		this.have = have;
		this.trades = Controller.getInstance().getTrades(have, want);
		this.trades.registerObserver();
	}

	@Override
	public SortableList<Tuple2<BigInteger, BigInteger>, Trade> getSortableList()
	{
		return this.trades;
	}

	public Trade getTrade(int row)
	{
		return this.trades.get(row).getB();
	}

	@Override
	public int getColumnCount()
	{
		return this.columnNames.length;
	}

	@Override
	public String getColumnName(int index)
	{
		return this.columnNames[index];
	}

	@Override
	public int getRowCount()
	{
		return this.trades.size();

	}

	@Override
	public Object getValueAt(int row, int column)
	{
		if(this.trades == null || row > this.trades.size() - 1 )
		{
			return null;
		}

		Trade trade = this.trades.get(row).getB();

		switch(column)
		{
		case COLUMN_TIMESTAMP:

			Date date = new Date(trade.getTimestamp());
			DateFormat format = DateFormat.getDateTimeInstance();
			return format.format(date);

		case COLUMN_TYPE:

			//Order order = trade.getInitiatorOrder(DBSet.getInstance());
			return trade.getInitiatorOrder(DBSet.getInstance()).getHave() == this.have.getKey() ? "Sell" : "Buy";

		case COLUMN_PRICE:

			if(trade.getAmount().compareTo(BigDecimal.ZERO) != 0)
				return trade.getPrice().divide(trade.getAmount(), 8, RoundingMode.FLOOR).toPlainString();
			else
				return BigDecimal.ZERO.setScale(8).toPlainString();

		case COLUMN_AMOUNT:

			return trade.getAmount().toPlainString();

		case COLUMN_TOTAL:

			return trade.getPrice().toPlainString();

		}

		return null;
	}

	@Override
	public void update(Observable o, Object arg)
	{
		try
		{
			this.syncUpdate(o, arg);
		}
		catch(Exception e)
		{
			//GUI ERROR
		}
	}

	public synchronized void syncUpdate(Observable o, Object arg)
	{
		ObserverMessage message = (ObserverMessage) arg;

		//CHECK IF LIST UPDATED
		if(message.getType() == ObserverMessage.ADD_TRADE_TYPE || message.getType() == ObserverMessage.REMOVE_TRADE_TYPE)
		{
			this.fireTableDataChanged();
		}
	}

	public void removeObservers()
	{
		this.trades.removeObserver();
		Controller.getInstance().deleteObserver(this);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

	<!-- spring bean configuration -->
	<bean id="apiManager" class="org.matthewroberts.apibase.service.impl.ApiManagerImpl">
		<property name="apiDao" ref="apiDao" />
	</bean>

	<bean id="apiDao" class="org.matthewroberts.apibase.persistence.impl.ApiDaoImpl">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<bean name="apiRest" class="org.matthewroberts.apibase.rest.ApiRest">
		<property name="apiManager" ref="apiManager" />
	</bean>
	<!-- end spring bean configuration -->

	<!-- database configuration -->
	<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    	<property name="jndiName" value="java:comp/env/jdbc/data" />
	</bean>

	<!-- For internal database connections only - don't forget to add MySQL connector jar! -->
	<!--
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.user}" />
		<property name="password" value="${jdbc.pass}" />
	</bean>
	-->
	<!-- end database configuration -->

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>

	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- end database configuration -->

	<!-- security configuration -->
	<bean id="securityContextPersistenceFilter"
		class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
		<property name='securityContextRepository'>
			<bean
				class='org.springframework.security.web.context.HttpSessionSecurityContextRepository'>
				<property name='allowSessionCreation' value='false' />
			</bean>
		</property>
	</bean>
	<!-- end security configuration -->

	<!-- exception handling -->
	<bean class="org.matthewroberts.apibase.util.ExceptionResolver" >
        <property name="exceptionMappings">
            <props>
                <prop key="org.springframework.web.servlet.PageNotFound">notFound</prop>
                <prop key="java.lang.Exception">failure</prop>
            </props>
        </property>
    </bean>
	<!-- end exception handling -->

	<!-- transaction configuration -->
	<aop:config>
		<aop:advisor pointcut="execution(* *..ApiManager.*(..))"
			advice-ref="txAdvice" />
	</aop:config>

	<tx:advice id="txAdvice">
		<tx:attributes>
			<tx:method name="save*" />
			<tx:method name="*" read-only="false" />
		</tx:attributes>
	</tx:advice>
	<!-- end transaction configuration -->
</beans>


text:
<?php

declare(strict_types=1);

namespace Cmfcmf\Module\MediaModule\Importer;

class ImporterCollection
{
    /**
     * @var ImporterInterface[]
     */
    private $importers;

    public function __construct()
    {
        $this->importers = [];
    }

    /**
     * Adds an importer to the collection.
     *
     * @param ImporterInterface $importer
     */
    public function addImporter(ImporterInterface $importer)
    {
        $this->importers[$importer->getId()] = $importer;
    }

    /**
     * Returns all importers.
     *
     * @return array|ImporterInterface[]
     */
    public function getImporters()
    {
        return $this->importers;
    }

    public function getImporter($id)
    {
        if (!isset($this->importers[$id])) {
            throw new \InvalidArgumentException('An importer with the specified id does not exist!');
        }

        return $this->importers[$id];
    }

    public function hasImporter($id)
    {
        return isset($this->importers[$id]);
    }
}


text:
<?php

// Login block
if(!isLoggedIn()) {
	echo '
';
		echo '
';
			echo '
'.lang('module_titles_txt_2').' '.lang('login_txt_4').'
';
		echo '
';
		echo '
';
			echo '<form action="'.__BASE_URL__.'login" method="post">';
				echo '
';
					echo '<input type="text" class="form-control" id="loginBox1" name="webengineLogin_user" required>';
				echo '
';
				echo '
';
					echo '<input type="password" class="form-control" id="loginBox2" name="webengineLogin_pwd" required>';
				echo '
';
				echo '<button type="submit" name="webengineLogin_submit" value="submit" class="btn btn-primary">'.lang('login_txt_3').'</button>';
			echo '</form>';
		echo '
';
	echo '
';

	// join now banner
	echo '

';
}

// Usercp block
if(isLoggedIn()) {
	echo '
';
		echo '
';
			echo '
'.lang('usercp_menu_title').' logout
';
		echo '
';
		echo '
';
				templateBuildUsercp();
		echo '
';
	echo '
';
}

// download banner
echo '

';

// Server info block
if(is_array($srvInfo)) {
	echo '
';
		echo '
';
			echo '
'.lang('sidebar_srvinfo_txt_1').'
';
		echo '
';
		echo '
';
			echo '
';
				if(check_value(config('server_info_season', true))) echo '
'.lang('sidebar_srvinfo_txt_6').'	'.config('server_info_season', true).'
';
				if(check_value(config('server_info_exp', true))) echo '
'.lang('sidebar_srvinfo_txt_7').'	'.config('server_info_exp', true).'
';
				if(check_value(config('server_info_masterexp', true))) echo '
'.lang('sidebar_srvinfo_txt_8').'	'.config('server_info_masterexp', true).'
';
				if(check_value(config('server_info_drop', true))) echo '
'.lang('sidebar_srvinfo_txt_9').'	'.config('server_info_drop', true).'
';
				echo '
'.lang('sidebar_srvinfo_txt_2').'	'.number_format($srvInfo[0]).'
';
				echo '
'.lang('sidebar_srvinfo_txt_3').'	'.number_format($srvInfo[1]).'
';
				echo '
'.lang('sidebar_srvinfo_txt_4').'	'.number_format($srvInfo[2]).'
';
				if(check_value(config('maximum_online', true))) echo '
'.lang('sidebar_srvinfo_txt_5').'	'.number_format($onlinePlayers).'
';
			echo '
';
		echo '
';
	echo '
';
}

// Castle Siege Block
templateCastleSiegeWidget();

// Top Level
$levelRankingData = LoadCacheData('rankings_level.cache');
$topLevelLimit = 5;
if(is_array($levelRankingData)) {
    $topLevel = array_slice($levelRankingData, 0, $topLevelLimit+1);
    echo '
';
        echo '
';
            echo '
'.lang('rankings_txt_1').'+
';
        echo '
';
        echo '
';
            echo '
';
                echo '
';
					echo '
';
						echo ''.lang('rankings_txt_10').'	'; // Character
						echo ''.lang('rankings_txt_11').'	'; // Class
						echo ''.lang('rankings_txt_12').'	'; // Level
					echo '
';
                echo '
';
                echo '
';
                foreach($topLevel as $key => $row) {
                    if($key == 0) continue;
                    echo '
';
                        echo ''.playerProfile($row[0]).'	';
                        echo ''.getPlayerClass($row[1]).'	';
                        echo ''.number_format($row[2]).'	';
                    echo '
';
                }
            echo '
';
            echo '
';
        echo '
';
    echo '
';
}


text:
Minimal Apache HTTPD SSL with Docker Configuration
==================================

This is a minimal SSL configuration for apache httpd with multiple docker repositories.  It assumes artifactory and
httpd are running on the same machine. You can use artifactory.conf as a starting point for your installation.

To run the demo:

docker build --rm --tag art_apache_https_dockers .
docker run -d --name art_apache_https_dockers art_apache_https_dockers

#To find the IP of the newly running container use:
docker inspect --format '{{ .NetworkSettings.IPAddress }}' art_apache_https_dockers

__Note__
This assumes a file named local.sh that contains something like:

<pre>
sed -i '/mirrorlist/d;s/#baseurl/baseurl/;s~mirror.centos.org~artifactory-us.jfrog.info/artifactory~' /etc/yum.repos.d/CentOS-*.repo
rm /etc/yum.repos.d/Artifactory*
</pre>

This edits the CentOS yum repositories to point at your local artifactory.  Change the artifactory-us.jfrog.info to your
local artifactory instance.

We supply a blank one here so the Dockerfile works.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Revision: 2972 $ -->
     <sect1 id="variable.compile.id">
      <title>$compile_id</title>
      <para>
           Identificatore persistente di compilazione. In alternativa a passare
           lo stesso compile_id ad ogni chiamata di funzione, potete impostare
           questa variabile ed il suo valore verrà usato implicitamente da quel
           momento in poi.
      </para>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
<?php

defined('_JEXEC') or die;

require_once JPATH_COMPONENT.'/helpers/route.php';

$controller	= JControllerLegacy::getInstance('Weblinks');
$controller->execute(JFactory::getApplication()->input->get('task'));
$controller->redirect();


text:
namespace {

// The key to which a random subkey will be appended. This key itself will never
// be deleted.
const wchar_t kTestHKCUOverrideKeyPrefix[] = L"SOFTWARE\\Chromium Unit Tests\\";
const char kTestHKCUOverrideEnvironmentVariable[] =
    "IE_IMPORTER_TEST_OVERRIDE_HKCU";

// Reads the environment variable set by a previous call to
// SetTestRegistryOverride() into |key| if it exists and |key| is not NULL.
// Returns true if the variable was successfully read.
bool GetTestKeyFromEnvironment(base::string16* key) {
  scoped_ptr<base::Environment> env(base::Environment::Create());
  std::string value;
  bool result = env->GetVar(kTestHKCUOverrideEnvironmentVariable, &value);
  if (result)
    *key = UTF8ToUTF16(value);
  return result;
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// IEImporterTestRegistryOverrider, public:

IEImporterTestRegistryOverrider::IEImporterTestRegistryOverrider()
    : temporary_key_(kTestHKCUOverrideKeyPrefix +
                     UTF8ToUTF16(base::GenerateGUID())) {
  DCHECK(!GetTestKeyFromEnvironment(NULL));

  scoped_ptr<base::Environment> env(base::Environment::Create());
  bool success = env->SetVar(kTestHKCUOverrideEnvironmentVariable,
                             UTF16ToUTF8(temporary_key_));
  DCHECK(success);
}

IEImporterTestRegistryOverrider::~IEImporterTestRegistryOverrider() {
  base::win::RegKey reg_key(HKEY_CURRENT_USER, temporary_key_.c_str(),
                            KEY_ALL_ACCESS);
  DCHECK(reg_key.Valid());
  reg_key.DeleteKey(L"");

  scoped_ptr<base::Environment> env(base::Environment::Create());
  bool success = env->UnSetVar(kTestHKCUOverrideEnvironmentVariable);
  DCHECK(success);
}

// static
base::string16 IEImporterTestRegistryOverrider::GetTestRegistryOverride() {
  base::string16 key;
  if (!GetTestKeyFromEnvironment(&key))
    return string16();
  return key;
}


text:
#include "rugged.h"

extern VALUE rb_mRugged;
extern VALUE rb_cRuggedRepo;
extern VALUE rb_eRuggedError;
extern VALUE rb_cRuggedRemote;
VALUE rb_cRuggedRemoteCollection;

/*
 *  call-seq:
 *    RemoteCollection.new(repo) -> remotes
 *
 *  Creates and returns a new collection of remotes for the given +repo+.
 */
static VALUE rb_git_remote_collection_initialize(VALUE self, VALUE repo)
{
	rugged_set_owner(self, repo);
	return self;
}

/*
 *  call-seq:
 *    remotes.create_anonymous(url) -> remote
 *
 *  Return a new remote with +url+ in +repository+ , the remote is not persisted:
 *  - +url+: a valid remote url
 *
 *  Returns a new Rugged::Remote object.
 *
 *    @repo.remotes.create_anonymous('git://github.com/libgit2/libgit2.git') #=> #<Rugged::Remote:0x00000001fbfa80>
 */
static VALUE rb_git_remote_collection_create_anonymous(VALUE self, VALUE rb_url)
{
	git_remote *remote;
	git_repository *repo;
	int error;

	VALUE rb_repo = rugged_owner(self);

	rugged_check_repo(rb_repo);
	Data_Get_Struct(rb_repo, git_repository, repo);

	Check_Type(rb_url, T_STRING);
	rugged_validate_remote_url(rb_url);

	error = git_remote_create_anonymous(
			&remote,
			repo,
			StringValueCStr(rb_url),
			NULL);

	rugged_exception_check(error);

	return rugged_remote_new(rb_repo, remote);
}

/*
 *  call-seq:
 *     remotes.create(name, url) -> remote
 *
 *  Add a new remote with +name+ and +url+ to +repository+
 *  - +url+: a valid remote url
 *  - +name+: a valid remote name
 *
 *  Returns a new Rugged::Remote object.
 *
 *    @repo.remotes.create('origin', 'git://github.com/libgit2/rugged.git') #=> #<Rugged::Remote:0x00000001fbfa80>
 */
static VALUE rb_git_remote_collection_create(VALUE self, VALUE rb_name, VALUE rb_url)
{
	git_remote *remote;
	git_repository *repo;
	int error;

	VALUE rb_repo = rugged_owner(self);

	rugged_check_repo(rb_repo);
	Data_Get_Struct(rb_repo, git_repository, repo);

	Check_Type(rb_name, T_STRING);

	Check_Type(rb_url, T_STRING);
	rugged_validate_remote_url(rb_url);

	error = git_remote_create(
			&remote,
			repo,
			StringValueCStr(rb_name),
			StringValueCStr(rb_url));

	rugged_exception_check(error);

	return rugged_remote_new(rb_repo, remote);
}

/*
 *  call-seq:
 *    remotes[name] -> remote or nil
 *
 *  Lookup a remote in the collection with the given +name+.
 *
 *  Returns a new Rugged::Remote object or +nil+ if the
 *  remote doesn't exist.
 *
 *    @repo.remotes["origin"] #=> #<Rugged::Remote:0x00000001fbfa80>
 */
static VALUE rb_git_remote_collection_aref(VALUE self, VALUE rb_name)
{
	git_remote *remote;
	git_repository *repo;
	int error;

	VALUE rb_repo = rugged_owner(self);
	rugged_check_repo(rb_repo);
	Data_Get_Struct(rb_repo, git_repository, repo);

	Check_Type(rb_name, T_STRING);

	error = git_remote_load(&remote, repo, StringValueCStr(rb_name));

	if (error == GIT_ENOTFOUND)
		return Qnil;

	rugged_exception_check(error);

	return rugged_remote_new(rb_repo, remote);
}

static VALUE rb_git_remote_collection__each(VALUE self, int only_names)
{
	git_repository *repo;
	git_strarray remotes;
	size_t i;
	int error = 0;
	int exception = 0;

	VALUE rb_repo;

	if (!rb_block_given_p()) {
		if (only_names)
			return rb_funcall(self, rb_intern("to_enum"), 1, CSTR2SYM("each_name"));
		else
			return rb_funcall(self, rb_intern("to_enum"), 1, CSTR2SYM("each"));
	}

	rb_repo = rugged_owner(self);
	rugged_check_repo(rb_repo);
	Data_Get_Struct(rb_repo, git_repository, repo);

	error = git_remote_list(&remotes, repo);
	rugged_exception_check(error);

	if (only_names) {
		for (i = 0; !exception && i < remotes.count; ++i) {
			rb_protect(rb_yield, rb_str_new_utf8(remotes.strings[i]), &exception);
		}
	} else {
		for (i = 0; !exception && !error && i < remotes.count; ++i) {
			git_remote *remote;

			if (!(error = git_remote_load(&remote, repo, remotes.strings[i])))
				rb_protect(rb_yield, rugged_remote_new(rb_repo, remote), &exception);
		}
	}

	git_strarray_free(&remotes);

	if (exception)
		rb_jump_tag(exception);

	rugged_exception_check(error);

	return Qnil;
}

/*
 *  call-seq:
 *    remotes.each { |remote| } -> nil
 *    remotes.each -> enumerator
 *
 *  Iterate through all the remotes in the collection's +repository+.
 *
 *  The given block will be called once with a Rugged::Remote
 *  instance for each remote.
 *
 *  If no block is given, an enumerator will be returned.
 */
static VALUE rb_git_remote_collection_each(VALUE self)
{
	return rb_git_remote_collection__each(self, 0);
}

/*
 *  call-seq:
 *    remotes.each_name { |str| } -> nil
 *    remotes.each_name -> enumerator
 *
 *  Iterate through all the remote names in the collection's +repository+.
 *
 *  The given block will be called once with the name of each remote.
 *
 *  If no block is given, an enumerator will be returned.
 */
static VALUE rb_git_remote_collection_each_name(VALUE self)
{
	return rb_git_remote_collection__each(self, 1);
}

/*
 *  call-seq:
 *    remotes.delete(remote) -> nil
 *    remotes.delete(name) -> nil
 *
 *  Delete the specified remote.
 *
 *    repo.remotes.delete("origin")
 *    # Remote no longer exists in the configuration.
 */
static VALUE rb_git_remote_collection_delete(VALUE self, VALUE rb_name_or_remote)
{
	VALUE rb_repo = rugged_owner(self);
	git_remote *remote;
	git_repository *repo;
	int error;

	if (rb_obj_is_kind_of(rb_name_or_remote, rb_cRuggedRemote))
		rb_name_or_remote = rb_funcall(rb_name_or_remote, rb_intern("name"), 0);

	if (TYPE(rb_name_or_remote) != T_STRING)
		rb_raise(rb_eTypeError, "Expecting a String or Rugged::Remote instance");

	rugged_check_repo(rb_repo);
	Data_Get_Struct(rb_repo, git_repository, repo);

	error = git_remote_load(&remote, repo, StringValueCStr(rb_name_or_remote));
	rugged_exception_check(error);

	error = git_remote_delete(remote);
	rugged_exception_check(error);

	return Qnil;
}

void Init_rugged_remote_collection(void)
{
	rb_cRuggedRemoteCollection = rb_define_class_under(rb_mRugged, "RemoteCollection", rb_cObject);
	rb_include_module(rb_cRuggedRemoteCollection, rb_mEnumerable);

	rb_define_method(rb_cRuggedRemoteCollection, "initialize",       rb_git_remote_collection_initialize, 1);

	rb_define_method(rb_cRuggedRemoteCollection, "[]",               rb_git_remote_collection_aref, 1);

	rb_define_method(rb_cRuggedRemoteCollection, "create",           rb_git_remote_collection_create, 2);
	rb_define_method(rb_cRuggedRemoteCollection, "create_anonymous", rb_git_remote_collection_create_anonymous, 1);

	rb_define_method(rb_cRuggedRemoteCollection, "each",             rb_git_remote_collection_each, 0);
	rb_define_method(rb_cRuggedRemoteCollection, "each_name",        rb_git_remote_collection_each_name, 0);

	rb_define_method(rb_cRuggedRemoteCollection, "delete",           rb_git_remote_collection_delete, 1);
}