Print statistics for the dead cells
496649
def printDeadCells(self):
    
    columnCasualties = numpy.zeros(self.numberOfColumns())
    for cell in self.deadCells:
      col = self.columnForCell(cell)
      columnCasualties[col] += 1
    for col in range(self.numberOfColumns()):
      print col, columnCasualties[col]
760959
def print_event_statistics(self):
        """"""
        logger.info('All events by type')
        logger.info('-------------------')
        for k, v in self.all_events.items():
            logger.info('%s, %s' % (k, len(v)))
        logger.info('-------------------')
1120765
def print_event_count():
    """"""
    for source in archive.list_event_sources():
        event_count = 0
        for group in archive.list_event_histogram(source):
            for rec in group.records:
                event_count += rec.count
        print('  {: <40} {: >20}'.format(source, event_count))
278138
def output_row(self, name):
        ""
        print("%10s        %4d     %0.3f        %0.3f        %0.3f"%(
            name, self.gold, self.precision(), self.recall(), self.fscore()))
1126571
@SuppressWarnings("deprecation")
	public final void printStatisticsHTML(Appendable out) throws IOException, E {
		// Get the data
		boolean myIsClosed;
		synchronized(poolLock) {
			myIsClosed = isClosed;
		}
		// Don't write while holding the lock to avoid possible blocking
		int numConnections;
		boolean[] isConnecteds;
		long[] createTimes;
		long[] connectCounts;
		long[] useCounts;
		long[] totalTimes;
		boolean[] isBusies;
		long[] startTimes;
		long[] releaseTimes;
		Throwable[] allocateStackTraces;
		synchronized(poolLock) {
			numConnections = allConnections.size();
			isConnecteds = new boolean[numConnections];
			createTimes = new long[numConnections];
			connectCounts = new long[numConnections];
			useCounts = new long[numConnections];
			totalTimes = new long[numConnections];
			isBusies = new boolean[numConnections];
			startTimes = new long[numConnections];
			releaseTimes = new long[numConnections];
			allocateStackTraces = new Throwable[numConnections];
			for(int c=0;c<numConnections;c++) {
				PooledConnection<C> pooledConnection = allConnections.get(c);
				isConnecteds[c] = pooledConnection.connection != null;
				createTimes[c] = pooledConnection.createTime;
				connectCounts[c] = pooledConnection.connectCount.get();
				useCounts[c] = pooledConnection.useCount.get();
				totalTimes[c] = pooledConnection.totalTime.get();
				isBusies[c] = busyConnections.contains(pooledConnection);
				startTimes[c] = pooledConnection.startTime;
				releaseTimes[c] = pooledConnection.releaseTime;
				allocateStackTraces[c] = pooledConnection.allocateStackTrace;
			}
		}
		long time = System.currentTimeMillis();
		long timeLen = time-startTime;

		// Print the stats
		out.append("<table style='border:1px;' cellspacing='0' cellpadding='2'>\n");
		printConnectionStats(out);
		out.append("  <tr><td>Max Connection Pool Size:</td><td>").append(Integer.toString(poolSize)).append("</td></tr>\n"
				+ "  <tr><td>Connection Clean Interval:</td><td>");
		com.aoindustries.util.EncodingUtils.encodeHtml(StringUtility.getDecimalTimeLengthString(delayTime), out);
		out.append("</td></tr>\n"
				+ "  <tr><td>Max Idle Time:</td><td>");
		com.aoindustries.util.EncodingUtils.encodeHtml(StringUtility.getDecimalTimeLengthString(maxIdleTime), out);
		out.append("</td></tr>\n"
				+ "  <tr><td>Max Connection Age:</td><td>");
		com.aoindustries.util.EncodingUtils.encodeHtml(maxConnectionAge==UNLIMITED_MAX_CONNECTION_AGE?"Unlimited":StringUtility.getDecimalTimeLengthString(maxConnectionAge), out);
		out.append("</td></tr>\n"
				+ "  <tr><td>Is Closed:</td><td>").append(Boolean.toString(myIsClosed)).append("</td></tr>\n"
				+ "</table>\n"
				+ "<br /><br />\n"
				+ "<table style='border:1px;' cellspacing='0' cellpadding='2'>\n"
				+ "  <tr><th colspan='11'><span style='font-size:large;'>Connections</span></th></tr>\n"
				+ "  <tr>\n"
				+ "    <th>Connection #</th>\n"
				+ "    <th>Is Connected</th>\n"
				+ "    <th>Conn Age</th>\n"
				+ "    <th>Conn Count</th>\n"
				+ "    <th>Use Count</th>\n"
				+ "    <th>Total Time</th>\n"
				+ "    <th>% of Time</th>\n"
				+ "    <th>State</th>\n"
				+ "    <th>State Time</th>\n"
				+ "    <th>Ave Trans Time</th>\n"
				+ "    <th>Stack Trace</th>\n"
				+ "  </tr>\n");

		int totalConnected = 0;
		long totalConnects = 0;
		long totalUses = 0;
		long totalTotalTime = 0;
		int totalBusy = 0;

		for(int c=0;c<numConnections;c++) {
			long connCount = connectCounts[c];
			boolean isConnected = isConnecteds[c];
			long useCount = useCounts[c];
			long totalTime = totalTimes[c];
			boolean isBusy = isBusies[c];
			if(isBusy) totalTime += time - startTimes[c];
			long stateTime = isBusy ? (time-startTimes[c]):(time-releaseTimes[c]);
			out.append("  <tr>\n"
					+ "    <td>").append(Integer.toString(c+1)).append("</td>\n"
					+ "    <td>").append(isConnected?"Yes":"No").append("</td>\n"
					+ "    <td>");
			if(isConnected) com.aoindustries.util.EncodingUtils.encodeHtml(StringUtility.getDecimalTimeLengthString(time-createTimes[c]), out);
			else out.append("&#160;");
			out.append("    <td>").append(Long.toString(connCount)).append("</td>\n"
					+ "    <td>").append(Long.toString(useCount)).append("</td>\n"
					+ "    <td>");
			com.aoindustries.util.EncodingUtils.encodeHtml(StringUtility.getDecimalTimeLengthString(totalTime), out);
			out.append("</td>\n"
					+ "    <td>").append(Float.toString(totalTime*100/(float)timeLen)).append("%</td>\n"
					+ "    <td>").append(isBusy?"In Use":isConnected?"Idle":"Closed").append("</td>\n"
					+ "    <td>");
			com.aoindustries.util.EncodingUtils.encodeHtml(StringUtility.getDecimalTimeLengthString(stateTime), out);
			out.append("</td>\n"
					+ "    <td>").append(Long.toString(totalTime*1000/useCount)).append("&#181;s</td>\n"
					+ "    <td>");
			Throwable T = allocateStackTraces[c];
			if(T == null) out.append("&#160;");
			else {
				out.append("      <a href='#' onclick='var elem = document.getElementById(\"stack_").append(Integer.toString(c)).append("\").style; elem.visibility=(elem.visibility==\"visible\" ? \"hidden\" : \"visible\"); return false;'>Stack Trace</a>\n"
						+ "      <span id='stack_").append(Integer.toString(c)).append("' style='text-align:left; white-space:nowrap; position:absolute; visibility: hidden; z-index:").append(Integer.toString(c+1)).append("'>\n"
						+ "        <pre style='text-align:left; background-color:white; border: 2px solid; border-color: black;'>\n");
				ErrorPrinter.printStackTraces(T, out);
				out.append("        </pre>\n"
						+ "      </span>\n");
			}
			out.append("</td>\n"
					+ "  </tr>\n");

			// Update totals
			if(isConnected) totalConnected++;
			totalConnects+=connCount;
			totalUses+=useCount;
			totalTotalTime+=totalTime;
			if(isBusy) totalBusy++;
		}
		out.append("  <tr>\n"
				+ "    <td><b>Total</b></td>\n"
				+ "    <td>").append(Integer.toString(totalConnected)).append("</td>\n"
				+ "    <td>&#160;</td>\n"
				+ "    <td>").append(Long.toString(totalConnects)).append("</td>\n"
				+ "    <td>").append(Long.toString(totalUses)).append("</td>\n"
				+ "    <td>");
		com.aoindustries.util.EncodingUtils.encodeHtml(StringUtility.getDecimalTimeLengthString(totalTotalTime), out);
		out.append("</td>\n"
				+ "    <td>").append(Float.toString(timeLen==0 ? 0 : (totalTotalTime*100/(float)timeLen))).append("%</td>\n"
				+ "    <td>").append(Integer.toString(totalBusy)).append("</td>\n"
				+ "    <td>");
		com.aoindustries.util.EncodingUtils.encodeHtml(StringUtility.getDecimalTimeLengthString(timeLen), out);
		out.append("</td>\n"
				+ "    <td>").append(Long.toString(totalUses==0 ? 0 : (totalTotalTime*1000/totalUses))).append("&#181;s</td>\n"
				+ "    <td>&#160;</td>\n"
				+ "  </tr>\n"
				+ "</table>\n");
	}
873152
def main():
    
    allowed_format = ("emf", "eps", "pdf", "png", "ps", \
                      "raw", "rgba", "svg", "svgz")
    p = OptionParser(main.__doc__)
    p.add_option("--skip", default=0, type="int",
            help="skip the first several lines [default: %default]")
    p.add_option("--col", default=0, type="int", help="Get the n-th column")
    p.set_histogram()
    p.add_option("--tags", dest="tags", default=None,
            help="tags for data if multiple input files, comma sep")
    p.add_option("--ascii", default=False, action="store_true",
            help="print ASCII text stem-leaf plot [default: %default]")
    p.add_option("--base", default="0", choices=("0", "2", "10"),
            help="use logarithm axis with base, 0 to disable [default: %default]")
    p.add_option("--facet", default=False, action="store_true",
            help="place multiple histograms side-by-side [default: %default]")
    p.add_option("--fill", default="white",
            help="color of the bin [default: %default]")
    p.add_option("--format", default="pdf", choices=allowed_format,
            help="Generate image of format [default: %default]")
    p.add_option("--quick", default=False, action="store_true",
            help="Use quick plot, assuming bins are already counted")
    p.add_option("--noprintstats", default=False, action="store_true",
            help="Write basic stats when using --quick")
    opts, args = p.parse_args()

    if len(args) < 1:
        sys.exit(not p.print_help())

    skip = opts.skip
    vmin, vmax = opts.vmin, opts.vmax
    bins = opts.bins
    xlabel, title = opts.xlabel, opts.title
    title = title or args[0]
    base = int(opts.base)
    fileno = len(args)

    if opts.quick:
        assert fileno == 1, "Single input file expected using --quick"
        filename = args[0]
        figname = filename.rsplit(".", 1)[0] + ".pdf"
        data = DictFile(filename, keycast=int, cast=int)
        quickplot(data, vmin, vmax, xlabel, title, figname=figname,
                  print_stats=(not opts.noprintstats))
        return

    if fileno == 1:
        histogram(args[0], vmin, vmax, xlabel, title, outfmt=opts.format,
                bins=bins, skip=skip, ascii=opts.ascii,
                base=base, fill=opts.fill, col=opts.col)
    else:
        histogram_multiple(args, vmin, vmax, xlabel, title, outfmt=opts.format,
                tags=opts.tags, bins=bins, skip=skip, ascii=opts.ascii,
                facet=opts.facet, fill=opts.fill)
1141982
def count(args):
    
    from jcvi.graphics.histogram import stem_leaf_plot
    from jcvi.utils.cbook import SummaryStats

    p = OptionParser(count.__doc__)
    p.add_option("--csv", help="Write depth per contig to file")
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    fastafile, = args
    csv = open(opts.csv, "w") if opts.csv else None

    f = Fasta(fastafile, lazy=True)
    sizes = []
    for desc, rec in f.iterdescriptions_ordered():
        if desc.startswith("singleton"):
            sizes.append(1)
            continue

        # consensus_for_cluster_0 with 63 sequences
        if "with" in desc:
            name, w, size, seqs = desc.split()
            if csv:
                print("\t".join(str(x)
                                for x in (name, size, len(rec))), file=csv)
            assert w == "with"
            sizes.append(int(size))
        # MRD85:00603:02472;size=167;
        else:
            name, size, tail = desc.split(";")
            sizes.append(int(size.replace("size=", "")))

    if csv:
        csv.close()
        logging.debug("File written to `{0}`".format(opts.csv))

    s = SummaryStats(sizes)
    print(s, file=sys.stderr)
    stem_leaf_plot(s.data, 0, 100, 20, title="Cluster size")
635109
def stats(args):
    
    from jcvi.utils.cbook import percentage

    p = OptionParser(stats.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    blocksfile, = args
    fp = open(blocksfile)
    counts = defaultdict(int)
    total = orthologous = 0
    for row in fp:
        atoms = row.rstrip().split("\t")
        hits = [x for x in atoms[1:] if x != '.']
        counts[len(hits)] += 1
        total += 1
        if atoms[1] != '.':
            orthologous += 1

    print("Total lines: {0}".format(total), file=sys.stderr)
    for i, n in sorted(counts.items()):
        print("Count {0}: {1}".format(i, percentage(n, total)), file=sys.stderr)

    print(file=sys.stderr)

    matches = sum(n for i, n in counts.items() if i != 0)
    print("Total lines with matches: {0}".\
                format(percentage(matches, total)), file=sys.stderr)
    for i, n in sorted(counts.items()):
        if i == 0:
            continue

        print("Count {0}: {1}".format(i, percentage(n, matches)), file=sys.stderr)

    print(file=sys.stderr)
    print("Orthologous matches: {0}".\
                format(percentage(orthologous, matches)), file=sys.stderr)
1189678
def _print_stats(cls, stats: Statistics, human_format_speed: bool=True):
        ''''''
        time_length = datetime.timedelta(
            seconds=int(stats.stop_time - stats.start_time)
        )
        file_size = wpull.string.format_size(stats.size)

        if stats.bandwidth_meter.num_samples:
            speed = stats.bandwidth_meter.speed()

            if human_format_speed:
                speed_size_str = wpull.string.format_size(speed)
            else:
                speed_size_str = '{:.1f} b'.format(speed * 8)
        else:
            speed_size_str = _('-- B')

        _logger.info(_('FINISHED.'))
        _logger.info(__(
            _(
                'Duration: {preformatted_timedelta}. '
                'Speed: {preformatted_speed_size}/s.'
            ),
            preformatted_timedelta=time_length,
            preformatted_speed_size=speed_size_str,
        ))
        _logger.info(__(
            gettext.ngettext(
                'Downloaded: {num_files} file, {preformatted_file_size}.',
                'Downloaded: {num_files} files, {preformatted_file_size}.',
                stats.files
            ),
            num_files=stats.files,
            preformatted_file_size=file_size
        ))

        if stats.is_quota_exceeded:
            _logger.info(_('Download quota exceeded.'))
1183382
def _progress_print(self, sent, total):
        
        percent = min(int(sent*100.0/total), 100)
        sys.stdout.write('\r{0}[{1}{2}] {3}{4}%{5}'.
                         format(color.Green, '#'*(percent/2), ' '*(50-percent/2), color.Yellow, percent, color.Normal))
        sys.stdout.flush()
556659
def print_(rows, limit=15, sort='size', order='descending'):
    
    localrows = []
    for row in rows:
        localrows.append(list(row))
    # input validation
    sortby = ['type', '#', 'size']
    if sort not in sortby:
        raise ValueError("invalid sort, should be one of" + str(sortby))
    orders = ['ascending', 'descending']
    if order not in orders:
        raise ValueError("invalid order, should be one of" + str(orders))
    # sort rows
    if sortby.index(sort) == 0:
        if order == "ascending":
            localrows.sort(key=lambda x: _repr(x[0]))
        elif order == "descending":
            localrows.sort(key=lambda x: _repr(x[0]), reverse=True)
    else:
        if order == "ascending":
            localrows.sort(key=lambda x: x[sortby.index(sort)])
        elif order == "descending":
            localrows.sort(key=lambda x: x[sortby.index(sort)], reverse=True)
    # limit rows
    localrows = localrows[0:limit]
    for row in localrows:
        row[2] = stringutils.pp(row[2])
    # print rows
    localrows.insert(0,["types", "# objects", "total size"])
    _print_table(localrows)
1098237
def printDiagnostics(exp, sequences, objects, args, verbosity=0):
  """"""
  print "Experiment start time:", time.ctime()
  print "\nExperiment arguments:"
  pprint.pprint(args)

  r = sequences.objectConfusion()
  print "Average common pairs in sequences=", r[0],
  print ", features=",r[2]

  r = objects.objectConfusion()
  print "Average common pairs in objects=", r[0],
  print ", locations=",r[1],
  print ", features=",r[2]

  # For detailed debugging
  if verbosity > 0:
    print "\nObjects are:"
    for o in objects:
      pairs = objects[o]
      pairs.sort()
      print str(o) + ": " + str(pairs)
    print "\nSequences:"
    for i in sequences:
      print i,sequences[i]

  print "\nNetwork parameters:"
  pprint.pprint(exp.config)
984775
def printiterstats(self, itst):
        

        itdsp = tuple([getattr(itst, self.hdrmap[col]) for col in self.hdrtxt])
        print(self.fmtstr % itdsp)
519073
def _cell_output(cell):
    """"""
    outputs = cell.get('outputs', [])
    # Add stdout.
    stdout = ('\n'.join(_ensure_string(output.get('text', ''))
                        for output in outputs)).rstrip()
    # Add text output.
    text_outputs = []
    for output in outputs:
        out = output.get('data', {}).get('text/plain', [])
        out = _ensure_string(out)
        # HACK: skip <matplotlib ...> outputs.
        if out.startswith('<matplotlib'):
            continue
        text_outputs.append(out)
    return stdout + '\n'.join(text_outputs).rstrip()
996778
def print_stats(genomes):
    
    header = ['#genome', 'contig', 'locus', 'position', 'strand', 'length', \
                'sample', 'coverage', \
                'ref. Pn/Ps', 'ref SNP density', \
                'consensus Pn/Ps', 'consensus SNP density', \
                'product']
    print('\t'.join(header))
    for genome, contigs in list(genomes.items()):
        for contig, samples in list(contigs.items()):
            for sample, stats in list(samples.items()):
                for locus, rates in list(stats['sub_rates'].items()):
                    length = rates['info']['length']
                    position, strand = rates['info']['position']
                    position = '%s-%s' % position
                    out = [genome, contig, locus, position, strand, length, \
                            sample, '%.2f' % (rates['cov']), \
                            rates['ref PnPs'], rates['ref SNP density'], \
                            rates['consensus PnPs'], rates['consensus SNP density'], \
                            rates['info']['product'][0]]
                    print('\t'.join([str(i) for i in out]))
745552
def print_summary(self, stream=sys.stdout, indent=""):
        
        stream.write("%sTotal files      : %i\n" %
                     (indent, len(self.file_dict)))
        stream.write("%s  Input files    : %i\n" %
                     (indent, len(self.input_files)))
        stream.write("%s  Output files   : %i\n" %
                     (indent, len(self.output_files)))
        stream.write("%s  Internal files : %i\n" %
                     (indent, len(self.internal_files)))
        stream.write("%s  Temp files     : %i\n" %
                     (indent, len(self.temp_files)))
780379
def main(show_details:['-l']=False, cols:['-w', '--width']='', *files):
    '''
    
    '''
    print(files)
    print(show_details)
    print(cols)