text:
#include <cmath>

#include "Tudat/Mathematics/BasicMathematics/mathematicalConstants.h"
#include "Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h"
#include "Tudat/Mathematics/BasicMathematics/linearAlgebra.h"

#include "Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/unifiedStateModelQuaternionElementConversions.h"

namespace tudat
{

namespace orbital_element_conversions
{

//! Convert Keplerian elements to unified state model elements with quaternions.
Eigen::Vector7d convertKeplerianToUnifiedStateModelQuaternionsElements(
        const Eigen::Vector6d& keplerianElements,
        const double centralBodyGravitationalParameter )
{
    using mathematical_constants::PI;

    // Declaring eventual output vector.
    Eigen::Vector7d convertedUnifiedStateModelElements = Eigen::Vector7d::Zero( );

    // Define the tolerance of a singularity
    const double singularityTolerance = 20.0 * std::numeric_limits< double >::epsilon( );

    // If eccentricity is outside range [0,inf)
    if ( keplerianElements( eccentricityIndex ) < 0.0 )
    {
        //Define the error message
        std::stringstream errorMessage;
        errorMessage << "Eccentricity is expected in range [0,inf)\n"
                     << "Specified eccentricity: " << keplerianElements( eccentricityIndex ) << std::endl;

        // Throw exception
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }

    // If inclination is outside range [0,PI]
    if ( ( keplerianElements( inclinationIndex ) < 0.0 ) || ( keplerianElements( inclinationIndex ) > PI ) )
    {
        // Define the error message.
        std::stringstream errorMessage;
        errorMessage << "Inclination is expected in range [0," << PI << "]\n"
                     << "Specified inclination: " << keplerianElements( inclinationIndex ) << " rad." << std::endl;

        // Throw exception.
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }

    // If argument of pericenter is outside range [0,2.0 * PI]
    if ( ( keplerianElements( argumentOfPeriapsisIndex ) < 0.0 ) || ( keplerianElements( argumentOfPeriapsisIndex ) >
                                                                      2.0 * PI ) )
    {
        // Define the error message.
        std::stringstream errorMessage;
        errorMessage << "Argument of periapsis is expected in range [0," << 2.0 * PI << "]\n"
                     << "Specified inclination: " << keplerianElements( argumentOfPeriapsisIndex ) << " rad." << std::endl;

        // Throw exception.
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }

    // If right ascension of ascending node is outside range [0,2.0 * PI]
    if ( ( keplerianElements( longitudeOfAscendingNodeIndex ) < 0.0 ) ||
         ( keplerianElements( longitudeOfAscendingNodeIndex ) > 2.0 * PI ) )
    {
        // Define the error message.
        std::stringstream errorMessage;
        errorMessage << "RAAN is expected in range [0," << 2.0 * PI << "]\n"
                     << "Specified inclination: " << keplerianElements( longitudeOfAscendingNodeIndex ) << " rad."
                     << std::endl;

        // Throw exception.
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }

    // If true anomaly is outside range [0,2.0 * PI]
    if ( ( keplerianElements( trueAnomalyIndex ) < 0.0 ) || ( keplerianElements( trueAnomalyIndex ) > 2.0 * PI ) )
    {
        // Define the error message.
        std::stringstream errorMessage;
        errorMessage << "True anomaly is expected in range [0," << 2.0 * PI << "]\n"
                     << "Specified inclination: " << keplerianElements( trueAnomalyIndex ) << " rad." << std::endl;

        // Throw exception.
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }

    // If inclination is zero and the right ascension of ascending node is non-zero
    if ( ( std::fabs( keplerianElements( inclinationIndex ) ) < singularityTolerance ) &&
         ( std::fabs( keplerianElements( longitudeOfAscendingNodeIndex ) ) > singularityTolerance ) )
    {
        // Define the error message.
        std::stringstream errorMessage;
        errorMessage << "When the inclination is zero, the right ascending node should be zero by definition\n"
                     << "Specified right ascension of ascending node: " <<
                        keplerianElements( longitudeOfAscendingNodeIndex ) << " rad." << std::endl;

        // Throw exception.
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }

    // If eccentricity is zero and the argument of pericenter is non-zero
    if ( ( std::fabs( keplerianElements( eccentricityIndex ) ) < singularityTolerance ) &&
         ( std::fabs( keplerianElements( argumentOfPeriapsisIndex ) ) > singularityTolerance ) )
    {
        // Define the error message.
        std::stringstream errorMessage;
        errorMessage << "When the eccentricity is zero, the argument of pericenter should be zero by definition\n"
                     << "Specified argument of pericenter: " <<
                        keplerianElements( argumentOfPeriapsisIndex ) << " rad." << std::endl;

        // Throw exception.
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }

    // If semi-major axis is negative and the eccentricity is smaller or equal to one
    if ( ( keplerianElements( semiMajorAxisIndex ) < 0.0 ) && ( keplerianElements( eccentricityIndex ) <= 1.0 ) )
    {
        // Define the error message.
        std::stringstream errorMessage;
        errorMessage << "When the semi-major axis is negative, the eccentricity should be larger than one\n"
                     << "Specified semi-major axis: " << keplerianElements( semiMajorAxisIndex ) << " m.\n"
                     << "Specified eccentricity: " << keplerianElements( eccentricityIndex ) << " rad." << std::endl;

        // Throw exception.
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }

    // If semi-major axis is positive and the eccentricity is larger than one
    if ( ( keplerianElements( semiMajorAxisIndex ) > 0.0 ) && ( keplerianElements( eccentricityIndex ) > 1.0 ) )
    {
        // Define the error message.
        std::stringstream errorMessage;
        errorMessage << "When the semi-major axis is positive, the eccentricity should be smaller than or equal to one\n"
                     << "Specified semi-major axis: " << keplerianElements( semiMajorAxisIndex ) << " m.\n"
                     << "Specified eccentricity: " << keplerianElements( eccentricityIndex ) << " rad." << std::endl;

        // Throw exception.
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }
    // Else, nothing wrong and continue

    // Compute the C hodograph element of the unified state model
    if ( std::fabs( keplerianElements( eccentricityIndex ) - 1.0) < singularityTolerance )
        // parabolic orbit -> semi-major axis is not defined
    {
        convertedUnifiedStateModelElements( CHodographUSM7Index ) =
                std::sqrt( centralBodyGravitationalParameter / keplerianElements( semiLatusRectumIndex ) );
    }
    else
    {
        convertedUnifiedStateModelElements( CHodographUSM7Index ) =
                std::sqrt( centralBodyGravitationalParameter / ( keplerianElements( semiMajorAxisIndex )
                                                                 * ( 1 - keplerianElements( eccentricityIndex ) *
                                                                     keplerianElements( eccentricityIndex ) ) ) );
    }

    // Calculate the additional R hodograph parameter
    double RHodographElement = keplerianElements( eccentricityIndex ) *
            convertedUnifiedStateModelElements( CHodographUSM7Index );

    // Compute the Rf1 hodograph element of the unified state model
    convertedUnifiedStateModelElements( Rf1HodographUSM7Index ) =
            - RHodographElement * std::sin( keplerianElements( longitudeOfAscendingNodeIndex )
                                            + keplerianElements( argumentOfPeriapsisIndex ) );

    // Compute the Rf2 hodograph element of the unified state model
    convertedUnifiedStateModelElements( Rf2HodographUSM7Index ) =
            RHodographElement * std::cos( keplerianElements( longitudeOfAscendingNodeIndex )
                                          + keplerianElements( argumentOfPeriapsisIndex ) );

    // Calculate the additional argument of longitude u
    double argumentOfLatitude = keplerianElements( argumentOfPeriapsisIndex ) +
            keplerianElements( trueAnomalyIndex );

    // Compute the eta quaternion of the unified state model
    convertedUnifiedStateModelElements( etaUSM7Index ) =
            std::cos( 0.5 * keplerianElements( inclinationIndex ) ) *
            std::cos( 0.5 * ( keplerianElements( longitudeOfAscendingNodeIndex ) + argumentOfLatitude ) );

    // Compute the epsilon1 quaternion of the unified state model
    convertedUnifiedStateModelElements( epsilon1USM7Index ) =
            std::sin( 0.5 * keplerianElements( inclinationIndex ) ) *
            std::cos( 0.5 * ( keplerianElements( longitudeOfAscendingNodeIndex ) - argumentOfLatitude ) );

    // Compute the epsilon2 quaternion of the unified state model
    convertedUnifiedStateModelElements( epsilon2USM7Index ) =
            std::sin( 0.5 * keplerianElements( inclinationIndex ) ) *
            std::sin( 0.5 * ( keplerianElements( longitudeOfAscendingNodeIndex ) - argumentOfLatitude ) );

    // Compute the epsilon3 quaternion of the unified state model
    convertedUnifiedStateModelElements( epsilon3USM7Index ) =
            std::cos( 0.5 * keplerianElements( inclinationIndex ) ) *
            std::sin( 0.5 * ( keplerianElements( longitudeOfAscendingNodeIndex ) + argumentOfLatitude ) );

    // Give back result
    return convertedUnifiedStateModelElements;
}

//! Convert unified state model elements with quaternions to Keplerian elements.
Eigen::Vector6d convertUnifiedStateModelQuaternionsToKeplerianElements(
        const Eigen::Vector7d& unifiedStateModelElements,
        const double centralBodyGravitationalParameter,
        const bool forceQuaternionNormalization )
{
    using mathematical_constants::PI;

    // Declaring eventual output vector.
    Eigen::Vector6d convertedKeplerianElements = Eigen::Vector6d::Zero( );

    // Define the tolerance of a singularity
    const double singularityTolerance = 20.0 * std::numeric_limits< double >::epsilon( );

    // Check whether the unified state model elements are within expected limits
    // If inclination is zero and the right ascension of ascending node is non-zero
    Eigen::Vector4d quaternionsVector = unifiedStateModelElements.segment( etaUSM7Index, 4 );
    const double normOfQuaternionElements = quaternionsVector.norm( );
    if ( std::fabs( normOfQuaternionElements - 1.0 ) > singularityTolerance )
    {
        if ( forceQuaternionNormalization )
        {
            quaternionsVector /= normOfQuaternionElements;
        }
        else
        {
            // Define the error message.
            std::stringstream errorMessage;
            errorMessage << "The norm of the quaternion should be equal to one.\n"
                         << "Norm of the specified quaternion is: " << normOfQuaternionElements - 1.0 << " + 1." << std::endl;

            // Throw exception.
            throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
        }
    }
    // Else, nothing wrong and continue

    // Extract quaternion elements
    double etaQuaternionParameter = quaternionsVector( etaQuaternionIndex );
    double epsilon1QuaternionParameter = quaternionsVector( epsilon1QuaternionIndex );
    double epsilon2QuaternionParameter = quaternionsVector( epsilon2QuaternionIndex );
    double epsilon3QuaternionParameter = quaternionsVector( epsilon3QuaternionIndex );

    // Check whether the orbit is pure-retrograde
    if ( ( std::fabs( epsilon3QuaternionParameter ) < singularityTolerance ) &&
         ( std::fabs( etaQuaternionParameter ) < singularityTolerance ) )
        // pure-retrograde orbit -> inclination = PI
    {
        // Define the error message
        std::stringstream errorMessage;
        errorMessage << "Pure-retrograde orbit (inclination = PI).\n"
                     << "Unified state model elements cannot be transformed to Kepler elements." << std::endl;

        // Throw exception
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }

    // Compute auxiliary parameters cosineLambda, sineLambda and lambda
    double denominator = epsilon3QuaternionParameter * epsilon3QuaternionParameter +
            etaQuaternionParameter * etaQuaternionParameter;
    double cosineLambda = ( etaQuaternionParameter * etaQuaternionParameter -
                            epsilon3QuaternionParameter * epsilon3QuaternionParameter ) / denominator;
    double sineLambda = ( 2.0 * epsilon3QuaternionParameter *
                          etaQuaternionParameter ) / denominator;
    double rightAscensionOfLatitude = std::atan2( sineLambda, cosineLambda );

    // Compute auxiliary parameters auxiliaryParameter1 and auxiliaryParameter2
    double auxiliaryParameter1 = unifiedStateModelElements( Rf1HodographUSM7Index ) * cosineLambda +
            unifiedStateModelElements( Rf2HodographUSM7Index ) * sineLambda;
    double auxiliaryParameter2 = unifiedStateModelElements( CHodographUSM7Index ) -
            unifiedStateModelElements( Rf1HodographUSM7Index ) * sineLambda +
            unifiedStateModelElements( Rf2HodographUSM7Index ) * cosineLambda;

    // Compute auxiliary R hodograph parameter
    double RHodographElement = std::sqrt( unifiedStateModelElements( Rf1HodographUSM7Index ) *
                                          unifiedStateModelElements( Rf1HodographUSM7Index ) +
                                          unifiedStateModelElements( Rf2HodographUSM7Index ) *
                                          unifiedStateModelElements( Rf2HodographUSM7Index ) );

    // Compute eccentricity
    convertedKeplerianElements( eccentricityIndex ) =
            RHodographElement / unifiedStateModelElements( CHodographUSM7Index );

    // Compute semi-major axis or, in case of a parabolic orbit, the semi-latus rectum.
    if ( std::fabs( convertedKeplerianElements( eccentricityIndex ) - 1.0 ) < singularityTolerance )
        // parabolic orbit -> semi-major axis is not defined. Use semi-latus rectum instead.
    {
        convertedKeplerianElements( semiLatusRectumIndex ) = centralBodyGravitationalParameter /
                ( unifiedStateModelElements( CHodographUSM7Index ) * unifiedStateModelElements( CHodographUSM7Index ) );
    }
    else
    {
        convertedKeplerianElements( semiMajorAxisIndex ) =
                centralBodyGravitationalParameter /
                ( std::pow( unifiedStateModelElements( CHodographUSM7Index ), 2 ) *
                  ( 1 - std::pow( convertedKeplerianElements( eccentricityIndex ), 2 ) ) );
    }

    // Compute inclination
    convertedKeplerianElements( inclinationIndex ) =
            std::acos( 1.0 - 2.0 * ( epsilon1QuaternionParameter * epsilon1QuaternionParameter +
                                     epsilon2QuaternionParameter * epsilon2QuaternionParameter ) );
    // This acos is always defined correctly because the inclination is always below pi rad.

    // Find sine and cosine of longitude of ascending node separately
    double sineOmega = epsilon1QuaternionParameter * epsilon3QuaternionParameter +
            epsilon2QuaternionParameter * etaQuaternionParameter;
    double cosineOmega = epsilon1QuaternionParameter * etaQuaternionParameter -
            epsilon2QuaternionParameter * epsilon3QuaternionParameter;
    denominator = std::sqrt( cosineOmega * cosineOmega +
                             sineOmega * sineOmega ); // overwrite old denominator

    // Compute longitude of ascending node
    if ( std::fabs( convertedKeplerianElements( inclinationIndex ) - PI ) < singularityTolerance )
        // pure-retrograde orbit -> inclination = PI
    {
        // Define the error message
        std::stringstream errorMessage;
        errorMessage << "Pure-retrograde orbit (inclination = PI).\n"
                     << "Unified state model elements cannot be transformed to Kepler elements." << std::endl;

        // Throw exception
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }
    else if ( std::fabs( denominator ) < singularityTolerance )
        // null denominator, find work-around
    {
        convertedKeplerianElements( longitudeOfAscendingNodeIndex ) = 0.0; // by definition
    }
    else
    {
        // Compute longitude of ascending node
        convertedKeplerianElements( longitudeOfAscendingNodeIndex ) = std::atan2(
                    sineOmega / denominator, cosineOmega / denominator );

        // Round off small values of the right ascension of ascending node to zero
        if ( std::fabs( convertedKeplerianElements( longitudeOfAscendingNodeIndex ) ) < singularityTolerance )
        {
            convertedKeplerianElements( longitudeOfAscendingNodeIndex ) = 0.0;
        }

        // Ensure the longitude of ascending node is positive
        while ( convertedKeplerianElements( longitudeOfAscendingNodeIndex ) < 0.0 )
            // Because of the previous if statement, if the longitude of ascending node is smaller than 0, it will
            // always be smaller than -singularityTolerance
        {
            convertedKeplerianElements( longitudeOfAscendingNodeIndex ) += 2.0 * PI;
        }
    }

    // Compute true anomaly and argument of periapsis
    if ( std::fabs( RHodographElement ) < singularityTolerance ) // circular orbit
    {
        convertedKeplerianElements( argumentOfPeriapsisIndex ) = 0.0; // by definition
        convertedKeplerianElements( trueAnomalyIndex ) =
                rightAscensionOfLatitude - convertedKeplerianElements( longitudeOfAscendingNodeIndex );

        // Round off small theta to zero
        if ( std::fabs( convertedKeplerianElements( trueAnomalyIndex ) ) < singularityTolerance )
        {
            convertedKeplerianElements( trueAnomalyIndex ) = 0.0;
        }

        // Ensure the true anomaly is positive
        while ( convertedKeplerianElements( trueAnomalyIndex ) < 0.0 )
            // Because of the previous if statement, if the true anomaly is smaller than zero, it will always be smaller than
            // -singularityTolerance
        {
            convertedKeplerianElements( trueAnomalyIndex ) += 2.0 * PI;
        }
    }
    else
    {
        convertedKeplerianElements( trueAnomalyIndex ) =
                std::atan2( ( auxiliaryParameter1 / RHodographElement ),
                            ( ( auxiliaryParameter2 - unifiedStateModelElements( CHodographUSM7Index ) )
                              / RHodographElement ) );

        // Round off small theta to zero
        if ( std::fabs( convertedKeplerianElements( trueAnomalyIndex ) ) < singularityTolerance )
        {
            convertedKeplerianElements( trueAnomalyIndex ) = 0.0;
        }

        // Ensure the true anomaly is positive
        while ( convertedKeplerianElements( trueAnomalyIndex ) < 0.0 )
            // Because of the previous if statement, if the true anomaly is smaller than zero, it will always
            // be smaller than -singularityTolerance
        {
            convertedKeplerianElements( trueAnomalyIndex ) += 2.0 * PI;
        }

        convertedKeplerianElements( argumentOfPeriapsisIndex ) =
                rightAscensionOfLatitude -
                convertedKeplerianElements( longitudeOfAscendingNodeIndex ) -
                convertedKeplerianElements( trueAnomalyIndex );

        // Round off small omega to zero
        if ( std::fabs( convertedKeplerianElements( argumentOfPeriapsisIndex ) ) < singularityTolerance )
        {
            convertedKeplerianElements( argumentOfPeriapsisIndex ) = 0.0;
        }

        // Ensure the argument of periapsis is positive
        while ( convertedKeplerianElements( argumentOfPeriapsisIndex ) < 0.0 )
            // Because of the previous if statement, if the argument of pericenter is smaller than zero,
            // it will be smaller than -singularityTolerance
        {
            convertedKeplerianElements( argumentOfPeriapsisIndex ) += 2.0 * PI;
        }
    }

    // Give back result
    return convertedKeplerianElements;
}

////! Convert Cartesian elements to unified state model elements with quaternions.
Eigen::Vector7d convertCartesianToUnifiedStateModelQuaternionsElements(
        const Eigen::Vector6d& cartesianElements,
        const double centralBodyGravitationalParameter )
{
    using mathematical_constants::PI;

    // Declaring eventual output vector.
    Eigen::Vector7d convertedUnifiedStateModelElements = Eigen::Vector7d::Zero( );

    // Define the tolerance of a singularity
    const double singularityTolerance = 20.0 * std::numeric_limits< double >::epsilon( );

    // Find Cartesian position and velocity vectors and magnitudes
    Eigen::Vector3d positionVector = cartesianElements.segment( xCartesianPositionIndex, 3 );
    double positionMagnitude = positionVector.norm( );
    Eigen::Vector3d velocityVector = cartesianElements.segment( xCartesianVelocityIndex, 3 );

    // Determine specific angular momentum vector and magnitude
    Eigen::Vector3d angularMomentumVector = positionVector.cross( velocityVector );
    double angularMomentumMagnitude = angularMomentumVector.norm( );

    // Check whether the orbit is pure-retrograde
    double angularMomentumMagnitudeMinusZComponent = angularMomentumMagnitude + angularMomentumVector( 2 );
    if ( std::fabs( angularMomentumMagnitudeMinusZComponent ) < singularityTolerance )
        // pure-retrograde orbit -> inclination = PI
    {
        // Define the error message
        std::stringstream errorMessage;
        errorMessage << "Pure-retrograde orbit (inclination = PI).\n"
                     << "Unified state model elements cannot be transformed to Kepler elements." << std::endl;

        // Throw exception
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }

    // Find C hodograph element of the unified state model
    convertedUnifiedStateModelElements( CHodographUSM7Index ) = centralBodyGravitationalParameter /
            angularMomentumMagnitude;

    // Find direction cosine matrix with position and angular momentum vectors
    Eigen::Matrix3d directionCosineMatrix = Eigen::Matrix3d::Zero( );
    directionCosineMatrix.block( 0, 0, 1, 3 ) = positionVector.normalized( ).transpose( );
    directionCosineMatrix.block( 1, 0, 1, 3 ) = ( angularMomentumVector.normalized( ).cross(
                                                      positionVector.normalized( ) ) ).transpose( );
    directionCosineMatrix.block( 2, 0, 1, 3 ) = angularMomentumVector.normalized( ).transpose( );

    // Compute square of quaternions
    double traceDirectionCosineMatrix = directionCosineMatrix.trace( );
    Eigen::Vector4d quaternionsSquaredVector;
    for ( unsigned int i = 0; i < 3; i++ )
    {
        quaternionsSquaredVector( i ) = ( 1.0 - traceDirectionCosineMatrix + 2.0 *
                                         directionCosineMatrix( i, i ) ) / 4.0;
    }
    quaternionsSquaredVector( 3 ) = ( 1.0 + traceDirectionCosineMatrix ) / 4.0;

    // Based on the maximum value, find the quaternion elements
    Eigen::Vector4d::Index indexLargestQuaternionElement;
    double valueLargestQuaternionElement = quaternionsSquaredVector.maxCoeff( &indexLargestQuaternionElement );
    switch ( indexLargestQuaternionElement )
    {
    case 0:
    {
        // Find value of largest quaternion parameter
        convertedUnifiedStateModelElements( epsilon1USM7Index ) = std::sqrt( valueLargestQuaternionElement );

        // Find other values
        Eigen::Vector3d auxiliaryVector = Eigen::Vector3d::Zero( );
        auxiliaryVector( 0 ) = directionCosineMatrix( 1, 0 ) + directionCosineMatrix( 0, 1 );
        auxiliaryVector( 1 ) = directionCosineMatrix( 2, 0 ) + directionCosineMatrix( 0, 2 );
        auxiliaryVector( 2 ) = directionCosineMatrix( 1, 2 ) - directionCosineMatrix( 2, 1 );
        auxiliaryVector /= 4 * convertedUnifiedStateModelElements( epsilon1USM7Index );

        // Distribute to state vector
        convertedUnifiedStateModelElements( epsilon2USM7Index ) = auxiliaryVector( 0 );
        convertedUnifiedStateModelElements( epsilon3USM7Index ) = auxiliaryVector( 1 );
        convertedUnifiedStateModelElements( etaUSM7Index ) = auxiliaryVector( 2 );
        break;
    }
    case 1:
    {
        // Find value of largest quaternion parameter
        convertedUnifiedStateModelElements( epsilon2USM7Index ) = std::sqrt( valueLargestQuaternionElement );

        // Find other values
        Eigen::Vector3d auxiliaryVector = Eigen::Vector3d::Zero( );
        auxiliaryVector( 0 ) = directionCosineMatrix( 0, 1 ) + directionCosineMatrix( 1, 0 );
        auxiliaryVector( 1 ) = directionCosineMatrix( 2, 1 ) + directionCosineMatrix( 1, 2 );
        auxiliaryVector( 2 ) = directionCosineMatrix( 2, 0 ) - directionCosineMatrix( 0, 2 );
        auxiliaryVector /= 4 * convertedUnifiedStateModelElements( epsilon2USM7Index );

        // Distribute to state vector
        convertedUnifiedStateModelElements( epsilon1USM7Index ) = auxiliaryVector( 0 );
        convertedUnifiedStateModelElements( epsilon3USM7Index ) = auxiliaryVector( 1 );
        convertedUnifiedStateModelElements( etaUSM7Index ) = auxiliaryVector( 2 );
        break;
    }
    case 2:
    {
        // Find value of largest quaternion parameter
        convertedUnifiedStateModelElements( epsilon3USM7Index ) = std::sqrt( valueLargestQuaternionElement );

        // Find other values
        Eigen::Vector3d auxiliaryVector = Eigen::Vector3d::Zero( );
        auxiliaryVector( 0 ) = directionCosineMatrix( 0, 2 ) + directionCosineMatrix( 2, 0 );
        auxiliaryVector( 1 ) = directionCosineMatrix( 1, 2 ) + directionCosineMatrix( 2, 1 );
        auxiliaryVector( 2 ) = directionCosineMatrix( 0, 1 ) - directionCosineMatrix( 1, 0 );
        auxiliaryVector /= 4 * convertedUnifiedStateModelElements( epsilon3USM7Index );

        // Distribute to state vector
        convertedUnifiedStateModelElements( epsilon1USM7Index ) = auxiliaryVector( 0 );
        convertedUnifiedStateModelElements( epsilon2USM7Index ) = auxiliaryVector( 1 );
        convertedUnifiedStateModelElements( etaUSM7Index ) = auxiliaryVector( 2 );
        break;
    }
    case 3:
    {
        // Find value of largest quaternion parameter
        convertedUnifiedStateModelElements( etaUSM7Index ) = std::sqrt( valueLargestQuaternionElement );

        // Find other values
        Eigen::Vector3d auxiliaryVector = Eigen::Vector3d::Zero( );
        auxiliaryVector( 0 ) = directionCosineMatrix( 1, 2 ) - directionCosineMatrix( 2, 1 );
        auxiliaryVector( 1 ) = directionCosineMatrix( 2, 0 ) - directionCosineMatrix( 0, 2 );
        auxiliaryVector( 2 ) = directionCosineMatrix( 0, 1 ) - directionCosineMatrix( 1, 0 );
        auxiliaryVector /= 4 * convertedUnifiedStateModelElements( etaUSM7Index );

        // Distribute to state vector
        convertedUnifiedStateModelElements( epsilon1USM7Index ) = auxiliaryVector( 0 );
        convertedUnifiedStateModelElements( epsilon2USM7Index ) = auxiliaryVector( 1 );
        convertedUnifiedStateModelElements( epsilon3USM7Index ) = auxiliaryVector( 2 );
        break;
    }
    default:
    {
        // Define the error message.
        std::stringstream errorMessage;
        errorMessage << "Could not find the maximum value of the quaternion.\n"
                     << "Specified squared quaternion: " << quaternionsSquaredVector.transpose( ) << std::endl;

        // Throw exception.
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }
    }

    // Compute sine and cosine of right ascension of latitude (lambda)
    double denominator = convertedUnifiedStateModelElements( epsilon3USM7Index ) *
            convertedUnifiedStateModelElements( epsilon3USM7Index ) +
            convertedUnifiedStateModelElements( etaUSM7Index ) *
            convertedUnifiedStateModelElements( etaUSM7Index );
    double cosineLambda = ( convertedUnifiedStateModelElements( etaUSM7Index ) *
                            convertedUnifiedStateModelElements( etaUSM7Index ) -
                            convertedUnifiedStateModelElements( epsilon3USM7Index ) *
                            convertedUnifiedStateModelElements( epsilon3USM7Index ) ) / denominator;
    double sineLambda = ( 2.0 * convertedUnifiedStateModelElements( epsilon3USM7Index ) *
                          convertedUnifiedStateModelElements( etaUSM7Index ) ) / denominator;

    // Compute auxiliary parameters
    double radialVelocity = positionVector.dot( velocityVector ) / positionMagnitude;
    Eigen::Vector3d auxiliaryParameter3 = radialVelocity / positionMagnitude * positionVector;
    double auxiliaryParameter2 = ( velocityVector - auxiliaryParameter3 ).norm( );
    double auxiliaryParameter1 = ( ( radialVelocity >= 0 ) ? 1.0 : - 1.0 ) *
            auxiliaryParameter3.norm( ); // take norm now that vector value has been used
    // The sign of first velocity component depends on true anomaly (positive if < PI), and true anomaly can be
    // related to the radial velocity

    // Compute Rf1 and Rf2 hodograph elements
    convertedUnifiedStateModelElements( Rf1HodographUSM7Index ) = auxiliaryParameter1 * cosineLambda -
            ( auxiliaryParameter2 - convertedUnifiedStateModelElements( CHodographUSM7Index ) ) * sineLambda;
    convertedUnifiedStateModelElements( Rf2HodographUSM7Index ) = auxiliaryParameter1 * sineLambda +
            ( auxiliaryParameter2 - convertedUnifiedStateModelElements( CHodographUSM7Index ) ) * cosineLambda;

    // Give back result
    return convertedUnifiedStateModelElements;
}

//! Convert unified state model elements with quaternions to Cartesian elements.
Eigen::Vector6d convertUnifiedStateModelQuaternionsToCartesianElements(
        const Eigen::Vector7d& unifiedStateModelElements,
        const double centralBodyGravitationalParameter,
        const bool forceQuaternionNormalization )
{
    using mathematical_constants::PI;

    // Declaring eventual output vector.
    Eigen::Vector6d convertedCartesianElements = Eigen::Vector6d::Zero( );

    // Define the tolerance of a singularity
    const double singularityTolerance = 20.0 * std::numeric_limits< double >::epsilon( );

    // Extract quaternion elements
    Eigen::Vector4d quaternionsVector = unifiedStateModelElements.segment( etaUSM7Index, 4 );
    const double normOfQuaternionElements = quaternionsVector.norm( );
    if ( std::fabs( normOfQuaternionElements - 1.0 ) > singularityTolerance )
    {
        if ( forceQuaternionNormalization )
        {
            quaternionsVector /= normOfQuaternionElements;
        }
        else
        {
            // Define the error message.
            std::stringstream errorMessage;
            errorMessage << "The norm of the quaternion should be equal to one.\n"
                         << "Norm of the specified quaternion is: " << normOfQuaternionElements - 1.0 << " + 1." << std::endl;

            // Throw exception.
            throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
        }
    }
    // Else, nothing wrong and continue

    // Extract quaternion elements
    double etaQuaternionParameter = quaternionsVector( etaQuaternionIndex );
    double epsilon3QuaternionParameter = quaternionsVector( epsilon3QuaternionIndex );

    // Declare auxiliary parameters before using them in the if statement
    double cosineLambda;
    double sineLambda;
//    double rightAscensionOfLatitude;

    // Compute auxiliary parameters cosineLambda, sineLambda and lambda
    if ( ( std::fabs( epsilon3QuaternionParameter ) < singularityTolerance ) &&
         ( std::fabs( etaQuaternionParameter ) < singularityTolerance ) )
        // pure-retrograde orbit -> inclination = PI
    {
        // Define the error message
        std::stringstream errorMessage;
        errorMessage << "Pure-retrograde orbit (inclination = PI).\n"
                     << "Unified state model elements cannot be transformed to Kepler elements." << std::endl;

        // Throw exception
        throw std::runtime_error( std::runtime_error( errorMessage.str( ) ) );
    }
    else
    {
        double denominator = epsilon3QuaternionParameter * epsilon3QuaternionParameter +
                etaQuaternionParameter * etaQuaternionParameter;
        cosineLambda = ( etaQuaternionParameter * etaQuaternionParameter -
                         epsilon3QuaternionParameter * epsilon3QuaternionParameter ) / denominator;
        sineLambda = ( 2.0 * epsilon3QuaternionParameter *
                       etaQuaternionParameter ) / denominator;
//        rightAscensionOfLatitude = std::atan2( sineLambda, cosineLambda );
    }

    // Compute auxiliary parameters auxiliaryParameter1, auxiliaryParameter2 and auxiliaryVector1
    double auxiliaryParameter1 = unifiedStateModelElements( Rf1HodographUSM7Index ) * cosineLambda +
            unifiedStateModelElements( Rf2HodographUSM7Index ) * sineLambda;
    double auxiliaryParameter2 = unifiedStateModelElements( CHodographUSM7Index ) -
            unifiedStateModelElements( Rf1HodographUSM7Index ) * sineLambda +
            unifiedStateModelElements( Rf2HodographUSM7Index ) * cosineLambda;
    Eigen::Vector2d auxiliaryVector1;
    auxiliaryVector1( 0 ) = auxiliaryParameter1;
    auxiliaryVector1( 1 ) = auxiliaryParameter2;

    // Find direction cosine matrix in terms of quaternions
    Eigen::Matrix3d inverseDirectionCosineMatrix = linear_algebra::convertVectorToQuaternionFormat(
                quaternionsVector ).toRotationMatrix( );

    // Get Cartesian position vector
    convertedCartesianElements.segment( xCartesianPositionIndex, 3 ) =
            centralBodyGravitationalParameter / unifiedStateModelElements( CHodographUSM7Index ) /
            auxiliaryParameter2 * inverseDirectionCosineMatrix.block( 0, 0, 3, 1 ); // take first column of matrix

    // Get Cartesian velocity vector
    convertedCartesianElements.segment( xCartesianVelocityIndex, 3 ) =
            inverseDirectionCosineMatrix.block( 0, 0, 3, 2 ) * auxiliaryVector1;

    // Give back result
    return convertedCartesianElements;
}

} // close namespace orbital_element_conversions

} // close namespace tudat


text:
package stroom.annotation.shared;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonInclude(Include.NON_NULL)
public class Annotation {

    public static final String TITLE = "Title";
    public static final String SUBJECT = "Subject";
    public static final String COMMENT = "Comment";
    public static final String STATUS = "Status";
    public static final String ASSIGNED_TO = "Assigned";
    public static final String LINK = "Link";
    public static final String UNLINK = "Unlink";

    @JsonProperty
    private Long id;
    @JsonProperty
    private Integer version;
    @JsonProperty
    private Long createTime;
    @JsonProperty
    private String createUser;
    @JsonProperty
    private Long updateTime;
    @JsonProperty
    private String updateUser;
    @JsonProperty
    private String title;
    @JsonProperty
    private String subject;
    @JsonProperty
    private String status;
    @JsonProperty
    private String assignedTo;
    @JsonProperty
    private String comment;
    @JsonProperty
    private String history;

    public Annotation() {
    }

    @JsonCreator
    public Annotation(@JsonProperty("id") final Long id,
                      @JsonProperty("version") final Integer version,
                      @JsonProperty("createTime") final Long createTime,
                      @JsonProperty("createUser") final String createUser,
                      @JsonProperty("updateTime") final Long updateTime,
                      @JsonProperty("updateUser") final String updateUser,
                      @JsonProperty("title") final String title,
                      @JsonProperty("subject") final String subject,
                      @JsonProperty("status") final String status,
                      @JsonProperty("assignedTo") final String assignedTo,
                      @JsonProperty("comment") final String comment,
                      @JsonProperty("history") final String history) {
        this.id = id;
        this.version = version;
        this.createTime = createTime;
        this.createUser = createUser;
        this.updateTime = updateTime;
        this.updateUser = updateUser;
        this.title = title;
        this.subject = subject;
        this.status = status;
        this.assignedTo = assignedTo;
        this.comment = comment;
        this.history = history;
    }

    public Long getId() {
        return id;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(final Integer version) {
        this.version = version;
    }

    public Long getCreateTime() {
        return createTime;
    }

    public void setCreateTime(final Long createTime) {
        this.createTime = createTime;
    }

    public String getCreateUser() {
        return createUser;
    }

    public void setCreateUser(final String createUser) {
        this.createUser = createUser;
    }

    public Long getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(final Long updateTime) {
        this.updateTime = updateTime;
    }

    public String getUpdateUser() {
        return updateUser;
    }

    public void setUpdateUser(final String updateUser) {
        this.updateUser = updateUser;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(final String title) {
        this.title = title;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(final String subject) {
        this.subject = subject;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(final String status) {
        this.status = status;
    }

    public String getAssignedTo() {
        return assignedTo;
    }

    public void setAssignedTo(final String assignedTo) {
        this.assignedTo = assignedTo;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(final String comment) {
        this.comment = comment;
    }

    public String getHistory() {
        return history;
    }

    public void setHistory(final String history) {
        this.history = history;
    }

    @Override
    public String toString() {
        return "id=" + id;
    }
}

redpajama_set_name: RedPajamaGithub


text:
var app = require('../lib/app.js'),
	$ = require('jquery'),
	Parallax = require('../lib/canvas/parallax.js'),
	Ticker = require('../lib/canvas/ticker.js'),
	labelHeight,
	linkHeight,
	headlines = [];

var velocities = [{
	'direction': 1,
	'speed': 20 + Math.random() * 20
}, {
	'direction': -1,
	'speed': 20 + Math.random() * 20
}, {
	'direction': 1,
	'speed': 20 + Math.random() * 20
}, {
	'direction': -1,
	'speed': 20 + Math.random() * 20
}];

var options = {
	'parallax': {
		'background-color': '#101010',
		'sourceSet': [
			'/images/portfolio/bg-desktop.png'
		],
		'refresh': function(index, c, ct, now) {
			var v = velocities[index],
				w = v.speed * now / 1024,
				dx = v.direction * w % c.width;
			return {
				'tx': dx
			};
		}
	},
	'ticker': {
		'headlines': []
	}
};

function offsetOverlay() {
	labelHeight = parseInt($('.client-label').css('height'), 10);
	linkHeight = $('.client-link').height();

	$('.client-descriptor-wrapper').css({
		'top': -labelHeight
	});
}

function registerHandlers() {
	$('.client-link').on('click', function(e) {
		var descriptor = $(this).find('.client-descriptor-wrapper');
		if (parseInt(descriptor.css('top'), 10) !== -linkHeight) {
			e.preventDefault();
			descriptor.css('top', -linkHeight);
		}
	});

	$('.client-descriptor-wrapper').hover(function() {
		$(this).css({
			'top': -linkHeight
		});
	}, function() {
		$(this).css({
			'top': -labelHeight
		});
	});
}

$(document).ready(function() {
	app.init();
	registerHandlers();
	// var parallax = new Parallax(options.parallax);
	// parallax.play();
	//
	// $('.ticker-text').each(function() {
	// 	headlines.push($(this).text());
	// });
	// options.ticker.headlines = headlines;
	// var ticker = new Ticker(options.ticker);
	// ticker.play();
	//
	// offsetOverlay();
	// $(window).on('resize', offsetOverlay);
});


text:
<html>
<body>
<script src="../../resources/js-test.js"></script>
<script>
description("Tests that moving nodes across documents does not crash.");

if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

function runTest()
{
    root = document.getElementById('root').contentDocument;
    test = root.getElementById('test');
    var doc = document.implementation.createDocument(null, '');
    doc.adoptNode(test);
    test.appendChild(root.getElementById('svg').cloneNode(0));
    document.open();
    document.write('PASS');
    document.close();
    setTimeout('finish();', 0);
}

function finish()
{
    gc();
    document.adoptNode(test);
    if (window.testRunner)
        testRunner.notifyDone();
}
</script>
<object data="resources/node-move-to-new-document-crash.svg" id="root" onload="runTest()"/></object>
</body>
</html>


text:
package com.formulasearchengine.mathosphere.mlp.text;

import com.formulasearchengine.mathosphere.mlp.contracts.TextExtractorMapper;
import com.formulasearchengine.mathosphere.mlp.pojos.MathTag;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.util.List;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;

/**
 * Created by Moritz on 15.12.2015.
 */
public class MathConverterTest {

    @Test
    public void findFormulaFromWikiText() throws Exception {
        String text = WikiTextUtilsTest.getTestResource("com/formulasearchengine/mathosphere/mlp/gold/eval_dataset_sample.xml");
        text = TextExtractorMapper.unescape(text);
        final MathConverter mathConverter = new MathConverter(text);
        final String real = mathConverter.getStrippedOutput();
        System.out.println(real);
    }

    @Test
    public void testChem1() throws Exception {
        String wikiText = IOUtils.toString(getClass().getResourceAsStream("../titration_wiki.txt"),"UTF-8");
        final MathConverter mathConverter = new MathConverter(wikiText);
        mathConverter.getStrippedOutput();
        final List<MathTag> mathTags = mathConverter.getMathTags();
        assertEquals(34, mathTags.size());
        assertEquals(22, mathTags.stream().filter(mathTag -> mathTag.getMarkUpType()
                == WikiTextUtils.MathMarkUpType.LATEXCE).count());
    }

    @Test
    public void testGo() throws Exception {
        String wikiText = IOUtils.toString(getClass().getResourceAsStream("legendre_wiki.txt"),"UTF-8");
        final MathConverter mathConverter = new MathConverter(wikiText);
        final String real = mathConverter.getStrippedOutput();
        assertThat(real, containsString("Let FORMULA_"));
    }

    @Test
    public void testGo10() throws Exception {
        String wikiText = "''a''x.";
        //wikiText = TextExtractorMapper.unescape(wikiText);
        final MathConverter mathConverter = new MathConverter(wikiText);
        final String real = mathConverter.getOutput();
        assertThat(real, containsString("<math>a</math> x"));
    }

    @Test
    public void testGo11() throws Exception {
        String wikiText = "Let the coin tosses be represented by a sequence {{nowrap|1=''X''<sub>0</sub>, ''X''<sub>1</sub>, &hellip;}}";
        wikiText = TextExtractorMapper.unescape(wikiText);
        final MathConverter mathConverter = new MathConverter(wikiText);
        final String real = mathConverter.getOutput();
        assertThat(real, containsString("<math>\\mathit{X}_{0}"));
    }

    @Test
    public void testGo2() throws Exception {
        String wikiText = IOUtils.toString(getClass().getResourceAsStream("../performance/hamiltonian_wiki.txt"),"UTF-8");
        final MathConverter mathConverter = new MathConverter(wikiText);
        final String real = mathConverter.getOutput();
        assertThat(real, containsString("denoted by <math>H</math> , also \"Ȟ\" or <math>\\hat{H}</math> . "));
    }

    @Test
    public void testGo3() throws Exception {
        String wikiText = "Let '''<math> \\Omega </math>''' be an [[open subset]] of ℝ''n''. A  function '''<math> u </math>''' belonging to '''[[Lp space|<math>L^1(\\Omega)</math>]]''' is said of '''bounded variation''' ('''BV function'''), and written";
        final MathConverter mathConverter = new MathConverter(wikiText);
        final String real = mathConverter.getOutput();
        assertThat(real, containsString("<math>L^1(\\Omega)</math>"));
    }

    @Test
    public void testGo4() throws Exception {
        String wikiText = "{| style="margin: 1em auto 1em auto;"\n" +
                "|-\n" +
                "| style="width:350px" |\n" +
                "<!--START-->{| style="text-align: center; border: 1px solid darkgray; width:300px"\n" +
                "|-\n" +
                "|colspan="2"|<span style="color:darkgray;">No column/row is empty:</span>\n"
                +
                "|- style="vertical-align:top;"\n" +
                "|[[File:Predicate logic; 2 variables; example matrix a2e1.svg|thumb|center|120px|1. <math>\\forall x \\exist y Lyx</math>:<br>Everyone is loved by someone.]]\n"
                +
                "|[[File:Predicate logic; 2 variables; example matrix a1e2.svg|thumb|center|120px|2. <math>\\forall x \\exist y Lxy</math>:<br>Everyone loves someone.]]\n"
                +
                "|}<!--END-->\n" +
                "| rowspan="2" style="width:210px" |\n" +
                "<!--START-->{| style="text-align: center; border: 1px solid darkgray; width:160px"\n" +
                "|-\n" +
                "|colspan="2"|<span style="color:darkgray;">The diagonal is<br>nonempty/full:</span>\n"
                +
                "|- style="vertical-align:top;"\n" +
                "|[[File:Predicate logic; 2 variables; example matrix e(12).svg|thumb|center|120px|5. <math>\\exist x Lxx</math>:<br>Someone loves himself.]]\n"
                +
                "|- style="vertical-align:top;"\n" +
                "|[[File:Predicate logic; 2 variables; example matrix a(12).svg|thumb|center|120px|6. <math>\\forall x Lxx</math>:<br>Everyone loves himself.]]\n"
                +
                "|}<!--END-->\n" +
                "| rowspan="2" style="width:250px" |\n" +
                "<!--START-->{| style="text-align: center; border: 1px solid darkgray; width:160px"\n" +
                "|-\n" +
                "|colspan="2"|<span style="color:darkgray;">The matrix is<br>nonempty/full:</span>\n"
                +
                "|- style="vertical-align:top;"\n" +
                "|[[File:Predicate logic; 2 variables; example matrix e12.svg|thumb|center|120px|7. <math>\\exist x \\exist y Lxy</math>:<br>Someone loves someone.<br><br>8. <math>\\exist x \\exist y Lyx</math>:<br>Someone is loved by someone.]]\n"
                +
                "|- style="vertical-align:top;"\n" +
                "|[[File:Predicate logic; 2 variables; example matrix a12.svg|thumb|center|120px|9. <math>\\forall x \\forall y Lxy</math>:<br>Everyone loves everyone.<br><br>10. <math>\\forall x \\forall y Lyx</math>:<br>Everyone is loved by everyone.]]\n"
                +
                "|}<!--END-->\n" +
                "|rowspan="2"|[[File:Predicate logic; 2 variables; implications.svg|thumb|250px|right|[[Hasse diagram]] of the implications]]\n"
                +
                "|-\n" +
                "|\n" +
                "<!--START-->{| style="text-align: center; border: 1px solid darkgray; width:300px"\n" +
                "|-\n" +
                "|colspan="2"|<span style="color:darkgray;">One row/column is full:</span>\n"
                +
                "|- style="vertical-align:top;"\n" +
                "|[[File:Predicate logic; 2 variables; example matrix e1a2.svg|thumb|center|120px|3. <math>\\exist x \\forall y Lxy</math>:<br>Someone loves everyone.]]\n"
                +
                "|[[File:Predicate logic; 2 variables; example matrix e2a1.svg|thumb|center|120px|4. <math>\\exist x \\forall y Lyx</math>:<br>Someone is loved by everyone.]]\n"
                +
                "|}<!--END-->\n" +
                "|}";
        wikiText = TextExtractorMapper.unescape(wikiText);
        final MathConverter mathConverter = new MathConverter(wikiText);
        final String real = mathConverter.getOutput();
        //assertThat(real, containsString ("<math>L^1(\\Omega)</math>"));
    }

    @Test
    public void testGo5() throws Exception {
        String wikiText = "{{mvar|φ}}";
        wikiText = TextExtractorMapper.unescape(wikiText);
        final MathConverter mathConverter = new MathConverter(wikiText);
        final String real = mathConverter.getOutput();
        assertThat(real, containsString("<math>\\varphi</math>"));
    }

    @Test
    public void testGo6() throws Exception {
        String wikiText = "{{math|10/19 &middot; 7000 &minus; 18/38 &middot; 7000 {{=}} 368.42}}";
        wikiText = TextExtractorMapper.unescape(wikiText);
        final MathConverter mathConverter = new MathConverter(wikiText);
        final String real = mathConverter.getOutput();
        assertThat(real, containsString("<math>10/19 {\\cdot} 7000 - 18/38 {\\cdot} 7000</math>"));
    }

    @Test
    public void testGo7() throws Exception {
        String wikiText = "{{NumBlk|::|Input &nbsp; <math>\\int_{-\\infty}^{\\infty} c_{\\omega}\\,x_{\\omega}(t) \\, \\operatorname{d}\\omega</math> &nbsp; produces output &nbsp; <math>\\int_{-\\infty}^{\\infty} c_{\\omega}\\,y_{\\omega}(t) \\, \\operatorname{d}\\omega\\,</math>|{{EquationRef|Eq.1}}}}\n";
        wikiText = TextExtractorMapper.unescape(wikiText);
        final MathConverter mathConverter = new MathConverter(wikiText);
        final String real = mathConverter.getOutput();
        assertThat(real, containsString("<math>\\int_{-\\infty}^{\\infty}"));
    }

    @Test
    public void testGo8() throws Exception {
        String wikiText =
                "<ref><math>\\beta= \\alpha/3</math> where <math>\\alpha</math> is the\n"
                        +
                        "quantity used by Deshpande–Fleck</ref>";
        wikiText = TextExtractorMapper.unescape(wikiText);
        final MathConverter mathConverter = new MathConverter(wikiText);
        final String real = mathConverter.getOutput();
        assertThat(real, containsString("<math>\\beta= \\alpha/3"));
    }

    @Test
    public void testGo9() throws Exception {
        String wikiText = "Word\n<math>x</math>\nend.";
        //wikiText = TextExtractorMapper.unescape(wikiText);
        final MathConverter mathConverter = new MathConverter(wikiText);
        final String real = mathConverter.getOutput();
        assertThat(real, containsString("Word <math>x</math> end."));
    }

    @Test
    public void testWiki2Tex() throws Exception {
        String text = "a, b, '''c''', ''d''";
        final MathConverter mathConverter = new MathConverter(text);
        final String real = mathConverter.wiki2Tex(text);
        assertThat(real, containsString("_{a}"));
        assertThat(real, containsString("^{b}"));
        assertThat(real, containsString("\\mathbf{c}"));
        assertThat(real, containsString("\\mathit{d}"));
        assertThat(real, equalTo("_{a}, ^{b}, \\mathbf{c}, \\mathit{d}"));
    }
}


text:
package org.videolan.libvlc;

import android.net.Uri;

import org.videolan.libvlc.util.AndroidUtil;
import org.videolan.libvlc.util.HWDecoderUtil;

import java.io.FileDescriptor;

@SuppressWarnings("unused")
public class Media extends VLCObject<Media.Event> {
    private final static String TAG = "LibVLC/Media";

    public static class Event extends VLCEvent {
        public static final int MetaChanged = 0;
        public static final int SubItemAdded = 1;
        public static final int DurationChanged = 2;
        public static final int ParsedChanged = 3;
        //public static final int Freed                      = 4;
        public static final int StateChanged = 5;
        public static final int SubItemTreeAdded = 6;

        protected Event(int type) {
            super(type);
        }
    }

    public interface EventListener extends VLCEvent.Listener<Media.Event> {}

    /**
     * libvlc_media_type_t
     */
    public static class Type {
        public static final int Unknown = 0;
        public static final int File = 1;
        public static final int Directory = 2;
        public static final int Disc = 3;
        public static final int Stream = 4;
        public static final int Playlist = 5;
    }

    /**
     * see libvlc_meta_t
     */
    public static class Meta {
        public static final int Title = 0;
        public static final int Artist = 1;
        public static final int Genre = 2;
        public static final int Copyright = 3;
        public static final int Album = 4;
        public static final int TrackNumber = 5;
        public static final int Description = 6;
        public static final int Rating = 7;
        public static final int Date = 8;
        public static final int Setting = 9;
        public static final int URL = 10;
        public static final int Language = 11;
        public static final int NowPlaying = 12;
        public static final int Publisher = 13;
        public static final int EncodedBy = 14;
        public static final int ArtworkURL = 15;
        public static final int TrackID = 16;
        public static final int TrackTotal = 17;
        public static final int Director = 18;
        public static final int Season = 19;
        public static final int Episode = 20;
        public static final int ShowName = 21;
        public static final int Actors = 22;
        public static final int AlbumArtist = 23;
        public static final int DiscNumber = 24;
        public static final int MAX = 25;
    }

    /**
     * see libvlc_state_t
     */
    public static class State {
        public static final int NothingSpecial = 0;
        public static final int Opening = 1;
        public static final int Buffering = 2;
        public static final int Playing = 3;
        public static final int Paused = 4;
        public static final int Stopped = 5;
        public static final int Ended = 6;
        public static final int Error = 7;
        public static final int MAX = 8;
    }

    /**
     * see libvlc_media_parse_flag_t
     */
    public static class Parse {
        public static final int ParseLocal   = 0;
        public static final int ParseNetwork = 0x01;
        public static final int FetchLocal   = 0x02;
        public static final int FetchNetwork = 0x04;
    }

    /**
     * see libvlc_media_track_t
     */
    public static abstract class Track {
        public static class Type {
            public static final int Unknown = -1;
            public static final int Audio = 0;
            public static final int Video = 1;
            public static final int Text = 2;
        }

        public final int type;
        public final String codec;
        public final String originalCodec;
        public final int id;
        public final int profile;
        public final int level;
        public final int bitrate;
        public final String language;
        public final String description;

        private Track(int type, String codec, String originalCodec, int id, int profile,
                int level, int bitrate, String language, String description) {
            this.type = type;
            this.codec = codec;
            this.originalCodec = originalCodec;
            this.id = id;
            this.profile = profile;
            this.level = level;
            this.bitrate = bitrate;
            this.language = language;
            this.description = description;
        }
    }

    /**
     * see libvlc_audio_track_t
     */
    public static class AudioTrack extends Track {
        public final int channels;
        public final int rate;

        private AudioTrack(String codec, String originalCodec, int id, int profile,
                int level, int bitrate, String language, String description,
                int channels, int rate) {
            super(Type.Audio, codec, originalCodec, id, profile, level, bitrate, language, description);
            this.channels = channels;
            this.rate = rate;
        }
    }

    @SuppressWarnings("unused") /* Used from JNI */
    private static Track createAudioTrackFromNative(String codec, String originalCodec, int id, int profile,
            int level, int bitrate, String language, String description,
            int channels, int rate) {
        return new AudioTrack(codec, originalCodec, id, profile,
                level, bitrate, language, description,
                channels, rate);
    }

    /**
     * see libvlc_video_track_t
     */
    public static class VideoTrack extends Track {
        public final int height;
        public final int width;
        public final int sarNum;
        public final int sarDen;
        public final int frameRateNum;
        public final int frameRateDen;

        private VideoTrack(String codec, String originalCodec, int id, int profile,
                int level, int bitrate, String language, String description,
                int height, int width, int sarNum, int sarDen, int frameRateNum, int frameRateDen) {
            super(Type.Video, codec, originalCodec, id, profile, level, bitrate, language, description);
            this.height = height;
            this.width = width;
            this.sarNum = sarNum;
            this.sarDen = sarDen;
            this.frameRateNum = frameRateNum;
            this.frameRateDen = frameRateDen;
        }
    }

    /* Used from JNI */
    private static Track createVideoTrackFromNative(String codec, String originalCodec, int id, int profile,
            int level, int bitrate, String language, String description,
            int height, int width, int sarNum, int sarDen, int frameRateNum, int frameRateDen) {
        return new VideoTrack(codec, originalCodec, id, profile,
                level, bitrate, language, description,
                height, width, sarNum, sarDen, frameRateNum, frameRateDen);
    }

    /**
     * see libvlc_subtitle_track_t
     */
    public static class SubtitleTrack extends Track {
        public final String encoding;

        private SubtitleTrack(String codec, String originalCodec, int id, int profile,
                int level, int bitrate, String language, String description,
                String encoding) {
            super(Type.Text, codec, originalCodec, id, profile, level, bitrate, language, description);
            this.encoding = encoding;
        }
    }

    @SuppressWarnings("unused") /* Used from JNI */
    private static Track createSubtitleTrackFromNative(String codec, String originalCodec, int id, int profile,
            int level, int bitrate, String language, String description,
            String encoding) {
        return new SubtitleTrack(codec, originalCodec, id, profile,
                level, bitrate, language, description,
                encoding);
    }

    private static final int PARSE_STATUS_INIT = 0x00;
    private static final int PARSE_STATUS_PARSING = 0x01;
    private static final int PARSE_STATUS_PARSED = 0x02;

    private Uri mUri = null;
    private MediaList mSubItems = null;
    private int mParseStatus = PARSE_STATUS_INIT;
    private final String mNativeMetas[] = new String[Meta.MAX];
    private Track mNativeTracks[] = null;
    private long mDuration = -1;
    private int mState = -1;
    private int mType = -1;
    private boolean mCodecOptionSet = false;

    /**
     * Create a Media from libVLC and a local path starting with '/'.
     *
     * @param libVLC a valid libVLC
     * @param path an absolute local path
     */
    public Media(LibVLC libVLC, String path) {
        nativeNewFromPath(libVLC, path);
        mUri = UriFromMrl(nativeGetMrl());
    }

    /**
     * Create a Media from libVLC and a Uri
     *
     * @param libVLC a valid libVLC
     * @param uri a valid RFC 2396 Uri
     */
    public Media(LibVLC libVLC, Uri uri) {
        nativeNewFromLocation(libVLC, locationFromUri(uri));
        mUri = uri;
    }

    /**
     * Create a Media from libVLC and a FileDescriptor
     *
     * @param libVLC a valid LibVLC
     * @param fd file descriptor object
     */
    public Media(LibVLC libVLC, FileDescriptor fd) {
        nativeNewFromFd(libVLC, fd);
        mUri = UriFromMrl(nativeGetMrl());
    }

    /**
     *
     * @param ml Should not be released and locked
     * @param index index of the Media from the MediaList
     */
    protected Media(MediaList ml, int index) {
        if (ml == null || ml.isReleased())
            throw new IllegalArgumentException("MediaList is null or released");
        if (!ml.isLocked())
            throw new IllegalStateException("MediaList should be locked");
        nativeNewFromMediaList(ml, index);
        mUri = UriFromMrl(nativeGetMrl());
    }

    private static final String URI_AUTHORIZED_CHARS = "!'()*";

    /**
     * VLC authorize only "-._~" in Mrl format, android Uri authorize "_-!.~'()*".
     * Therefore, decode the characters authorized by Android Uri when creating an Uri from VLC.
     */
    private static Uri UriFromMrl(String mrl) {
        final char array[] = mrl.toCharArray();
        final StringBuilder sb = new StringBuilder(array.length);

        for (int i = 0; i < array.length; ++i) {
            final char c = array[i];
            if (c == '%') {
                if (array.length - i < 3)
                    throw new IllegalArgumentException("bad mrl format");

                final int hex = Integer.parseInt(new String(array, i + 1, 2), 16);
                if (URI_AUTHORIZED_CHARS.indexOf(hex) != -1) {
                    sb.append((char)hex);
                    i += 2;
                    continue;
                }
            }
            sb.append(c);
        }

        return Uri.parse(sb.toString());
    }

    /**
     * VLC authorize only "-._~" in Mrl format, android Uri authorize "_-!.~'()*".
     * Therefore, encode the characters authorized by Android Uri when creating a mrl from an Uri.
     */
    private static String locationFromUri(Uri uri) {
        final char array[] = uri.toString().toCharArray();
        final StringBuilder sb = new StringBuilder(array.length * 2);

        for (final char c : array) {
            if (URI_AUTHORIZED_CHARS.indexOf(c) != -1)
                sb.append("%").append(Integer.toHexString(c));
            else
                sb.append(c);
        }

        return sb.toString();
    }

    public void setEventListener(EventListener listener) {
        super.setEventListener(listener);
    }

    @Override
    protected synchronized Event onEventNative(int eventType, long arg1, float arg2) {
        switch (eventType) {
        case Event.MetaChanged:
            // either we update all metas (if first call) or we update a specific meta
            int id = (int) arg1;
            if (id >= 0 && id < Meta.MAX)
                mNativeMetas[id] = null;
            break;
        case Event.DurationChanged:
            mDuration = -1;
            break;
        case Event.ParsedChanged:
            postParse();
            break;
        case Event.StateChanged:
            mState = -1;
            break;
        }
        return new Event(eventType);
    }

    /**
     * Get the MRL associated with the Media.
     */
    public synchronized Uri getUri() {
        return mUri;
    }

    /**
     * Get the duration of the media.
     */
    public long getDuration() {
        synchronized (this) {
            if (mDuration != -1)
                return mDuration;
            if (isReleased())
                return 0;
        }
        final long duration = nativeGetDuration();
        synchronized (this) {
            mDuration = duration;
            return mDuration;
        }
    }

    /**
     * Get the state of the media.
     *
     * @see State
     */
    public int getState() {
        synchronized (this) {
            if (mState != -1)
                return mState;
            if (isReleased())
                return State.Error;
        }
        final int state = nativeGetState();
        synchronized (this) {
            mState = state;
            return mState;
        }
    }

    /**
     * Get the subItems MediaList associated with the Media. This Media should be alive (not released).
     *
     * @return subItems as a MediaList. This MediaList should be released with {@link #release()}.
     */
    public MediaList subItems() {
        synchronized (this) {
            if (mSubItems != null) {
                mSubItems.retain();
                return mSubItems;
            }
        }
        final MediaList subItems = new MediaList(this);
        synchronized (this) {
            mSubItems = subItems;
            mSubItems.retain();
            return mSubItems;
        }
    }

    private synchronized void postParse() {
        // fetch if parsed and not fetched
        mParseStatus &= ~PARSE_STATUS_PARSING;
        mParseStatus |= PARSE_STATUS_PARSED;
        mNativeTracks = null;
        mDuration = -1;
        mState = -1;
        mType = -1;
    }

    /**
     * Parse the media synchronously with a flag. This Media should be alive (not released).
     *
     * @param flags see {@link Parse}
     * @return true in case of success, false otherwise.
     */
    public boolean parse(int flags) {
        boolean parse = false;
        synchronized (this) {
            if ((mParseStatus & (PARSE_STATUS_PARSED | PARSE_STATUS_PARSING)) == 0) {
                mParseStatus |= PARSE_STATUS_PARSING;
                parse = true;
            }
        }
        if (parse && nativeParse(flags)) {
            postParse();
            return true;
        } else
            return false;
    }

    /**
     * Parse the media and local art synchronously. This Media should be alive (not released).
     *
     * @return true in case of success, false otherwise.
     */
    public boolean parse() {
        return parse(Parse.FetchLocal);
    }

    /**
     * Parse the media asynchronously with a flag. This Media should be alive (not released).
     *
     * To track when this is over you can listen to {@link Event#ParsedChanged}
     * event (only if this methods returned true).
     *
     * @param flags see {@link Parse}
     * @return true in case of success, false otherwise.
     */
    public boolean parseAsync(int flags) {
        boolean parse = false;
        synchronized (this) {
            if ((mParseStatus & (PARSE_STATUS_PARSED | PARSE_STATUS_PARSING)) == 0) {
                mParseStatus |= PARSE_STATUS_PARSING;
                parse = true;
            }
        }
        return parse && nativeParseAsync(flags);
    }

    /**
     * Parse the media and local art asynchronously. This Media should be alive (not released).
     *
     * @see #parseAsync(int)
     */
    public boolean parseAsync() {
        return parseAsync(Parse.FetchLocal);
    }

    /**
     * Returns true if the media is parsed This Media should be alive (not released).
     */
    public synchronized boolean isParsed() {
        return (mParseStatus & PARSE_STATUS_PARSED) != 0;
    }

    /**
     * Get the type of the media
     *
     * @see {@link Type}
     */
    public int getType() {
        synchronized (this) {
            if (mType != -1)
                return mType;
            if (isReleased())
                return Type.Unknown;
        }
        final int type = nativeGetType();
        synchronized (this) {
            mType = type;
            return mType;
        }
    }

    private Track[] getTracks() {
        synchronized (this) {
            if (mNativeTracks != null)
                return mNativeTracks;
            if (isReleased())
                return null;
        }
        final Track[] tracks = nativeGetTracks();
        synchronized (this) {
            mNativeTracks = tracks;
            return mNativeTracks;
        }
    }

    /**
     * Get the Track count.
     */
    public int getTrackCount() {
        final Track[] tracks = getTracks();
        return tracks != null ? tracks.length : 0;
    }

    /**
     * Get a Track
     * The Track can be casted to {@link AudioTrack}, {@link VideoTrack} or {@link SubtitleTrack} in function of the {@link Track.Type}.
     *
     * @param idx index of the track
     * @return Track or null if not idx is not valid
     * @see #getTrackCount()
     */
    public Track getTrack(int idx) {
        final Track[] tracks = getTracks();
        if (tracks == null || idx < 0 || idx >= tracks.length)
            return null;
        return tracks[idx];
    }

    /**
     * Get a Meta.
     *
     * @param id see {@link Meta}
     * @return meta or null if not found
     */
    public String getMeta(int id) {
        if (id < 0 || id >= Meta.MAX)
            return null;

        synchronized (this) {
            if (mNativeMetas[id] != null)
                return mNativeMetas[id];
            if (isReleased())
                return null;
        }

        final String meta = nativeGetMeta(id);
        synchronized (this) {
            mNativeMetas[id] = meta;
            return meta;
        }
    }

    private static String getMediaCodecModule() {
        return AndroidUtil.isLolliPopOrLater() ? "mediacodec_ndk" : "mediacodec_jni";
    }

    /**
     * Add or remove hw acceleration media options
     *
     * @param enabled if true, hw decoder will be used
     * @param force force hw acceleration even for unknown devices
     */
    public void setHWDecoderEnabled(boolean enabled, boolean force) {
        final HWDecoderUtil.Decoder decoder = enabled ?
                HWDecoderUtil.getDecoderFromDevice() :
                HWDecoderUtil.Decoder.NONE;

        if (decoder == HWDecoderUtil.Decoder.NONE ||
                (decoder == HWDecoderUtil.Decoder.UNKNOWN && !force)) {
            addOption(":codec=all");
            return;
        }

        /*
         * Set higher caching values if using iomx decoding, since some omx
         * decoders have a very high latency, and if the preroll data isn't
         * enough to make the decoder output a frame, the playback timing gets
         * started too soon, and every decoded frame appears to be too late.
         * On Nexus One, the decoder latency seems to be 25 input packets
         * for 320x170 H.264, a few packets less on higher resolutions.
         * On Nexus S, the decoder latency seems to be about 7 packets.
         */
        addOption(":file-caching=1500");
        addOption(":network-caching=1500");

        final StringBuilder sb = new StringBuilder(":codec=");
        if (decoder == HWDecoderUtil.Decoder.MEDIACODEC)
            sb.append(getMediaCodecModule()).append(",");
        else if (decoder == HWDecoderUtil.Decoder.OMX)
            sb.append("iomx,");
        else
            sb.append(getMediaCodecModule()).append(",iomx,");
        sb.append("all");

        addOption(sb.toString());
    }

    /**
     * Enable HWDecoder options if not already set
     */
    protected void setDefaultMediaPlayerOptions() {
        boolean codecOptionSet;
        synchronized (this) {
            codecOptionSet = mCodecOptionSet;
            mCodecOptionSet = true;
        }
        if (!codecOptionSet)
            setHWDecoderEnabled(true, false);
    }

    /**
     * Add an option to this Media. This Media should be alive (not released).
     *
     * @param option ":option" or ":option=value"
     */
    public void addOption(String option) {
        synchronized (this) {
            if (!mCodecOptionSet && option.startsWith(":codec="))
                mCodecOptionSet = true;
        }
        nativeAddOption(option);
    }

    @Override
    protected void onReleaseNative() {
        if (mSubItems != null)
            mSubItems.release();
        nativeRelease();
    }

    /* JNI */
    private native void nativeNewFromPath(LibVLC libVLC, String path);
    private native void nativeNewFromLocation(LibVLC libVLC, String location);
    private native void nativeNewFromFd(LibVLC libVLC, FileDescriptor fd);
    private native void nativeNewFromMediaList(MediaList ml, int index);
    private native void nativeRelease();
    private native boolean nativeParseAsync(int flags);
    private native boolean nativeParse(int flags);
    private native String nativeGetMrl();
    private native int nativeGetState();
    private native String nativeGetMeta(int id);
    private native Track[] nativeGetTracks();
    private native long nativeGetDuration();
    private native int nativeGetType();
    private native void nativeAddOption(String option);
}


text:
title: PhoneGap Simulator Update
date: 2009-11-03 15:50:37 Z
categories:
- app
author: Yohei Shimomae
link: http://blogs.nitobi.com/yohei/2009/11/03/phonegap-simulator-update/
status: publish
type: post
format: html
---

PhoneGap Simulator Update

[› Visit the original post](http://blogs.nitobi.com/yohei/2009/11/03/phonegap-simulator-update/)


text:
@interface BMPredictionHeaderView : UIView

@property (nonatomic, copy) NSString* title;
@property (nonatomic) float confidence;

@end


text:
namespace L4p.Common.DumpToLogs
{
    public interface IAmAComponent
    {
        string Name { get; }
        string Version { get; }
        string LogName { get; }
    }

    class UnknownComponent : IAmAComponent
    {
        string IAmAComponent.Name { get { return "Unknown"; } }
        string IAmAComponent.Version { get { return "0.0.0"; } }
        string IAmAComponent.LogName { get { return "temp.log"; } }
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>org.apache.lucene.analysis.de (Lucene 4.6.1 API)</title>
<meta name="date" content="2014-01-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Help

PREV PACKAGE

NEXT PACKAGE

FRAMES

NO FRAMES

All Classes

Package org.apache.lucene.analysis.de

Analyzer for German.

See: Description

Class Summary

Class
Description

GermanAnalyzer

Analyzer for German language.

GermanLightStemFilter

A TokenFilter that applies GermanLightStemmer to stem German
 words.

GermanLightStemFilterFactory

Factory for GermanLightStemFilter.

GermanLightStemmer

Light Stemmer for German.

GermanMinimalStemFilter

A TokenFilter that applies GermanMinimalStemmer to stem German
 words.

GermanMinimalStemFilterFactory

Factory for GermanMinimalStemFilter.

GermanMinimalStemmer

Minimal Stemmer for German.

GermanNormalizationFilter

Normalizes German characters according to the heuristics
 of the
 German2 snowball algorithm.

GermanNormalizationFilterFactory

Factory for GermanNormalizationFilter.

GermanStemFilter

A TokenFilter that stems German words.

GermanStemFilterFactory

Factory for GermanStemFilter.

GermanStemmer

A stemmer for German words.

Package org.apache.lucene.analysis.de Description

Analyzer for German.

Overview

Package

Class

Use

Tree

Deprecated

Help

PREV PACKAGE

NEXT PACKAGE

FRAMES

NO FRAMES

All Classes

          Copyright © 2000-2014 Apache Software Foundation.  All Rights Reserved.


text:
package io.datakernel.launchers.remotefs;

import io.datakernel.config.Config;
import io.datakernel.config.ConfigConverters;
import io.datakernel.config.ConfigModule;
import io.datakernel.di.annotation.Inject;
import io.datakernel.di.annotation.Optional;
import io.datakernel.di.annotation.Provides;
import io.datakernel.di.module.Module;
import io.datakernel.eventloop.Eventloop;
import io.datakernel.eventloop.ThrottlingController;
import io.datakernel.jmx.JmxModule;
import io.datakernel.launcher.Launcher;
import io.datakernel.remotefs.RemoteFsServer;
import io.datakernel.service.ServiceGraphModule;

import java.util.concurrent.Executor;

import static io.datakernel.config.ConfigConverters.ofPath;
import static io.datakernel.di.module.Modules.combine;
import static io.datakernel.launchers.initializers.Initializers.ofEventloop;
import static io.datakernel.launchers.remotefs.Initializers.ofRemoteFsServer;

public abstract class RemoteFsServerLauncher extends Launcher {
	public static final String PROPERTIES_FILE = "remotefs-server.properties";

	@Inject
	RemoteFsServer remoteFsServer;

	@Provides
	public Eventloop eventloop(Config config, @Optional ThrottlingController throttlingController) {
		return Eventloop.create()
				.initialize(ofEventloop(config.getChild("eventloop")))
				.initialize(eventloop -> eventloop.withInspector(throttlingController));
	}

	@Provides
	RemoteFsServer remoteFsServer(Eventloop eventloop, Executor executor,
			Config config) {
		return RemoteFsServer.create(eventloop, executor, config.get(ofPath(), "remotefs.path"))
				.initialize(ofRemoteFsServer(config.getChild("remotefs")));

	}

	@Provides
	Executor executor(Config config) {
		return ConfigConverters.getExecutor(config.getChild("remotefs.executor"));
	}

	@Provides
	Config config() {
		return Config.create()
				.overrideWith(Config.ofClassPathProperties(PROPERTIES_FILE, true))
				.overrideWith(Config.ofSystemProperties("config"));
	}

	@Override
	protected final Module getModule() {
		return combine(
				ServiceGraphModule.create(),
				JmxModule.create(),
				ConfigModule.create()
						.withEffectiveConfigLogger());
	}

	@Override
	protected void run() throws Exception {
		awaitShutdown();
	}

	public static void main(String[] args) throws Exception {
		Launcher launcher = new RemoteFsServerLauncher() {};
		launcher.launch(args);
	}
}


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

<title>Point (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<meta name="keywords" content="java.awt.Point class">
<meta name="keywords" content="x">
<meta name="keywords" content="y">
<meta name="keywords" content="getX()">
<meta name="keywords" content="getY()">
<meta name="keywords" content="getLocation()">
<meta name="keywords" content="setLocation()">
<meta name="keywords" content="move()">
<meta name="keywords" content="translate()">
<meta name="keywords" content="equals()">
<meta name="keywords" content="toString()">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

java.awt

Class Point

java.lang.Object

java.awt.geom.Point2D

java.awt.Point

All Implemented Interfaces:

Serializable, Cloneable

public class Point
extends Point2D
implements Serializable

A point representing a location in (x,y) coordinate space,
 specified in integer precision.

Since:

1.0

See Also:

Serialized Form

Nested Class Summary

Nested classes/interfaces inherited from class java.awt.geom.Point2D

Point2D.Double, Point2D.Float

Field Summary

Fields

Modifier and Type
Field and Description

int
x

The X coordinate of this Point.

int
y

The Y coordinate of this Point.

Constructor Summary

Constructors

Constructor and Description

Point()

Constructs and initializes a point at the origin
 (0, 0) of the coordinate space.

Point(int x,
     int y)

Constructs and initializes a point at the specified
 (x,y) location in the coordinate space.

Point(Point p)

Constructs and initializes a point with the same location as
 the specified Point object.

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(Object obj)

Determines whether or not two points are equal.

Point
getLocation()

Returns the location of this point.

double
getX()

Returns the X coordinate of this Point2D in
 double precision.

double
getY()

Returns the Y coordinate of this Point2D in
 double precision.

void
move(int x,
    int y)

Moves this point to the specified location in the
 (x,y) coordinate plane.

void
setLocation(double x,
           double y)

Sets the location of this point to the specified double coordinates.

void
setLocation(int x,
           int y)

Changes the point to have the specified location.

void
setLocation(Point p)

Sets the location of the point to the specified location.

String
toString()

Returns a string representation of this point and its location
 in the (x,y) coordinate space.

void
translate(int dx,
         int dy)

Translates this point, at location (x,y),
 by dx along the x axis and dy
 along the y axis so that it now represents the point
 (x+dx,y+dy).

Methods inherited from class java.awt.geom.Point2D

clone, distance, distance, distance, distanceSq, distanceSq, distanceSq, hashCode, setLocation

Methods inherited from class java.lang.Object

finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

x

public int x

The X coordinate of this Point.
 If no X coordinate is set it will default to 0.

Since:

1.0

See Also:

getLocation(),
move(int, int)

y

public int y

The Y coordinate of this Point.
 If no Y coordinate is set it will default to 0.

Since:

1.0

See Also:

getLocation(),
move(int, int)

Constructor Detail

Point

public Point()

Constructs and initializes a point at the origin
 (0, 0) of the coordinate space.

Since:

1.1

Point

public Point(Point p)

Constructs and initializes a point with the same location as
 the specified Point object.

Parameters:

p - a point

Since:

1.1

Point

public Point(int x,
     int y)

Constructs and initializes a point at the specified
 (x,y) location in the coordinate space.

Parameters:

x - the X coordinate of the newly constructed Point

y - the Y coordinate of the newly constructed Point

Since:

1.0

Method Detail

getX

public double getX()

Returns the X coordinate of this Point2D in
 double precision.

Specified by:

getX in class Point2D

Returns:

the X coordinate of this Point2D.

Since:

1.2

getY

public double getY()

Returns the Y coordinate of this Point2D in
 double precision.

Specified by:

getY in class Point2D

Returns:

the Y coordinate of this Point2D.

Since:

1.2

getLocation

public Point getLocation()

Returns the location of this point.
 This method is included for completeness, to parallel the
 getLocation method of Component.

Returns:

a copy of this point, at the same location

Since:

1.1

See Also:

Component.getLocation(),
setLocation(java.awt.Point),
setLocation(int, int)

setLocation

public void setLocation(Point p)

Sets the location of the point to the specified location.
 This method is included for completeness, to parallel the
 setLocation method of Component.

Parameters:

p - a point, the new location for this point

Since:

1.1

See Also:

Component.setLocation(java.awt.Point),
getLocation()

setLocation

public void setLocation(int x,
               int y)

Changes the point to have the specified location.

 This method is included for completeness, to parallel the
 setLocation method of Component.
 Its behavior is identical with move(int, int).

Parameters:

x - the X coordinate of the new location

y - the Y coordinate of the new location

Since:

1.1

See Also:

Component.setLocation(int, int),
getLocation(),
move(int, int)

setLocation

public void setLocation(double x,
               double y)

Sets the location of this point to the specified double coordinates.
 The double values will be rounded to integer values.
 Any number smaller than Integer.MIN_VALUE
 will be reset to MIN_VALUE, and any number
 larger than Integer.MAX_VALUE will be
 reset to MAX_VALUE.

Specified by:

setLocation in class Point2D

Parameters:

x - the X coordinate of the new location

y - the Y coordinate of the new location

See Also:

getLocation()

move

public void move(int x,
        int y)

Moves this point to the specified location in the
 (x,y) coordinate plane. This method
 is identical with setLocation(int, int).

Parameters:

x - the X coordinate of the new location

y - the Y coordinate of the new location

See Also:

Component.setLocation(int, int)

translate

public void translate(int dx,
             int dy)

Translates this point, at location (x,y),
 by dx along the x axis and dy
 along the y axis so that it now represents the point
 (x+dx,y+dy).

Parameters:

dx - the distance to move this point
                            along the X axis

dy - the distance to move this point
                            along the Y axis

equals

public boolean equals(Object obj)

Determines whether or not two points are equal. Two instances of
 Point2D are equal if the values of their
 x and y member fields, representing
 their position in the coordinate space, are the same.

Overrides:

equals in class Point2D

Parameters:

obj - an object to be compared with this Point2D

Returns:

true if the object to be compared is
         an instance of Point2D and has
         the same values; false otherwise.

See Also:

Object.hashCode(),
HashMap

toString

public String toString()

Returns a string representation of this point and its location
 in the (x,y) coordinate space. This method is
 intended to be used only for debugging purposes, and the content
 and format of the returned string may vary between implementations.
 The returned string may be empty but may not be null.

Overrides:

toString in class Object

Returns:

a string representation of this point

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
<!doctype html>

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <title>Server Error</title>
    <meta name="description" content="Mozilla's Localization Platform">
    <meta name="author" content="Mozilla">
    <meta name="color-scheme" content="only light">

Teams

Projects

Contributors

Machinery

Oops!

Something is wrong. We're going to fix it soon.