calculate the count lines in the image with most points
189885
private ImageDeskew.HoughLine[] getTop(int count) {

        ImageDeskew.HoughLine[] hl = new ImageDeskew.HoughLine[count];
        for (int i = 0; i < count; i++) {
            hl[i] = new ImageDeskew.HoughLine();
        }

        ImageDeskew.HoughLine tmp;

        for (int i = 0; i < (this.cHMatrix.length - 1); i++) {
            if (this.cHMatrix[i] > hl[count - 1].count) {
                hl[count - 1].count = this.cHMatrix[i];
                hl[count - 1].index = i;
                int j = count - 1;
                while ((j > 0) && (hl[j].count > hl[j - 1].count)) {
                    tmp = hl[j];
                    hl[j] = hl[j - 1];
                    hl[j - 1] = tmp;
                    j--;
                }
            }
        }

        int alphaIndex;
        int dIndex;
        
        for (int i = 0; i < count; i++) {
            dIndex = hl[i].index / cSteps; // integer division, no
            // remainder
            alphaIndex = hl[i].index - dIndex * cSteps;
            hl[i].alpha = getAlpha(alphaIndex);
            hl[i].d = dIndex + cDMin;
        }

        return hl;
    }
244679
def finite_pixels(self):
        
        finite_px = np.where(np.isfinite(self.data))
        finite_px = np.c_[finite_px[0], finite_px[1]]
        return finite_px
183244
private int getTotalLandscapePointsInPage(CriterionBidLandscapePage page) {
    if (page.getEntries() == null) {
      return 0;
    }
    int totalLandscapePointsInPage = 0;
    for (CriterionBidLandscape criterionBidLandscape : page.getEntries()) {
      totalLandscapePointsInPage += criterionBidLandscape.getLandscapePoints().length;
    }
    return totalLandscapePointsInPage;
  }
1286044
function imageBounding(image) {
  var imageObj = element_object(image);
  if (!imageObj) return null;

  if (!imageObj.transform) imageObj.transform = 'matrix(1 0 0 1 0 0)';
  var matrix = helper.matrixStrToArr(imageObj.transform.trim());
  var width = imageObj.width;
  var height = imageObj.height;

  // The matrix variable contains 6 numbers, let's call them
  // a, b, c, d, e, f
  var a = matrix[0];
  var b = matrix[1];
  var c = matrix[2];
  var d = matrix[3];
  var e = matrix[4];
  var f = matrix[5];

  // The original top left point of the image is unknown. The e and f
  // in the matrix is the transformed top left point.
  // Now assume translate is applied to the image first, we have the
  // following points: (e, f), (e+w, f), (e+w, f+h), (e, f+h)
  var points1 = [e, f, e + width, f, e + width, f + height, e, f + height];

  // Then apply trasform matrix (a b c d 0 0) to these points, the
  // formula is newX = a*x + c*y, newY = b*x + d*y
  var points2 = [];
  for (var i = 0; i < points1.length; i += 2) {
    points2[i] = a * points1[i] + c * points1[i + 1];
    points2[i + 1] = b * points1[i] + d * points1[i + 1];
  }

  // Find the delta of the top left point and apply it to all the points
  var dx = points2[0] - points1[0];
  var dy = points2[1] - points1[1];
  var points = [e, f];
  for (var i = 2; i < points1.length; i += 2) {
    points[i] = points2[i] - dx;
    points[i + 1] = points2[i + 1] - dy;
  }

  var left = Number.POSITIVE_INFINITY;
  var right = Number.NEGATIVE_INFINITY;
  var top = Number.POSITIVE_INFINITY;
  var bottom = Number.NEGATIVE_INFINITY;

  for (var i = 0; i < points.length; i += 2) {
    if (points[i] < left) left = points[i];
    if (points[i] > right) right = points[i];
    if (points[i + 1] < top) top = points[i + 1];
    if (points[i + 1] > bottom) bottom = points[i + 1];
  }

  return {
    left: left,
    right: right,
    top: top,
    bottom: bottom,
    width: right - left,
    height: bottom - top
  };
}
879569
public static void countRegionPixels(GrayS32 labeled , int totalRegions , int counts[] ) {

		Arrays.fill(counts,0,totalRegions,0);

		for( int y = 0; y < labeled.height; y++ ) {
			int index = labeled.startIndex + y*labeled.stride;
			for( int x = 0; x < labeled.width; x++ ) {
				counts[labeled.data[index++]]++;
			}
		}
	}
138043
private void calcOffsets()
    {
        //Find the longest line
        int rowidx[] = new int[rows.size()];
        int maxCells = 0;
        for (int r = 0; r < rows.size(); r++)
        {
            int count = rows.elementAt(r).getCellCount();
            if (count > maxCells) maxCells = count;
            rowidx[r] = 0;
            rows.elementAt(r).rewind();
        }
        
        //determine the cell positions
        int col = 0;
        boolean cell_found = true;
        while (cell_found)
        {
            cell_found = false;
            int r = 0;
            while (r < rows.size())
            {
                TableRowBox row = rows.elementAt(r);
                if (row.hasNext())
                {
                    cell_found = true;
                    if (rowidx[r] <= col) //we are not in the middle of some colspan for this row
                    {
                        //get the current element
                        TableCellBox cell = row.next();
                        //set the new position
                        cell.setCellPosition(rowidx[r], r);
                        //move the row indices
                        for (int nr = r; nr < r + cell.getRowspan(); nr++)
                        {
                            if (nr < rows.size())
                            {
                                rowidx[nr] += cell.getColspan();
                                if (rowidx[nr] > numCols) numCols = rowidx[nr]; 
                            }
                            else
                                cell.rowspan--;
                        }
                        r += cell.getRowspan();
                    }
                    else
                        r++;
                }
                else
                    r++;
            }
            col++;
        }    
        //build the cell array
        for (int i = 0; i < rows.size(); i++)
            rows.elementAt(i).rewind();
        cells = new TableCellBox[numCols][rows.size()];
        for (int c = 0; c < maxCells; c++)
        {
            for (int r = 0; r < rows.size(); r++)
            {
                TableRowBox row = rows.elementAt(r);
                if (row.hasNext())
                {
                    TableCellBox cell = row.next();
                    if (cell.getRow() + cell.getRowspan() > rows.size())
                        cell.setRowspan(rows.size() - cell.getRow());
                    if (cell.getColumn() + cell.getColspan() > numCols)
                        cell.setColspan(numCols - cell.getColumn());
                    
                    int endrow = cell.getRow() + cell.getRowspan();
                    int endcol = cell.getColumn() + cell.getColspan();
                    //add it to the mesh
                    for (int nr = cell.getRow(); nr < endrow; nr++)
                        for (int nc = cell.getColumn(); nc < endcol; nc++)
                            cells[nc][nr] = cell;
                }
            }
        }
    }
1306473
def get_curr_lines(self):
        
        start = max(0, self._coord.line - 5)
        end = min(len(self._template_lines), self._coord.line + 4)

        lines = [(x, self._template_lines[x]) for x in six.moves.range(start, end, 1)]
        return self._coord.line, lines
142655
def _total_rectangles(tree):
    '''
    
    '''
    return sum(len(sec.children) + sec.points.shape[0] - 1
               for sec in tree.iter_sections())
683726
int getLineCount() {
       
        if ( lineCount > -1 ) return lineCount;
        
        lineMetrics.clear();
        double totLines = 0.0, prevMinY = 1.0, prevMaxY = -1.0;
        int totCharSoFar = 0;

        for ( Node n : children ) {
           
            Bounds nodeBounds = n.getBoundsInParent();
            int length = (n instanceof Text) ? ((Text) n).getText().length() : 1;
            PathElement[] shape = flow.rangeShape( totCharSoFar, totCharSoFar+length );
            double lines = Math.max( 1.0, Math.floor( shape.length / 5 ) );
            double nodeMinY = Math.max( 0.0, nodeBounds.getMinY() );
            
            if ( nodeMinY >= prevMinY && lines > 1 )  totLines += lines - 1;  // Multiline Text node 
            else if ( nodeMinY >= prevMaxY )  totLines += lines;

            if ( lineMetrics.size() < totLines ) {                            // Add additional lines
               
                if ( shape.length == 0 ) {
                   lineMetrics.add( new TextFlowSpan( totCharSoFar, length, nodeMinY, nodeBounds.getWidth(), nodeBounds.getHeight() ) );
                    totCharSoFar += length;
                }
                else for ( int ele = 1; ele < shape.length; ele += 5 ) {
                    // Calculate the segment's line's length and width up to this point
                    LineTo eleLine = (LineTo) shape[ele];
                    double segWidth = eleLine.getX(), lineMinY = eleLine.getY();
                    double charHeight = ((LineTo) shape[ele+1]).getY() - lineMinY;
                    Point2D endPoint = new Point2D( segWidth-1, lineMinY + charHeight / 2 );

                    // hitTest queries TextFlow layout internally and returns the position of the
                    // last char (nearest endPoint) on the line, irrespective of the current Text node !
                    int segLen = flow.hitTest( endPoint ).getCharIndex();
                    segLen -= totCharSoFar - 1;

                    if ( ele == 1 && nodeMinY < prevMaxY ) {
                        adjustLineMetrics( segLen, segWidth - ((MoveTo) shape[ele-1]).getX(), charHeight );
                    }
                    else {
                       lineMetrics.add( new TextFlowSpan( totCharSoFar, segLen, lineMinY, segWidth, charHeight ) );
                    }

                    totCharSoFar += segLen;
                }
            }
            else {
                // Adjust current line metrics with additional Text or Node embedded in this line 
                adjustLineMetrics( length, nodeBounds.getWidth(), nodeBounds.getHeight() );
                totCharSoFar += length;
            }

            prevMaxY = nodeBounds.getMaxY();
            prevMinY = nodeMinY;
        }
        
        lineCount = (int) totLines;
        return lineCount;
    }
52560
def findViewsContainingPoint(self, (x, y), _filter=None):
        '''
        
        '''

        if not _filter:
            _filter = lambda v: True

        return [v for v in self.views if (v.containsPoint((x,y)) and _filter(v))]
844281
def count_lines(fname, mode='rU'):
    '''
    '''

    with open(fname, mode) as f:
        for i, l in enumerate(f):
            pass
    return i + 1
1169560
def sort(polylines):
    
    for n, c in enumerate(polylines):
        l = len(c)
        if l > 2:
            # DEFINE FIRST AND LAST INDEX A THOSE TWO POINTS THAT
            # HAVE THE BIGGEST DIFFERENCE FROM A MIDDLE:
            mid = c.mean(axis=0)

            distV = (c - mid)
            dists = norm(distV, axis=-1)

            firstI = np.argmax(dists)
            sign = np.sign(distV[firstI])

            dd = np.logical_or(np.sign(distV[:, 0]) != sign[0],
                               np.sign(distV[:, 1]) != sign[1])

            dists[~dd] = 0
            lastI = np.argmax(dists)

            ind = _sort(c, firstI, lastI)
            c = c[ind]
            polylines[n] = c
800662
def points(ys, width=None):
    '''
    '''
    if width is None:
        width = terminal.width()

    ys = np.array(ys)
    n = len(ys)
    y_min, y_max = np.min(ys), np.max(ys)
    n_bins = min(width, n)
    bins_per_n = float(n_bins) / float(n)
    # print n, n_bins, n_per_bin, bins_per_n
    sums = np.zeros(n_bins)
    counts = np.zeros(n_bins)
    for i, y in enumerate(ys):
        bin = int(i * bins_per_n)
        sums[bin] += y
        counts[bin] += 1
    bin_means = sums / counts
    # we want the lowest bin_height to be 0.0, and highest bin_height to be 1.0
    bin_heights = normalize(bin_means)
    bin_chars = (bin_heights * (len(terminal.bars) - 1)).astype(int)
    # print sums, counts, bin_means
    cells = [terminal.bars[bin_char] for bin_char in bin_chars]
    print '[%+f]' % y_max
    print u''.join(cells)
    print '[%+f]' % y_min
476937
protected void findBitCounts(GrayF32 gray , double threshold ) {
		// compute binary image using an adaptive algorithm to handle shadows
		ThresholdImageOps.threshold(gray,binaryInner,(float)threshold,true);

		Arrays.fill(counts, 0);
		for (int row = 0; row < gridWidth; row++) {
			int y0 = row * binaryInner.width / gridWidth + 2;
			int y1 = (row + 1) * binaryInner.width / gridWidth - 2;
			for (int col = 0; col < gridWidth; col++) {
				int x0 = col * binaryInner.width / gridWidth + 2;
				int x1 = (col + 1) * binaryInner.width / gridWidth - 2;

				int total = 0;
				for (int i = y0; i < y1; i++) {
					int index = i * binaryInner.width + x0;
					for (int j = x0; j < x1; j++) {
						total += binaryInner.data[index++];
					}
				}

				counts[row * gridWidth + col] = total;
			}
		}
	}
1109182
def count_selfintersections(self):
        
        # This can be solved more efficiently with sweep line
        counter = 0
        for i, j in itertools.combinations(range(len(self.lineSegments)), 2):
            inters = get_segments_intersections(self.lineSegments[i],
                                                self.lineSegments[j])
            if abs(i-j) > 1 and len(inters) > 0:
                counter += 1
        return counter
140768
def _drawLine(self, image):
        """"""
        w, h = image.size
        w *= 5
        h *= 5

        l_image = Image.new('RGBA', (w, h), (0, 0, 0, 0))
        l_draw = ImageDraw.Draw(l_image)

        x1 = int(w * random.uniform(0, 0.1))
        y1 = int(h * random.uniform(0, 1))
        x2 = int(w * random.uniform(0.9, 1))
        y2 = int(h * random.uniform(0, 1))

        # Line width modifier was chosen as an educated guess
        # based on default image area.
        l_width = round((w * h)**0.5 * 2.284e-2)

        # Draw
        l_draw.line(((x1, y1), (x2, y2)), fill=(0, 0, 0, 255), width=l_width)

        # Transform
        l_image = self._rndLineTransform(l_image)
        l_image = l_image.resize(image.size, resample=self.resample)

        # Paste onto image
        image.paste(l_image, (0, 0), l_image)
324130
def count_lines(self, code):
        
        return sum(bool(line.strip()) for line in code.splitlines())