Python print report

60 Python code examples are found related to " print report". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: eval.py    From semeval2017-scienceie with Apache License 2.0 7 votes vote down vote up
def print_report(metrics, targets, digits=2):
    def _get_line(results, target, columns):
        line = [target]
        for column in columns[:-1]:
            line.append("{0:0.{1}f}".format(results[column], digits))
        line.append("%s" % results[columns[-1]])
        return line

    columns = ['precision', 'recall', 'f1-score', 'support']

    fmt = '%11s' + '%9s' * 4 + '\n'
    report = [fmt % tuple([''] + columns)]
    report.append('\n')
    for target in targets:
        results = metrics[target]
        line = _get_line(results, target, columns)
        report.append(fmt % tuple(line))
    report.append('\n')

    # overall
    line = _get_line(metrics['overall'], 'avg / total', columns)
    report.append(fmt % tuple(line))
    report.append('\n')

    print(''.join(report)) 
Example 2
Source File: science_ie_eval.py    From sciwing with MIT License 6 votes vote down vote up
def print_report(metrics, targets, digits=2):
    def _get_line(results, target, columns):
        line = [target]
        for column in columns[:-1]:
            line.append("{0:0.{1}f}".format(results[column], digits))
        line.append("%s" % results[columns[-1]])
        return line

    columns = ["precision", "recall", "f1-score", "support"]

    fmt = "%11s" + "%9s" * 4 + "\n"
    report = [fmt % tuple([""] + columns)]
    report.append("\n")
    for target in targets:
        results = metrics[target]
        line = _get_line(results, target, columns)
        report.append(fmt % tuple(line))
    report.append("\n")

    # overall
    line = _get_line(metrics["overall"], "avg / total", columns)
    report.append(fmt % tuple(line))
    report.append("\n")

    print("".join(report)) 
Example 3
Source File: executions.py    From python-mistralclient with Apache License 2.0 6 votes vote down vote up
def print_report(self, report_json):
        self.print_line(
            "\nTo get more details on a task failure "
            "run: mistral task-get <id> -c 'State info'\n"
        )

        frame_line = '=' * 30

        self.print_line(
            '%s General Statistics %s\n' %
            (frame_line, frame_line)
        )
        self.print_statistics(report_json['statistics'])

        if 'root_workflow_execution' in report_json:
            self.print_line(
                '%s Workflow Execution Tree %s\n' %
                (frame_line, frame_line)
            )
            self.print_workflow_execution_entry(
                report_json['root_workflow_execution'],
                0
            ) 
Example 4
Source File: product_catalog_wizard.py    From LibrERP with GNU Affero General Public License v3.0 6 votes vote down vote up
def print_report(self, cr, uid, ids, context=None):
        print ids
        print context
        if context is None:
            context = {}
        datas = {'ids': context.get('active_ids', [])}
        print datas
        res = self.read(cr, uid, ids, ['category_id', 'pricelist_id', 'pricelist_id2'], context=context)
        print res
        res = res and res[0] or {}
        print res
        datas['form'] = res
        datas['form']['ids'] = context.get('active_ids', [])
        report_name = res['pricelist_id2'] and 'product.catalog.variant.extend2' or 'product.catalog.variant.extend'
        return {
            'type': 'ir.actions.report.xml',
            'report_name': report_name,
            'datas': datas,
        } 
Example 5
Source File: product_catalog_available.py    From LibrERP with GNU Affero General Public License v3.0 6 votes vote down vote up
def print_report_qty(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        datas = {'ids': context.get('active_ids', [])}
        res = self.browse(cr, uid, ids[0], context=context)
        # res = res and res[0] or {}
        datas['form'] = {}
        for key in ['category_id', 'pricelist_id', 'pricelist_id2']:
            datas['form'][key] = res[key] and res[key].id or False

        datas['form']['ids'] = context.get('active_ids', [])
        report_name = res['pricelist_id2'] and 'product.catalog.qty2' or 'product.catalog.qty'
        return {
            'type': 'ir.actions.report.xml',
            'report_name': report_name,
            'datas': datas,
        } 
Example 6
Source File: summary_builder.py    From dlcookbook-dlbs with Apache License 2.0 6 votes vote down vote up
def print_report_txt(description, header, report,
                         col1_key, col2_key, data_key):
        """ Writes a human readable report to a standard output.
        """
        print(description)
        print(header)
        for record in report:
            row = "%-20s %-10s" % (record[col1_key], record[col2_key])
            for idx in range(len(record['time'])):
                val = record[data_key][idx]
                if val >= 0:
                    if isinstance(val, int):
                        row = "%s %-10d" % (row, record[data_key][idx])
                    else:
                        row = "%s %-10.2f" % (row, record[data_key][idx])
                else:
                    row = "%s %-10s" % (row, '-')
            print(row)
        print("\n\n") 
Example 7
Source File: DescendantBookReport.py    From addons-source with GNU General Public License v2.0 6 votes vote down vote up
def print_report_reference(self, level, person, spouse, display_num):
        if person and spouse:
            mark = ReportUtils.get_person_mark(self.database, person)
            self.doc.start_paragraph("DR-Level%d" % min(level, 32))
            pname = self._name_display.display(person)
            sname = self._name_display.display(spouse)
            self.doc.write_text(
                _("see report: %(report)s, ref: %(reference)s : "
                  "%(person)s & %(spouse)s") % \
                 {'report':report_titles[display_num[0]], \
                  'reference':display_num[1], \
                  'person':pname, \
                  'spouse':sname}, mark)
            self.doc.end_paragraph()

#------------------------------------------------------------------------
#
# RecurseDown
#
#------------------------------------------------------------------------ 
Example 8
Source File: utilities.py    From Python-Machine-Learning-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
def print_accuracy_report(classifier, X, y, num_validations=5):
    accuracy = model_selection.cross_val_score(classifier, 
            X, y, scoring='accuracy', cv=num_validations)
    print("Accuracy: " + str(round(100*accuracy.mean(), 2)) + "%")

    f1 = model_selection.cross_val_score(classifier, 
            X, y, scoring='f1_weighted', cv=num_validations)
    print("F1: " + str(round(100*f1.mean(), 2)) + "%")

    precision = model_selection.cross_val_score(classifier, 
            X, y, scoring='precision_weighted', cv=num_validations)
    print("Precision: " + str(round(100*precision.mean(), 2)) + "%")

    recall = model_selection.cross_val_score(classifier, 
            X, y, scoring='recall_weighted', cv=num_validations)
    print("Recall: " + str(round(100*recall.mean(), 2)) + "%") 
Example 9
Source File: __init__.py    From AstroBox with GNU Affero General Public License v3.0 6 votes vote down vote up
def reportPrintJobFailed(self):
		currentFile = self._printerManager.selectedFile
		printTime = self._printerManager.getPrintTime()

		self._printerManager.printJobCancelled()

		filename = os.path.basename(currentFile['filename'])
		eventManager().fire(SystemEvent.PRINT_FAILED, {
			"file": currentFile['filename'],
			"filename": filename,
			"origin": currentFile['origin'],
			"time": printTime
		})
		##self._printerManager._fileManager.printFailed(filename, printTime)

	#
	# Call this function when print progress has changed
	# 
Example 10
Source File: __init__.py    From AstroBox with GNU Affero General Public License v3.0 6 votes vote down vote up
def reportPrintJobCompleted(self):
		self.disableMotorsAndHeater()

		currentFile = self._printerManager.selectedFile
		printTime = self._printerManager.getPrintTime()
		currentLayer = self._printerManager.getCurrentLayer()

		self._printerManager.mcPrintjobDone()

		self._changePrinterState(PrinterState.STATE_OPERATIONAL)

		self._printerManager._fileManager.printSucceeded(currentFile['filename'], printTime, currentLayer)
		eventManager().fire(SystemEvent.PRINT_DONE, {
			"file": currentFile['filename'],
			"filename": os.path.basename(currentFile['filename']),
			"origin": currentFile['origin'],
			"time": printTime,
			"layerCount": currentLayer
		})

	#
	# Report print job failed
	# 
Example 11
Source File: auditor.py    From ezdxf with MIT License 6 votes vote down vote up
def print_error_report(self, errors: List[ErrorEntry] = None, stream: TextIO = None) -> None:
        def entity_str(count, code, entity):
            if entity is not None:
                return f"{count:4d}. Issue [{code}] in {str(entity)}."
            else:
                return f"{count:4d}. Issue [{code}]."

        if errors is None:
            errors = self.errors
        else:
            errors = list(errors)

        if stream is None:
            stream = sys.stdout

        if len(errors) == 0:
            stream.write('No issues found.\n\n')
        else:
            stream.write(f'{len(errors)} issues found.\n\n')
            for count, error in enumerate(errors):
                stream.write(entity_str(count + 1, error.code, error.entity) + '\n')
                stream.write('   ' + error.message + '\n\n') 
Example 12
Source File: xmlrunner.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
def print_report(self, stream):
        """Print information about this test case in XML format to the
        supplied stream.

        """
        stream.write('  <testcase classname="%(class)s" name="%(method)s" time="%(time).4f">' % \
            {
                "class": self._class,
                "method": self._method,
                "time": self._time,
            })
        if self._failure != None:
            self._print_error(stream, 'failure', self._failure)
        if self._error != None:
            self._print_error(stream, 'error', self._error)
        stream.write('</testcase>\n') 
Example 13
Source File: vxhunter_analysis.py    From vxhunter with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def print_report(self):
        for line in self.report:
            print(line)

        # Print timer
        print('{:-^60}'.format(self.__class__.__name__ + " timer"))
        for line in self.timer_log:
            print(line)
        print('{}\r\n'.format("-" * 60)) 
Example 14
Source File: reporting.py    From lahja with MIT License 5 votes vote down vote up
def print_full_report(
    logger: Logger,
    backend: BaseBackend,
    num_consumer_processes: int,
    num_events: int,
    global_statistic: GlobalStatistic,
) -> None:

    print_global_header(logger, backend)
    print_global_entry(logger, num_consumer_processes, num_events, global_statistic)

    print_entry_header(logger)
    for total in global_statistic._entries:
        print_entry_line(logger, total) 
Example 15
Source File: docreport.py    From amir with GNU General Public License v3.0 5 votes vote down vote up
def printReport(self, sender):
        self.reportObj = WeasyprintReport()
        printjob = self.createPrintJob()
        if printjob != None:
            self.reportObj.doPrint(printjob) 
Example 16
Source File: _basinhopping.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def print_report(self, energy_trial, accept):
        """print a status update"""
        minres = self.storage.get_lowest()
        print("basinhopping step %d: f %g trial_f %g accepted %d "
              " lowest_f %g" % (self.nstep, self.energy, energy_trial,
                                accept, minres.fun)) 
Example 17
Source File: classification_model.py    From nupic.fluent with GNU Affero General Public License v3.0 5 votes vote down vote up
def printTrialReport(labels, refs, idx):
    """Print columns for sample #, actual label, and predicted label."""
    template = "{0:<10}|{1:<55}|{2:<55}"
    print "Evaluation results for the trial:"
    print template.format("#", "Actual", "Predicted")
    for i in xrange(len(labels[0])):
      if not any(labels[0][i]):
        # No predicted classes for this sample.
        print template.format(idx[i],
                              [refs[label] for label in labels[1][i]],
                              "(none)")
      else:
        print template.format(idx[i],
                              [refs[label] for label in labels[1][i]],
                              [refs[label] for label in labels[0][i]]) 
Example 18
Source File: xva.py    From openxenmanager with GNU General Public License v2.0 5 votes vote down vote up
def print_report(self):

        print "VM Details:"

        print "Name: %s" % self.xml_objects['name'].text
        if self.xml_objects['HVM_boot_policy'].text == "BIOS order":
            print "Type: HVM"
            hvm=True
        else:
            print "Type: Paravirtualised"
            hvm=False
        print "VCPUS: %s" % self.xml_objects['vcpus'].text
        print "Memory(bytes): %s" % self.xml_objects['memory_static_max'].text
        print "ACPI: %s" % self.xml_objects['acpi']
        print "APIC: %s" % self.xml_objects['apic']
        print "PAE: %s" % self.xml_objects['pae']
        print "NX: %s" % self.xml_objects['nx']
        print "Viridian: %s" % self.xml_objects['viridian']

        
        iteration = 0
        for disk in self.disks:
            if iteration == 0:
               if hvm:
                   print "Disk 0(Bootable): %s" % disk[1]
               else:
                   print "Disk xvda(Bootable): %s" % disk[1]
                   

            else:
               if hvm: 

                   print "Disk %d: %s" % ( iteration , disk[1])

               else:
                   print "Disk xvd%c: %s" % ( iteration + 97, disk[1])
               


            iteration = iteration + 1 
Example 19
Source File: runner.py    From nupic.fluent with GNU Affero General Public License v3.0 5 votes vote down vote up
def printFinalReport(trainSizes, accuracies):
    """Prints result accuracies."""
    template = "{0:<20}|{1:<10}"
    print "Evaluation results for this experiment:"
    print template.format("Size of training set", "Accuracy")
    for size, acc in itertools.izip(trainSizes, accuracies):
      print template.format(size, acc) 
Example 20
Source File: report_printer.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def print_report(self, report: PerformanceReport) -> None:
        """
        Print full performance report for case.

        :param report: performance report to print header for

        :return: None
        """
        self._print_header(report)
        self._print_resources(report) 
Example 21
Source File: crohme_convert.py    From hwrt with MIT License 5 votes vote down vote up
def print_report(score_place):
    logging.info("Total: %i", len(score_place))
    logging.info("mean: %0.2f", numpy.mean(score_place))
    logging.info("median: %0.2f", numpy.median(score_place))
    for i in [1, 3, 10, 50]:
        logging.info(
            "TOP-%i error: %0.4f",
            i,
            (len(score_place) - less_than(score_place, i)) / len(score_place),
        ) 
Example 22
Source File: trace_variable.py    From megaman with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def print_report(self,iiter):
        if self.verbose and iiter % self.printiter == 0:
            print ('Iteration number: {}'.format(iiter))
            print ('Last step size eta: {}'.format(self.etas[iiter]))
            print ('current loss (before gradient step): {}'
                   .format(self.loss[iiter]))
            print ('minimum loss: {}, at iteration: {}\n'
                   .format(self.lmin, self.miniter)) 
Example 23
Source File: wrapper.py    From pockyt with GNU General Public License v3.0 5 votes vote down vote up
def print_bug_report(message=""):
    """
    Prints a usable bug report
    """

    separator = "\n" + ("-" * 69) + "\n"

    error_message = message or traceback.format_exc().strip()
    python_version = str(sys.version)
    command = " ".join(sys.argv[1:])

    try:
        import pkg_resources
    except ImportError:
        packages_message = "`pkg_resources` is not installed!"
    else:
        packages_message = "\n".join(
            "{0} - {1}".format(package.key, package.version)
            for package in pkg_resources.working_set)

    print("{0}Bug Report :\n"
          "`pockyt` has encountered an error! "
          "Please submit this bug report at \n` {1} `.{0}"
          "Python Version:\n{2}{0}"
          "Installed Packages:\n{3}{0}"
          "Commmand:\n{4}{0}"
          "Error Message:\n{5}{0}".format(
              separator,
              API.ISSUE_URL,
              python_version,
              packages_message,
              command,
              error_message,
          )) 
Example 24
Source File: ringmasters.py    From goreviewpartner with GNU General Public License v3.0 5 votes vote down vote up
def print_status_report(self):
        """Write current competition status to standard output.

        This is for the 'show' command.

        """
        self.competition.write_short_report(sys.stdout) 
Example 25
Source File: report.py    From training with Apache License 2.0 5 votes vote down vote up
def print_report(self, verbose=True):

    # print summary
    print("\n" + "MLPERF SUBMISSION REPORT\n" + "========================\n")
    print("\n" + "SUMMARY\n" + "-------\n")
    print("Passed checks: {}\n".format(len(self.passed_checks)) +
          "Failed checks: {}\n".format(len(self.failed_checks)) +
          "Errors: {}".format(len(self.errors)))
    print("Note: the Errors indicate certain checks being skipped or " +
          "early terminated due to errors. The errors are likely caused " +
          "by failed checks above.")

    # print succeeded checks (in verbose mode only)
    if verbose:
      print("\n" + "PASSED CHECKS\n" + "-------------\n")
      for msg in self.passed_checks:
        print(msg)

    # print failed checks
    print("\n" + "FAILED CHECKS\n" + "-------------\n")
    for msg in self.failed_checks:
      print(msg)

    # print errors
    print("\n" + "ERRORS\n" + "------\n")
    for msg in self.errors:
      print(msg) 
Example 26
Source File: utils.py    From hat with MIT License 5 votes vote down vote up
def print_model_report(model):
    print('-'*100)
    print(model)
    print('Dimensions =',end=' ')
    count=0
    for p in model.parameters():
        print(p.size(),end=' ')
        count+=np.prod(p.size())
    print()
    print('Num parameters = %s'%(human_format(count)))
    print('-'*100)
    return count 
Example 27
Source File: __init__.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def print_report(frame, explain=False):
    """Pretty-print the report."""
    if cli.OUTPUT_FORMAT is None:
        if explain:
            frame.replace(True, ' ', inplace=True)
            frame.replace(False, 'X', inplace=True)
        dict_ = frame.to_dict(orient='split')
        del dict_['index']
        cli.out(
            tabulate.tabulate(
                dict_['data'], dict_['columns'], tablefmt='simple'
            )
        )

        if explain:
            cli.echo_green(
                '\nX: designates the factor that prohibits scheduling '
                'the instance on the given server'
            )

    elif cli.OUTPUT_FORMAT == 'yaml':
        fmt = plugin_manager.load('treadmill.formatters', 'yaml')
        cli.out(fmt.format(frame.to_dict(orient='records')))
    elif cli.OUTPUT_FORMAT == 'json':
        cli.out(frame.to_json(orient='records'))
    elif cli.OUTPUT_FORMAT == 'csv':
        cli.out(frame.to_csv(index=False))
    else:
        cli.out(tabulate.tabulate(frame, frame.columns, tablefmt='simple')) 
Example 28
Source File: channels_base.py    From topoflow with MIT License 5 votes vote down vote up
def print_status_report(self): 

        #----------------------------------------------------
        # Wherever depth is less than z0, assume that water
        # is not flowing and set u and Q to zero.
        # However, we also need (d gt 0) to avoid a divide
        # by zero problem, even when numerators are zero.
        #----------------------------------------------------
        # FLOWING = (d > (z0/aval))
        #*** FLOWING[noflow_IDs] = False    ;******
        
        wflow    = np.where( FLOWING != 0 )
        n_flow   = np.size( wflow[0] )
        n_pixels = self.rti.n_pixels
        percent  = np.float64(100.0) * (np.float64(n_flow) / n_pixels)
        fstr = ('%5.1f' % percent) + '%'
        # fstr = idl_func.string(percent, format='(F5.1)').strip() + '%'
        print ' Percentage of pixels with flow = ' + fstr
        print ' '

        self.update_mins_and_maxes(REPORT=True)
 
        wmax  = np.where(self.Q == self.Q_max)
        nwmax = np.size(wmax[0])
        print ' Max(Q) occurs at: ' + str( wmax[0] )
        #print,' Max attained at ', nwmax, ' pixels.'
        print ' '
        print '-------------------------------------------------'

    #   print_status_report()         
    #------------------------------------------------------------------- 
Example 29
Source File: run_processor.py    From temci with GNU General Public License v3.0 5 votes vote down vote up
def print_report(self) -> str:
        if in_standalone_mode:
            return
        """ Print a short report if possible. """
        try:
            ReporterRegistry.get_for_name("console", self.stats_helper).report(with_tester_results=False)
        except:
            pass 
Example 30
Source File: kernel_test_parse.py    From sanitizers with Apache License 2.0 5 votes vote down vote up
def PrintTestReport(test, run_reports):
  passed = 0
  failed = 0
  for result, _, _, _ in run_reports:
    if result:
      passed += 1
    else:
      failed += 1
  if passed and not failed:
    total_result = "PASSED (%d runs)" % passed
  elif failed and not passed:
    total_result = "FAILED (%d runs)" % failed
  else:
    total_result = "FLAKY (%d passed, %d failed, %d total)" % (
                   passed, failed, passed + failed)
  
  print "TEST %s: %s" % (test, total_result)  
  if args.brief:
    return
  for index, (_, failures, failed_asserts, lines) in enumerate(run_reports):
    if not failures and not failed_asserts:
      continue
    print "  Run %d"   % index
    for f in failures:
      print "    Failed: %s" % s
    missing_matches = not args.assert_candidates
    for a in failed_asserts:
      print "    Failed assert: %s" % a
      if args.assert_candidates:
        print "    Closest matches:"
        matches =  difflib.get_close_matches(a, lines, args.assert_candidates, 0.4)
        matches = [match for match in matches if not ASSERT_RE.search(match)]
        for match in matches:
          print "    " + match
        if not matches:
          missing_matches = True
    if args.failed_log and (failures or missing_matches):
      print "    Test log:"
      for l in lines:
        print "        " + l 
Example 31
Source File: gasmask.py    From gasmask with GNU General Public License v3.0 5 votes vote down vote up
def print_report(res, key, public_info, output_basename):
    """ Format the result output - Censys.io """
    r = res['results']
    print("count".ljust(10) + "\t" + key.split(".")[-1])
    for e in r:
        print(("%d" % e['doc_count']).ljust(10) + "\t" + str(e['key']).ljust(30))
        public_info = ("%d" % e['doc_count']).ljust(10) + "\t" + str(e['key']).ljust(30)

    CensysPublicReport('censys', public_info, output_basename) 
Example 32
Source File: utils.py    From aws-amicleaner with MIT License 5 votes vote down vote up
def print_report(candidates, full_report=False):

        """ Print AMI collection results """

        if not candidates:
            return

        groups_table = PrettyTable(["Group name", "candidates"])

        for group_name, amis in candidates.items():
            groups_table.add_row([group_name, len(amis)])
            eligible_amis_table = PrettyTable(
                ["AMI ID", "AMI Name", "Creation Date"]
            )
            for ami in amis:
                eligible_amis_table.add_row([
                    ami.id,
                    ami.name,
                    ami.creation_date
                ])
            if full_report:
                print(group_name)
                print(eligible_amis_table.get_string(sortby="AMI Name"), "\n\n")

        print("\nAMIs to be removed:")
        print(groups_table.get_string(sortby="Group name")) 
Example 33
Source File: pycm_output.py    From pycm with MIT License 5 votes vote down vote up
def compare_report_print(sorted_list, scores, best_name):
    """
    Return compare report.

    :param sorted_list: sorted list of cm's
    :type sorted_list: list
    :param scores: scores of cm's
    :type scores: dict
    :param best_name: best cm name
    :type best_name: str
    :return: printable result as str
    """
    title_items = ["Rank", "Name", "Class-Score", "Overall-Score"]
    class_scores_len = map(lambda x: len(
        str(x["class"])), list(scores.values()))
    shifts = ["%-" +
              str(len(sorted_list) +
                  4) +
              "s", "%-" +
              str(max(map(lambda x: len(str(x)), sorted_list)) +
                  4) +
              "s", "%-" +
              str(max(class_scores_len) + 11) + "s"]
    result = ""
    result += "Best : " + str(best_name) + "\n\n"
    result += ("".join(shifts)
               ) % tuple(title_items[:-1]) + title_items[-1] + "\n"
    prev_rank = 0
    for index, cm in enumerate(sorted_list):
        rank = index
        if scores[sorted_list[rank]] == scores[sorted_list[prev_rank]]:
            rank = prev_rank
        result += ("".join(shifts)) % (str(rank + 1), str(cm),
                                       str(scores[cm]["class"])) + str(scores[cm]["overall"]) + "\n"
        prev_rank = rank
    return result 
Example 34
Source File: pycm_compare.py    From pycm with MIT License 5 votes vote down vote up
def print_report(self):
        """
        Print Compare report.

        :return: None
        """
        report = compare_report_print(
            self.sorted, self.scores, self.best_name)
        print(report) 
Example 35
Source File: WorkloadBase.py    From browbeat with Apache License 2.0 5 votes vote down vote up
def print_report(result_dir, time_stamp):
        with open(os.path.join(result_dir,time_stamp + '.' + 'report'), 'w') as yaml_file:
            yaml_file.write("Browbeat Report Card\n")
            if not WorkloadBase.browbeat:
                yaml_file.write("No tests were enabled")
            else:
                yaml_file.write(yaml.dump(WorkloadBase.browbeat, default_flow_style=False)) 
Example 36
Source File: can_haz_image.py    From macops with Apache License 2.0 5 votes vote down vote up
def PrintReport(self, pkgreport):
    """Prints a report of installed packages."""
    print 'Packages installed:\n'
    for item in pkgreport:
      print '%s' % item 
Example 37
Source File: utils.py    From blow with Apache License 2.0 5 votes vote down vote up
def print_model_report(model,verbose=3):
    if verbose>1:
        print(model)
    if verbose>2:
        print('Dimensions =',end=' ')
    count=0
    for p in model.parameters():
        if verbose>2:
            print(p.size(),end=' ')
        count+=np.prod(p.size())
    if verbose>2:
        print()
    if verbose>0:
        print('Num parameters = %s'%(human_format(count)))
    return count 
Example 38
Source File: analyze.py    From brownie with MIT License 5 votes vote down vote up
def print_console_report(stdout_report) -> None:
    """Highlight and print a given stdout report to the console.

    This adds color formatting to the given stdout report and prints
    a summary of the vulnerabilities MythX has detected.

    :return: None
    """

    total_issues = sum(x for i in stdout_report.values() for x in i.values())
    if not total_issues:
        notify("SUCCESS", "No issues found!")
        return

    # display console report
    total_high_severity = sum(i.get("HIGH", 0) for i in stdout_report.values())
    if total_high_severity:
        notify(
            "WARNING", f"Found {total_issues} issues including {total_high_severity} high severity!"
        )
    else:
        print(f"Found {total_issues} issues:")
    for name in sorted(stdout_report):
        print(f"\n  contract: {color('bright magenta')}{name}{color}")
        for key in [i for i in ("HIGH", "MEDIUM", "LOW") if i in stdout_report[name]]:
            c = color("bright red" if key == "HIGH" else "bright yellow")
            print(f"    {key.title()}: {c}{stdout_report[name][key]}{color}") 
Example 39
Source File: transformers.py    From healthcareai-py with MIT License 5 votes vote down vote up
def printFillDictReport( self, lenghth_X ):
        
        header_names = [ 'Column Name', '  Number of\nmissing values', '% missing\n values', 'Top 3 impute values']
        print_data = []
        
        for colName, imputeData in self.fill_dict.items():
            length_imputeData = len(self.fill_dict[colName])
            sample_imputeData = imputeData[0:3]
            percentage_missing = length_imputeData/lenghth_X
            percentage_missing = "{:.2%}".format(percentage_missing)
            print_data.append( [colName, str(length_imputeData), percentage_missing, sample_imputeData] )
        
        table = tabulate( tabular_data=print_data, headers=header_names, tablefmt='fancy_grid', stralign='left', numalign='left')
        print(table)
        print("") 
Example 40
Source File: id_card_lva.py    From mrz with GNU General Public License v3.0 5 votes vote down vote up
def print_report(checker: TD1CodeChecker):
    print("REPORT")
    for r in checker.report:
        print(r[0] + ":" + str(r[1]).rjust(30 - len(r[0])))
    print("\nResult:" + str(td1_check).rjust(24).upper()) 
Example 41
Source File: _basinhopping.py    From Computable with MIT License 5 votes vote down vote up
def print_report(self, energy_trial, accept):
        xlowest, energy_lowest = self.storage.get_lowest()
        print("basinhopping step %d: f %g trial_f %g accepted %d "
              " lowest_f %g" % (self.nstep, self.energy, energy_trial,
                                accept, energy_lowest)) 
Example 42
Source File: clf_helpers.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def print_report(res):
        res.augment_if_needed()
        pred_enc = res.clf_probs.argmax(axis=1)
        res.extended_clf_report()
        report = sklearn.metrics.classification_report(
            y_true=res.y_test_enc, y_pred=pred_enc,
            target_names=res.class_names,
            sample_weight=res.sample_weight,
        )
        print('Precision/Recall Report:')
        print(report) 
Example 43
Source File: stats_metrics.py    From fanci with GNU General Public License v3.0 5 votes vote down vote up
def print_cummulative_clf_report(self):
        """
        Prints the cumulated classification report for all added runs
        :return:
        """
        log.info('Classification report:\n\n' + classification_report(self.y_true, self.y_pred,
                                                                      target_names=['Benign', 'Malicious'])) 
Example 44
Source File: find_risks.py    From PMapper with GNU Affero General Public License v3.0 5 votes vote down vote up
def print_report(report: Report) -> None:
    """Given a report, uses print() to print out their contents in a Markdown format."""

    # Preamble
    print('----------------------------------------------------------------')
    print('# Principal Mapper Findings')
    print()
    print('Findings identified in AWS account {}'.format(report.account))
    print()
    print('Date and Time: {}'.format(report.date_and_time.isoformat()))
    print()
    print(report.source)

    # Findings
    if len(report.findings) == 0:
        print()
        print("None found.")
        print()
    else:
        for finding in report.findings:
            print("## {}\n\n### Severity\n\n{}\n\n### Impact\n\n{}\n\n### Description\n\n{}\n\n### Recommendation\n\n{}"
                  "\n\n".format(finding.title, finding.severity, finding.impact, finding.description,
                                finding.recommendation)
                  )

    # Footer

    print()
    print('----------------------------------------------------------------') 
Example 45
Source File: open_invoices_xls.py    From LibrERP with GNU Affero General Public License v3.0 5 votes vote down vote up
def print_grouped_line_report(
            self, row_pos, account, _xs, xlwtlib, _p, data):

        if account.grouped_ledger_lines and account.partners_order:
            row_start_account = row_pos

            for partner_name, p_id, p_ref, p_name in account.partners_order:
                row_pos = self.print_row_code_account(
                    "regroup", account, row_pos, partner_name)

                for curr, grouped_lines in account.grouped_ledger_lines.\
                        get(p_id, []):

                    row_pos = self.print_group_currency(row_pos, curr, _p)
                    # Print row: Titles "Date-Period-Entry-Journal..."
                    row_pos = self.print_columns_title(
                        _p, row_pos, data, group_lines=True)

                    row_pos_start = row_pos
                    line_number = 0
                    for line in grouped_lines:
                        line_number += 1
                        row_pos, cumul_balance = self.print_group_lines(
                            row_pos, account, line, _p, line_number)
                    row_pos = self.print_group_cumul_partner(
                        row_pos, row_pos_start, account, _p, data)

            row_pos = self.print_group_cumul_account(
                row_pos, row_start_account, account)

        return row_pos

    # export the invoice AR/AP lines 
Example 46
Source File: timer.py    From chainer with MIT License 5 votes vote down vote up
def print_report(self, unit='auto', file=sys.stdout):
        """Prints a summary report of time profiling in links.

        Args:
            unit (str): Supplementary units used for computational times.
                `sec`, `ms`, `us`, `ns`, `auto`(default) and `auto_foreach`
                are supported. If `auto`, units of times are aligned to the
                largest, and if `auto_foreach`, units of times are adjusted for
                each element.
        """
        entries = [['LinkName', 'ElapsedTime', 'Occurrence']]
        auto_foreach = (unit == 'auto_foreach')
        if unit == 'auto':
            max_time = max(
                record['elapsed_time'] for record in self.summary().values())
            factor, unit = self._choose_unit(max_time)
        elif not auto_foreach:
            factor = self.table[unit]
        for link_name, record in self.summary().items():
            second = record['elapsed_time']
            if auto_foreach:
                factor, unit = self._choose_unit(second)
            elapsed_time = '%3.2f%s' % (second * factor, unit)
            occurrence = str(record['occurrence'])
            entries.append([link_name, elapsed_time, occurrence])
        entry_widths = []
        entry_widths.append(max(len(f) for f, _, _ in entries))
        entry_widths.append(max(len(e) for _, e, _ in entries))
        entry_widths.append(max(len(o) for _, _, o in entries))
        template = '  '.join('{:>%d}' % w for w in entry_widths)
        for link_name, elapsed_time, occurrence in entries:
            line = template.format(link_name, elapsed_time, occurrence)
            file.write(line)
            file.write('\n')
        file.flush()

    # TODO(crcrpar): Support backward pre/post process.
    # See https://github.com/chainer/chainer/issues/5197 
Example 47
Source File: plex-listattrs.py    From python-plexapi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def print_report(self):
        total_attrs = 0
        for clsname in sorted(self.attrs.keys()):
            if self._clsname_match(clsname):
                meta = self.attrs[clsname]
                count = meta['total']
                print(_('\n%s (%s)\n%s' % (clsname, count, '-' * 30), 'yellow'))
                attrs = sorted(set(list(meta['xml'].keys()) + list(meta['obj'].keys())))
                for attr in attrs:
                    state = self._attr_state(clsname, attr, meta)
                    count = meta['xml'].get(attr, 0)
                    categories = ','.join(meta['categories'].get(attr, ['--']))
                    examples = '; '.join(list(meta['examples'].get(attr, ['--']))[:3])[:80]
                    print('%7s  %3s  %-30s  %-20s  %s' % (count, state, attr, categories, examples))
                    total_attrs += count
        print(_('\nSUMMARY\n%s' % ('-' * 30), 'yellow'))
        print('%7s  %3s  %3s  %3s  %-20s  %s' % ('total', 'new', 'old', 'doc', 'categories', 'clsname'))
        for clsname in sorted(self.attrs.keys()):
            if self._clsname_match(clsname):
                print('%7s  %12s  %12s  %12s  %s' % (self.attrs[clsname]['total'],
                    _(self.attrs[clsname]['new'] or '', 'cyan'),
                    _(self.attrs[clsname]['old'] or '', 'red'),
                    _(self.attrs[clsname]['doc'] or '', 'purple'),
                    clsname))
        print('\nPlex Version     %s' % self.plex.version)
        print('PlexAPI Version  %s' % plexapi.VERSION)
        print('Total Objects    %s' % sum([x['total'] for x in self.attrs.values()]))
        print('Runtime          %s min\n' % self.runtime) 
Example 48
Source File: eval.py    From factRuEval-2016 with MIT License 5 votes vote down vote up
def printReport(self, name, out_dir):
        if len(out_dir) == 0:
            return

        is_perfect = self.em.metrics['overall'].f1 == 1.0
        os.makedirs(out_dir, exist_ok=True)

        filename = ('' if is_perfect else '_') +  name + '.report.txt'
        with open(os.path.join(out_dir, filename), 'w', encoding='utf-8') as f:
            f.write(self.buildReport())


######################################################################################### 
Example 49
Source File: restaurant.py    From python-class with MIT License 5 votes vote down vote up
def print_sales_report(self):
        """ Print daily sales report. Example:

            PB&J : 2
            Cheeseburger : 5
            Milkshake : 3
            -----
            Total: $27.23
        """
        # YOUR CODE HERE 
Example 50
Source File: service_report_generator.py    From frost with Mozilla Public License 2.0 5 votes vote down vote up
def print_report(self):
        for test in self.test_results:
            self._print_test_header(
                test,
                self.test_results[test][0]["description"],
                self.test_results[test][0]["rationale"],
            )

            self._print_test_result_tables(test)

            print("\n---\n\n", file=self.fout) 
Example 51
Source File: sql.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def printReport(self):
        """
        Print a report of all the SQL statements executed to date.
        """

        total_statements = len(self.statements)
        total_rows = sum([statement[1] for statement in self.statements])
        total_time = sum([statement[2] for statement in self.statements]) * 1000.0

        toFile = StringIO()
        toFile.write("*** SQL Stats ***\n")
        toFile.write("\n")
        toFile.write("Label: %s\n" % (self.label,))
        toFile.write("Unique statements: %d\n" % (len(set([statement[0] for statement in self.statements]),),))
        toFile.write("Total statements: %d\n" % (total_statements,))
        toFile.write("Total rows: %d\n" % (total_rows,))
        toFile.write("Total time (ms): %.3f\n" % (total_time,))
        t_last_end = self.startTime
        for sql, rows, t_taken, t_end in self.statements:
            toFile.write("\n")
            toFile.write("SQL: %s\n" % (sql,))
            toFile.write("Rows: %s\n" % (rows,))
            toFile.write("Time (ms): %.3f\n" % (t_taken * 1000.0,))
            toFile.write("Idle (ms): %.3f\n" % ((t_end - t_taken - t_last_end) * 1000.0,))
            toFile.write("Elapsed (ms): %.3f\n" % ((t_end - self.startTime) * 1000.0,))
            t_last_end = t_end
        toFile.write("Commit (ms): %.3f\n" % ((time.time() - t_last_end) * 1000.0,))
        toFile.write("***\n\n")

        if self.logFileName:
            with open(self.logFileName, "a") as f:
                f.write(toFile.getvalue())
        else:
            log.error(toFile.getvalue())

        return (total_statements, total_rows, total_time,) 
Example 52
Source File: __init__.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def reportPrintProgressChanged(self):
		self._printerManager.mcProgress()

	#
	# Call this function when there a layer change
	# 
Example 53
Source File: fees_detail_report_wizard.py    From -Odoo--- with GNU General Public License v3.0 5 votes vote down vote up
def print_report(self):
        data = {}
        if self.fees_filter == 'student':
            data['fees_filter'] = self.fees_filter
            data['student'] = self.student_id.id
        else:
            data['fees_filter'] = self.fees_filter
            data['course'] = self.course_id.id

        report = self.env.ref(
            'lxb-fees.action_report_fees_detail_analysis')
        return report.report_action(self, data=data) 
Example 54
Source File: line_profile.py    From cupy with MIT License 5 votes vote down vote up
def print_report(self, file=sys.stdout):
        """Prints a report of line memory profiling."""
        line = '_root (%s, %s)\n' % self._root.humanized_bytes()
        file.write(line)
        for child in self._root.children:
            self._print_frame(child, depth=1, file=file)
        file.flush() 
Example 55
Source File: fit.py    From fooof with Apache License 2.0 5 votes vote down vote up
def print_report_issue(concise=False):
        """Prints instructions on how to report bugs and/or problematic fits.

        Parameters
        ----------
        concise : bool, optional, default: False
            Whether to print the report in a concise mode, or not.
        """

        print(gen_issue_str(concise)) 
Example 56
Source File: utils.py    From UCB with MIT License 5 votes vote down vote up
def print_model_report(model):
    print('-'*100)
    print(model)
    print('Dimensions =',end=' ')
    count=0
    for p in model.parameters():
        print(p.size(),end=' ')
        count+=np.prod(p.size())

    print()
    print('Num parameters = %s'%(human_format(count)), human_format(sum(p.numel() for p in model.parameters())))
    print('-'*100)
    return count 
Example 57
Source File: topoflow_driver.py    From topoflow with MIT License 4 votes vote down vote up
def print_mass_balance_report(self):            

        #--------------------------------------
        # Updated for new framework. (2/5/13)
        #--------------------------------------
        vol_P  = self.vol_P
        vol_SM = self.vol_SM
        vol_IN = self.vol_IN
        vol_Rg = self.vol_Rg
        vol_ET = self.vol_ET
        vol_GW = self.vol_GW
        vol_R  = self.vol_R
        
        TF_Print('Volume rain        = ' + str(vol_P)  + ' [m^3]')
        TF_Print('Volume snowmelt    = ' + str(vol_SM) + ' [m^3]')
        TF_Print('Volume infiltrated = ' + str(vol_IN) + ' [m^3]')
        TF_Print('Volume evaporated  = ' + str(vol_ET) + ' [m^3]')
        TF_Print('Volume seepage     = ' + str(vol_GW) + ' [m^3]')
        TF_Print('Volume runoff      = ' + str(vol_R)  + ' [m^3]')
        TF_Print('Volume bottom loss = ' + str(vol_Rg) + ' [m^3]')
        TF_Print(' ')

        RICHARDS = self.ip.get_scalar_long('RICHARDS')
        print 'In topoflow.print_mass_balance_report(),'
        print '   RICHARDS =', RICHARDS
        print ' '
        if (RICHARDS):    
            #----------------------------------------
            # Richards' equation for infiltration
            # Ground water losses not counted above
            #----------------------------------------
            da         = self.da
            n_pixels   = self.n_pixels   #####
            vol_stored = np.float64(0)
            SCALAR_dz  = (np.size( self.ip.dz ) == 1)
            SCALAR_da  = (np.size(da) == 1)     #(assume da is scalar or grid)
            #-----------------------------------
            dim_q  = np.ndim( self.ip.q )
            dim_qi = np.ndim( self.ip.qi )
            #----------------------------------
            for k in xrange(self.ip.nz):
                #--------------------------------------
                # In this loop, dz is always a scalar
                #--------------------------------------
                if (SCALAR_dz):    
                    dz = self.ip.dz
                else:    
                    dz = self.ip.dz[k]
                if (dim_q == 3):    
                    qq = self.ip.q[k,:,:]
                else:    
                    qq = self.ip.q[k]
                if (dim_qi == 3):    
                    qqi = self.ip.qi[k,:,:]
                else:    
                    qqi = self.ip.qi[k]
                #----------------------------------------
                # Get increase in q over initial values
                # (but q may have decreased due to ET)
                #----------------------------------------
                dq = (qq - qqi)   #(grid or scalar)
                da
                SCALAR_dq = (np.size(dq) == 1)
                if (SCALAR_da and SCALAR_dq):    
                    dm = dq * (dz * da * n_pixels)      #(da is a SCALAR)
                else:    
                    dm = np.sum(np.double(dq * (da * dz)))    #(da is a GRID)
                vol_stored += dm
            mass_error = np.float64(100) * (vol_IN - vol_stored) / vol_IN
            err_str = ('%6.2f' % mass_error) + ' % '
            TF_Print('Volume stored      = ' + TF_String(vol_stored) + ' [m^3]')
            TF_Print('Volume error       = ' + err_str)
        TF_Print(' ')

    #   print_mass_balance_report()
    #------------------------------------------------------------- 
Example 58
Source File: BMI_base.py    From topoflow with MIT License 4 votes vote down vote up
def print_final_report(self, comp_name='BMI component',
                           mode='nondriver'):

        if (mode == 'nondriver'):
            print comp_name + ': Finished.'
            return

        if not(hasattr( self, 'in_directory' )):
            return   # (2/20/12)
        
        #-------------------
        # Print the report
        #-------------------
        hline = ''.ljust(60, '-')
        print hline
        print comp_name
        print time.asctime()
        print ' '
        print 'Input directory:      ' + self.in_directory
        print 'Output directory:     ' + self.out_directory
        print 'Site prefix:          ' + self.site_prefix
        print 'Case prefix:          ' + self.case_prefix
        print ' '

        #-----------------------------------
        # Construct sinulation time string
        #-----------------------------------
        sim_units    = ' [' + self.time_units + ']'
        sim_time_str = str(self.time) + sim_units
        
        #----------------------------
        # Construct run time string
        #----------------------------
        run_time_str = self.get_run_time_string() 

        print 'Simulated time:      ' + sim_time_str
        print 'Program run time:    ' + run_time_str
        print ' '
        print 'Number of timesteps: ' + str(self.time_index)
        print 'Process timestep:    ' + str(self.dt) + sim_units
        print 'Number of columns:   ' + str(self.nx)
        print 'Number of rows:      ' + str(self.ny)
        print ' '
        print 'Finished. (' + self.case_prefix + ')'
        print ' '

        ## finish_str = ': Finished. (' + self.case_prefix + ')'
        ## print finish_str
        ## print comp_name + finish_str
        
    #   print_final_report()
    #-------------------------------------------------------------------