sort the corners of a given quadrilateral of the type
    corners : [ [xi,yi],... ]

    to an anti-clockwise order starting with the bottom left corner

    or (if plotted as image where y increases to the bottom):
    clockwise, starting top left
971366
def sortCorners(corners):
    '''
    
    '''
    corners = np.asarray(corners)
    # bring edges in order:
    corners2 = corners[ConvexHull(corners).vertices]
   
    if len(corners2) == 3:
        # sometimes ConvexHull one point is missing because it is
        # within the hull triangle
        # find the right position of set corner as the minimum perimeter
        # built with that point as different indices
        for c in corners:
            if c not in corners2:
                break
        perimeter = []
        for n in range(0, 4):
            corners3 = np.insert(corners2, n, c, axis=0)
            perimeter.append(
                np.linalg.norm(
                    np.diff(
                        corners3,
                        axis=0),
                    axis=1).sum())
        n = np.argmin(perimeter)
        corners2 = np.insert(corners2, n, c, axis=0)

    # find the edge with the right angle to the quad middle:
    mn = corners2.mean(axis=0)
    d = (corners2 - mn)
    ascent = np.arctan2(d[:, 1], d[:, 0])
    bl = np.abs(BL_ANGLE + ascent).argmin()
    # build a index list starting with bl:
    i = list(range(bl, 4))
    i.extend(list(range(0, bl)))
    return corners2[i]
59118
void handleAmbiguousVertexes(List<ChessboardCorner> corners) {
		List<Vertex> candidates = new ArrayList<>();
		for (int idx = 0; idx < vertexes.size(); idx++) {
			Vertex target = vertexes.get(idx);

			// median distance was previously found based on the closer neighbors. In an actual chessboard
			// there are solid white and black squares with no features, in theory
			double threshold = target.neighborDistance *ambiguousTol;

			candidates.clear();
			// only need to search parallel since perpendicular nodes won't be confused for the target
			for (int i = 0; i < target.parallel.size(); i++) {
				Edge c = target.parallel.get(i);
				if( c.distance <= threshold ) {
					candidates.add(c.dst);
				}
			}

			if( candidates.size() > 0 ) {
				candidates.add(target);

				int bestIndex = -1;
				double bestScore = 0;

//				System.out.println("==== Resolving ambiguity. src="+target.index);
				for (int i = 0; i < candidates.size(); i++) {
					Vertex v = candidates.get(i);
//					System.out.println("   candidate = "+v.index);
					double intensity = corners.get(v.index).intensity;
					if( intensity > bestScore ) {
						bestScore = intensity;
						bestIndex = i;
					}
				}
//				System.out.println("==== Resolved ambiguity. Selected "+candidates.get(bestIndex).index);

				for (int i = 0; i < candidates.size(); i++) {
					if( i == bestIndex )
						continue;
					removeReferences(candidates.get(i),EdgeType.PARALLEL);
					removeReferences(candidates.get(i),EdgeType.PERPENDICULAR);
				}
			}
		}
	}
1007809
private List<Coordinate> sortX(List<Coordinate> coordinates) {
		List<Coordinate> sorted = new ArrayList<Coordinate>(coordinates);
		Collections.sort(sorted, new XComparator());
		return sorted;
	}
1172982
private List<Coordinate> sortY(List<Coordinate> coordinates) {
		List<Coordinate> sorted = new ArrayList<Coordinate>(coordinates);
		Collections.sort(sorted, new YComparator());
		return sorted;
	}
1305582
def rotate_orth(self, quads):
        ""
        with _LeptonicaErrorTrap():
            return Pix(lept.pixRotateOrth(self._cdata, quads))
461100
def rectangle(self, x0, y0, x1, y1):
        """"""
        x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
        self.polyline([[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]])
1329509
function ( axis, startX, startY, endX, endY ) {
        var result = 'none';

        if ( axis == 'horizontal' ) {
            if ( startX > endX ) {
                result = 'left';
            } else if ( startX < endX ) {
                result = 'right';
            }
        } else {
            if ( startY > endY ) {
                result = 'top';
            } else if ( startY < endY ) {
                result = 'bottom';
            }
        }

        return result;
    }
123484
public static void sort(int n, int[] Xip, int Xip_offset, int[] Xlen, int Xlen_offset,
			double[] LU, int[] Tp, int[] Tj, double[] Tx, int[] W)
	{
		/*int[]*/double[] Xi ;
		double[] Xx ;
		int p, i, j, nz, tp, xlen, pend ;
		int[] len = new int[1] ;
		int[] Xi_offset = new int[1] ;
		int[] Xx_offset = new int[1] ;

		ASSERT (klu_valid_LU (n, FALSE, Xip, Xip_offset, Xlen, Xlen_offset, LU)) ;

		/* count the number of entries in each row of L or U */
		for (i = 0 ; i < n ; i++)
		{
			W [i] = 0 ;
		}
		for (j = 0 ; j < n ; j++)
		{
			Xi = Xx = GET_POINTER (LU, Xip, Xip_offset, Xlen, Xlen_offset, Xi_offset, Xx_offset, j, len) ;
			for (p = 0 ; p < len[0] ; p++)
			{
				W [(int) Xi [Xi_offset[0] + p]]++ ;
			}
		}

		/* construct the row pointers for T */
		nz = 0 ;
		for (i = 0 ; i < n ; i++)
		{
			Tp [i] = nz ;
			nz += W [i] ;
		}
		Tp [n] = nz ;
		for (i = 0 ; i < n ; i++)
		{
			W [i] = Tp [i] ;
		}

		/* transpose the matrix into Tp, Ti, Tx */
		for (j = 0 ; j < n ; j++)
		{
			Xi = Xx = GET_POINTER (LU, Xip, Xip_offset, Xlen, Xlen_offset, Xi_offset, Xx_offset, j, len) ;
			for (p = 0 ; p < len[0] ; p++)
			{
				tp = W [(int) Xi [Xi_offset[0] + p]]++ ;
				Tj [tp] = j ;
				Tx [tp] = Xx [Xx_offset[0] + p] ;
			}
		}

		/* transpose the matrix back into Xip, Xlen, Xi, Xx */
		for (j = 0 ; j < n ; j++)
		{
			W [j] = 0 ;
		}
		for (i = 0 ; i < n ; i++)
		{
			pend = Tp [i+1] ;
			for (p = Tp [i] ; p < pend ; p++)
			{
				j = Tj [p] ;
				Xi = Xx = GET_POINTER (LU, Xip, Xip_offset, Xlen, Xlen_offset, Xi_offset, Xx_offset, j, len) ;
				xlen = W [j]++ ;
				Xi [Xi_offset[0] + xlen] = i ;
				Xx [Xx_offset[0] + xlen] = Tx [p] ;
			}
		}

		ASSERT (klu_valid_LU (n, FALSE, Xip, Xip_offset, Xlen, Xlen_offset, LU)) ;
	}
312331
function orderBy(dimension, direction) {
  if (arguments.length === 1) {
    direction = 'ASCENDING'
  }

  if (!dimension) {
    throw new FieldError('Dimension is not specified')
  }
  else if (!~['ascending', 'descending'].indexOf(direction.toLowerCase())) {
    throw new FieldError('Bad orderBy direction: ' + direction)
  }

  return {
    dimension: dimension,
    direction: direction
  }
}
1016668
def _compute_sorted_indices(self):
        
        sorted_indices = []
        for to_sort in [self.y] + self.x:
            data_w_indices = [(val, i) for (i, val) in enumerate(to_sort)]
            data_w_indices.sort()
            sorted_indices.append([i for val, i in data_w_indices])
        # save in meaningful variable names
        self._yi_sorted = sorted_indices[0]  # list (like self.y)
        self._xi_sorted = sorted_indices[1:]
945139
def permute(self, ordering: np.ndarray, axis: int) -> None:
		
		if self._file.__contains__("tiles"):
			del self._file['tiles']

		ordering = list(np.array(ordering).flatten())  # Flatten the ordering, in case we got a column vector
		self.layers._permute(ordering, axis=axis)
		if axis == 0:
			self.row_attrs._permute(ordering)
			self.row_graphs._permute(ordering)
		if axis == 1:
			self.col_attrs._permute(ordering)
			self.col_graphs._permute(ordering)
138260
def sort(m, reverse=False):
    """"""
    ty = type(m)
    if ty == matrix:
        m = list(m)
    m = sorted(m, reverse=reverse)
    if ty == matrix:
        m = matrix(m)
    return m
811556
def vert_opposites_per_edge(self):
        """"""
        result = {}
        for f in self.f:
            for i in range(3):
                key = [f[i], f[(i+1)%3]]
                key.sort()
                key = tuple(key)
                val = f[(i+2)%3]

                if key in result:
                    result[key].append(val)
                else:
                    result[key] = [val]
        return result
425920
def _get_bins(self, kind, order, reverse=False):
        

        if kind == "radius":
            start = self.max_radius * self.radius_inner
            end = self.max_radius

        elif kind == "angle":
            start = self.start_angle
            end = self.start_angle + 2 * np.pi

        bounds = np.linspace(start, end, len(order) + 1)
        bins = np.vstack([bounds[:-1], bounds[1:]]).T

        if reverse:
            bins = bins[::-1]

        return dict(zip(order, bins))
1372607
public boolean orderSquareCorners( SquareGrid grid ) {

		// the first pass interleaves every other row
		for (int row = 0; row < grid.rows; row++) {

			for (int col = 0; col < grid.columns; col++) {
				orderNodeGrid(grid, row, col);
				Polygon2D_F64 square = grid.get(row,col).square;

				for (int i = 0; i < 4; i++) {
					square.vertexes.data[i] = ordered[i];
				}
			}
		}

		return true;
	}
1046540
def next(self):
        """"""
        left = next(self.seq_left)
        if self.width is None:
            self.width = len(left) / self.nplanes_left
        if self.bitdepth is None:
            # Detect bitdepth
            if hasattr(left, 'itemsize'):  # array
                self.bitdepth = left.itemsize * 8
            elif isinstance(left, (bytes, bytearray)):  # bytearray
                self.bitdepth = 8
            else:
                raise Error("Unknown bitdepth for merging planes")
        right = next(self.seq_right)
        rowlength = self.nplanes_res * self.width
        new = self.newarray(rowlength)
        if type(left) == type(right) == type(new):
            # slice assignment
            for i in range(self.nplanes_left):
                new[i::self.nplanes_res] = left[i::self.nplanes_left]
            for i in range(self.nplanes_right):
                i_ = i + self.nplanes_left
                new[i_::self.nplanes_res] = right[i::self.nplanes_right]
        else:
            for i in range(self.nplanes_left):
                for j in range(self.width):
                    new[(i * self.nplanes_res) + j] =\
                        left[(i * self.nplanes_left) + j]
            for i in range(self.nplanes_right):
                i_ = i + self.nplanes_left
                for j in range(self.width):
                    new[(i_ * self.nplanes_res) + j] =\
                        right[(i * self.nplanes_right) + j]
        return new
664698
private void moveAtFirst(int n_from) {
		int eT = elements[0];
		int eF = elements[n_from];
		positions[eT] = -1;
		positions[eF] = 0;
		elements[0] = eF;
		elements[n_from] = -1;
	}