Calculate which point on the LineSegment is nearest to the given coordinate. Will be perpendicular or one of the
end-points.

@param c
The coordinate to check.
@return The point on the LineSegment nearest to the given coordinate.
515645
public Coordinate nearest(Coordinate c) {
		double len = this.getLength();

		double u = (c.getX() - this.c1.getX()) * (this.c2.getX() - this.c1.getX()) + (c.getY() - this.c1.getY())
				* (this.c2.getY() - this.c1.getY());
		u = u / (len * len);

		if (u < 0.00001 || u > 1) {
			// Shortest point not within LineSegment, so take closest end-point.
			LineSegment ls1 = new LineSegment(c, this.c1);
			LineSegment ls2 = new LineSegment(c, this.c2);
			double len1 = ls1.getLength();
			double len2 = ls2.getLength();
			if (len1 < len2) {
				return this.c1;
			}
			return this.c2;
		} else {
			// Intersecting point is on the line, use the formula: P = P1 + u (P2 - P1)
			double x1 = this.c1.getX() + u * (this.c2.getX() - this.c1.getX());
			double y1 = this.c1.getY() + u * (this.c2.getY() - this.c1.getY());
			return new Coordinate(x1, y1);
		}
	}
54985
def get_closest_point_to_line(A, B, P):
    '''
    
    '''
    AP = XYPoint(P.x - A.x, P.y - A.y)
    AB = XYPoint(B.x - A.x, B.y - A.y)
    ab2 = AB.x * AB.x + AB.y * AB.y
    ap_ab = AP.x * AB.x + AP.y * AB.y
    t = ap_ab / ab2

    if t < 0.0:
        t = 0.0
    elif t > 1.0:
        t = 1.0

    return XYPoint(A.x + AB.x * t, A.y + AB.y * t)
307808
int selectCorner( GridInfo info ) {

		info.lookupGridCorners(cornerList);

		int bestCorner = -1;
		double bestScore = Double.MAX_VALUE;
		boolean bestIsCornerSquare = false;

		for (int i = 0; i < cornerList.size(); i++) {
			Node n = cornerList.get(i);

			boolean corner = isCornerValidOrigin(n);

			// If there are no corner points which are valid corners, then any corner can be the origin if
			// allowNoCorner is true
			if( corner || (allowNoCorner && !bestIsCornerSquare) ) {
				// sanity check the shape
				if( checkShape != null ) {
					if( i%2==0 ) {
						if( !checkShape.isValidShape(info.rows,info.cols)) {
							continue;
						}
					} else {
						if( !checkShape.isValidShape(info.cols,info.rows)) {
							continue;
						}
					}
				}

				// If the distance is to (0,0) pixel is smaller or this is a corner square and the other best
				// is not a corner square
				double distance = n.normSq();
				if( distance < bestScore || (!bestIsCornerSquare && corner )) {
					bestIsCornerSquare |= corner;
					bestScore = distance;
					bestCorner = i;
				}
			}
		}
		info.hasCornerSquare = bestIsCornerSquare;
		return bestCorner;
	}
1251505
public static double getClockwiseAngleBetweenThreePoints(final Point2D p0, final Point2D c, final Point2D p1)
    {
        final Point2D a = c.sub(p1);

        final Point2D b = c.sub(p0);

        return Math.atan2(a.getY(), a.getX()) - Math.atan2(b.getY(), b.getX());
    }
944943
public void getClosestPoint(Vector2f point, Vector2f result) {
		loc.set(point);
		loc.sub(start);

		float projDistance = vec.dot(loc);

		projDistance /= vec.lengthSquared();

		if (projDistance < 0) {
			result.set(start);
			return;
		}
		if (projDistance > 1) {
			result.set(end);
			return;
		}

		result.x = start.getX() + projDistance * vec.getX();
		result.y = start.getY() + projDistance * vec.getY();
	}
786560
public static boolean intersects(Geometry one, Geometry two) {
		if (one == null || two == null || isEmpty(one) || isEmpty(two)) {
			return false;
		}
		if (Geometry.POINT.equals(one.getGeometryType())) {
			return intersectsPoint(one, two);
		} else if (Geometry.LINE_STRING.equals(one.getGeometryType())) {
			return intersectsLineString(one, two);
		} else if (Geometry.MULTI_POINT.equals(one.getGeometryType())
				|| Geometry.MULTI_LINE_STRING.equals(one.getGeometryType())) {
			return intersectsMultiSomething(one, two);
		}
		List<Coordinate> coords1 = new ArrayList<Coordinate>();
		List<Coordinate> coords2 = new ArrayList<Coordinate>();
		getAllCoordinates(one, coords1);
		getAllCoordinates(two, coords2);

		for (int i = 0; i < coords1.size() - 1; i++) {
			for (int j = 0; j < coords2.size() - 1; j++) {
				if (MathService.intersectsLineSegment(coords1.get(i), coords1.get(i + 1), coords2.get(j),
						coords2.get(j + 1))) {
					return true;
				}
			}
		}
		return false;
	}
363878
protected SegmentType getSegmentType(JComponent c) {
        Object      buttonType  = c.getClientProperty("JButton.buttonType");
        SegmentType segmentType = SegmentType.NONE;

        if (buttonType != null && buttonType instanceof String && ((String) buttonType).startsWith("segmented")) {
            String position = (String) c.getClientProperty("JButton.segmentPosition");

            if ("first".equals(position)) {
                segmentType = SegmentType.FIRST;
            } else if ("middle".equals(position)) {
                segmentType = SegmentType.MIDDLE;
            } else if ("last".equals(position)) {
                segmentType = SegmentType.LAST;
            }
        }

        return segmentType;
    }
413808
function closestPointnd(c, positions, x, result) {
  var D = numeric.rep([c.length, c.length], 0.0);
  var dvec = numeric.rep([c.length], 0.0);
  for(var i=0; i<c.length; ++i) {
    var pi = positions[c[i]];
    dvec[i] = numeric.dot(pi, x);
    for(var j=0; j<c.length; ++j) {
      var pj = positions[c[j]];
      D[i][j] = D[j][i] = numeric.dot(pi, pj);
    }
  }
  var A = numeric.rep([c.length, c.length+2], 0.0);
  var b = numeric.rep([c.length+2], 0.0);
  b[0] = 1.0-EPSILON;
  b[1] = -(1.0+EPSILON);
  for(var i=0; i<c.length; ++i) {
    A[i][0]   = 1;
    A[i][1]   = -1
    A[i][i+2] = 1;
  }
  for(var attempts=0; attempts<15; ++attempts) {
    var fortran_poop = numeric.solveQP(D, dvec, A, b);
    if(fortran_poop.message.length > 0) {
      //Quadratic form may be singular, perturb and resolve
      for(var i=0; i<c.length; ++i) {
        D[i][i] += 1e-8;
      }
      continue;
    } else if(isNaN(fortran_poop.value[0])) {
      break;
    } else {
      //Success!
      var solution = fortran_poop.solution;
      for(var i=0; i<x.length; ++i) {
        result[i] = 0.0;
        for(var j=0; j<solution.length; ++j) {
          result[i] += solution[j] * positions[c[j]][i];
        }
      }
      return 2.0 * fortran_poop.value[0] + numeric.dot(x,x);
    }
  }
  for(var i=0; i<x.length; ++i) {
    result[i] = Number.NaN;
  }
  return Number.NaN;
}
680543
private Stack grahamScan(Coordinate[] c) {
        Coordinate p;
        Stack ps = new Stack();
        p = (Coordinate) ps.push(c[0]);
        p = (Coordinate) ps.push(c[1]);
        p = (Coordinate) ps.push(c[2]);
        for (int i = 3; i < c.length; i++) {
            p = (Coordinate) ps.pop();
            // check for empty stack to guard against robustness problems
            while (
                    ! ps.empty() &&
                            CGAlgorithms.computeOrientation((Coordinate) ps.peek(), p, c[i]) > 0) {
                p = (Coordinate) ps.pop();
            }
            p = (Coordinate) ps.push(p);
            p = (Coordinate) ps.push(c[i]);
        }
        p = (Coordinate) ps.push(c[0]);
        return ps;
    }
202827
private double computeAngle(RoadPolyline segment, boolean fromStartPoint) {
		double angle = Double.NaN;
		Point2d p1 = null;
		Point2d p2 = null;
		if (segment.getPointCount() > 1) {
			if (fromStartPoint) {
				final RoadConnection startPoint = segment.getBeginPoint(StandardRoadConnection.class);
				if (startPoint == this) {
					p1 = startPoint.getPoint();
					p2 = segment.getPointAt(1);
					// Because the Y axis is directly to the bottom of the screen
					// it is necessary to invert it to reply an counterclockwise angle
					angle = MathUtil.clampCyclic(
							Vector2D.signedAngle(
									1, 0, p2.getX() - p1.getX(), p1.getY() - p2.getY()),
							0, MathConstants.TWO_PI);
				} else {
					throw new IllegalArgumentException(
							Locale.getString("ERROR_ALREADY_CONNECTED_START", //$NON-NLS-1$
									segment,
									p1,
									p2,
									startPoint));
				}
			} else {
				final RoadConnection endPoint = segment.getEndPoint(StandardRoadConnection.class);
				if (endPoint == this) {
					p1 = endPoint.getPoint();
					p2 = segment.getAntepenulvianPoint();
					// Because the Y axis is directly to the bottom of the screen
					// it is necessary to invert it to reply an counterclockwise angle
					angle = MathUtil.clampCyclic(
							Vector2D.signedAngle(
									1, 0, p2.getX() - p1.getX(), p1.getY() - p2.getY()),
							0, MathConstants.TWO_PI);
				} else {
					throw new IllegalArgumentException(
							Locale.getString("ERROR_ALREADY_CONNECTED_END", //$NON-NLS-1$
									segment,
									p1,
									p2,
									endPoint));
				}
			}

			if (Double.isNaN(angle) || Double.isInfinite(angle)) {
				throw new IllegalArgumentException(
						Locale.getString("ERROR_SAME_POINTS", //$NON-NLS-1$
								segment, p1, p2));
			}
		} else {
			throw new IllegalArgumentException(
					Locale.getString("ERROR_NOT_ENOUGH_POINTS", //$NON-NLS-1$
							segment));
		}

		return angle;
	}
2544
public boolean containsPoint(INDArray point) {
        double first = point.getDouble(0), second = point.getDouble(1);
        return x - hw <= first && x + hw >= first && y - hh <= second && y + hh >= second;
    }
583746
public static List<LineString> getSectionsFromCoordinates( List<Coordinate> coordinates, double width ) {

        if (coordinates.size() < 3) {
            throw new IllegalArgumentException("This method works only on lines with at least 3 coordinates.");
        }
        double halfWidth = width / 2.0;
        List<LineString> linesList = new ArrayList<LineString>();
        // first section
        Coordinate centerCoordinate = coordinates.get(0);
        LineSegment l1 = new LineSegment(centerCoordinate, coordinates.get(1));
        Coordinate leftCoordinate = l1.pointAlongOffset(0.0, halfWidth);
        Coordinate rightCoordinate = l1.pointAlongOffset(0.0, -halfWidth);
        LineString lineString = geomFactory.createLineString(new Coordinate[]{leftCoordinate, centerCoordinate, rightCoordinate});
        linesList.add(lineString);

        for( int i = 1; i < coordinates.size() - 1; i++ ) {
            Coordinate previous = coordinates.get(i - 1);
            Coordinate current = coordinates.get(i);
            Coordinate after = coordinates.get(i + 1);

            double firstAngle = azimuth(current, previous);
            double secondAngle = azimuth(current, after);

            double a1 = min(firstAngle, secondAngle);
            double a2 = max(firstAngle, secondAngle);

            double centerAngle = a1 + (a2 - a1) / 2.0;

            AffineTransformation rotationInstance = AffineTransformation.rotationInstance(-toRadians(centerAngle), current.x,
                    current.y);

            LineString vertical = geomFactory.createLineString(new Coordinate[]{new Coordinate(current.x, current.y + halfWidth),
                    current, new Coordinate(current.x, current.y - halfWidth)});
            Geometry transformed = rotationInstance.transform(vertical);
            linesList.add((LineString) transformed);
        }

        // last section
        centerCoordinate = coordinates.get(coordinates.size() - 1);
        LineSegment l2 = new LineSegment(centerCoordinate, coordinates.get(coordinates.size() - 2));
        leftCoordinate = l2.pointAlongOffset(0.0, halfWidth);
        rightCoordinate = l2.pointAlongOffset(0.0, -halfWidth);
        lineString = geomFactory.createLineString(new Coordinate[]{leftCoordinate, centerCoordinate, rightCoordinate});
        linesList.add(lineString);

        return linesList;
    }
1299253
public Vector3 findClosePoint(Vector3 pointToDelete) {
		Triangle triangle = find(pointToDelete);
		Vector3 p1 = triangle.p1();
		Vector3 p2 = triangle.p2();
		double d1 = distanceXY(p1, pointToDelete);
		double d2 = distanceXY(p2, pointToDelete);
		if(triangle.isHalfplane()) {
			if(d1<=d2) {
				return p1;
			}
			else {
				return p2;
			}
		} else {
			Vector3 p3 = triangle.p3();

			double d3 = distanceXY(p3, pointToDelete);

			if(d1<=d2 && d1<=d3) {
				return p1;
			}
			else if(d2<=d1 && d2<=d3) {
				return p2;
			}
			else {
				return p3;
			}
		}
	}
598014
public static Point closestInteriorPoint (IRectangle r, IPoint p, Point out) {
        out.set(MathUtil.clamp(p.x(), r.minX(), r.maxX()),
                MathUtil.clamp(p.y(), r.minY(), r.maxY()));
        return out;
    }
878109
private Coordinate[] getOrderedNodes( Coordinate c, Coordinate coordinate1, Coordinate coordinate2, Coordinate coordinate3 ) {
        double d = distance3d(c, coordinate1, null);
        Coordinate nearest = coordinate1;
        Coordinate c2 = coordinate2;
        Coordinate c3 = coordinate3;

        double d2 = distance3d(c, coordinate2, null);
        if (d2 < d) {
            nearest = coordinate2;
            d = d2;
            c2 = coordinate1;
            c3 = coordinate3;
        }
        double d3 = distance3d(c, coordinate3, null);
        if (d3 < d) {
            nearest = coordinate3;
            c2 = coordinate1;
            c3 = coordinate2;
        }
        return new Coordinate[]{nearest, c2, c3};
    }
106629
public Point getLegendPosition(int lineNr, int chainNr) {
		int x = DEFAULT_X_SPACE ;

		int y = lineNr * DEFAULT_Y_STEP + DEFAULT_Y_SPACE;

		y += chainNr * DEFAULT_LINE_SEPARATION;

		Point p = new Point(x,y);
		return p;
	}
1204459
public double getDistanceToCenter(Point point) {
        return Nd4j.getExecutioner().execAndReturn(
                        ClusterUtils.createDistanceFunctionOp(distanceFunction, center.getArray(), point.getArray()))
                        .getFinalResult().doubleValue();
    }