Input: <p > Selects 4 pairs of points . Each point in the pair represents an end point in a line segment which is tangent to both ellipseA and ellipseB . Both ellipses are assumed to not intersect each other . If a fatal error occurs the function will return false . However it can return true and did not converge . To check for convergence call { @link #isConverged () } . < / p > [CODESPLIT] public boolean process ( EllipseRotated_F64 ellipseA , EllipseRotated_F64 ellipseB , Point2D_F64 tangentA0 , Point2D_F64 tangentA1 , Point2D_F64 tangentA2 , Point2D_F64 tangentA3 , Point2D_F64 tangentB0 , Point2D_F64 tangentB1 , Point2D_F64 tangentB2 , Point2D_F64 tangentB3 ) { converged = false ; // initialize by picking an arbitrary point on A and then finding the points on B in which // a line is tangent to B and passes through the point on A if ( ! initialize ( ellipseA , ellipseB , tangentA0 , tangentA1 , tangentA2 , tangentA3 , tangentB0 , tangentB1 , tangentB2 , tangentB3 ) ) return false ; // update the location of each point until it converges or the maximum number of iterations has been exceeded int iteration = 0 ; for ( ; iteration < maxIterations ; iteration ++ ) { boolean allGood = false ; sumDifference = 0 ; if ( ! selectTangent ( tangentA0 , tangentB0 , ellipseB , tangentB0 , false ) ) return false ; if ( ! selectTangent ( tangentA1 , tangentB1 , ellipseB , tangentB1 , true ) ) return false ; if ( ! selectTangent ( tangentA2 , tangentB2 , ellipseB , tangentB2 , true ) ) return false ; if ( ! selectTangent ( tangentA3 , tangentB3 , ellipseB , tangentB3 , false ) ) return false ; if ( Math . sqrt ( sumDifference ) / 4.0 <= convergenceTol ) { allGood = true ; } sumDifference = 0 ; if ( ! selectTangent ( tangentB0 , tangentA0 , ellipseA , tangentA0 , false ) ) return false ; if ( ! selectTangent ( tangentB1 , tangentA1 , ellipseA , tangentA1 , true ) ) return false ; if ( ! selectTangent ( tangentB2 , tangentA2 , ellipseA , tangentA2 , true ) ) return false ; if ( ! selectTangent ( tangentB3 , tangentA3 , ellipseA , tangentA3 , false ) ) return false ; if ( allGood && Math . sqrt ( sumDifference ) / 4.0 <= convergenceTol ) { break ; } } converged = iteration < maxIterations ; return true ; }


Input: Select the initial tangent points on the ellipses . This is done by : [CODESPLIT] boolean initialize ( EllipseRotated_F64 ellipseA , EllipseRotated_F64 ellipseB , Point2D_F64 tangentA0 , Point2D_F64 tangentA1 , Point2D_F64 tangentA2 , Point2D_F64 tangentA3 , Point2D_F64 tangentB0 , Point2D_F64 tangentB1 , Point2D_F64 tangentB2 , Point2D_F64 tangentB3 ) { centerLine . set ( ellipseA . center , ellipseB . center ) ; UtilLine2D_F64 . convert ( centerLine , lineGeneral ) ; Intersection2D_F64 . intersection ( lineGeneral , ellipseA , temp0 , temp1 , - 1 ) ; if ( temp0 . distance2 ( ellipseB . center ) < temp1 . distance2 ( ellipseB . center ) ) { tangentA0 . set ( temp0 ) ; } else { tangentA0 . set ( temp1 ) ; } // Two seed points for B.  This points will be on two different sides of center line if ( ! tangentLines ( tangentA0 , ellipseB , tangentB0 , tangentB1 ) ) return false ; // Find initial seed of 4 points on ellipse A.  Careful which pairs of points cross or // don't cross the center line if ( ! selectTangent ( tangentB0 , tangentA0 , ellipseA , tangentA0 , false ) ) return false ; if ( ! selectTangent ( tangentB0 , tangentA0 , ellipseA , tangentA1 , true ) ) return false ; if ( ! selectTangent ( tangentB1 , tangentA0 , ellipseA , tangentA2 , true ) ) return false ; if ( ! selectTangent ( tangentB1 , tangentA0 , ellipseA , tangentA3 , false ) ) return false ; // not all of the B's have been initialized.  That's ok.  It will just have a large error // the first iteration return true ; }


Input: Selects a tangent point on the ellipse which is closest to the original source point of A . [CODESPLIT] boolean selectTangent ( Point2D_F64 a , Point2D_F64 previousTangent , EllipseRotated_F64 ellipse , Point2D_F64 tangent , boolean cross ) { if ( ! tangentLines ( a , ellipse , temp0 , temp1 ) ) return false ; tempLine . a = a ; tempLine . b = temp0 ; boolean crossed0 = Intersection2D_F64 . intersection ( centerLine , tempLine , junk ) != null ; tempLine . b = temp1 ; boolean crossed1 = Intersection2D_F64 . intersection ( centerLine , tempLine , junk ) != null ; if ( crossed0 == crossed1 ) throw new RuntimeException ( "Well this didn't work" ) ; if ( cross == crossed0 ) { sumDifference += previousTangent . distance2 ( temp0 ) ; tangent . set ( temp0 ) ; } else { sumDifference += previousTangent . distance2 ( temp1 ) ; tangent . set ( temp1 ) ; } return true ; }


Input: Makes sure x0 y0 is the lower extent and x1 y1 is the upper extent [CODESPLIT] public void enforceExtents ( ) { if ( x1 < x0 ) { int tmp = x1 ; x1 = x0 ; x0 = tmp ; } if ( y1 < y0 ) { int tmp = y1 ; y1 = y0 ; y0 = tmp ; } }


Input: <p > Returns the Euclidean distance squared from this to a . No floating point operations are used . < / p > [CODESPLIT] public int distance2 ( Point2D_I32 a ) { int dx = x - a . x ; int dy = y - a . y ; return dx * dx + dy * dy ; }


Input: Finds the best fit matrix in SO ( 3 ) for the input matrix . [CODESPLIT] public static void bestFit ( DMatrixRMaj A ) { SingularValueDecomposition_F64 < DMatrixRMaj > svd = DecompositionFactory_DDRM . svd ( true , true , true ) ; if ( ! svd . decompose ( A ) ) throw new RuntimeException ( "SVD Failed" ) ; CommonOps_DDRM . multTransB ( svd . getU ( null , false ) , svd . getV ( null , false ) , A ) ; // determinant should be +1 double det = CommonOps_DDRM . det ( A ) ; if ( det < 0 ) CommonOps_DDRM . scale ( - 1 , A ) ; }


Input: Used to retrieve the corners of the box . [CODESPLIT] public Point3D_F64 getCorner ( int index , Point3D_F64 corner ) { if ( corner == null ) corner = new Point3D_F64 ( ) ; corner . set ( p ) ; if ( ( index & 0x01 ) != 0 ) { corner . x += lengthX ; } if ( ( index & 0x02 ) != 0 ) { corner . y += lengthY ; } if ( ( index & 0x04 ) != 0 ) { corner . z += lengthZ ; } return corner ; }


Input: Distance of the closest point between two lines . Parallel lines are correctly handled . [CODESPLIT] public static double distance ( LineParametric3D_F64 l0 , LineParametric3D_F64 l1 ) { double x = l0 . p . x - l1 . p . x ; double y = l0 . p . y - l1 . p . y ; double z = l0 . p . z - l1 . p . z ; // this solution is from: http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline3d/ double dv01v1 = MiscOps . dot ( x , y , z , l1 . slope ) ; double dv1v0 = MiscOps . dot ( l1 . slope , l0 . slope ) ; double dv1v1 = MiscOps . dot ( l1 . slope , l1 . slope ) ; double bottom = MiscOps . dot ( l0 . slope , l0 . slope ) * dv1v1 - dv1v0 * dv1v0 ; double t0 ; if ( bottom == 0 ) { // handle parallel lines t0 = 0 ; } else { t0 = ( dv01v1 * dv1v0 - MiscOps . dot ( x , y , z , l0 . slope ) * dv1v1 ) / bottom ; } // ( d1343 + mua d4321 ) / d4343 double t1 = ( dv01v1 + t0 * dv1v0 ) / dv1v1 ; double dx = ( l0 . p . x + t0 * l0 . slope . x ) - ( l1 . p . x + t1 * l1 . slope . x ) ; double dy = ( l0 . p . y + t0 * l0 . slope . y ) - ( l1 . p . y + t1 * l1 . slope . y ) ; double dz = ( l0 . p . z + t0 * l0 . slope . z ) - ( l1 . p . z + t1 * l1 . slope . z ) ; // round off error can make distanceSq go negative when it is very close to zero double distanceSq = dx * dx + dy * dy + dz * dz ; if ( distanceSq < 0 ) return 0 ; else return Math . sqrt ( distanceSq ) ; }


Input: Distance from the point to the closest point on the line . [CODESPLIT] public static double distance ( LineParametric3D_F64 l , Point3D_F64 p ) { double x = l . p . x - p . x ; double y = l . p . y - p . y ; double z = l . p . z - p . z ; double cc = x * x + y * y + z * z ; // could avoid a square root here by computing b*b directly // however that is most likely more prone to numerical overflow since the numerator will need to be squared // before division can reduce its "power" double b = MiscOps . dot ( x , y , z , l . slope ) / l . slope . norm ( ) ; double distanceSq = cc - b * b ; // round off error can make distanceSq go negative when it is very close to zero if ( distanceSq < 0 ) { return 0 ; } else { return Math . sqrt ( distanceSq ) ; } }


Input: Distance from the point to the closest point on the line segment . [CODESPLIT] public static double distance ( LineSegment3D_F64 l , Point3D_F64 p ) { double dx = p . x - l . a . x ; double dy = p . y - l . a . y ; double dz = p . z - l . a . z ; double cc = dx * dx + dy * dy + dz * dz ; double slope_x = l . b . x - l . a . x ; double slope_y = l . b . y - l . a . y ; double slope_z = l . b . z - l . a . z ; double n = ( double ) Math . sqrt ( slope_x * slope_x + slope_y * slope_y + slope_z * slope_z ) ; double d = ( slope_x * dx + slope_y * dy + slope_z * dz ) / n ; // check end points if ( d <= 0 ) return p . distance ( l . a ) ; else if ( d >= n ) return p . distance ( l . b ) ; double distanceSq = cc - d * d ; // round off error can make distanceSq go negative when it is very close to zero if ( distanceSq < 0 ) { return 0 ; } else { return Math . sqrt ( distanceSq ) ; } }


Input: Distance between a plane and a point . A signed distance is returned where a positive value is returned if the point is on the same side of the plane as the normal and the opposite if it s on the other . [CODESPLIT] public static double distance ( PlaneGeneral3D_F64 plane , Point3D_F64 point ) { double top = plane . A * point . x + plane . B * point . y + plane . C * point . z - plane . D ; return top / Math . sqrt ( plane . A * plane . A + plane . B * plane . B + plane . C * plane . C ) ; }


Input: Returns the signed distance a point is from the sphere s surface . If the point is outside of the sphere it s distance will be positive . If it is inside it will be negative . <p > < / p > distance = ||sphere . center - point|| - r [CODESPLIT] public static double distance ( Sphere3D_F64 sphere , Point3D_F64 point ) { double r = point . distance ( sphere . center ) ; return r - sphere . radius ; }


Input: Returns the signed distance a point is from the cylinder s surface . If the point is outside of the cylinder it s distance will be positive . If it is inside it will be negative . [CODESPLIT] public static double distance ( Cylinder3D_F64 cylinder , Point3D_F64 point ) { double r = Distance3D_F64 . distance ( cylinder . line , point ) ; return r - cylinder . radius ; }


Input: Signed distance from a 3D point to 3D triangle . The sign indicates which side of the triangle the point is on . See { @link georegression . metric . alg . DistancePointTriangle3D_F64 } for the details . [CODESPLIT] public static double distance ( Triangle3D_F64 triangle , Point3D_F64 point ) { DistancePointTriangle3D_F64 alg = new DistancePointTriangle3D_F64 ( ) ; alg . setTriangle ( triangle . v0 , triangle . v1 , triangle . v2 ) ; Point3D_F64 cp = new Point3D_F64 ( ) ; alg . closestPoint ( point , cp ) ; double d = point . distance ( cp ) ; return alg . sign ( point ) * d ; }


Input: where = p + t * slope . [CODESPLIT] public void setPointOnLine ( double t , Point3D_F64 where ) { where . x = p . x + t * slope . x ; where . y = p . y + t * slope . y ; where . z = p . z + t * slope . z ; }


Input: Returns a point along the line . See parametric equation in class description . [CODESPLIT] public Point3D_F64 getPointOnLine ( double t ) { return new Point3D_F64 ( slope . x * t + p . x , slope . y * t + p . y , slope . z * t + p . z ) ; }


Input: <p > Returns the Euclidean distance of the closest point on the line from a point . < / p > [CODESPLIT] public static double distance ( LineParametric2D_F64 line , Point2D_F64 p ) { return Math . sqrt ( distanceSq ( line , p ) ) ; }


Input: <p > Returns the Euclidean distance of the closest point on the line from a point . < / p > [CODESPLIT] public static double distance ( LineParametric2D_F64 line , double x , double y ) { return Math . sqrt ( distanceSq ( line , x , y ) ) ; }


Input: <p > Returns the Euclidean distance squared of the closest point on the line from a point . < / p > [CODESPLIT] public static double distanceSq ( LineParametric2D_F64 line , Point2D_F64 p ) { double scale = Math . max ( Math . abs ( line . slope . x ) , Math . abs ( line . slope . y ) ) ; double t = ClosestPoint2D_F64 . closestPointT ( line , p , scale ) ; double a = ( line . slope . x / scale ) * t + line . p . x ; double b = ( line . slope . y / scale ) * t + line . p . y ; double dx = p . x - a ; double dy = p . y - b ; return dx * dx + dy * dy ; }


Input: <p > Returns the Euclidean distance of the closest point on a line segment to the specified point . < / p > [CODESPLIT] public static double distance ( LineSegment2D_F64 line , Point2D_F64 p ) { return Math . sqrt ( distanceSq ( line , p ) ) ; }


Input: <p > Returns the Euclidean distance of the closest point on a line segment to the specified point . < / p > [CODESPLIT] public static double distance ( LineSegment2D_F64 line , double x , double y ) { return Math . sqrt ( distanceSq ( line , x , y ) ) ; }


Input: <p > Returns the Euclidean distance squared of the closest point on a line segment to the specified point . < / p > [CODESPLIT] public static double distanceSq ( LineSegment2D_F64 line , Point2D_F64 p ) { double a = line . b . x - line . a . x ; double b = line . b . y - line . a . y ; double t = a * ( p . x - line . a . x ) + b * ( p . y - line . a . y ) ; t /= ( a * a + b * b ) ; // if the point of intersection is past the end points return the distance // from the closest end point if ( t < 0 ) { return UtilPoint2D_F64 . distanceSq ( line . a . x , line . a . y , p . x , p . y ) ; } else if ( t > 1.0 ) return UtilPoint2D_F64 . distanceSq ( line . b . x , line . b . y , p . x , p . y ) ; // return the distance of the closest point on the line return UtilPoint2D_F64 . distanceSq ( line . a . x + t * a , line . a . y + t * b , p . x , p . y ) ; }


Input: Finds the distance between the two line segments [CODESPLIT] public static double distance ( LineSegment2D_F64 segmentA , LineSegment2D_F64 segmentB ) { return Math . sqrt ( distanceSq ( segmentA , segmentB ) ) ; }


Input: Finds the distance squared between the two line segments [CODESPLIT] public static double distanceSq ( LineSegment2D_F64 segmentA , LineSegment2D_F64 segmentB ) { // intersection of the two lines relative to A double slopeAX = segmentA . slopeX ( ) ; double slopeAY = segmentA . slopeY ( ) ; double slopeBX = segmentB . slopeX ( ) ; double slopeBY = segmentB . slopeY ( ) ; double ta = slopeBX * ( segmentA . a . y - segmentB . a . y ) - slopeBY * ( segmentA . a . x - segmentB . a . x ) ; double bottom = slopeBY * slopeAX - slopeAY * slopeBX ; // see they intersect if ( bottom != 0 ) { // see if the intersection is inside of lineA ta /= bottom ; if ( ta >= 0 && ta <= 1.0 ) { // see if the intersection is inside of lineB double tb = slopeAX * ( segmentB . a . y - segmentA . a . y ) - slopeAY * ( segmentB . a . x - segmentA . a . x ) ; tb /= slopeAY * slopeBX - slopeBY * slopeAX ; if ( tb >= 0 && tb <= 1.0 ) return 0 ; } } double closest = Double . MAX_VALUE ; closest = Math . min ( closest , distanceSq ( segmentA , segmentB . a ) ) ; closest = Math . min ( closest , distanceSq ( segmentA , segmentB . b ) ) ; closest = Math . min ( closest , distanceSq ( segmentB , segmentA . a ) ) ; closest = Math . min ( closest , distanceSq ( segmentB , segmentA . b ) ) ; return closest ; }


Input: Returns the Euclidean distance of the closest point on the quadrilateral to the provided point . [CODESPLIT] public static double distance ( Quadrilateral_F64 quad , Point2D_F64 p ) { return Math . sqrt ( distanceSq ( quad , p ) ) ; }


Input: Returns the Euclidean distance squared of the closest point on the quadrilateral to the provided point . [CODESPLIT] public static double distanceSq ( Quadrilateral_F64 quad , Point2D_F64 p ) { LineSegment2D_F64 seg = LineSegment2D_F64 . wrap ( quad . a , quad . b ) ; double a = distanceSq ( seg , p ) ; seg . a = quad . b ; seg . b = quad . c ; a = Math . min ( a , distanceSq ( seg , p ) ) ; seg . a = quad . c ; seg . b = quad . d ; a = Math . min ( a , distanceSq ( seg , p ) ) ; seg . a = quad . d ; seg . b = quad . a ; return Math . min ( a , distanceSq ( seg , p ) ) ; }


Input: Returns the Euclidean distance of the closest point on the Polygon to the provided point . [CODESPLIT] public static double distance ( Polygon2D_F64 poly , Point2D_F64 p ) { return Math . sqrt ( distanceSq ( poly , p , null ) ) ; }


Input: Returns the Euclidean distance squared of the closest point on the Polygon to the provided point . [CODESPLIT] public static double distanceSq ( Polygon2D_F64 poly , Point2D_F64 p , LineSegment2D_F64 storage ) { if ( storage == null ) storage = LineSegment2D_F64 . wrap ( null , null ) ; double minimum = Double . MAX_VALUE ; for ( int i = 0 ; i < poly . size ( ) ; i ++ ) { int j = ( i + 1 ) % poly . size ( ) ; storage . a = poly . vertexes . data [ i ] ; storage . b = poly . vertexes . data [ j ] ; double d = distanceSq ( storage , p ) ; if ( d < minimum ) minimum = d ; } return minimum ; }


Input: <p > Returns the Euclidean distance of the closest point on the line to the specified point . < / p > [CODESPLIT] public static double distance ( LineGeneral2D_F64 line , Point2D_F64 p ) { return Math . abs ( line . A * p . x + line . B * p . y + line . C ) / Math . sqrt ( line . A * line . A + line . B * line . B ) ; }


Input: <p > Returns the signed Euclidean distance of the closest point on the line to the specified point . The line is assumed be normalized . See { @link LineGeneral2D_F64 } for details on normalization . < / p > [CODESPLIT] public static double distanceNorm ( LineGeneral2D_F64 line , Point2D_F64 p ) { return Math . abs ( line . A * p . x + line . B * p . y + line . C ) ; }


Input: Returns the distance of the closest point on the line from the origin [CODESPLIT] public static double distanceOrigin ( LineParametric2D_F64 line ) { double top = line . slope . y * line . p . x - line . slope . x * line . p . y ; return Math . abs ( top ) / line . slope . norm ( ) ; }


Input: Euclidean distance of closest point on ellipse to point p . [CODESPLIT] public static double distance ( EllipseRotated_F64 ellipse , Point2D_F64 p ) { return Math . sqrt ( distance2 ( ellipse , p ) ) ; }


Input: Euclidean distance squared of closest point on ellipse to point p . [CODESPLIT] public static double distance2 ( EllipseRotated_F64 ellipse , Point2D_F64 p ) { // put point into ellipse's reference frame double cphi = Math . cos ( ellipse . phi ) ; double sphi = Math . sin ( ellipse . phi ) ; double xc = p . x - ellipse . center . x ; double yc = p . y - ellipse . center . y ; double r = Math . sqrt ( xc * xc + yc * yc ) ; double x = cphi * xc + sphi * yc ; double y = - sphi * xc + cphi * yc ; double ct = x / r ; double st = y / r ; x = ellipse . center . x + ellipse . a * ct * cphi - ellipse . b * st * sphi ; y = ellipse . center . y + ellipse . a * ct * sphi + ellipse . b * st * cphi ; return p . distance2 ( x , y ) ; }


Input: Adds the next transform in the sequence . [CODESPLIT] public void addTransform ( boolean forward , T tran ) { path . add ( new Node < T > ( tran , forward ) ) ; }


Input: <p > Finds the closest point on line to the specified point . < / p > [CODESPLIT] public static Point2D_F64 closestPoint ( LineGeneral2D_F64 line , Point2D_F64 p , Point2D_F64 output ) { if ( output == null ) output = new Point2D_F64 ( ) ; double AA = line . A * line . A ; double AB = line . A * line . B ; double BB = line . B * line . B ; output . y = AA * p . y - AB * p . x - line . B * line . C ; output . y /= AA + BB ; output . x = BB * p . x - AB * p . y - line . A * line . C ; output . x /= AA + BB ; return output ; }


Input: <p > Finds the closest point on line to the specified point . < / p > [CODESPLIT] public static Point2D_F64 closestPoint ( LineParametric2D_F64 line , Point2D_F64 p , Point2D_F64 output ) { if ( output == null ) output = new Point2D_F64 ( ) ; double t = closestPointT ( line , p ) ; output . x = line . p . x + line . slope . x * t ; output . y = line . p . y + line . slope . y * t ; return output ; }


Input: <p > Computes the closest point along the line as a function of t : <br > [ x y ] = [ x_0 y_0 ] + t· [ slopeX slopeY ] < / p > [CODESPLIT] public static double closestPointT ( LineParametric2D_F64 line , Point2D_F64 p ) { double t = line . slope . x * ( p . x - line . p . x ) + line . slope . y * ( p . y - line . p . y ) ; t /= line . slope . x * line . slope . x + line . slope . y * line . slope . y ; return t ; }


Input: <p > Computes the closest point along the line as a function of t : <br > [ x y ] = [ x_0 y_0 ] + t· [ slopeX slopeY ] < / p > [CODESPLIT] public static double closestPointT ( LineParametric2D_F64 line , double x , double y , double scale ) { double sx = line . slope . x / scale ; double sy = line . slope . y / scale ; double t = sx * ( x - line . p . x ) + sy * ( y - line . p . y ) ; t /= sx * sx + sy * sy ; return t ; }


Input: Finds the closest point on the line segment to the provided point p . [CODESPLIT] public static Point2D_F64 closestPoint ( LineSegment2D_F64 line , Point2D_F64 p , Point2D_F64 output ) { if ( output == null ) output = new Point2D_F64 ( ) ; double slopeX = line . b . x - line . a . x ; double slopeY = line . b . y - line . a . y ; double t = slopeX * ( p . x - line . a . x ) + slopeY * ( p . y - line . a . y ) ; t /= slopeX * slopeX + slopeY * slopeY ; if ( t < 0 ) t = 0 ; else if ( t > 1 ) t = 1 ; output . x = line . a . x + slopeX * t ; output . y = line . a . y + slopeY * t ; return output ; }


Input: Computes the closest point on an ellipse to the provided point . If there are multiple solutions then one is arbitrarily chosen . [CODESPLIT] public static Point2D_F64 closestPoint ( EllipseRotated_F64 ellipse , Point2D_F64 p ) { ClosestPointEllipseAngle_F64 alg = new ClosestPointEllipseAngle_F64 ( GrlConstants . TEST_F64 , 30 ) ; alg . setEllipse ( ellipse ) ; alg . process ( p ) ; return alg . getClosest ( ) ; }


Input: Fits the polynomial curve to the data . [CODESPLIT] public boolean process ( double [ ] data , int offset , int length , PolynomialCurve_F64 output ) { int N = length / 2 ; int numCoefs = output . size ( ) ; A . reshape ( N , numCoefs ) ; b . reshape ( N , 1 ) ; x . reshape ( numCoefs , 1 ) ; int end = offset + length ; for ( int i = offset , idxA = 0 ; i < end ; i += 2 ) { double x = data [ i ] ; double y = data [ i + 1 ] ; double pow = 1.0 ; for ( int j = 0 ; j < numCoefs ; j ++ ) { A . data [ idxA ++ ] = pow ; pow *= x ; } b . data [ i / 2 ] = y ; } if ( ! solver . setA ( A ) ) return false ; solver . solve ( b , x ) ; for ( int i = 0 ; i < numCoefs ; i ++ ) { output . set ( i , x . data [ i ] ) ; } return true ; }


Input: Fits the conic to the points . Strongly recommended that you transform the points such that they have zero mean and a standard deviation along x and y axis independently . [CODESPLIT] @ Override public boolean process ( List < Point2D_F64 > points , ConicGeneral_F64 output ) { final int N = points . size ( ) ; if ( N < 3 ) throw new IllegalArgumentException ( "At least 3 points required" ) ; CommonOps_DDF6 . fill ( ATA , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double x = p . x ; double y = p . y ; double xx = x * x ; double xxx = xx * x ; double yy = y * y ; double yyy = yy * y ; ATA . a11 += xx * xx ; ATA . a12 += xxx * y ; ATA . a13 += xx * yy ; ATA . a14 += xxx ; ATA . a15 += xx * y ; ATA . a16 += xx ; ATA . a22 += xx * yy ; ATA . a23 += x * yyy ; //			ATA.a24 += xx*y; ATA . a25 += x * yy ; ATA . a26 += x * y ; ATA . a33 += yyy * y ; //			ATA.a34 += x*yy; ATA . a35 += yyy ; ATA . a36 += yy ; //			ATA.a44 += xx; ATA . a45 += x * y ; ATA . a46 += x ; //			ATA.a55 += yy; ATA . a56 += y ; } ATA . a21 = ATA . a12 ; ATA . a24 = ATA . a15 ; ATA . a31 = ATA . a13 ; ATA . a32 = ATA . a23 ; ATA . a34 = ATA . a25 ; ATA . a41 = ATA . a14 ; ATA . a42 = ATA . a24 ; ATA . a43 = ATA . a34 ; ATA . a44 = ATA . a16 ; ATA . a51 = ATA . a15 ; ATA . a52 = ATA . a25 ; ATA . a53 = ATA . a35 ; ATA . a54 = ATA . a45 ; ATA . a55 = ATA . a36 ; ATA . a61 = ATA . a16 ; ATA . a62 = ATA . a26 ; ATA . a63 = ATA . a36 ; ATA . a64 = ATA . a56 ; ATA . a65 = ATA . a56 ; ATA . a66 = N ; ConvertDMatrixStruct . convert ( ATA , tmp ) ; if ( ! solver . process ( tmp , 1 , nullspace ) ) return false ; output . A = nullspace . data [ 0 ] ; output . B = nullspace . data [ 1 ] ; output . C = nullspace . data [ 2 ] ; output . D = nullspace . data [ 3 ] ; output . E = nullspace . data [ 4 ] ; output . F = nullspace . data [ 5 ] ; return true ; }


Input: Creates a random vector where each axis is selected from a uniform distribution . [CODESPLIT] public static Vector3D_F64 createRandom ( double min , double max , Random rand ) { double range = max - min ; Vector3D_F64 a = new Vector3D_F64 ( ) ; a . x = range * rand . nextDouble ( ) + min ; a . y = range * rand . nextDouble ( ) + min ; a . z = range * rand . nextDouble ( ) + min ; return a ; }


Input: Selects a vector which will be perpendicular . [CODESPLIT] public static Vector3D_F64 perpendicularCanonical ( Vector3D_F64 A , Vector3D_F64 output ) { if ( output == null ) output = new Vector3D_F64 ( ) ; // normalize for scaling double scale = Math . abs ( A . x ) + Math . abs ( A . y ) + Math . abs ( A . z ) ; if ( scale == 0 ) { output . set ( 0 , 0 , 0 ) ; } else { double x = A . x / scale ; double y = A . y / scale ; double z = A . z / scale ; // For numerical stability ensure that the largest variable is swapped if ( Math . abs ( x ) > Math . abs ( y ) ) { output . set ( z , 0 , - x ) ; } else { output . set ( 0 , z , - y ) ; } } return output ; }


Input: Checks to see if the two vectors are identical to within tolerance . Each axis is checked individually . [CODESPLIT] public static boolean isIdentical ( Vector3D_F64 a , Vector3D_F64 b , double tol ) { if ( Math . abs ( a . x - b . x ) > tol ) return false ; if ( Math . abs ( a . y - b . y ) > tol ) return false ; return Math . abs ( a . z - b . z ) <= tol ; }


Input: Rescales the vector such that its normal is equal to one . [CODESPLIT] public static void normalize ( Vector3D_F64 v ) { double a = v . norm ( ) ; v . x /= a ; v . y /= a ; v . z /= a ; }


Input: Creates a matrix from the set of column vectors . Each vector is a column in the new matrix . [CODESPLIT] public static DMatrixRMaj createMatrix ( DMatrixRMaj R , Vector3D_F64 ... v ) { if ( R == null ) { R = new DMatrixRMaj ( 3 , v . length ) ; } for ( int i = 0 ; i < v . length ; i ++ ) { R . set ( 0 , i , v [ i ] . x ) ; R . set ( 1 , i , v [ i ] . y ) ; R . set ( 2 , i , v [ i ] . z ) ; } return R ; }


Input: Converts matrices into vectors . All matrices must be vectors with 3 elements . [CODESPLIT] public static Vector3D_F64 convert ( DMatrixRMaj m ) { Vector3D_F64 v = new Vector3D_F64 ( ) ; v . x = ( double ) m . data [ 0 ] ; v . y = ( double ) m . data [ 1 ] ; v . z = ( double ) m . data [ 2 ] ; return v ; }


Input: Returns the acute angle between the two vectors . Computed using the dot product . [CODESPLIT] public static double acute ( GeoTuple3D_F64 a , GeoTuple3D_F64 b ) { double dot = a . x * b . x + a . y * b . y + a . z * b . z ; double value = dot / ( a . norm ( ) * b . norm ( ) ) ; if ( value > 1.0 ) value = 1.0 ; else if ( value < - 1.0 ) value = - 1.0 ; return Math . acos ( value ) ; }


Input: <p > In - place addition< / p > [CODESPLIT] public void plusIP ( GeoTuple3D_F64 a ) { x += a . x ; y += a . y ; z += a . z ; }


Input: <p > Addition< / p > [CODESPLIT] public T plus ( GeoTuple3D_F64 a ) { T ret = createNewInstance ( ) ; ret . x = x + a . x ; ret . y = y + a . y ; ret . z = z + a . z ; return ret ; }


Input: Scalar multiplication [CODESPLIT] public T times ( double scalar ) { T ret = createNewInstance ( ) ; ret . x = x * scalar ; ret . y = y * scalar ; ret . z = z * scalar ; return ret ; }


Input: Checks to see if the two rectangles intersect each other [CODESPLIT] public static boolean intersects ( Rectangle2D_I32 a , Rectangle2D_I32 b ) { return ( a . x0 < b . x1 && a . x1 > b . x0 && a . y0 < b . y1 && a . y1 > b . y0 ) ; }


Input: Finds the intersection between two rectangles . If the rectangles don t intersect then false is returned . [CODESPLIT] public static boolean intersection ( Rectangle2D_I32 a , Rectangle2D_I32 b , Rectangle2D_I32 result ) { if ( ! intersects ( a , b ) ) return false ; result . x0 = Math . max ( a . x0 , b . x0 ) ; result . x1 = Math . min ( a . x1 , b . x1 ) ; result . y0 = Math . max ( a . y0 , b . y0 ) ; result . y1 = Math . min ( a . y1 , b . y1 ) ; return true ; }


Input: http : // www . ecse . rpi . edu / Homepages / wrf / Research / Short_Notes / pnpoly . html [CODESPLIT] public static boolean containConvex ( Polygon2D_I32 polygon , Point2D_I32 pt ) { final int N = polygon . size ( ) ; boolean c = false ; for ( int i = 0 , j = N - 1 ; i < N ; j = i ++ ) { Point2D_I32 a = polygon . vertexes . data [ i ] ; Point2D_I32 b = polygon . vertexes . data [ j ] ; if ( ( ( a . y > pt . y ) != ( b . y > pt . y ) ) && ( pt . x < ( b . x - a . x ) * ( pt . y - a . y ) / ( b . y - a . y ) + a . x ) ) c = ! c ; } return c ; }


Input: Checks to see if the point is contained inside the concave polygon . [CODESPLIT] public static boolean containConcave ( Polygon2D_I32 polygon , Point2D_I32 pt ) { final int N = polygon . size ( ) ; int left = 0 ; int right = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { Point2D_I32 a = polygon . vertexes . data [ i ] ; Point2D_I32 b = polygon . vertexes . data [ i + 1 ] ; if ( ( pt . y >= a . y && pt . y < b . y ) || ( pt . y >= b . y && pt . y < a . y ) ) { // location of line segment along x-axis at y = pt.y double x = b . y == a . y ? pt . x : ( pt . y - a . y ) * ( b . x - a . x ) / ( double ) ( b . y - a . y ) + a . x ; if ( x <= pt . x ) left ++ ; else if ( x > pt . x ) right ++ ; } } Point2D_I32 a = polygon . vertexes . data [ N - 1 ] ; Point2D_I32 b = polygon . vertexes . data [ 0 ] ; if ( ( pt . y >= a . y && pt . y < b . y ) || ( pt . y >= b . y && pt . y < a . y ) ) { // location of line segment along x-axis at y = pt.y double x = b . y == a . y ? pt . x : ( pt . y - pt . y ) * ( b . x - a . x ) / ( double ) ( b . y - a . y ) + a . x ; if ( x <= pt . x ) left ++ ; else if ( x > pt . x ) right ++ ; } return ( left % 2 == 1 && right % 2 == 1 ) ; }


Input: True if the point is contained inside the rectangle [CODESPLIT] public static boolean contains ( RectangleLength2D_I32 a , int x , int y ) { if ( a . getX ( ) <= x && a . getX ( ) + a . getWidth ( ) > x ) { return a . getY ( ) <= y && a . getY ( ) + a . getHeight ( ) > y ; } return false ; }


Input: True if the point is contained inside the rectangle [CODESPLIT] public static boolean contains ( Rectangle2D_I32 a , int x , int y ) { return ( x >= a . x0 && y >= a . y0 && x < a . x1 && y < a . y1 ) ; }


Input: <p > Addition< / p > [CODESPLIT] public T plus ( GeoTuple2D_F64 a ) { T ret = createNewInstance ( ) ; ret . x = x + a . x ; ret . y = y + a . y ; return ret ; }


Input: Euclidean distance from the point [CODESPLIT] public double distance ( double x , double y ) { double dx = x - this . x ; double dy = y - this . y ; return Math . sqrt ( dx * dx + dy * dy ) ; }


Input: Specifies the ellipse which point distance is going to be found from [CODESPLIT] public void setEllipse ( EllipseRotated_F64 ellipse ) { this . ellipse = ellipse ; ce = Math . cos ( ellipse . phi ) ; se = Math . sin ( ellipse . phi ) ; }


Input: Find the closest point on the ellipse to the specified point . To get the solution call { @link #getClosest () } [CODESPLIT] public void process ( Point2D_F64 point ) { // put point into ellipse's coordinate system double xc = point . x - ellipse . center . x ; double yc = point . y - ellipse . center . y ; // double x = ce * xc + se * yc ; double y = - se * xc + ce * yc ; // initial guess for the angle theta = Math . atan2 ( ellipse . a * y , ellipse . b * x ) ; double a2_m_b2 = ellipse . a * ellipse . a - ellipse . b * ellipse . b ; // use Newton's Method to find the solution int i = 0 ; for ( ; i < maxIterations ; i ++ ) { double c = Math . cos ( theta ) ; double s = Math . sin ( theta ) ; double f = a2_m_b2 * c * s - x * ellipse . a * s + y * ellipse . b * c ; if ( Math . abs ( f ) < tol ) break ; double d = a2_m_b2 * ( c * c - s * s ) - x * ellipse . a * c - y * ellipse . b * s ; theta = theta - f / d ; } // compute solution in ellipse coordinate frame x = ellipse . a * ( double ) Math . cos ( theta ) ; y = ellipse . b * ( double ) Math . sin ( theta ) ; // put back into original coordinate system closest . x = ce * x - se * y + ellipse . center . x ; closest . y = se * x + ce * y + ellipse . center . y ; }


Input: Converts the quaternion into a unit quaternion . [CODESPLIT] public void normalize ( ) { double n = Math . sqrt ( w * w + x * x + y * y + z * z ) ; w /= n ; x /= n ; y /= n ; z /= n ; }


Input: Fits the conic to the points . Strongly recommended that you transform the points such that they have zero mean and a standard deviation along x and y axis independently . [CODESPLIT] @ Override public boolean process ( List < Point2D_F64 > points , ConicGeneral_F64 output ) { final int N = points . size ( ) ; if ( N < 3 ) throw new IllegalArgumentException ( "At least 3 points required" ) ; A . reshape ( N , 6 ) ; for ( int i = 0 , index = 0 ; i < N ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double x = p . x ; double y = p . y ; A . data [ index ++ ] = x * x ; A . data [ index ++ ] = x * y ; A . data [ index ++ ] = y * y ; A . data [ index ++ ] = x ; A . data [ index ++ ] = y ; A . data [ index ++ ] = 1 ; } if ( ! solver . process ( A , 1 , nullspace ) ) return false ; output . A = nullspace . data [ 0 ] ; output . B = nullspace . data [ 1 ] ; output . C = nullspace . data [ 2 ] ; output . D = nullspace . data [ 3 ] ; output . E = nullspace . data [ 4 ] ; output . F = nullspace . data [ 5 ] ; return true ; }


Input: Computes the area of an arbitrary triangle from 3 - vertices . [CODESPLIT] public static double triangle ( Point2D_F64 a , Point2D_F64 b , Point2D_F64 c ) { double inner = a . x * ( b . y - c . y ) + b . x * ( c . y - a . y ) + c . x * ( a . y - b . y ) ; return Math . abs ( inner / 2.0 ) ; }


Input: Area of a quadrilateral computed from two triangles . [CODESPLIT] public static double quadrilateral ( Quadrilateral_F64 quad ) { double bx = quad . b . x - quad . a . x ; double by = quad . b . y - quad . a . y ; double cx = quad . c . x - quad . a . x ; double cy = quad . c . y - quad . a . y ; double dx = quad . d . x - quad . a . x ; double dy = quad . d . y - quad . a . y ; if ( ( bx * cy - by * cx >= 0 ) == ( cx * dy - cy * dx >= 0 ) ) { return triangle ( quad . a , quad . b , quad . c ) + triangle ( quad . a , quad . c , quad . d ) ; } else { return triangle ( quad . a , quad . b , quad . d ) + triangle ( quad . b , quad . c , quad . d ) ; } }


Input: Area of a simple polygon . Meaning it can be concave or convex but can t have self intersections [CODESPLIT] public static double polygonSimple ( Polygon2D_F64 poly ) { double total = 0 ; Point2D_F64 v0 = poly . get ( 0 ) ; Point2D_F64 v1 = poly . get ( 1 ) ; for ( int i = 2 ; i < poly . size ( ) ; i ++ ) { Point2D_F64 v2 = poly . get ( i ) ; total += v1 . x * ( v2 . y - v0 . y ) ; v0 = v1 ; v1 = v2 ; } Point2D_F64 v2 = poly . get ( 0 ) ; total += v1 . x * ( v2 . y - v0 . y ) ; v0 = v1 ; v1 = v2 ; v2 = poly . get ( 1 ) ; total += v1 . x * ( v2 . y - v0 . y ) ; return Math . abs ( total / 2.0 ) ; }


Input: Finds the point which has the mean location of all the points in the list . This is also known as the centroid . [CODESPLIT] public static Point2D_F64 mean ( List < Point2D_F64 > list , Point2D_F64 mean ) { if ( mean == null ) mean = new Point2D_F64 ( ) ; double x = 0 ; double y = 0 ; for ( Point2D_F64 p : list ) { x += p . getX ( ) ; y += p . getY ( ) ; } x /= list . size ( ) ; y /= list . size ( ) ; mean . set ( x , y ) ; return mean ; }


Input: Finds the point which has the mean location of all the points in the array . This is also known as the centroid . [CODESPLIT] public static Point2D_F64 mean ( Point2D_F64 [ ] list , int offset , int length , Point2D_F64 mean ) { if ( mean == null ) mean = new Point2D_F64 ( ) ; double x = 0 ; double y = 0 ; for ( int i = 0 ; i < length ; i ++ ) { Point2D_F64 p = list [ offset + i ] ; x += p . getX ( ) ; y += p . getY ( ) ; } x /= length ; y /= length ; mean . set ( x , y ) ; return mean ; }


Input: Computes the mean / average of two points . [CODESPLIT] public static Point2D_F64 mean ( Point2D_F64 a , Point2D_F64 b , Point2D_F64 mean ) { if ( mean == null ) mean = new Point2D_F64 ( ) ; mean . x = ( a . x + b . x ) / 2.0 ; mean . y = ( a . y + b . y ) / 2.0 ; return mean ; }


Input: Finds the minimal volume { @link georegression . struct . shapes . RectangleLength2D_F64 } which contains all the points . [CODESPLIT] public static RectangleLength2D_F64 bounding ( List < Point2D_F64 > points , RectangleLength2D_F64 bounding ) { if ( bounding == null ) bounding = new RectangleLength2D_F64 ( ) ; double minX = Double . MAX_VALUE , maxX = - Double . MAX_VALUE ; double minY = Double . MAX_VALUE , maxY = - Double . MAX_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_F64 p = points . get ( i ) ; if ( p . x < minX ) minX = p . x ; if ( p . x > maxX ) maxX = p . x ; if ( p . y < minY ) minY = p . y ; if ( p . y > maxY ) maxY = p . y ; } bounding . x0 = minX ; bounding . y0 = minY ; bounding . width = maxX - minX ; bounding . height = maxY - minY ; // make sure rounding doesn't cause a point to be out of bounds bounding . width += Math . max ( 0 , ( maxX - ( bounding . x0 + bounding . width ) ) * 10.0 ) ; bounding . height += Math . max ( 0 , ( maxY - ( bounding . y0 + bounding . height ) ) * 10.0 ) ; return bounding ; }


Input: Finds the minimal volume { @link georegression . struct . shapes . RectangleLength2D_F64 } which contains all the points . [CODESPLIT] public static Rectangle2D_F64 bounding ( List < Point2D_F64 > points , Rectangle2D_F64 bounding ) { if ( bounding == null ) bounding = new Rectangle2D_F64 ( ) ; double minX = Double . MAX_VALUE , maxX = - Double . MAX_VALUE ; double minY = Double . MAX_VALUE , maxY = - Double . MAX_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_F64 p = points . get ( i ) ; if ( p . x < minX ) minX = p . x ; if ( p . x > maxX ) maxX = p . x ; if ( p . y < minY ) minY = p . y ; if ( p . y > maxY ) maxY = p . y ; } bounding . set ( minX , minY , maxX , maxY ) ; return bounding ; }


Input: Puts the points into counter - clockwise order around their center . [CODESPLIT] public static List < Point2D_F64 > orderCCW ( List < Point2D_F64 > points ) { Point2D_F64 center = mean ( points , null ) ; double angles [ ] = new double [ points . size ( ) ] ; for ( int i = 0 ; i < angles . length ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double dx = p . x - center . x ; double dy = p . y - center . y ; angles [ i ] = Math . atan2 ( dy , dx ) ; } int order [ ] = new int [ points . size ( ) ] ; QuickSort_F64 sorter = new QuickSort_F64 ( ) ; sorter . sort ( angles , 0 , points . size ( ) , order ) ; List < Point2D_F64 > out = new ArrayList < Point2D_F64 > ( points . size ( ) ) ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { out . add ( points . get ( order [ i ] ) ) ; } return out ; }


Input: Computes the mean and covariance matrix from the set of points . This describes a normal distribution [CODESPLIT] public static void computeNormal ( List < Point2D_F64 > points , Point2D_F64 mean , DMatrix covariance ) { if ( covariance . getNumCols ( ) != 2 || covariance . getNumRows ( ) != 2 ) { if ( covariance instanceof ReshapeMatrix ) { ( ( ReshapeMatrix ) covariance ) . reshape ( 2 , 2 ) ; } else { throw new IllegalArgumentException ( "Must be a 2x2 matrix" ) ; } } mean ( points , mean ) ; double xx = 0 , xy = 0 , yy = 0 ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double dx = p . x - mean . x ; double dy = p . y - mean . y ; xx += dx * dx ; xy += dx * dy ; yy += dy * dy ; } xx /= points . size ( ) ; xy /= points . size ( ) ; yy /= points . size ( ) ; covariance . unsafe_set ( 0 , 0 , xx ) ; covariance . unsafe_set ( 0 , 1 , xy ) ; covariance . unsafe_set ( 1 , 0 , xy ) ; covariance . unsafe_set ( 1 , 1 , yy ) ; }


Input: Randomly generates points from the specified normal distribution [CODESPLIT] public static List < Point2D_F64 > randomNorm ( Point2D_F64 mean , DMatrix covariance , int count , Random rand , @ Nullable List < Point2D_F64 > output ) { if ( output == null ) output = new ArrayList <> ( ) ; // extract values of covariance double cxx = covariance . get ( 0 , 0 ) ; double cxy = covariance . get ( 0 , 1 ) ; double cyy = covariance . get ( 1 , 1 ) ; // perform cholesky decomposition double sxx = Math . sqrt ( cxx ) ; double sxy = cxy / cxx ; double syy = Math . sqrt ( cyy - sxy * sxy ) ; for ( int i = 0 ; i < count ; i ++ ) { Point2D_F64 p = new Point2D_F64 ( ) ; double x = rand . nextGaussian ( ) ; double y = rand . nextGaussian ( ) ; p . x = mean . x + sxx * x + sxy * y ; p . y = mean . y + sxy * x + syy * y ; output . add ( p ) ; } return output ; }


Input: A * x + B * y + C = 0 [CODESPLIT] public void set ( double a , double b , double c ) { this . A = a ; this . B = b ; this . C = c ; }


Input: Ensures that A * A + B * B == 1 [CODESPLIT] public void normalize ( ) { double d = Math . sqrt ( A * A + B * B ) ; A /= d ; B /= d ; C /= d ; }


Input: In - place minus operation . this = a - b . [CODESPLIT] public void minus ( Point2D_F64 a , Point2D_F64 b ) { x = a . x - b . x ; y = a . y - b . y ; }


Input: Finds the minimum area bounding rectangle which is aligned to the x and y axis around the list of points . Note ( x0 y0 ) is inclusive and ( x1 y1 ) is exclusive . [CODESPLIT] public static void bounding ( List < Point2D_I32 > points , Rectangle2D_I32 rectangle ) { rectangle . x0 = Integer . MAX_VALUE ; rectangle . y0 = Integer . MAX_VALUE ; rectangle . x1 = Integer . MIN_VALUE ; rectangle . y1 = Integer . MIN_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_I32 p = points . get ( i ) ; if ( p . x < rectangle . x0 ) rectangle . x0 = p . x ; if ( p . x > rectangle . x1 ) rectangle . x1 = p . x ; if ( p . y < rectangle . y0 ) rectangle . y0 = p . y ; if ( p . y > rectangle . y1 ) rectangle . y1 = p . y ; } rectangle . x1 ++ ; rectangle . y1 ++ ; }


Input: Finds the minimum area bounding rectangle which is aligned to the x and y axis around the polygon . Note ( x0 y0 ) is inclusive and ( x1 y1 ) is exclusive . [CODESPLIT] public static void bounding ( Polygon2D_I32 quad , Rectangle2D_I32 rectangle ) { UtilPolygons2D_I32 . bounding ( quad . vertexes . toList ( ) , rectangle ) ; }


Input: Returns true if the polygon is ordered in a counter - clockwise order . This is done by summing up the interior angles . [CODESPLIT] public static boolean isCCW ( List < Point2D_I32 > polygon ) { final int N = polygon . size ( ) ; int sign = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int j = ( i + 1 ) % N ; int k = ( i + 2 ) % N ; if ( isPositiveZ ( polygon . get ( i ) , polygon . get ( j ) , polygon . get ( k ) ) ) { sign ++ ; } else { sign -- ; } } return sign < 0 ; }


Input: Flips the order of points inside the polygon . The first index will remain the same will otherwise be reversed [CODESPLIT] public static void flip ( Polygon2D_I32 a ) { int N = a . size ( ) ; int H = N / 2 ; for ( int i = 1 ; i <= H ; i ++ ) { int j = N - i ; Point2D_I32 tmp = a . vertexes . data [ i ] ; a . vertexes . data [ i ] = a . vertexes . data [ j ] ; a . vertexes . data [ j ] = tmp ; } }


Input: Determines if the polugon is convex or concave . [CODESPLIT] public static boolean isConvex ( Polygon2D_I32 poly ) { // if the cross product of all consecutive triples is positive or negative then it is convex final int N = poly . size ( ) ; int numPositive = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int j = ( i + 1 ) % N ; int k = ( i + 2 ) % N ; Point2D_I32 a = poly . vertexes . data [ i ] ; Point2D_I32 b = poly . vertexes . data [ j ] ; Point2D_I32 c = poly . vertexes . data [ k ] ; int dx0 = a . x - b . x ; int dy0 = a . y - b . y ; int dx1 = c . x - b . x ; int dy1 = c . y - b . y ; int z = dx0 * dy1 - dy0 * dx1 ; if ( z > 0 ) numPositive ++ ; // z can be zero if there are duplicate points. // not sure if it should throw an exception if its "bad" or not } return ( numPositive == 0 || numPositive == N ) ; }


Input: Returns true if the cross product would result in a strictly positive z ( e . g . z &gt ; 0 ) . If true then the order is clockwise . [CODESPLIT] public static boolean isPositiveZ ( Point2D_I32 a , Point2D_I32 b , Point2D_I32 c ) { int dx0 = a . x - b . x ; int dy0 = a . y - b . y ; int dx1 = c . x - b . x ; int dy1 = c . y - b . y ; int z = dx0 * dy1 - dy0 * dx1 ; return z > 0 ; }


Input: Checks to see if the vertexes of the two polygon s are the same up to the specified tolerance [CODESPLIT] public static boolean isIdentical ( Polygon2D_I32 a , Polygon2D_I32 b ) { if ( a . size ( ) != b . size ( ) ) return false ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { if ( ! a . get ( i ) . equals ( b . get ( i ) ) ) return false ; } return true ; }


Input: Checks to see if the vertexes of the two polygon s are the same up to the specified tolerance and allows for a shift in their order [CODESPLIT] public static boolean isEquivalent ( Polygon2D_I32 a , Polygon2D_I32 b ) { if ( a . size ( ) != b . size ( ) ) return false ; // first find two vertexes which are the same Point2D_I32 a0 = a . get ( 0 ) ; int match = - 1 ; for ( int i = 0 ; i < b . size ( ) ; i ++ ) { if ( a0 . equals ( b . get ( i ) ) ) { match = i ; break ; } } if ( match < 0 ) return false ; // now go in a circle and see if they all line up for ( int i = 1 ; i < b . size ( ) ; i ++ ) { Point2D_I32 ai = a . get ( i ) ; Point2D_I32 bi = b . get ( ( match + i ) % b . size ( ) ) ; if ( ! ai . equals ( bi ) ) { return false ; } } return true ; }


Input: Finds the point which has the mean location of all the points in the list . This is also known as the centroid . [CODESPLIT] public static Point2D_I32 mean ( List < Point2D_I32 > list , Point2D_I32 mean ) { if ( mean == null ) mean = new Point2D_I32 ( ) ; int sumX = 0 , sumY = 0 ; int N = list . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_I32 p = list . get ( i ) ; sumX += p . x ; sumY += p . y ; } mean . x = sumX / N ; mean . y = sumY / N ; return mean ; }


Input: <p > In - place addition< / p > [CODESPLIT] public void plusIP ( GeoTuple4D_F64 a ) { x += a . x ; y += a . y ; z += a . z ; w += a . w ; }


Input: In - place scalar multiplication [CODESPLIT] public void timesIP ( double scalar ) { x *= scalar ; y *= scalar ; z *= scalar ; w *= scalar ; }


Input: Returns the absolute value of the component with the largest absolute value [CODESPLIT] public double maxAbs ( ) { double absX = Math . abs ( x ) ; double absY = Math . abs ( y ) ; double absZ = Math . abs ( z ) ; double absW = Math . abs ( w ) ; double found = Math . max ( absX , absY ) ; if ( found < absZ ) found = absZ ; if ( found < absW ) found = absW ; return found ; }


Input: <p > Fits points to the quadratic polynomial . It s recommended that you apply a linear transform to the points to ensure that they have zero mean and a standard deviation of 1 . Then reverse the transform on the result . A solution is found using the pseudo inverse and inverse by minor matrices . < / p > [CODESPLIT] public static boolean fitMM ( double [ ] data , int offset , int length , PolynomialQuadratic1D_F64 output , @ Nullable DMatrix3x3 work ) { if ( work == null ) work = new DMatrix3x3 ( ) ; final int N = length / 2 ; // Unrolled pseudo inverse // coef = inv(A^T*A)*A^T*y double sx0 = N , sx1 = 0 , sx2 = 0 ; double sx3 = 0 ; double sx4 = 0 ; double b0 = 0 , b1 = 0 , b2 = 0 ; int end = offset + length ; for ( int i = offset ; i < end ; i += 2 ) { double x = data [ i ] ; double y = data [ i + 1 ] ; double x2 = x * x ; sx1 += x ; sx2 += x2 ; sx3 += x2 * x ; sx4 += x2 * x2 ; b0 += y ; b1 += x * y ; b2 += x2 * y ; } DMatrix3x3 A = work ; A . set ( sx0 , sx1 , sx2 , sx1 , sx2 , sx3 , sx2 , sx3 , sx4 ) ; if ( ! CommonOps_DDF3 . invert ( A , A ) ) // TODO use a symmetric inverse. Should be slightly faster return false ; // output = inv(A)*B      Unrolled here for speed output . a = A . a11 * b0 + A . a12 * b1 + A . a13 * b2 ; output . b = A . a21 * b0 + A . a22 * b1 + A . a23 * b2 ; output . c = A . a31 * b0 + A . a32 * b1 + A . a33 * b2 ; return true ; }


Input: <p > Fits points to the quadratic polynomial using a QRP linear solver . < / p > [CODESPLIT] public static boolean fitQRP ( double [ ] data , int offset , int length , PolynomialQuadratic1D_F64 output ) { FitPolynomialSolverTall_F64 solver = new FitPolynomialSolverTall_F64 ( ) ; return solver . process ( data , offset , length , output ) ; }


Input: <p > Fits points to the cubic polynomial . It s recommended that you apply a linear transform to the points to ensure that they have zero mean and a standard deviation of 1 . Then reverse the transform on the result . A solution is found using the pseudo inverse and inverse by minor matrices . < / p > [CODESPLIT] public static boolean fitMM ( double [ ] data , int offset , int length , PolynomialCubic1D_F64 output , @ Nullable DMatrix4x4 A ) { if ( A == null ) A = new DMatrix4x4 ( ) ; final int N = length / 2 ; if ( N < 4 ) throw new IllegalArgumentException ( "Need at least 4 points and not " + N ) ; // Unrolled pseudo inverse // coef = inv(A^T*A)*A^T*y double sx1 = 0 , sx2 = 0 , sx3 = 0 , sx4 = 0 , sx5 = 0 , sx6 = 0 ; double b0 = 0 , b1 = 0 , b2 = 0 , b3 = 0 ; int end = offset + length ; for ( int i = offset ; i < end ; i += 2 ) { double x = data [ i ] ; double y = data [ i + 1 ] ; double x2 = x * x ; double x3 = x2 * x ; double x4 = x2 * x2 ; sx1 += x ; sx2 += x2 ; sx3 += x3 ; sx4 += x4 ; sx5 += x4 * x ; sx6 += x4 * x2 ; b0 += y ; b1 += x * y ; b2 += x2 * y ; b3 += x3 * y ; } A . set ( N , sx1 , sx2 , sx3 , sx1 , sx2 , sx3 , sx4 , sx2 , sx3 , sx4 , sx5 , sx3 , sx4 , sx5 , sx6 ) ; if ( ! CommonOps_DDF4 . invert ( A , A ) ) // TODO use a symmetric inverse. Should be slightly faster return false ; // output = inv(A)*B      Unrolled here for speed output . a = A . a11 * b0 + A . a12 * b1 + A . a13 * b2 + A . a14 * b3 ; output . b = A . a21 * b0 + A . a22 * b1 + A . a23 * b2 + A . a24 * b3 ; output . c = A . a31 * b0 + A . a32 * b1 + A . a33 * b2 + A . a34 * b3 ; output . d = A . a41 * b0 + A . a42 * b1 + A . a43 * b2 + A . a44 * b3 ; return true ; }


Input: <p > Fits points to a 2D quadratic polynomial . There are two inputs and one output for each data point . It s recommended that you apply a linear transform to the points . < / p > [CODESPLIT] public static boolean fit ( double [ ] data , int offset , int length , PolynomialQuadratic2D_F64 output ) { final int N = length / 3 ; if ( N < 6 ) throw new IllegalArgumentException ( "Need at least 6 points and not " + N ) ; // Unrolled pseudo inverse // coef = inv(A^T*A)*A^T*y double sx1 = 0 , sy1 = 0 , sx1y1 = 0 , sx2 = 0 , sy2 = 0 , sx2y1 = 0 , sx1y2 = 0 , sx2y2 = 0 , sx3 = 0 , sy3 = 0 , sx3y1 = 0 , sx1y3 = 0 , sx4 = 0 , sy4 = 0 ; double b0 = 0 , b1 = 0 , b2 = 0 , b3 = 0 , b4 = 0 , b5 = 0 ; int end = offset + length ; for ( int i = offset ; i < end ; i += 3 ) { double x = data [ i ] ; double y = data [ i + 1 ] ; double z = data [ i + 2 ] ; double x2 = x * x ; double x3 = x2 * x ; double x4 = x2 * x2 ; double y2 = y * y ; double y3 = y2 * y ; double y4 = y2 * y2 ; sx1 += x ; sx2 += x2 ; sx3 += x3 ; sx4 += x4 ; sy1 += y ; sy2 += y2 ; sy3 += y3 ; sy4 += y4 ; sx1y1 += x * y ; sx2y1 += x2 * y ; sx1y2 += x * y2 ; sx2y2 += x2 * y2 ; sx3y1 += x3 * y ; sx1y3 += x * y3 ; b0 += z ; b1 += x * z ; b2 += y * z ; b3 += x * y * z ; b4 += x2 * z ; b5 += y2 * z ; } // using a fixed size matrix because the notation is much nicer DMatrix6x6 A = new DMatrix6x6 ( ) ; A . set ( N , sx1 , sy1 , sx1y1 , sx2 , sy2 , sx1 , sx2 , sx1y1 , sx2y1 , sx3 , sx1y2 , sy1 , sx1y1 , sy2 , sx1y2 , sx2y1 , sy3 , sx1y1 , sx2y1 , sx1y2 , sx2y2 , sx3y1 , sx1y3 , sx2 , sx3 , sx2y1 , sx3y1 , sx4 , sx2y2 , sy2 , sx1y2 , sy3 , sx1y3 , sx2y2 , sy4 ) ; DMatrixRMaj _A = new DMatrixRMaj ( 6 , 6 ) ; ConvertDMatrixStruct . convert ( A , _A ) ; // pseudo inverse is required to handle degenerate matrices, e.g. lines LinearSolverDense < DMatrixRMaj > solver = LinearSolverFactory_DDRM . pseudoInverse ( true ) ; if ( ! solver . setA ( _A ) ) return false ; solver . invert ( _A ) ; DMatrixRMaj B = new DMatrixRMaj ( 6 , 1 , true , b0 , b1 , b2 , b3 , b4 , b5 ) ; DMatrixRMaj Y = new DMatrixRMaj ( 6 , 1 ) ; CommonOps_DDRM . mult ( _A , B , Y ) ; // output = inv(A)*B      Unrolled here for speed output . a = Y . data [ 0 ] ; output . b = Y . data [ 1 ] ; output . c = Y . data [ 2 ] ; output . d = Y . data [ 3 ] ; output . e = Y . data [ 4 ] ; output . f = Y . data [ 5 ] ; return true ; }


Input: Euclidean distance between the two specified points [CODESPLIT] public static double distance ( double x0 , double y0 , double z0 , double x1 , double y1 , double z1 ) { return norm ( x1 - x0 , y1 - y0 , z1 - z0 ) ; }


Input: Euclidean distance squared between the two specified points [CODESPLIT] public static double distanceSq ( double x0 , double y0 , double z0 , double x1 , double y1 , double z1 ) { double dx = x1 - x0 ; double dy = y1 - y0 ; double dz = z1 - z0 ; return dx * dx + dy * dy + dz * dz ; }


Input: Randomly generates a set of points on the plane centered at the plane s origin using a uniform distribution . [CODESPLIT] public static List < Point3D_F64 > random ( PlaneNormal3D_F64 plane , double max , int num , Random rand ) { List < Point3D_F64 > ret = new ArrayList <> ( ) ; Vector3D_F64 axisX = new Vector3D_F64 ( ) ; Vector3D_F64 axisY = new Vector3D_F64 ( ) ; UtilPlane3D_F64 . selectAxis2D ( plane . n , axisX , axisY ) ; for ( int i = 0 ; i < num ; i ++ ) { double x = 2 * max * ( rand . nextDouble ( ) - 0.5 ) ; double y = 2 * max * ( rand . nextDouble ( ) - 0.5 ) ; Point3D_F64 p = new Point3D_F64 ( ) ; p . x = plane . p . x + axisX . x * x + axisY . x * y ; p . y = plane . p . y + axisX . y * x + axisY . y * y ; p . z = plane . p . z + axisX . z * x + axisY . z * y ; ret . add ( p ) ; } return ret ; }


Input: Creates a list of random points from a uniform distribution along each axis [CODESPLIT] public static List < Point3D_F64 > random ( Point3D_F64 mean , double minX , double maxX , double minY , double maxY , double minZ , double maxZ , int num , Random rand ) { List < Point3D_F64 > ret = new ArrayList <> ( ) ; for ( int i = 0 ; i < num ; i ++ ) { Point3D_F64 p = new Point3D_F64 ( ) ; p . x = mean . x + rand . nextDouble ( ) * ( maxX - minX ) + minX ; p . y = mean . y + rand . nextDouble ( ) * ( maxY - minY ) + minY ; p . z = mean . z + rand . nextDouble ( ) * ( maxZ - minZ ) + minZ ; ret . add ( p ) ; } return ret ; }


Input: Creates a list of random points from a normal distribution along each axis [CODESPLIT] public static List < Point3D_F64 > randomN ( Point3D_F64 mean , double stdX , double stdY , double stdZ , int num , Random rand ) { List < Point3D_F64 > ret = new ArrayList <> ( ) ; for ( int i = 0 ; i < num ; i ++ ) { Point3D_F64 p = new Point3D_F64 ( ) ; p . x = mean . x + rand . nextGaussian ( ) * stdX ; p . y = mean . y + rand . nextGaussian ( ) * stdY ; p . z = mean . z + rand . nextGaussian ( ) * stdZ ; ret . add ( p ) ; } return ret ; }


Input: Computes the mean of the list of points . [CODESPLIT] public static Point3D_F64 mean ( List < Point3D_F64 > points , Point3D_F64 mean ) { if ( mean == null ) mean = new Point3D_F64 ( ) ; double x = 0 , y = 0 , z = 0 ; for ( Point3D_F64 p : points ) { x += p . x ; y += p . y ; z += p . z ; } mean . x = x / points . size ( ) ; mean . y = y / points . size ( ) ; mean . z = z / points . size ( ) ; return mean ; }


Input: Computes the mean of the list of points up to element num . [CODESPLIT] public static Point3D_F64 mean ( List < Point3D_F64 > points , int num , Point3D_F64 mean ) { if ( mean == null ) mean = new Point3D_F64 ( ) ; double x = 0 , y = 0 , z = 0 ; for ( int i = 0 ; i < num ; i ++ ) { Point3D_F64 p = points . get ( i ) ; x += p . x ; y += p . y ; z += p . z ; } mean . x = x / num ; mean . y = y / num ; mean . z = z / num ; return mean ; }


Input: Finds the minimal volume { @link Box3D_F64 } which contains all the points . [CODESPLIT] public static void boundingBox ( List < Point3D_F64 > points , Box3D_F64 bounding ) { double minX = Double . MAX_VALUE , maxX = - Double . MAX_VALUE ; double minY = Double . MAX_VALUE , maxY = - Double . MAX_VALUE ; double minZ = Double . MAX_VALUE , maxZ = - Double . MAX_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point3D_F64 p = points . get ( i ) ; if ( p . x < minX ) minX = p . x ; if ( p . x > maxX ) maxX = p . x ; if ( p . y < minY ) minY = p . y ; if ( p . y > maxY ) maxY = p . y ; if ( p . z < minZ ) minZ = p . z ; if ( p . z > maxZ ) maxZ = p . z ; } bounding . p0 . set ( minX , minY , minZ ) ; bounding . p1 . set ( maxX , maxY , maxZ ) ; }


Input: Discards any cached principal for the given collection of credentials . [CODESPLIT] public void invalidateAll ( Iterable < JwtContext > credentials ) { credentials . forEach ( context -> cache . invalidate ( context . getJwt ( ) ) ) ; }


Input: Discards any cached principal for the collection of credentials satisfying the given predicate . [CODESPLIT] public void invalidateAll ( Predicate < ? super JwtContext > predicate ) { cache . asMap ( ) . entrySet ( ) . stream ( ) . map ( entry -> entry . getValue ( ) . getKey ( ) ) . filter ( predicate :: test ) . map ( JwtContext :: getJwt ) . forEach ( cache :: invalidate ) ; }


Input: Combine the given String collections into a set using case - insensitive matching . If there are multiple instances of the same string but with different capitalization only the first one found will be included . [CODESPLIT] @ SafeVarargs public static Set < String > combineToSet ( Collection < String > ... collections ) { Set < String > result = new HashSet < String > ( ) ; Set < String > lowercaseSet = new HashSet < String > ( ) ; for ( Collection < String > collection : collections ) { if ( collection != null ) { for ( String value : collection ) { if ( ! lowercaseSet . contains ( value . toLowerCase ( ) ) ) { lowercaseSet . add ( value . toLowerCase ( ) ) ; result . add ( value ) ; } } } } return result ; }


Input: Get the set of features defined in the server . xml [CODESPLIT] public Set < String > getServerFeatures ( File serverDirectory ) { Set < String > result = getConfigDropinsFeatures ( null , serverDirectory , "defaults" ) ; result = getServerXmlFeatures ( result , new File ( serverDirectory , "server.xml" ) , null ) ; // add the overrides at the end since they should not be replaced by any previous content return getConfigDropinsFeatures ( result , serverDirectory , "overrides" ) ; }


Input: Gets features from the configDropins s defaults or overrides directory [CODESPLIT] private Set < String > getConfigDropinsFeatures ( Set < String > origResult , File serverDirectory , String folderName ) { Set < String > result = origResult ; File configDropinsFolder ; try { configDropinsFolder = new File ( new File ( serverDirectory , "configDropins" ) , folderName ) . getCanonicalFile ( ) ; } catch ( IOException e ) { // skip this directory if its path cannot be queried warn ( "The " + serverDirectory + "/configDropins/" + folderName + " directory cannot be accessed. Skipping its server features." ) ; debug ( e ) ; return result ; } File [ ] configDropinsXmls = configDropinsFolder . listFiles ( new FilenameFilter ( ) { @ Override public boolean accept ( File dir , String name ) { return name . endsWith ( ".xml" ) ; } } ) ; if ( configDropinsXmls == null || configDropinsXmls . length == 0 ) { return result ; } // sort the files in alphabetical order so that overrides will happen in the proper order Comparator < File > comparator = new Comparator < File > ( ) { @ Override public int compare ( File left , File right ) { return left . getAbsolutePath ( ) . toLowerCase ( ) . compareTo ( right . getAbsolutePath ( ) . toLowerCase ( ) ) ; } } ; Collections . sort ( Arrays . asList ( configDropinsXmls ) , comparator ) ; for ( File xml : configDropinsXmls ) { Set < String > features = getServerXmlFeatures ( result , xml , null ) ; if ( features != null ) { result = features ; } } return result ; }


Input: Adds features from the given server file into the origResult or a new set if origResult is null . [CODESPLIT] private Set < String > getServerXmlFeatures ( Set < String > origResult , File serverFile , List < File > parsedXmls ) { Set < String > result = origResult ; List < File > updatedParsedXmls = parsedXmls != null ? parsedXmls : new ArrayList < File > ( ) ; File canonicalServerFile ; try { canonicalServerFile = serverFile . getCanonicalFile ( ) ; } catch ( IOException e ) { // skip this server.xml if its path cannot be queried warn ( "The server file " + serverFile + " cannot be accessed. Skipping its features." ) ; debug ( e ) ; return result ; } updatedParsedXmls . add ( canonicalServerFile ) ; if ( canonicalServerFile . exists ( ) ) { try { Document doc = new XmlDocument ( ) { public Document getDocument ( File file ) throws IOException , ParserConfigurationException , SAXException { createDocument ( file ) ; return doc ; } } . getDocument ( canonicalServerFile ) ; Element root = doc . getDocumentElement ( ) ; NodeList nodes = root . getChildNodes ( ) ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { if ( nodes . item ( i ) instanceof Element ) { Element child = ( Element ) nodes . item ( i ) ; if ( "featureManager" . equals ( child . getNodeName ( ) ) ) { if ( result == null ) { result = new HashSet < String > ( ) ; } result . addAll ( parseFeatureManagerNode ( child ) ) ; } else if ( "include" . equals ( child . getNodeName ( ) ) ) { result = parseIncludeNode ( result , canonicalServerFile , child , updatedParsedXmls ) ; } } } } catch ( IOException | ParserConfigurationException | SAXException e ) { // just skip this server.xml if it cannot be parsed warn ( "The server file " + serverFile + " cannot be parsed. Skipping its features." ) ; debug ( e ) ; return result ; } } return result ; }


Input: Parse features from an include node . [CODESPLIT] private Set < String > parseIncludeNode ( Set < String > origResult , File serverFile , Element node , List < File > updatedParsedXmls ) { Set < String > result = origResult ; String includeFileName = node . getAttribute ( "location" ) ; if ( includeFileName == null || includeFileName . trim ( ) . isEmpty ( ) ) { return result ; } File includeFile = null ; if ( isURL ( includeFileName ) ) { try { File tempFile = File . createTempFile ( "serverFromURL" , ".xml" ) ; FileUtils . copyURLToFile ( new URL ( includeFileName ) , tempFile , COPY_FILE_TIMEOUT_MILLIS , COPY_FILE_TIMEOUT_MILLIS ) ; includeFile = tempFile ; } catch ( IOException e ) { // skip this xml if it cannot be accessed from URL warn ( "The server file " + serverFile + " includes a URL " + includeFileName + " that cannot be accessed. Skipping the included features." ) ; debug ( e ) ; return result ; } } else { includeFile = new File ( includeFileName ) ; } try { if ( ! includeFile . isAbsolute ( ) ) { includeFile = new File ( serverFile . getParentFile ( ) . getAbsolutePath ( ) , includeFileName ) . getCanonicalFile ( ) ; } else { includeFile = includeFile . getCanonicalFile ( ) ; } } catch ( IOException e ) { // skip this xml if its path cannot be queried warn ( "The server file " + serverFile + " includes a file " + includeFileName + " that cannot be accessed. Skipping the included features." ) ; debug ( e ) ; return result ; } if ( ! updatedParsedXmls . contains ( includeFile ) ) { String onConflict = node . getAttribute ( "onConflict" ) ; Set < String > features = getServerXmlFeatures ( null , includeFile , updatedParsedXmls ) ; result = handleOnConflict ( result , onConflict , features ) ; } return result ; }


Input: Parse feature elements from a featureManager node trimming whitespace and treating everything as lowercase . [CODESPLIT] private static Set < String > parseFeatureManagerNode ( Element node ) { Set < String > result = new HashSet < String > ( ) ; NodeList features = node . getElementsByTagName ( "feature" ) ; if ( features != null ) { for ( int j = 0 ; j < features . getLength ( ) ; j ++ ) { String content = features . item ( j ) . getTextContent ( ) ; if ( content != null ) { if ( content . contains ( ":" ) ) { String [ ] split = content . split ( ":" , 2 ) ; result . add ( split [ 1 ] . trim ( ) . toLowerCase ( ) ) ; } else { result . add ( content . trim ( ) . toLowerCase ( ) ) ; } } } } return result ; }


Input: Get the JSON files corresponding to the product properties from the lib / versions / * . properties files [CODESPLIT] private Set < File > downloadProductJsons ( ) throws PluginExecutionException { // download JSONs Set < File > downloadedJsons = new HashSet < File > ( ) ; for ( ProductProperties properties : propertiesList ) { File json = downloadJsons ( properties . getId ( ) , properties . getVersion ( ) ) ; if ( json != null ) { downloadedJsons . add ( json ) ; } } return downloadedJsons ; }


Input: Download the JSON file for the given product . [CODESPLIT] private File downloadJsons ( String productId , String productVersion ) { String jsonGroupId = productId + ".features" ; try { return downloadArtifact ( jsonGroupId , "features" , "json" , productVersion ) ; } catch ( PluginExecutionException e ) { debug ( "Cannot find json for productId " + productId + ", productVersion " + productVersion , e ) ; return null ; } }


Input: Returns true if this scenario is not supported for installing from Maven repository which is one of the following conditions : from parameter is specified ( don t need Maven repositories ) or esa files are specified in the configuration ( not supported with Maven for now ) [CODESPLIT] private boolean hasUnsupportedParameters ( String from , Set < String > pluginListedEsas ) { boolean hasFrom = from != null ; boolean hasPluginListedEsas = ! pluginListedEsas . isEmpty ( ) ; debug ( "hasFrom: " + hasFrom ) ; debug ( "hasPluginListedEsas: " + hasPluginListedEsas ) ; return hasFrom || hasPluginListedEsas ; }


Input: Gets the set of all Open Liberty features by scanning the product JSONs . [CODESPLIT] public static Set < String > getOpenLibertyFeatureSet ( Set < File > jsons ) throws PluginExecutionException { Set < String > libertyFeatures = new HashSet < String > ( ) ; for ( File file : jsons ) { Scanner s = null ; try { s = new Scanner ( file ) ; // scan Maven coordinates for artifactIds that belong to the Open Liberty groupId while ( s . findWithinHorizon ( OPEN_LIBERTY_GROUP_ID + ":([^:]*):" , 0 ) != null ) { MatchResult match = s . match ( ) ; if ( match . groupCount ( ) >= 1 ) { libertyFeatures . add ( match . group ( 1 ) ) ; } } } catch ( FileNotFoundException e ) { throw new PluginExecutionException ( "The JSON file is not found at " + file . getAbsolutePath ( ) , e ) ; } finally { if ( s != null ) { s . close ( ) ; } } } return libertyFeatures ; }


Input: Returns true if all features in featuresToInstall are Open Liberty features . [CODESPLIT] private boolean isOnlyOpenLibertyFeatures ( List < String > featuresToInstall ) throws PluginExecutionException { boolean result = containsIgnoreCase ( getOpenLibertyFeatureSet ( downloadedJsons ) , featuresToInstall ) ; debug ( "Is installing only Open Liberty features? " + result ) ; return result ; }


Input: Returns whether the reference collection contains all of the strings in the target collection ignoring case . [CODESPLIT] public static boolean containsIgnoreCase ( Collection < String > reference , Collection < String > target ) { return toLowerCase ( reference ) . containsAll ( toLowerCase ( target ) ) ; }


Input: Resolve download and install features from a Maven repository . This method calls the resolver with the given JSONs and feature list downloads the ESAs corresponding to the resolved features then installs those features . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public void installFeatures ( boolean isAcceptLicense , List < String > featuresToInstall ) throws PluginExecutionException { List < File > jsonRepos = new ArrayList < File > ( downloadedJsons ) ; debug ( "JSON repos: " + jsonRepos ) ; info ( "Installing features: " + featuresToInstall ) ; // override license acceptance if installing only Open Liberty features boolean acceptLicenseMapValue = isOnlyOpenLibertyFeatures ( featuresToInstall ) ? true : isAcceptLicense ; try { Map < String , Object > mapBasedInstallKernel = createMapBasedInstallKernelInstance ( installDirectory ) ; mapBasedInstallKernel . put ( "install.local.esa" , true ) ; mapBasedInstallKernel . put ( "single.json.file" , jsonRepos ) ; mapBasedInstallKernel . put ( "features.to.resolve" , featuresToInstall ) ; mapBasedInstallKernel . put ( "license.accept" , acceptLicenseMapValue ) ; if ( isDebugEnabled ( ) ) { mapBasedInstallKernel . put ( "debug" , Level . FINEST ) ; } Collection < ? > resolvedFeatures = ( Collection < ? > ) mapBasedInstallKernel . get ( "action.result" ) ; if ( resolvedFeatures == null ) { debug ( "action.exception.stacktrace: " + mapBasedInstallKernel . get ( "action.exception.stacktrace" ) ) ; String exceptionMessage = ( String ) mapBasedInstallKernel . get ( "action.error.message" ) ; throw new PluginExecutionException ( exceptionMessage ) ; } else if ( resolvedFeatures . isEmpty ( ) ) { debug ( "action.exception.stacktrace: " + mapBasedInstallKernel . get ( "action.exception.stacktrace" ) ) ; String exceptionMessage = ( String ) mapBasedInstallKernel . get ( "action.error.message" ) ; if ( exceptionMessage == null ) { debug ( "resolvedFeatures was empty but the install kernel did not issue any messages" ) ; info ( "The features are already installed, so no action is needed." ) ; return ; } else if ( exceptionMessage . contains ( "CWWKF1250I" ) ) { info ( exceptionMessage ) ; info ( "The features are already installed, so no action is needed." ) ; return ; } else { throw new PluginExecutionException ( exceptionMessage ) ; } } Collection < File > artifacts = downloadEsas ( resolvedFeatures ) ; StringBuilder installedFeaturesBuilder = new StringBuilder ( ) ; Collection < String > actionReturnResult = new ArrayList < String > ( ) ; for ( File esaFile : artifacts ) { mapBasedInstallKernel . put ( "license.accept" , acceptLicenseMapValue ) ; mapBasedInstallKernel . put ( "action.install" , esaFile ) ; if ( to != null ) { mapBasedInstallKernel . put ( "to.extension" , to ) ; debug ( "Installing to extension: " + to ) ; } Integer ac = ( Integer ) mapBasedInstallKernel . get ( "action.result" ) ; debug ( "action.result: " + ac ) ; debug ( "action.error.message: " + mapBasedInstallKernel . get ( "action.error.message" ) ) ; if ( mapBasedInstallKernel . get ( "action.error.message" ) != null ) { debug ( "action.exception.stacktrace: " + mapBasedInstallKernel . get ( "action.exception.stacktrace" ) ) ; String exceptionMessage = ( String ) mapBasedInstallKernel . get ( "action.error.message" ) ; debug ( exceptionMessage ) ; throw new PluginExecutionException ( exceptionMessage ) ; } else if ( mapBasedInstallKernel . get ( "action.install.result" ) != null ) { actionReturnResult . addAll ( ( Collection < String > ) mapBasedInstallKernel . get ( "action.install.result" ) ) ; } } for ( String installResult : actionReturnResult ) { installedFeaturesBuilder . append ( installResult ) . append ( " " ) ; } productInfoValidate ( ) ; info ( "The following features have been installed: " + installedFeaturesBuilder . toString ( ) ) ; } catch ( PrivilegedActionException e ) { throw new PluginExecutionException ( "Could not load the jar " + installJarFile . getAbsolutePath ( ) , e ) ; } }


Input: Download the override bundle from the repository with the given groupId and artifactId corresponding to the latest version in the range between the current Open Liberty version ( inclusive ) and the next version ( exclusive ) . Returns a string in the format filepath ; BundleName where BundleName is the bundle symbolic name from its manifest . [CODESPLIT] public String getOverrideBundleDescriptor ( String groupId , String artifactId ) throws PluginExecutionException { File overrideJar = downloadOverrideJar ( groupId , artifactId ) ; if ( overrideJar != null && overrideJar . exists ( ) ) { String symbolicName = extractSymbolicName ( overrideJar ) ; if ( symbolicName != null ) { return overrideJar . getAbsolutePath ( ) + ";" + symbolicName ; } } return null ; }


Input: Gets the next product version number . [CODESPLIT] public static String getNextProductVersion ( String version ) throws PluginExecutionException { String result = null ; int versionSplittingIndex = version . lastIndexOf ( "." ) + 1 ; if ( versionSplittingIndex == 0 ) { throw new PluginExecutionException ( "Product version " + version + " is not in the expected format. It must have period separated version segments." ) ; } String quarterVersion = version . substring ( versionSplittingIndex ) ; int nextQuarterSpecifier ; try { nextQuarterSpecifier = Integer . parseInt ( quarterVersion ) + 1 ; } catch ( NumberFormatException e ) { throw new PluginExecutionException ( "Product version " + version + " is not in the expected format. Its last segment is expected to be an integer." , e ) ; } result = version . substring ( 0 , versionSplittingIndex ) + nextQuarterSpecifier ; return result ; }


Input: Extracts the bundle symbolic name from the jar manifest . [CODESPLIT] public static String extractSymbolicName ( File jar ) throws PluginExecutionException { JarFile jarFile = null ; try { jarFile = new JarFile ( jar ) ; return jarFile . getManifest ( ) . getMainAttributes ( ) . getValue ( "Bundle-SymbolicName" ) ; } catch ( IOException e ) { throw new PluginExecutionException ( "Could not load the jar " + jar . getAbsolutePath ( ) , e ) ; } finally { if ( jarFile != null ) { try { jarFile . close ( ) ; } catch ( IOException e ) { // nothing to do here } } } }


Input: Find latest install map jar from specified directory [CODESPLIT] public static File getMapBasedInstallKernelJar ( File dir ) { File [ ] installMapJars = dir . listFiles ( new FilenameFilter ( ) { @ Override public boolean accept ( File dir , String name ) { return name . startsWith ( INSTALL_MAP_PREFIX ) && name . endsWith ( INSTALL_MAP_SUFFIX ) ; } } ) ; File result = null ; if ( installMapJars != null ) { for ( File jar : installMapJars ) { if ( isReplacementJar ( result , jar ) ) { result = jar ; } } } return result ; }


Input: Returns whether file2 can replace file1 as the install map jar . [CODESPLIT] private static boolean isReplacementJar ( File file1 , File file2 ) { if ( file1 == null ) { return true ; } else if ( file2 == null ) { return false ; } else { String version1 = extractVersion ( file1 . getName ( ) ) ; String version2 = extractVersion ( file2 . getName ( ) ) ; return compare ( version1 , version2 ) < 0 ; } }


Input: Returns the extracted version from fileName [CODESPLIT] private static String extractVersion ( String fileName ) { int startIndex = INSTALL_MAP_PREFIX . length ( ) + 1 ; // skip the underscore after the prefix int endIndex = fileName . lastIndexOf ( INSTALL_MAP_SUFFIX ) ; if ( startIndex < endIndex ) { return fileName . substring ( startIndex , endIndex ) ; } else { return null ; } }


Input: Performs pairwise comparison of version strings including nulls and non - integer components . [CODESPLIT] private static int compare ( String version1 , String version2 ) { if ( version1 == null && version2 == null ) { return 0 ; } else if ( version1 == null && version2 != null ) { return - 1 ; } else if ( version1 != null && version2 == null ) { return 1 ; } String [ ] components1 = version1 . split ( "\\." ) ; String [ ] components2 = version2 . split ( "\\." ) ; for ( int i = 0 ; i < components1 . length && i < components2 . length ; i ++ ) { int comparison ; try { comparison = new Integer ( components1 [ i ] ) . compareTo ( new Integer ( components2 [ i ] ) ) ; } catch ( NumberFormatException e ) { comparison = components1 [ i ] . compareTo ( components2 [ i ] ) ; } if ( comparison != 0 ) { return comparison ; } } return components1 . length - components2 . length ; }


Input: Performs product validation by running bin / productInfo validate [CODESPLIT] private void productInfoValidate ( ) throws PluginExecutionException { String output = productInfo ( installDirectory , "validate" ) ; if ( output == null ) { throw new PluginExecutionException ( "Could not perform product validation. The productInfo command returned with no output" ) ; } else if ( output . contains ( "[ERROR]" ) ) { throw new PluginExecutionException ( output ) ; } else { info ( "Product validation completed successfully." ) ; } }


Input: Runs the productInfo command and returns the output [CODESPLIT] public static String productInfo ( File installDirectory , String action ) throws PluginExecutionException { Process pr = null ; InputStream is = null ; Scanner s = null ; Worker worker = null ; try { String command ; if ( OSUtil . isWindows ( ) ) { command = installDirectory + "\\bin\\productInfo.bat " + action ; } else { command = installDirectory + "/bin/productInfo " + action ; } pr = Runtime . getRuntime ( ) . exec ( command ) ; worker = new Worker ( pr ) ; worker . start ( ) ; worker . join ( 300000 ) ; if ( worker . exit == null ) { throw new PluginExecutionException ( "productInfo command timed out" ) ; } int exitValue = pr . exitValue ( ) ; if ( exitValue != 0 ) { throw new PluginExecutionException ( "productInfo exited with return code " + exitValue ) ; } is = pr . getInputStream ( ) ; s = new Scanner ( is ) ; // use regex to match the beginning of the input s . useDelimiter ( "\\A" ) ; if ( s . hasNext ( ) ) { return s . next ( ) ; } return null ; } catch ( IOException ex ) { throw new PluginExecutionException ( "productInfo error: " + ex ) ; } catch ( InterruptedException ex ) { worker . interrupt ( ) ; Thread . currentThread ( ) . interrupt ( ) ; throw new PluginExecutionException ( "productInfo error: " + ex ) ; } finally { if ( s != null ) { s . close ( ) ; } if ( is != null ) { try { is . close ( ) ; } catch ( IOException e ) { } } if ( pr != null ) { pr . destroy ( ) ; } } }


Input: Check whether the given artifact is a Spring Boot Uber JAR [CODESPLIT] public static boolean isSpringBootUberJar ( File artifact ) { if ( artifact == null || ! artifact . exists ( ) || ! artifact . isFile ( ) ) { return false ; } try ( JarFile jarFile = new JarFile ( artifact ) ) { Manifest manifest = jarFile . getManifest ( ) ; if ( manifest != null ) { Attributes attributes = manifest . getMainAttributes ( ) ; if ( attributes . getValue ( BOOT_VERSION_ATTRIBUTE ) != null && attributes . getValue ( BOOT_START_CLASS_ATTRIBUTE ) != null ) { return true ; } else { //Checking that there is a spring-boot-VERSION.RELEASE.jar in the BOOT-INF/lib directory //Handles the Gradle case where the spring plugin does not set the properties in the manifest Enumeration < JarEntry > entries = jarFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry entry = entries . nextElement ( ) ; String entryName = entry . getName ( ) ; if ( ! entryName . startsWith ( "org" ) && ( entryName . matches ( BOOT_JAR_EXPRESSION ) || entryName . matches ( BOOT_WAR_EXPRESSION ) ) ) { return true ; } } } } } catch ( IOException e ) { } return false ; }


Input: Converts Map<String String > to Map<LibertyPropertyI String > . Validates each key property name . [CODESPLIT] public static Map < LibertyPropertyI , String > getArquillianProperties ( Map < String , String > arquillianProperties , Class < ? > cls ) throws ArquillianConfigurationException { Map < LibertyPropertyI , String > props = new HashMap < LibertyPropertyI , String > ( ) ; if ( arquillianProperties != null && ! arquillianProperties . isEmpty ( ) ) { for ( Entry < String , String > entry : arquillianProperties . entrySet ( ) ) { String key = entry . getKey ( ) ; String value = entry . getValue ( ) ; if ( key != null && value != null ) { LibertyPropertyI p = getArquillianProperty ( key , cls ) ; props . put ( p , value ) ; } } } return props ; }


Input: Check that the given key exists in ArquillianProperties [CODESPLIT] private static LibertyPropertyI getArquillianProperty ( String key , Class < ? > cls ) throws ArquillianConfigurationException { try { if ( cls == LibertyManagedObject . LibertyManagedProperty . class ) { return LibertyManagedObject . LibertyManagedProperty . valueOf ( key ) ; } else if ( cls == LibertyRemoteObject . LibertyRemoteProperty . class ) { return LibertyRemoteObject . LibertyRemoteProperty . valueOf ( key ) ; } } catch ( IllegalArgumentException e ) { throw new ArquillianConfigurationException ( "Property \"" + key + "\" in arquillianProperties does not exist. You probably have a typo." ) ; } throw new ArquillianConfigurationException ( "This should never happen." ) ; }


Input: We assume any environment that is not headless will have a web browser to display the image in a web page . [CODESPLIT] @ Override public boolean isWorkingInThisEnvironment ( String forFile ) { return ! GraphicsEnvironment . isHeadless ( ) && GenericDiffReporter . isFileExtensionValid ( forFile , GenericDiffReporter . IMAGE_FILE_EXTENSIONS ) ; }


Input: Prints a request for a text input to the window . <br > <b > Example : < / b > { @code String name = FancyMessageBox . askForTextInput ( What is your nickname? Nicknames ) ; } [CODESPLIT] public static String askForTextInput ( String message , String title ) { return fancyMessageBox . askForTextInput ( message , title ) ; }


Input: Prints the message to the window . <br > <b > Example : < / b > { @code FancyMessageBox . showMessage ( Girl programmers rule! Just the Facts ) ; } [CODESPLIT] public static void showMesage ( String message , String title , ImageIcon icon ) { fancyMessageBox . showMessage ( message , title , icon ) ; }


Input: Parses a file <div > <b > Example : < / b > { @code parser . parseRtfFile ( filename data ) } < / div > [CODESPLIT] public static String parseRtfFile ( String fileName , Object data ) { try { String text = FileUtils . readFromClassPath ( data . getClass ( ) , fileName ) ; return parse ( text , "\\{" , "\\}" , data ) ; } catch ( Exception e ) { throw ObjectUtils . throwAsError ( e ) ; } }


Input: Paints a circle <div > <b > Example : < / b > { @code circle . paint ( g caller ) } < / div > [CODESPLIT] @ Override public void paint ( Graphics2D g , JPanel caller ) { Color color2 = PenColors . getTransparentVersion ( mainColor , percentTransparent ) ; g . setColor ( color2 ) ; g . fillOval ( x - radius , y - radius , radius * 2 , radius * 2 ) ; }


Input: Makes a cool shape fast <div > <b > Example : < / b > { [CODESPLIT] public static void drawShape ( int sides , Color color , int length , int width ) { Tortoise . show ( ) ; Tortoise . setSpeed ( 7 ) ; Tortoise . getBackgroundWindow ( ) . getCanvas ( ) . setBackground ( PenColors . Yellows . Goldenrod ) ; new Text ( "TKP Java - Make Some Shapes!" ) . setTopLeft ( 225 , 50 ) . addTo ( Tortoise . getBackgroundWindow ( ) ) ; for ( int i = 0 ; i < sides ; i ++ ) { Tortoise . setPenColor ( color ) ; Tortoise . setPenWidth ( width ) ; Tortoise . move ( length ) ; Tortoise . turn ( 360 / sides ) ; } VirtualProctor . setClassName ( "Grace Hopper's Class" ) ; VirtualProctor . setName ( "Jean Bartik" ) ; }


Input: Draws an entire Tortoise -- fast! <div > <b > Example : < / b > { [CODESPLIT] public static void drawTortoise ( ) { Tortoise . show ( ) ; Tortoise . setSpeed ( 9 ) ; Tortoise . getBackgroundWindow ( ) . setBackground ( PenColors . Greens . DarkSeaGreen ) ; new Text ( "TKP Java - It's the Tortoise!" ) . setTopLeft ( 200 , 75 ) . addTo ( Tortoise . getBackgroundWindow ( ) ) ; Tortoise . setPenColor ( PenColors . Greens . Green ) ; Tortoise . setPenWidth ( 3 ) ; makeTortoiseBody ( ) ; Tortoise . setPenColor ( PenColors . Browns . Brown ) ; Tortoise . turn ( - 65 ) ; Tortoise . makeTortoiseLeg ( ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 150 ) ; Tortoise . turn ( - 90 ) ; Tortoise . makeTortoiseLeg ( ) ; }


Input: Checks if a tortoise can eat a slice of a pizza <div > <b > Example : < / b > { @code tortoise . eatPizza ( pizza ) } < / div > [CODESPLIT] public boolean eatPizza ( Pizza pizza ) { if ( ! pizza . takeSlice ( ) ) { return false ; } if ( this . topping == null ) { return true ; } if ( this . topping != Topping . Cheese ) { return pizza . hasTopping ( topping ) ; } return pizza . wasCooked ( ) && pizza . hasTopping ( topping ) ; }


Input: Create the makeASquare recipe -- #11 . 1 [CODESPLIT] private static void makeASquare ( double length ) { //  If the current length is greater than 10 --#10.2 if ( length > 10 ) { //    Run the recipe moveToTheSquareStart with the current length  --#4.3 moveToTheSquareStart ( length ) ; // //    Do the following 4 times --#7.1  for ( int i = 0 ; i < 4 ; i ++ ) { //      Move the Tortoise the current length   Tortoise . move ( length ) ; //      MakeASquare with the current length divided by 1.7 (recipe below)--#11.3   makeASquare ( length / 1.7 ) ; //          If the current process count is less than 3 (HINT: use 'i') --#9 if ( i < 3 ) { //            Turn the tortoise 90 degrees to the right Tortoise . turn ( 90 ) ; // } //  End Repeat --#7.2   } //  MoveBackToCenter with the current length (recipe below)--#5.3  moveBackToCenter ( length ) ; //  Set the current length to the current length times two --#10.1 length = length * 2 ; } //  End of makeASquare recipe }


Input: Create the moveToTheSquareStart recipe -- #4 . 1 [CODESPLIT] private static void moveToTheSquareStart ( double length ) { //    Set the pen up for the tortoise --#1.2 Tortoise . setPenUp ( ) ; //    Move the tortoise the current length divided by two --#1.3 Tortoise . move ( length / 2 ) ; //    Turn the tortoise 90 degrees to the left --#2.1 Tortoise . turn ( - 90 ) ; //    Move the tortoise the current length divided by two --#2.2 Tortoise . move ( length / 2 ) ; //    Turn the tortoise 180 degrees to the right --#3.1 Tortoise . turn ( 180 ) ; //    Set the pen down for the tortoise --#3.2 Tortoise . setPenDown ( ) ; //  End of moveToTheSquareStart recipe --#4.2  }


Input: Create the moveBackToCenter recipe [CODESPLIT] private static void moveBackToCenter ( double length ) { Tortoise . setPenUp ( ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( length / 2 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( length / 2 ) ; Tortoise . turn ( 180 ) ; Tortoise . setPenDown ( ) ; // }


Input: A convenience function to check if two objects are equal . [CODESPLIT] public static boolean isEqual ( Object s1 , Object s2 ) { return s1 == s2 || ( s1 != null ) && s1 . equals ( s2 ) ; }


Input: Uses a RTF Viewer to display the results of a model ( or text ) <div > <b > Example : < / b > { @code viewer . displayRtfFile ( text ) } < / div > [CODESPLIT] public static void displayRtfFile ( String text ) { try { File file ; file = File . createTempFile ( "currentStory" , ".rtf" ) ; FileWriter f = new FileWriter ( file ) ; f . write ( text ) ; f . close ( ) ; TestUtils . displayFile ( file . getPath ( ) ) ; } catch ( IOException e ) { throw ObjectUtils . throwAsError ( e ) ; } }


Input: Loads an int from a String . [CODESPLIT] public static int load ( String i , int defaultValue , boolean stripNonNumeric ) { try { i = stripNonNumeric ? StringUtils . stripNonNumeric ( i , true , true ) : i ; defaultValue = Integer . parseInt ( i ) ; } catch ( Exception ignored ) { } return defaultValue ; }


Input: randomly chooses a number between the minimum and maximum <div > <b > Example : < / b > { @code int grade = NumberUtils . getRandomInt ( 1 100 ) ; } < / div > [CODESPLIT] public static int getRandomInt ( int minimum , int maximum ) { int diff = maximum - minimum ; if ( diff == 0 ) { return maximum ; } else { return RANDOM . nextInt ( diff ) + minimum ; } }


Input: Ignore the following It s needed to run the deep dive [CODESPLIT] private Tortoise [ ] throwPizzaParty ( ) { Tortoise karai = new Tortoise ( ) ; Tortoise cecil = new Tortoise ( ) ; Tortoise michealangelo = new Tortoise ( ) ; Tortoise fred = new Tortoise ( ) ; return new Tortoise [ ] { karai , cecil , michealangelo , fred } ; }


Input: Checks to see if a pizza has a particular kind of topping <div > <b > Example : < / b > { @code pizza . hasTopping ( topping ) } < / div > [CODESPLIT] public boolean hasTopping ( Topping topping ) { for ( Topping toppingToday : toppings ) { if ( toppingToday == topping ) { return true ; } } return false ; }


Input: ******************************************************************* [CODESPLIT] public boolean accept ( File pathname ) { String name = pathname . getName ( ) . toLowerCase ( ) ; boolean accept ; accept = ! ( name . equals ( "." ) || name . equals ( ".." ) ) && ! pathname . isDirectory ( ) ; return accept ; }


Input: ------------- Recipe for CreateColorPalette -- #8 . 2 [CODESPLIT] private static void createColorPalette ( ) { Color color1 = PenColors . Reds . Red ; Color color2 = PenColors . Oranges . DarkOrange ; Color color3 = PenColors . Yellows . Gold ; Color color4 = PenColors . Yellows . Yellow ; ColorWheel . addColor ( color1 ) ; ColorWheel . addColor ( color2 ) ; ColorWheel . addColor ( color3 ) ; ColorWheel . addColor ( color4 ) ; ColorWheel . addColor ( color4 ) ; ColorWheel . addColor ( color3 ) ; ColorWheel . addColor ( color2 ) ; ColorWheel . addColor ( color1 ) ; //  ------------- End of createColorPalette recipe --#8.3 }


Input: ------------- Recipe for DrawOctogon -- #9 . 2 [CODESPLIT] private static void drawOctogon ( ) { //     Do the following 8 times --#5.1 for ( int i = 0 ; i < 8 ; i ++ ) { //     Change the pen color of the line the tortoise draws to the next color on the color wheel --#3 Tortoise . setPenColor ( ColorWheel . getNextColor ( ) ) ; //     Move the tortoise 50 pixels --#2 Tortoise . move ( 50 ) ; //     Turn the tortoise 1/8th of 360 degrees to the right --#4 Tortoise . turn ( 360.0 / 8 ) ; //    End Repeat --#5.2  } //    ------------- End of drawOctogon recipe --#10.3 }


Input: Captures an image of the result of your program and displays it to you [CODESPLIT] public static void verify ( ) { try { Approvals . verify ( TURTLE . getImage ( ) ) ; } catch ( Exception e ) { throw ObjectUtils . throwAsError ( e ) ; } finally { TortoiseUtils . resetTurtle ( ) ; } }


Input: Calculate the <a href = http : // en . wikipedia . org / wiki / Taxicab_geometry > Manhattan Distance< / a > between two positions . [CODESPLIT] public static int getDistance ( Point start , Point end ) { return Math . abs ( start . x - end . x ) + Math . abs ( start . y - end . y ) ; }


Input: Create a copy of the puzzle where the blank swapped with the value in the target position [CODESPLIT] public Puzzle swapBlank ( int target ) { int [ ] copy = Arrays . copyOf ( cells , cells . length ) ; int x = copy [ target ] ; copy [ getBlankIndex ( ) ] = x ; copy [ target ] = 8 ; return new Puzzle ( copy ) ; }


Input: Calculate the distance between the goal by summing the distance between each cell and its goal . [CODESPLIT] public int getDistanceToGoal ( ) { int distance = 0 ; for ( int i = 0 ; i < cells . length ; i ++ ) { distance += getDistance ( i , cells [ i ] ) ; } return distance ; }


Input: Sets a sound that you can play through your speakers . Use a TKPSound ( there is a list ) <br > <b > Example : < / b > { [CODESPLIT] public synchronized void setSound ( TKPSound mySound ) { String sound = "soundFiles/" + mySound + ".wav" ; URL resource = this . getClass ( ) . getResource ( sound ) ; if ( resource == null ) { resource = this . getClass ( ) . getClassLoader ( ) . getResource ( sound ) ; } if ( resource == null ) { throw new IllegalStateException ( "Could not get TKPSound: " + sound ) ; } this . soundUrl = resource ; }


Input: Plays a TKPSound through your speakers . You must first set the TKPSound <br > <b > Example : < / b > { [CODESPLIT] public synchronized void playSound ( ) { final URL sound = this . soundUrl ; new Thread ( new Runnable ( ) { @ Override public void run ( ) { try { Clip clip = AudioSystem . getClip ( ) ; AudioInputStream inputStream = AudioSystem . getAudioInputStream ( sound ) ; clip . open ( inputStream ) ; clip . start ( ) ; } catch ( Exception e ) { System . out . println ( "play sound error: " + e . getMessage ( ) + " for " + sound ) ; } } } ) . start ( ) ; }


Input: Prints a formatted string to standard output using the specified format string and arguments and then flushes standard output . [CODESPLIT] public static void printf ( String format , Object ... args ) { out . printf ( LOCALE , format , args ) ; out . flush ( ) ; }


Input: Prints a formatted string to standard output using the locale and the specified format string and arguments ; then flushes standard output . [CODESPLIT] public static void printf ( Locale locale , String format , Object ... args ) { out . printf ( locale , format , args ) ; out . flush ( ) ; }


Input: Unit tests some of the methods in <tt > StdOut< / tt > . [CODESPLIT] public static void main ( String [ ] args ) { // write to stdout StdOut . println ( "Test" ) ; StdOut . println ( 17 ) ; StdOut . println ( true ) ; StdOut . printf ( "%.6f\n" , 1.0 / 7.0 ) ; }


Input: recipe for makeAFishyDecision with the numberOfFish [CODESPLIT] public static void makeAFishyDecision ( int numberOfFish ) { // Use a switch...case on the numberOfFish switch ( numberOfFish ) { // When the numberOfFish is -1 case - 1 : // Uncomment to create a string of this image String image = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/thumb-up.png" ; //  Create a new ImageIcon from your image ImageIcon icon = new ImageIcon ( image ) ; // Show a message with the fancy message box this text, this title and this icon... FancyMessageBox . showMesage ( "Had a Fish" , "Not hungry anymore..." , icon ) ; // End break ; // When the numberOfFish is 0   case 0 : // Uncomment to create a string of this image String image0 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/information.png" ; //  Create a new ImageIcon from your image ImageIcon icon0 = new ImageIcon ( image0 ) ; // Show a message with the fancy message box this text, this title and this icon... FancyMessageBox . showMesage ( "No Fish" , "Still hungry" , icon0 ) ; // End break ; // When the numberOfFish is 1     case 1 : // Uncomment to create a string of this image String image1 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/star.png" ; // Create a new ImageIcon from your image ImageIcon icon1 = new ImageIcon ( image1 ) ; // Show a message with the fancy message box this text, this title and this icon... FancyMessageBox . showMesage ( "One Fish" , "This one has a little star" , icon1 ) ; // End break ; // When the numberOfFish is 0     case 2 : // Uncomment to create a string of this image String image2 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/github.png" ; //  Create a new ImageIcon from your image ImageIcon icon2 = new ImageIcon ( image2 ) ; // Show a message with the fancy message box this text, this title and this icon... FancyMessageBox . showMesage ( "Two Fish" , "Funny things are everywhere" , icon2 ) ; // End break ; // Otherwise   default : // Uncomment to create a string of this image String image4 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/hint.png" ; // Create a new ImageIcon from your image ImageIcon icon4 = new ImageIcon ( image4 ) ; // Show a message with the fancy message box this text, this title and this icon... FancyMessageBox . showMesage ( "Vegetaraian meal" , "Fish are icky" , icon4 ) ; // End break ; } }


Input: Draws a line segment between ( <em > x< / em > <sub > 0< / sub > <em > y< / em > <sub > 0< / sub > ) and ( <em > x< / em > <sub > 1< / sub > <em > y< / em > <sub > 1< / sub > ) . [CODESPLIT] public static void line ( double x0 , double y0 , double x1 , double y1 ) { offscreen . draw ( new Line2D . Double ( scaleX ( x0 ) , scaleY ( y0 ) , scaleX ( x1 ) , scaleY ( y1 ) ) ) ; draw ( ) ; }


Input: Draws one pixel at ( <em > x< / em > <em > y< / em > ) . This method is private because pixels depend on the display . To achieve the same effect set the pen radius to 0 and call { @code point () } . [CODESPLIT] private static void pixel ( double x , double y ) { offscreen . fillRect ( ( int ) Math . round ( scaleX ( x ) ) , ( int ) Math . round ( scaleY ( y ) ) , 1 , 1 ) ; }


Input: Draws a point centered at ( <em > x< / em > <em > y< / em > ) . The point is a filled circle whose radius is equal to the pen radius . To draw a single - pixel point first set the pen radius to 0 . [CODESPLIT] public static void point ( double x , double y ) { double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double r = currentPenRadius ; float scaledPenRadius = ( float ) ( r * DEFAULT_SIZE ) ; if ( scaledPenRadius <= 1 ) pixel ( x , y ) ; else offscreen . fill ( new Ellipse2D . Double ( xs - scaledPenRadius / 2 , ys - scaledPenRadius / 2 , scaledPenRadius , scaledPenRadius ) ) ; draw ( ) ; }


Input: Draws a circle of the specified radius centered at ( <em > x< / em > <em > y< / em > ) . [CODESPLIT] public static void circle ( double x , double y , double radius ) { if ( ! ( radius >= 0 ) ) throw new IllegalArgumentException ( "radius must be nonnegative" ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * radius ) ; double hs = factorY ( 2 * radius ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Ellipse2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs ) ) ; draw ( ) ; }


Input: Draws an ellipse with the specified semimajor and semiminor axes centered at ( <em > x< / em > <em > y< / em > ) . [CODESPLIT] public static void ellipse ( double x , double y , double semiMajorAxis , double semiMinorAxis ) { if ( ! ( semiMajorAxis >= 0 ) ) throw new IllegalArgumentException ( "ellipse semimajor axis must be nonnegative" ) ; if ( ! ( semiMinorAxis >= 0 ) ) throw new IllegalArgumentException ( "ellipse semiminor axis must be nonnegative" ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * semiMajorAxis ) ; double hs = factorY ( 2 * semiMinorAxis ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Ellipse2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs ) ) ; draw ( ) ; }


Input: Draws a circular arc of the specified radius centered at ( <em > x< / em > <em > y< / em > ) from angle1 to angle2 ( in degrees ) . [CODESPLIT] public static void arc ( double x , double y , double radius , double angle1 , double angle2 ) { if ( radius < 0 ) throw new IllegalArgumentException ( "arc radius must be nonnegative" ) ; while ( angle2 < angle1 ) angle2 += 360 ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * radius ) ; double hs = factorY ( 2 * radius ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Arc2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs , angle1 , angle2 - angle1 , Arc2D . OPEN ) ) ; draw ( ) ; }