def OnReport(self,event): with wx.FileDialog(self, "Save Pdf File", wildcard="Input File (*.pdf)|*.pdf", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # the user changed their mind # save the current contents in the file pathname = fileDialog.GetPath() # pdf file try: num = int( self.text_ctrl_idTotal.GetValue() ) print(num) title = "none" #for i in range(0,num): obj = report.Report() obj.create_pdf(num,pathname,title) del obj except IOError: wx.LogError("Cannot save current data in file '%s'." % pathname)
def generate_report(self, start_day, days, users=[], channels=None): """ Generate a channel stats report starting on start_day, which is formatted as yyyy-mm-dd, and for the period of DAYS duration """ # print("Generating report for {}/{}/{}".format(start_day, days, user)) report_creator = report.Report(channels=channels) report_creator.set_users(users) dates = self.generate_dates(start_day, days) report_creator.set_start_date(dates[0]) report_creator.set_end_date(dates[-1]) # print("For the report of {} days starting {} we have dates {}".format(days, start_day, dates)) tables = [self.mtf.get_message_table(date) for date in dates] # print("Message table names: {}".format(tables)) for table in tables: messages = table.scan()["Items"] for message in messages: report_creator.message(message) report_creator.finalize() current_report = report_creator.data() return current_report
def PrintReport(self, dbsal): def GetSezione(tipo): out = '' if tipo in "PEO": out = [ 'STATO PATRIMONIALE', 'CONTO ECONOMICO', 'CONTI D\'ORDINE' ]["PEO".index(tipo)] return out dbsal.GetSezione = GetSezione def GetRisultato(): return self.risultato dbsal.GetRisultato = GetRisultato def GetEsercizio(): return self.esercizio dbsal.GetEsercizio = GetEsercizio rpt.Report(self, dbsal, "Saldi sottoconti per chiusura bilancio")
def dateErrors(dateclass, ballotclass): r = report.Report() t = report.Table() r.addTitle('Datetime Errors') if len(dateclass.D3) == 0: r.addTextBox('No date errors found') else: r.addTextBox( 'List machines with detected date anomalies. Includes last known "good" event as well as what event was determined to be the error and how many following events it affected.' ) t.addHeader('Machine') t.addHeader('Last Event') t.addHeader('Anomalous Event') t.addHeader('Occurances') for k, v in dateclass.D3.iteritems(): t.addRow([k, str(v[0]), str(v[1]), str(v[2])]) r.addTable(t) return r
def Stampa(self): def cn(x): return self.FindWindowByName(x) dec, aec, dep, aep = map( lambda x: cn(x).GetValue() or 0, 'progrlastecd progrlasteca progrlastepd progrlastepa'.split()) i = self.dbmov._info i.ripdare_ec, i.ripavere_ec = dec, aec i.ripdare_ep, i.ripavere_ep = dep, aep # i.anno_ec = self.dbese.GetEsercizioInCorso() i.anno_ec = cn('esercizio').GetValue() i.anno_ep = i.anno_ec - 1 dec, aec, dep, aep = map( lambda x: cn(x).GetValue() or 0, 'progrnextecd progrnexteca progrnextepd progrnextepa'.split()) i.esepre = (dep != 0 or aep != 0) for c in 'tiposta intatt intdes intanno intpag'.split(): setattr(i, c, cn(c).GetValue()) s = rpt.Report(self, self.dbmov, 'Giornale Generale') if cn('tiposta').GetValue() == 'D': aw.awu.MsgDialog(self, "Stampa giornale terminata.") if aw.awu.MsgDialog(self,\ """Confermando questa scelta, la stampa ottenuta diverrà definitiva, ovvero:\n""" """- le registrazioni coinvolte verrnno numerate definitivamente come sulla stampa;\n""" """- saranno nuovamente stampabili sul giornale, se necessario, solo mediante funzione di ristampa;\n""" """- i progressivi dare/avere verranno memorizzati in modo da essere ripresi alla stampa successiva.\n\n""" """Confermi l'elaborazione definitiva dei movimenti?""", style=wx.ICON_QUESTION|wx.YES_NO|wx.YES_DEFAULT) == wx.ID_YES: self.RendiStampaDefinitiva() prg = self.dbprg prg.ReadKey('ccg_giobol', '0') if prg.OneRow(): p = s.usedReport.oCanvas.userVariableList['intpag'] prg.progrimp1 = cn('intanno').GetValue() prg.progrimp2 = p.valore prg.Save() self.Close() self.SetValues()
def StampaScadenzario(self, singolo=False, sintesi=False): db = self.dbscad row = self.gridtot2.GetSelectedRows()[0] if row < db.RowsCount(): db.MoveRow(row) nome = "Scadenzario clienti-fornitori" cn = lambda x: self.FindWindowByName(x) cf = cn('pcftipocf').GetValue() db._info.gruppo = '' db._info.clifor = ['Clienti', 'Fornitori']['CF'.index(cf)] if sintesi: nome = "Sintesi " + nome testrec = db else: testrec = db.mastro if cn('pcfraggrage').GetValue(): nome += ' per agente' elif cn('pcfraggrzna').GetValue(): nome += ' per zona' def setCPP(rptdef, dbt): groups = rptdef.lGroup for g in groups: if groups[g].name == 'sottoconto': if self.dbscad._info.cpp: snp = 'true' else: snp = 'false' groups[g].isStartNewPage = snp rpt.Report(self, db, nome, testrec=testrec, noMove=singolo, exitOnGroup=singolo, startFunc=setCPP, filtersPanel=self.FindWindowByName('filterspanel'))
def generate_report(self, start_day, days, users=[], channels=[]): """ Generate a channel stats report starting on start_day, which is formatted as yyyy-mm-dd, and for the period of DAYS duration """ print("Generating report for {}/{}".format(start_day, days)) report_creator = report.Report() report_creator.set_users(users) report_creator.set_channels(channels) dates = self.generate_dates(start_day, days) report_creator.set_start_date(dates[0]) report_creator.set_end_date(dates[-1]) # print("For the report of {} days starting {} we have dates {}".format(days, start_day, dates)) # print("Message table names: {}".format(tables)) for date in dates: for message in self.Message.messages_for_day(date): report_creator.message(message) report_creator.finalize() current_report = report_creator.data() f = open("reports/{}-{}days-report.json".format(start_day, days), "w") f.write(json.dumps(current_report, indent=4)) f.close() return current_report
def print_report(itemset, ig, dataset, labels_and_uids_list, label): """ this function write details about the given 'itemset' to the report file :param itemset: :param ig: :param dataset: :param labels_and_uids_list: :param label: :return: """ rep = report.Report() rep.set_itemset(itemset) rep.set_ig(ig) for i, trans in enumerate(dataset): set_trans = set(trans) if itemset.issubset(set_trans): rep.add_genome(labels_and_uids_list[i][1]) if labels_and_uids_list[i][0] == label: rep.increase_num_of_label1() else: rep.increase_num_of_label2() rep.print_report(REPORT_FILE_PATH)
def PrintGiac(self): d = ListGiacenzeDialog(self) if d.ShowModal() == wx.ID_OK: def cn(x): return self.FindWindowByName(x) def dc(x): return d.FindWindowByName(x) gia = self.dbpro if dc('tipoprod').GetValue() == "S": inv = dbx.EditGiacenzeTable(tipval=gia.GetTipVal()) for f, p in gia._info.filters: inv.AddFilter(f, *p) magid, anno, tpv = map(lambda x: cn(x).GetValue(), 'magazz anno tipval'.split()) inv.AddBaseFilter("giafis IS NOT NULL AND giafis<>0") inv.procos.SetRelation( "procos.id_prod=prod.id AND procos.anno=%d" % anno) inv.progia.SetRelation( "progia.id_prod=prod.id AND progia.anno=%d AND progia.id_magazz=%d" % (anno, magid)) self.GetParent().SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) try: inv.Retrieve() finally: self.GetParent().SetCursor(wx.NullCursor) else: inv = gia i = inv._info i.proval = dc('tipoval').GetValue() i.giacon = dc('stagcon').GetValue() i.tipval = cn('tipval').GetValue() rpt.Report(self, inv, "Lista giacenze rilevate") d.Destroy()
def make_report(msg, user): """ generates a report out of a mail :param msg: email.parser.Message object :return: post: report.Report object """ # get a comparable date out of the email date = get_date_from_header(msg['Date']) author = msg['From'] # get mail author from email header if msg.is_multipart(): text = [] for part in msg.get_payload(): if part.get_content_type() == "text": text.append(part.get_payload()) elif part.get_content_type() == "application/pgp-signature": pass # ignore PGP signatures elif part.get_content_type() == "multipart/mixed": for p in part: if isinstance(p, str): text.append(p) elif p.get_content_type() == "text": text.append(part.get_payload()) else: logger.error("unknown MIMEtype: " + p.get_content_type()) else: logger.error("unknown MIMEtype: " + part.get_content_type()) text = '\n'.join(text) else: text = msg.get_payload() post = report.Report(author, "mail", text, None, date) user.save_seen_mail(date) return post
def run_batch(start_id, end_id, saving_target=2, cached_weather=True, batch_report=False): v_single_buildings = [] v_single_building_reports = [] for i in range(start_id, end_id + 1): print('--------------------------------------------------') print('Analyzing building ' + str(i)) single_building = run_single(bldg_id=i, saving_target=saving_target, use_default_benchmark_data=True, cached_weather=cached_weather)[1] v_single_buildings.append(single_building) if batch_report: report_path = os.path.dirname( os.path.dirname(os.path.realpath(__file__))) + '/outputs/' portfolio_out = portfolio.Portfolio('Sample Portfolio') portfolio_out.prepare_portfolio_report_data(v_single_buildings, report_path) report_portfolio = report.Report(portfolio=portfolio_out) report_portfolio.generate_portfolio_report(report_path)
def PrintData(self): rpt.Report(self, self.dbprm, "Condizioni promozionali di vendita")
def record(): # Sets a timer for one hour from when recording begins dt = datetime.now() + timedelta(hours=1) vid = cv2.VideoCapture(0) # Facial landmark library detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") currentCount = 0 while True: check, frame = vid.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray) for face in faces: landmarks = predictor(gray, face) # Finds position of landmarks in right eye. leftVerticalDistOne = distance(landmarks.part(37), landmarks.part(41)) leftVerticalDistTwo = distance(landmarks.part(38), landmarks.part(40)) leftHorizontalDist = distance(landmarks.part(36), landmarks.part(39)) leftEyeRatio = (leftVerticalDistOne + leftVerticalDistTwo) / (2 * leftHorizontalDist) # Finds position of landmarks in left eye. rightVerticalDistOne = distance(landmarks.part(43), landmarks.part(47)) rightVerticalDistTwo = distance(landmarks.part(44), landmarks.part(46)) rightHorizontalDist = distance(landmarks.part(42), landmarks.part(45)) rightEyeRatio = (rightVerticalDistTwo + rightVerticalDistOne) / (2 * rightHorizontalDist) avgEyeRatio = (leftEyeRatio + rightEyeRatio) / 2 # Checks if you blinked. Other if statements are to ensure that one blink is not counted as multiple if avgEyeRatio < threshold: print(avgEyeRatio) currentCount += 1 if currentCount == countThreshold and avgEyeRatio < threshold: global blinkCount blinkCount += 1 print(blinkCount) if currentCount > 0 and avgEyeRatio > 0.18: currentCount = 0 cv2.imshow("Frame", frame) # Sends a report of blinking status every hour. global Tracking if datetime.now() > dt and Tracking: newReport = report.Report(blinkCount, 60) newReport.sendMail() dt = datetime.now() + timedelta(hours=1) #Quits when pressing q if cv2.waitKey(1) & 0xFF == ord('q'): break vid.release() cv2.destroyAllWindows() print(blinkCount) return blinkCount
def handlego(self): r=report.Report() html=r.genAveSingleReportTonly("aveSingle2") self.web1.setHtml(html) pass
import glob import re import report import icalibtools re_generalparams = re.compile('log/(AMAC_[a-zA-Z0-9]+)_GeneralParams.log') # # Find all of the available AMAC tests reports = [] for path in glob.glob('log/AMAC_???_GeneralParams.log'): match = re_generalparams.match(path) reports.append(report.Report(match.group(1))) reports = report.Reports(reports) # # Perform the calibration icalib = icalibtools.calibrate(reports.icalib, fixCalib=True) # # Save data for amackey, amacgroup in icalib.groupby('AMAC'): amacgroup.to_csv('data/calib/icalib_%s.csv' % amackey, index=False) # # Save pretty images for ckey, cdata in reports.icalib.groupby( ['AMAC', 'Channel', 'BandgapControl', 'RampGain', 'OpAmpGain']):
canContinue = options.initOptions() if not canContinue: # Something changed in the .rc file that needs manual editing globs.closeEverythingAndExit(1) # Looking for version info on command line? (-V) if globs.opts['version']: # Print version info & exit versionInfo() globs.closeEverythingAndExit(0) # Open log file (finally!) globs.log.openLog(globs.opts['logpath'], globs.opts['logappend'], globs.opts['verbose']) # Open report object and validate report options # We may not be running reports, but the options will be needed later in the program globs.report = report.Report() if globs.report.validConfig is False: errmsg = 'Report configuration has errors. See log file {} for specific error messages.'.format( globs.logName) globs.log.err(errmsg) globs.log.write(globs.SEV_ERROR, function='main', action='ValidateConfig', msg=errmsg) globs.closeEverythingAndExit(0) if globs.opts[ 'validatereport'] == True: # We just want to validate the report. Exit from here without doing anyting else. globs.closeEverythingAndExit(0) # See if [apprise] is enabled in .rc file. If so, initialize Apprise options if str.lower(globs.optionManager.getRcOption('apprise',
def test_getattr(self): r = report.Report() r.values['mun_name'] = 'foobar' self.assertEqual(r.mun_name, 'foobar')
def PrintData(self): rpt.Report(self, self.dbvpv, 'Valutazione Prezzi Vendita')
sys.exit() # CLI : Send test message to Pagers ? if cmt.ARGS["pager_test"]: pager.send_test() sys.exit() # CLI : List available modules option ? if cmt.ARGS["listmodules"]: print("Available modules: ") for key in cmt.GLOBAL_MODULE_MAP: print(" - ", key) sys.exit() # ----------------- myreport = report.Report() myreport.print_header() # set global timer to limit global duration maxexec = cmt.CONF['global'].get("max_execution_time", cmt.MAX_EXECUTION_TIME) signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(maxexec) # seconds # main loop for modulename in cmt.GLOBAL_MODULE_MAP: if modulename in cmt.CONF: for checkname in cmt.CONF[modulename]: check_result = check.perform_check(checkname, modulename) if type(check_result) is str: if check_result == "break":
def OnPrint(self, event): rpt.Report(self, self.gridmov.dbmov, "Stato evasione movimenti") event.Skip()
import sys sys.path.append("..") import report rpt = report.Report( 'C:/Users/peter/Desktop/My-FyiReporting-master/Examples/SqliteExamples/SimpleTest1.rdl' ) rpt.export("pdf", "C:/Users/peter/Desktop/test/hello2.pdf")
def Stampa(self, dbt, rptname, rpttitle, **kwargs): dbt._info.titleprint = rpttitle rpt.Report(self, dbt, rptname, **kwargs)
def test_inc(self): r = report.Report() r.inc('foo') self.assertEqual(r.foo, 1) r.inc('foo', 2) self.assertEqual(r.foo, 3)
def test_get(self): r = report.Report() self.assertEqual(r.get('foo', 'bar'), 'bar') self.assertEqual(r.get('bar'), 0)
def crm_report(): return report.Report()
def main(): parser = ArgumentParser(description='PGObserver Frontend') parser.add_argument( '-c', '--config', help= 'Path to yaml config file with datastore connect details. See pgobserver_frontend.example.yaml for a sample file. \ Certain values can be overridden by ENV vars PGOBS_HOST, PGOBS_DBNAME, PGOBS_USER, PGOBS_PASSWORD [, PGOBS_PORT]' ) parser.add_argument( '--s3-config-path', help= 'Path style S3 URL to a key that holds the config file. Or PGOBS_CONFIG_S3_BUCKET env. var', metavar='https://s3-region.amazonaws.com/x/y/file.yaml', default=os.getenv('PGOBS_CONFIG_S3_BUCKET')) parser.add_argument( '-p', '--port', help='Web server port. Overrides value from config file', type=int) args = parser.parse_args() settings = collections.defaultdict(dict) if args.s3_config_path: # S3 has precedence if specified import aws_s3_configreader settings = aws_s3_configreader.get_config_as_dict_from_s3_file( args.s3_config_path) elif args.config: args.config = os.path.expanduser(args.config) if not os.path.exists(args.config): print 'WARNING. Config file {} not found! exiting...'.format( args.config) return print "trying to read config file from {}".format(args.config) with open(args.config, 'rb') as fd: settings = yaml.load(fd) # Make env vars overwrite yaml file, to run via docker without changing config file settings['database']['host'] = (os.getenv('PGOBS_HOST') or settings['database'].get('host')) settings['database']['port'] = (os.getenv('PGOBS_PORT') or settings['database'].get('port') or 5432) settings['database']['name'] = (os.getenv('PGOBS_DATABASE') or settings['database'].get('name')) settings['database']['frontend_user'] = ( os.getenv('PGOBS_USER') or settings['database'].get('frontend_user')) settings['database']['password'] = ( os.getenv('PGOBS_PASSWORD') or settings['database'].get('frontend_password')) if not (settings['database'].get('host') and settings['database'].get('name') and settings['database'].get('frontend_user')): print 'Mandatory datastore connect details missing!' print 'Check --config input or environment variables: PGOBS_HOST, PGOBS_DATABASE, PGOBS_USER, PGOBS_PASSWORD [, PGOBS_PORT]' print '' parser.print_help() return conn_string = ' '.join(( 'dbname=' + settings['database']['name'], 'host=' + settings['database']['host'], 'user='******'database']['frontend_user'], 'port=' + str(settings['database']['port']), )) print 'Setting connection string to ... ' + conn_string # finished print conn_string to the world, password can be added conn_string = conn_string + ' password='******'database'][ 'frontend_password'] datadb.setConnectionString(conn_string) current_dir = os.path.dirname(os.path.abspath(__file__)) conf = { 'global': { 'server.socket_host': '0.0.0.0', 'server.socket_port': args.port or settings.get('frontend', {}).get('port') or 8080 }, '/': { 'tools.staticdir.root': current_dir, 'request.dispatch': HostIdAndShortnameDispatcher() }, '/healthcheck': { 'tools.sessions.on': False }, '/static': { 'tools.staticdir.dir': 'static', 'tools.staticdir.on': True, 'tools.sessions.on': False }, '/manifest.info': { 'tools.staticfile.on': True, 'tools.staticfile.filename': os.path.join(current_dir, '..', 'MANIFEST.MF'), 'tools.auth_basic.on': False, 'tools.sessions.on': False }, } tplE.setup( settings) # setup of global variables and host data for usage in views root = welcomefrontend.WelcomeFrontend() root.host = monitorfrontend.MonitorFrontend() root.report = report.Report() root.export = export.Export() root.perftables = performance.PerfTables() root.perfapi = performance.PerfApi() root.perfindexes = performance.PerfIndexes() root.perfschemas = performance.PerfUnusedSchemas() root.perflocks = performance.PerfLocksReport() root.perfstatstatements = performance.PerfStatStatementsReport() root.perfbloat = performance.PerfBloat() root.sprocs = sprocsfrontend.SprocFrontend() root.tables = tablesfrontend.TableFrontend() root.indexes = indexesfrontend.IndexesFrontend() root.hosts = hostsfrontend.HostsFrontend() root.api = api.Root( root ) # JSON api exposure, enabling integration with other monitoring tools root.healthcheck = Healthcheck() if settings.get('oauth', {}).get('enable_oauth', False): print 'switching on oauth ...' import oauth root.oauth = oauth.Oauth(settings['oauth']) cherrypy.config.update({ 'tools.oauthtool.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': settings['oauth'].get('session_timeout', 43200) }) cherrypy.quickstart(root, config=conf)
def run(handleOK=False, debug=False): """ Runs the bot """ print english.produce_fuel coordinate = mapExtractor.getFuelstation() if None == coordinate: raise ValueError("Map positions are not initialized") print english.move_mouse_to_browser print english.start_in alphaBotUtility.countDownwards(5) infix = datetime.datetime.now().strftime("%d-%m-%y_%H-%M-%S") currentRun = 0 while True: currentReport = report.Report() if handleOK: clickOK() backgroundLayerPath = captchaExtractor.extractBackgroundLayer( coordinate[0], coordinate[1], nameInfix=infix) currentReport.setBackgroundLayer(backgroundLayerPath) # move to factory autopy.mouse.smooth_move(coordinate[0], coordinate[1]) # extract capture captchaPath = captchaExtractor.extractCaptcha(coordinate[0], coordinate[1], nameInfix=infix) currentReport.setCaptcha(captchaPath) delta_x = None delta_y = None (delta_x, delta_y) = tetragonDetector.findTetragonLineBased( captchaPath, report=currentReport, backgroundLayerPath=backgroundLayerPath, _debug=False) if not None == delta_x and not None == delta_y: target_x = int(coordinate[0] - 50 + delta_x) target_y = int(coordinate[1] + delta_y) currentReport.setTargetCoordinates(delta_x, delta_y) # move the mouse to prevent the blackening of the screen autopy.mouse.smooth_move(coordinate[0] - random.randint(0, 100), coordinate[1] - random.randint(0, 100)) # move to detected tetragon and click if not None == delta_x and not None == delta_y: clickCoordinate(target_x, target_y) currentReport.save("report_" + str(currentRun) + ".txt") currentRun += 1 # wait 60 seconds alphaBotUtility.countDownwards(60)
def test_init(self): r = report.Report(foo = 'bar') self.assertEqual(r.foo, 'bar')
def OnPrint(self, event): rpt.Report(self, self.gridmov.dbmov, "Lista movimenti magazzino") event.Skip()
def PrintData(self): rpt.Report(self, self.dbred, "Redditivita' vendite")