def printIndex(self): widget = QApplication.focusWidget() if self.state.printer is None: self.state.printer = QPrinter(QPrinter.HighResolution) self.state.printer.setColorMode(QPrinter.GrayScale) settings = QSettings() size = PaperSizeKind( int(settings.value(Gopt.Key.PaperSize, Gopt.Default.PaperSize))) self.state.printer.setPaperSize( QPrinter.Letter if size is PaperSizeKind.LETTER else QPrinter. A4) with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True): form = QPrintDialog(self.state.printer, self.state.window) form.setWindowTitle("Print Index") if form.exec_(): try: with Lib.DisableUI(*self.window.widgets()): config = self.state.model.configs().copy() config.Filename = "print.$$$" config.Printer = self.state.printer Output.outputEntries(self.state.model, config, "Printing", self.window.reportProgress) say("Printed") except Output.Error as err: say("Failed to print: {}".format(err)) logging.error("printIndex failed: {}".format(err)) Lib.restoreFocus(widget)
def generate_suite_desc(self): suite_def = suite_desc_template % ( \ get_fixture_array_name(self.suite), \ get_fixture_array_name(self.suite), \ get_fixture_array_name(self.suite) ) Output.output(suite_def, self.file)
def test_01(self): data = (("One", "1, 2, <b>3</b>, <i>15\u201320</i>"), ("Two", "[email protected]<i>tbl</i>, <i>[email protected]\u201320</i>")) basename = "TestPagesAtOutput" model = None try: model = Xix.Model.Model(self.username) model.open(":memory:", *self.args) self.assertEqual(0, len(model)) added = [] for term, pages in data: model.addEntry(Saf.AUTO, SortAs.wordByWordCMS16(term), term, pages=pages) added.append(term) self.assertEqual(len(data), len(model)) config = model.configs() i = 0 for extension in EXPORT_EXTENSIONS.keys(): with self.subTest(i=i): if extension not in {".*", ".ucp", ".pdf"}: i += 1 filename = basename + extension actualfile = "/tmp/" + filename expectedfile = os.path.join("tests/expected/", filename) config.Filename = actualfile self.files.append(config.Filename) Output.outputEntries(model, config, "", reportProgress) tests.Util.compare_files(self, actualfile, expectedfile) finally: if model is not None: model.close()
def runSearch(path, string, optionsList, returnResults, colors): # start the search thread and timer startTime = time.time() search = Search.Search(string, optionsList) search.start() # start the status thread status = Output.Status(optionsList, string, search, False, colors) status.start() # join the threads and grab the results search.join() results = search.finish() status.finish() status.join() # calculate the elapsed time elapsedTime = (time.time() - startTime) # print the search results Output.results(path, string, optionsList, results, elapsedTime, colors) if returnResults: return EXIT_RESULTS, results else: return EXIT_CLEAN, results
def start_simulation(self): time = 0.0 Output.DumpOneTimeStep(self.name, self.reactor, 0) while time < 0.05: #for i in range(1,self.timesteps + 1): dT, componentDiffusion = self.reactor.get_next_bireaction_time() disperse = dT / self.stepsize > self.threshold self.reactor.apply_forces(self.stepsize, dT, disperse, componentDiffusion) #if not i % 100: # print i # self.reactor.location_infuser() # Output.DumpOneTimeStep(self.name,self.reactor,i) self.reactor.boundaries.reflective(self.reactor) self.reactor.cellList.update_particlelist(self.reactor) time += dT if disperse else self.stepsize #print time Output.NewMSDScript(self.name) return time
def test_01_ixml(self): model = None try: model = Xix.Model.Model(self.username) infile = os.path.join(PATH, "TestIndex-Indented.xix") model.open(infile, *self.args) markups = list(model.markups()) self.assertListEqual([".ucp"], markups) extension = ".app" markup = Output.Markup.user_markup() markup.escapefunction = "html" markup.DocumentStart = "<itml>" markup.DocumentEnd = "</itml>" markup.SectionStart = "<sp>" markup.MainStart = "<itm>" markup.MainEnd = "{nl}" markup.Sub1Start = "<sit2>" markup.Sub1End = "{nl}" markup.Sub2Start = "<sit3>" markup.Sub2End = "{nl}" markup.Sub3Start = "<sit4>" markup.Sub3End = "{nl}" markup.Sub4Start = "<sit5>" markup.Sub4End = "{nl}" markup.Sub5Start = "<sit6>" markup.Sub5End = "{nl}" markup.Sub6Start = "<sit7>" markup.Sub6End = "{nl}" markup.Sub7Start = "<sit8>" markup.Sub7End = "{nl}" markup.Sub8Start = "<sit9>" markup.Sub8End = "{nl}" markup.Sub9Start = "<sit10>" markup.Sub9End = "{nl}" markup.RangeSeparator = "–" markup.AltFontStart = "<scp>" markup.AltFontEnd = "</scp>" markup.BoldStart = "<b>" markup.BoldEnd = "</b>" markup.ItalicStart = "<it>" markup.ItalicEnd = "</it>" markup.SubscriptStart = "<u.inf>" markup.SuperscriptStart = "<u.sup>" markup.UnderlineStart = "<e1>" markup.UnderlineEnd = "</e1>" model.updateMarkup(extension, markup) markups = list(model.markups()) self.assertListEqual([".app", ".ucp"], markups) actualfile = "/tmp/TestIndex.app" self.files.append(actualfile) expectedfile = "tests/expected/TestIndex.app" config = model.configs() config.Filename = actualfile Output.outputEntries(model, config, "", reportProgress) tests.Util.compare_files(self, actualfile, expectedfile) finally: if model is not None: model.deleteMarkup(".app") model.close()
def getChoiceFromList(player, prompt, list, noChoices=1): Output.menuWindow.clear() Output.printToWindow(prompt + '\n', Output.menuWindow) invalidActions = player._determineValidOptions(list) freeActions = player._determineFreeOptions(list) count = 1 indexMapping = {} for i, currOption in enumerate(list): if currOption in invalidActions.keys(): Output.printToWindow('{0:2d} - {1} - {2}\n'.format(count, currOption, invalidActions.get(currOption)), Output.menuWindow, colorPair=1) elif currOption in freeActions.keys(): Output.printToWindow('{0:2d} - {1} - {2}\n'.format(count, currOption, freeActions.get(currOption)), Output.menuWindow, colorPair=2) indexMapping[count] = currOption else: Output.printToWindow('{0:2d} - {1}\n'.format(count, currOption), Output.menuWindow) indexMapping[count] = currOption count += 1 chosenOption = [] while True: for i in range(0, noChoices): Output.printToWindow('%d of %d : '%(i, noChoices), Output.menuWindow) choice = int(Output.menuWindow.getstr(2)) #choice -= 48 if choice >= 1 and choice <= len(list): if choice in indexMapping: if noChoices > 1: chosenOption.append(indexMapping[int(choice)]) else: chosenOption = indexMapping[int(choice)] if len(chosenOption) > 0: return chosenOption
def manual_input(): print('-------------------------------------------------------') matrix = Input.insert_matrix() print("Matrix: ") Output.print_matrix(matrix) result = Determinant.calculate_determinant(matrix) print('Determinant: ' + str(Output.round_number(result)))
def print_menu(): # run menu while True: clear() print(''' Weather diary 1. Add/Edit Element 2. Remove Element 3. Show data 4. Show data by month 5. Exit ''') ans = Input.get_choice() # input menu key if ans == 1: W_diary.add_data() elif ans == 2: W_diary.rm_data() elif ans == 3: Output.show_data() elif ans == 4: Output.show_data_by_month() elif ans == 5: os._exit(1) else: print('Try again')
def generate_headers(self): self.generate_dep_headers() for header in self.fixture_files: Output.output( "#include \"" + os.path.relpath( header, os.path.dirname(os.path.abspath(self.target))) + "\"", self.file)
def generate_testcase_array(self): begin = testcase_array_template_begin % (get_testcase_array_var(self.fixture)) Output.output(begin, self.file) self.generate_testcase_array_content() Output.output(array_template_end, self.file)
def BusHeuPorCiudad(): origen = "nada" while origen == "nada": capital = input("ingrese capital de origen: ") origen = busHeu.BuscarIndice(capital, CapitalesArg) Resultados = busHeu.BusquedaHeuristicaDeUnOrigen(origen, CapitalesArg) #print(Resultados) Output.resultScreen(Resultados)
def show_single_photo(): if PhotoThread.photo_load_threads()[0].is_alive(): Output.debug("PLT is still running. Sleeping 0.5s before trying again.") Display.root().after(500, show_single_photo) return Display.show_single_photo() Output.debug("Display.show_single_photo() returned") Settings.WAIT_FOR_BUTTON_PRESS = True Settings.ON_BUTTON_PRESS = lambda: Settings.main_script.start()
def BusGenetic(): pob = Population(.8, .4) Output.resultScreen(pob.output()) print(pob.output()) while pob.Gen < 500: print(pob.output().get("total")) pob.nextGen() print(pob.output()) Output.resultScreen(pob.output())
def __init__(self): self.input = Input() self.input.game = self self.output = Output() self.player = Player() self.server = Server() self.server.game = self self.locations = dict() self.event = multiprocessing.queues.SimpleQueue()
def start_run(script): """Starts a new run. Is called whenever someone pushes the button (when the script is waiting for it, of course).""" global filename_schema global download_id Settings.runs += 1 download_id = ''.join(["%s" % randint(0, 9) for num in range(0, 8)]) filename_schema = time.strftime("photos/%Y%m%d-%H%M%S---" + download_id + "---{}.jpg") Output.debug("start_run results: download_id=" + download_id + " filename_schema=" + filename_schema) script.next_step()
def parameter_input(string_matrix): matrix = Input.get_matrix(string_matrix) result = Determinant.calculate_determinant(matrix) if str(result).lower().__contains__('e'): return Output.exponential_output(result) else: if result != 0: return Output.round_number(result) else: return 0
def CreateConnection(self): try: self.con = mysql.connector.Connect(host=self.host, user=self.username, password=self.password, database=self.database) self.mysql = self.con.cursor(dictionary=True) Output.Write("Connected to MySQL server", "success") except mysql.connector.Error: Output.Write("Connection to MySQL server has failed", "error")
def run(self): Output.debug("PhotoLoadThread " + str(self.index) + " starting...") # Load the photo Output.debug("PhotoLoadThread " + str(self.index) + ": Opening...") self.image = Image.open(self.filename) Output.debug("PhotoLoadThread " + str(self.index) + ": Fitting...") self.image = ImageOps.fit(self.image, (Display.image_size(self.fullsize), Display.image_size(self.fullsize))) Output.debug("PhotoLoadThread " + str(self.index) + ": TKing...") images()[self.index] = ImageTk.PhotoImage(self.image) Output.debug("PhotoLoadThread " + str(self.index) + " finished.")
def output_control_file(self): try: control_string, _ = self.produce_control_file() filename, _ = QFileDialog.getSaveFileName(None, "QFileDialog.getOpenFileName()", "", "Control File (*.txt);;") Output.save_text_to_file(control_string, filename) except NoStartSymbolError: QMessageBox.about(self, "Error", "A start symbol has to be selected") except MultipleStartSymbolsError: QMessageBox.about(self, "Error", "Multiple start symbols are not allowed") except NoImportedGrammarError: QMessageBox.about(self, "Error", "No grammar imported")
def main(): #Input config=Input.load_config("appconfig.yaml") employee_list=Input.generate_employee_data(config,Input.get_current_payperiod()) #Process for employee in employee_list: employee.process_employee_vcp() #Output print(Output.serialize(employee_list)) Output.save_to_db(config["db_setting"],employee_list)
def createRiceMap(year): ndvi = getDataForYear("NDVI", year) evi = getDataForYear("EVI", year) lswi = getDataForYear("LSWI", year) blue = getDataForYear("BLUE", year) riceMap = thresholdAlgo(ndvi, evi, lswi, blue) # vi = gdal.Open(os.path.join(dataFolderDir, "EVI_2005_DBSH.tif")) # HACK # geoT = vi.GetGeoTransform() # proj = vi.GetProjection() Output.createTiff(riceMap, 'Threshold', str(year)) print Evaluation.evaluate(riceMap, year)
def generate(self): fixture_desc_def = fixture_desc_template % ( \ get_fixture_desc_var(self.fixture), \ self.fixture.get_name(), \ os.path.basename(self.fixture.get_file_name()), \ get_testcase_array_var(self.fixture), \ get_testcase_array_var(self.fixture), \ get_testcase_array_var(self.fixture) ) Output.output(fixture_desc_def, self.file) if self.recordFixture: global fixtureDescs fixtureDescs.append(get_fixture_desc_var(self.fixture))
def test_02_ximl(self): model = None try: model = Xix.Model.Model(self.username) infile = os.path.join(PATH, "TestIndex-Indented.xix") model.open(infile, *self.args) config = model.configs() outfile = config.Filename = "/tmp/TestXiml1.ximl" Lib.remove_file(outfile) self.files.append(outfile) Output.outputEntries(model, config, "", reportProgress) finally: if model is not None: model.close()
def main(wish): # variable for checking type of errors error_code = 0 answer = "" result = False all_data = dict() try: # load information from json-file all_data, error_code = Json.reading_from_the_data_file() except: error_code = 2 if error_code == 0: answer, result, error_code = Logic.core(all_data, wish) if result == True: # management command: switch off if answer == "Ok, bye": subprocess.call(["shutdown", "/s"]) # management command: restart elif answer == "Ok, see you soon": subprocess.call(["shutdown", "/r"]) elif answer == "Ok, here it is": if platform.system() == "Windows": os.startfile("C:") elif platform.system() == "Darwin": subprocess.Popen(["open", "C:"]) else: subprocess.Popen(["xdg-open", "C:"]) else: # show answer to user Output.positive_output(answer) # if answer wasn't given... elif result == False: # show sorry-message to user Output.negative_output() # write wish to the list for future answers error_code = Json.writing_to_the_data_file(wish) return answer, result, error_code
def generate(self): fixture_desc_def = fixture_desc_template % ( \ get_fixture_desc_var(self.fixture), \ self.fixture.get_name(), \ os.path.basename(self.fixture.get_file_name()), \ get_testcase_array_var(self.fixture), \ get_testcase_array_var(self.fixture), \ get_testcase_array_var(self.fixture) ) Output.output(fixture_desc_def, self.file) if self.recordFixture : global fixtureDescs fixtureDescs.append(get_fixture_desc_var(self.fixture))
def __init__(self, filePath): self.crossReferenceTable = [] self.char = "" self.word = "" self.wordlist = {} self.payload = [] self.eventStack = ["GET_CHAR"] self.run = True self.classificator = Classificator(filePath) self.delimiter = Delimiter() self.agregator = Agregator() self.sorter = Sorter() self.output = Output()
class TextProcessing: def __init__(self, filePath): self.crossReferenceTable = [] self.char = "" self.word = "" self.wordlist = {} self.payload = [] self.eventStack = ["GET_CHAR"] self.run = True self.classificator = Classificator(filePath) self.delimiter = Delimiter() self.agregator = Agregator() self.sorter = Sorter() self.output = Output() def engine(self): while self.run == True: nextEvent = self.eventStack[-1] del self.eventStack[-1] res = self.eventHandler(nextEvent) def eventHandler(self, eventType): if eventType == "GET_CHAR": nextEvent, self.char = self.classificator.eventHandler(eventType) self.eventStack.append(nextEvent) if eventType == "GET_WORDS": nextEvent, res = self.delimiter.eventHandler(eventType, self.char) self.eventStack.append(nextEvent) self.word = res if eventType == "GET_WORD_LIST": nextEvent, res = self.agregator.eventHandler(eventType, self.word) self.eventStack.append(nextEvent) self.wordlist = res if eventType == "GET_CROSS_REFERENCE_TABLE": nextEvent, res = self.sorter.eventHandler(eventType, self.wordlist) self.eventStack.append(nextEvent) self.crossReferenceTable = res if eventType == "OUTPUT_TABLE": self.output.eventHandler(eventType, self.crossReferenceTable) self.run = False
def get_katalog(self, t_url): """ get catalog """ # print "GetKatalog" k_urls = t_url[0::2] counter = 0 for idx, k_url in enumerate(k_urls): while True: try: getimg = urllib.request.urlopen(k_urls[idx][1]) localfile = open(os.path.basename(k_urls[idx][1]), 'wb') localfile.write(getimg.read()) getimg.close() localfile.close() except Exception as _e: counter += 1 if counter <= 5: print("retry urlopen in GetKatalog...") continue if counter >= 5: Output(_e, 0, "Error in GetKatalog").call_result() else: counter = 0 break return k_urls
def process_transaction(zcblock: ledger.ZCBLOCK): #print('processing -----'+zcblock.transactionType) output_list = [] if zcblock.transactionType != "GENESIS": for output in zcblock.output_IDs[:-1]: #print("PROCESS") #print(type(output)) output_list.append(GlobalDB.VTP[output].outputBlock) output_list = [o for o in output_list if o is not None] if len(output_list) == 0: raise Exception("Number of incoming transactions must be greater than 0.") #print('here2') #print('processing: '+str(zcblock.transactionType)) if zcblock.transactionType == "GENESIS": genOutput = Output.Output(zcblock.amounts, [GlobalDB.compressedUB[zcblock.users[0]].sk]) zcblock.outputBlock = genOutput elif zcblock.transactionType == "TRANSFER": zcblock.outputBlock = ledger.run_transfer(GlobalDB.compressedUB[zcblock.users[0]], GlobalDB.compressedUB[zcblock.users[1]], zcblock.amounts[0], output_list[0]) elif zcblock.transactionType == "MERGE": zcblock.outputBlock = ledger.run_merge(GlobalDB.compressedUB[zcblock.users[0]], GlobalDB.compressedUB[zcblock.users[1]], zcblock.amounts[-1], output_list) elif zcblock.transactionType == "JOIN": givers = [] for i in range(len(zcblock.users)-1): givers.append(GlobalDB.compressedUB[zcblock.users[i]]) zcblock.outputBlock = ledger.run_join(givers, GlobalDB.compressedUB[zcblock.users[-1]], zcblock.amounts[:-1], zcblock.amounts[-1], output_list) else: print("excpetion raise time >:(") raise Exception("Invalid transaction type: "+zcblock.transactionType)
def test_range10MatrixWithNegatives(self): string_matrix = '28,45,-73,-75,46,36,21,26,48,30;-86,38,-32,82,-22,-19,-29,100,-72,-3;13,84,-76,-99,-78,94,14' \ ',-12,-4,56;43,-91,1,97,-11,59,61,-16,-31,-43;-60,-63,41,-52,-95,86,67,88,79,8;-28,-62,-20,' \ '-34,-51,12,-5,35,-8,-55;15,-93,34,-14,-54,-17,98,-85,-24,72;-81,18,-30,-47,50,11,39,66,90,7;' \ '-98,-87,-84,20,-97,89,19,-13,60,-23;96,44,-71,-36,-46,25,32,85,54,77' result = 619266553777932419372 self.assertEqual(program.parameter_input(string_matrix), Output.exponential_output(result))
def print_brlan(ra0): ra0 = ra0.split('-') br_lan = Br_lan.get_br_lan(ra0) br_lan_print = Output.output_res(br_lan) # print('**************************************************') # print('br-lan:', br_lan_print) return br_lan_print
def run(self): """Reduces TPTP syntax with control file provided as command line argument. """ args = self.argument_parser.parse_args() graphBuilder = TPTPGraphBuilder( file=Input.read_text_from_file(args.grammar), disable_rules_string=Input.read_text_from_file(args.control)) start_node = graphBuilder.nodes_dictionary.get( Node_Key("<start_symbol>", RuleType.GRAMMAR)) if start_node: if args.external_comment: Output.save_ordered_rules_from_graph_with_comments( args.output, start_node) else: Output.save_ordered_rules_from_graph(args.output, start_node)
def test_output_getConsole(self): output = Output.Output() output.consoleOut = 'abc' self.assertEqual(output.get_console(), 'abc')
def __init__(self, patterns_ini=None, input_format='pdf', dedup=False, library='pdfminer', output_format='csv', output_handler=None): basedir = os.path.abspath(os.path.dirname(__file__)) if patterns_ini is None: patterns_ini = os.path.join(basedir, 'data/patterns.ini') self.load_patterns(patterns_ini) wldir = os.path.join(basedir, 'data/whitelists') self.whitelist = self.load_whitelists(wldir) self.dedup = dedup if output_handler: self.handler = output_handler else: self.handler = Output.getHandler(output_format) self.ext_filter = "*." + input_format parser_format = "parse_" + input_format try: self.parser_func = getattr(self, parser_format) except AttributeError: e = 'Selected parser format is not supported: %s' % (input_format) raise NotImplementedError(e) self.library = library if input_format == 'pdf': if library not in IMPORTS: e = 'Selected PDF parser library not found: %s' % (library) raise ImportError(e) elif input_format == 'html': if 'beautifulsoup' not in IMPORTS: e = 'HTML parser library not found: BeautifulSoup' raise ImportError(e)
def get_thread(self): """ get thread """ print(self.thread) print("=====body=====\n\n") seed = requests.get(self.thread) soup = BeautifulSoup(seed.content, "html.parser") # body = soup.find_all("span") body = soup.find_all("span", class_="cntd") print(body) # del body[0:4] # body.pop() # body.pop() # body.pop() print("-----after body -----\n\n") print(body) end = body[0].text end = end.replace(u"頃消えます", "") if len(end) > 5: end = end[(len(end) - 5):] gabage = '"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" %s' browser = webbrowser.get(gabage) browser.open(self.thread) noti = "'display notification " " with title \"Get Deresute Thread!!!\"'" os.system("osascript -e" + noti) Line(self.thread).notify_line() Output("g", end, "Get Thread!!!").call_result()
def __init__(self, args): self.args = args self.predict = None self.dataset = None self.estimator = None self.preprocess = None self.modelselection = None self.output = None self.training_set_cap = None sys.path.insert(1, 'config') if self.args.predict != None: import Predict as pred try: self.predict = pred.Predict(self.args.predict) except ValueError as err: # return err raise ValueError(err) # return 0 else: import Dataset as cds try: self.dataset = cds.Dataset(self.args.dataset) except ValueError as err: # return err raise ValueError(err) import Estimator as ce try: self.estimator = ce.Estimator.create(self.args.estimator, self.dataset) except ValueError as err: # return err raise ValueError(err) import Preprocess as pp try: self.preprocess = pp.Preprocess(self.args.preprocess) except ValueError as err: # return err raise ValueError(err) import ModelSelection as ms try: self.modelselection = ms.ModelSelection( self.args.selection, self.estimator) except ValueError as err: # return err raise ValueError(err) if self.args.output != None: import Output try: self.output = Output.Output(self.args.output) except ValueError as err: # return err raise ValueError(err) if self.estimator.nick == 'knn': self.training_set_cap = self.output.training_set_cap
def CalculateAllSpecificHeats(): TQuantitiesDirPath = path.TQuantitiesDirPath #path.RecreateDir(TQuantitiesDirPath) TQuantitiesFileName = os.path.join(TQuantitiesDirPath, "Cv" + path.dataFileExtension) Ts, CvsDic, headerLines = CalculateAllCvs(TQuantitiesDirPath) CvLines = CreateCvsLines(Ts, CvsDic, headerLines) output.SaveLinesToFile(CvLines, TQuantitiesFileName)
def CalculateAllAveMsPerSite(): TQuantitiesDirPath = path.TQuantitiesDirPath #path.RecreateDir(TQuantitiesDirPath) TQuantitiesFileName = os.path.join(TQuantitiesDirPath, "avem" + path.dataFileExtension) Ts, avemsDic, headerLines = CalculateAllAvems(TQuantitiesDirPath) avemLines = CreateAvemsLines(Ts, avemsDic, headerLines) output.SaveLinesToFile(avemLines, TQuantitiesFileName)
def print_psr2(ra0): ra0 = ra0.split('-') br_lan = Br_lan.get_br_lan(ra0) psr2_prefix = PSR.psr_02(br_lan) psr2_print = Output.output_res(psr2_prefix) # print('**************************************************') # print('psr2_prefix:',psr2_print) return psr2_print
def main(): pygame.init() pygame.display.set_caption("N - queens problem") window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) n = GUI.inicijalizacija(window) if n == None: return False tabla = [[0 for x in range(n)] for y in range(n)] R_broj_kraljice = 0 R_broj_kombinacije = [0] * n tabla = Algoritam.trazenje_mogucih_pozicija(tabla, R_broj_kraljice, R_broj_kombinacije, n, window) if tabla == None: Output.nije_moguce(window, n) GUI.dugme(window, n)
def find(): """Returns the USB port address of the camera.""" global __path Output.debug("In USBDevice.find()") if Settings.SIMULATE_USB_DEVICE: __path = "/dev/bus/usb/042/023" Output.debug("Simulation! Pretending the device is " + __path + ".") return __path result = subprocess.Popen("gphoto2 --auto-detect", stdout=subprocess.PIPE, shell=True).stdout.read() Output.debug("Result of `gphoto2 --auto-detect`: " + result) match = re.compile("(?P<camera>[^\n]+?) +usb:(?P<device>[0-9]{3}),(?P<port>[0-9]{3})",re.MULTILINE).search(result) if match != None: Output.notice("Found camera: " + match.group('camera') + " on USB port " + match.group('device') + "," + match.group('port')) __path = "/dev/bus/usb/" + match.group('device') + "/" + match.group('port') Output.notice("Path is now: " + __path) return __path raise "Camera not found. Connect it to the Pi, switch it on and verify that `gphoto2 --auto-detect` finds it."
def test_range12MatrixWithNegatives(self): string_matrix = '-2,9,-46,17,50,-73,8,76,29,-77,-69,15;69,-16,65,62,24,-6,71,-80,40,-84,-19,95;27,-33,' \ '-75,-23,-67,-25,-27,36,89,70,-47,-29;85,-90,-97,84,-82,-39,-65,-26,-96,7,100,14;-49,' \ '-9,81,13,38,82,0,-66,-14,44,48,94;-42,78,-35,-86,54,-4,-59,66,4,-72,21,-52;55,39,-58,' \ '-57,-53,-85,-20,-18,49,-79,72,92;83,97,74,52,43,-36,-76,-24,-54,22,56,23;-37,93,-32,18,' \ '-10,-78,3,28,-15,96,-41,-31;-81,47,75,33,12,-94,98,-64,-38,19,-70,-21;80,-48,-7,11,25,' \ '42,31,-56,32,-51,91,-87;-91,63,10,-99,-93,58,26,-45,20,-92,-55,88' result = 3708810380587217049754426 self.assertEqual(program.parameter_input(string_matrix), Output.exponential_output(result))
def next_step(self): Settings.WAIT_FOR_BUTTON_PRESS = False Settings.AFTER_ID = None delay, command, additional, target_branch = self.lines[self.line] self.line += 1 if self.line>=len(self.lines): self.line = 0 if command=="text": if target_branch is not None: Settings.ON_BUTTON_PRESS = lambda: target_branch.start() Settings.WAIT_FOR_BUTTON_PRESS = True Display.display_text(additional) elif command=="photo": Output.debug("Photo! Number " + str(additional)) functions.call_photo_thread(additional) elif command=="overview": if target_branch is not None: Settings.ON_BUTTON_PRESS = lambda: target_branch.start() Settings.WAIT_FOR_BUTTON_PRESS = True Display.show_overview() elif command=="clear": Display.clear() elif command=="branch": Display.root().after(delay, lambda: target_branch.start()) return elif command=="wait": Settings.ON_BUTTON_PRESS = self.next_step Settings.WAIT_FOR_BUTTON_PRESS = True return elif command=="init_run": functions.start_run(self) return # check if the next command is a "photo" if self.lines[self.line][1]=="photo": delay = max(delay - Settings.PHOTO_DELAY, 1) if Settings.DEBUG_SHORT_DELAYS: delay = delay / 100 + 1 #Output.debug("Waiting: " + str(delay)) Settings.AFTER_ID = Display.root().after(delay, self.next_step)
def __generate_test_def(self, test_invocation, name=None, index=None, group=None): testcase_def = testcase_template % ( \ get_testcase_class_name(self.fixture, self.testcase, index), \ get_testcase_class_name(self.fixture, self.testcase, index), \ get_testcase_display_name(self.testcase, group), \ self.fixture.get_name(), \ self.suite, \ get_depends_var(self.fixture, self.testcase), \ get_file_name(self.testcase), \ self.testcase.get_line_number(), \ get_fixture_id(self.fixture), \ get_fixture_id(self.fixture), \ test_invocation, \ len(self.testcase.get_tags() + self.fixture.get_tags()), \ get_testcase_tags(self.testcase, self.fixture), \ get_fixture_id(self.fixture), \ get_testcase_instance_name(self.fixture, self.testcase, name, index) \ ) Output.output(testcase_def, self.file)
def doConstructionPhase(self): self.phaseStatus = {} phaseActions = CONPHASEACTIONS + self.currFreeActions + [ACTPHASESKIP] availableActions = [] while True: availableActions = phaseActions + self._addFreeActions() action = self._choiceConstructionPhase(availableActions) Output.updateScreen() if action == ACTBUILDTHEATER: if self._choiceBuildTheaterYN() == YES: self._delMoney(THEATERCOST) self.theaterStack.addCards(Cards.Deck([Cards.Theater(type=PRIVATE, screens=3, status=OPEN)])) self.phaseStatus[THEATERBOUGHT] = True elif action == ACTPHASESKIP: return True Output.updateScreen() return True
def parse_funct(filename, config, db_handler): start_time = datetime.datetime.now() history = {} result = {"start_time": start_time, "data": history} r = Request(config=config, decode="utf-8-sig") # Signal handler try: signal.signal(signal.SIGINT, r.signal_handler) # Do nothing in main thread except: pass if config.depth >= 0: linktexts = [] linktexts.append((config.target_url, config.target_name)) history.update(r.navigate(linktexts=linktexts, history=history, config=config, decode="utf-8-sig")) Output.output_handler(result=result, config=config, output_filename=filename, db_handler=db_handler) r.close()
def generate_fixture_array(self): global fixtureDescs if not self.recordFixture : for fixtureDesc in fixtureDescs : Output.output("extern TESTNGPP_NS::TestFixtureDesc "+fixtureDesc+";", self.file) fixture_array_def = fixture_array_template_begin % (get_fixture_array_name(self.suite)) Output.output(fixture_array_def, self.file) self.generate_fixture_desc_array() if not self.recordFixture : # output recorded fixture descs for fixtureDesc in fixtureDescs : Output.output("&"+fixtureDesc+",", self.file) Output.output(array_template_end, self.file)
def reset(): """Calls usbreset to reset the USB port.""" Output.debug("In USBDevice.reset()") if Settings.SIMULATE_USB_DEVICE: Output.debug("Simulation. Resetting nothing.") return cmd = os.path.abspath(os.path.dirname(sys.argv[0])) + "/usbreset " + get_path() Output.debug("Executing: " + cmd) subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).stdout.read()
def writeSearchHistory(fastSearchDir, string, optionsList, results, time): # if the file already exists, append to it, otherwise create it if os.path.exists(fastSearchDir + 'Support' + os.sep + recentSearchesFileName): recentSearchesFile = open(fastSearchDir + 'Support' + os.sep + recentSearchesFileName, 'a') else: recentSearchesFile = open(fastSearchDir + 'Support' + os.sep + recentSearchesFileName, 'w') numResults = Output.getNumResults(results) if numResults > 0: recentSearchesFile.write('-----------------------------\n') recentSearchesFile.write('Date and Time: ' + strftime("%Y-%m-%d %H:%M:%S") + '\n') recentSearchesFile.write('Root Directory: ' + optionsList[5] + '\n') recentSearchesFile.write('Search String: ' + string + '\n') recentSearchesFile.write('Search Time: ' + str(time) + '\n') recentSearchesFile.write('Result Count: ' + str(numResults) + '\n') recentSearchesFile.write('\n--Results--') # scan through and print the full path for each folder result (if folders are displayed) if optionsList[1] == 1 or optionsList[1] == 2: recentSearchesFile.write('\n\n::Matching Folder Names::') if len(results[0]) != 0: for item in results[0]: recentSearchesFile.write('\n' + item) else: recentSearchesFile.write('\n-None Found-') # scan through and print full paths for each file result (if files are displayed) if optionsList[1] == 0 or optionsList[1] == 2: recentSearchesFile.write('\n\n::Matching File Names::') if len(results[1]) != 0: for item in results[1]: recentSearchesFile.write('\n' + item) else: recentSearchesFile.write('\n-None Found-') # scan through and print full paths for each file the string was found within (if a deep search was run) if optionsList[0]: recentSearchesFile.write('\n\n::Found in Files::') if len(results[2]) != 0: for item in results[2]: recentSearchesFile.write('\n' + item[0] + '\n On Line%s: ' % (len(item[1]) != 1 and 's' or '') + str(item[1])) else: recentSearchesFile.write('\n-None Found-') recentSearchesFile.write('\n-----------------------------\n\n') recentSearchesFile.close()
def button_pressed(some_var=None): if Settings.WAIT_FOR_BUTTON_PRESS: Settings.WAIT_FOR_BUTTON_PRESS = False if Settings.ON_BUTTON_PRESS is not None: Output.debug("Button pressed. Running code") temp = Settings.ON_BUTTON_PRESS Settings.ON_BUTTON_PRESS = None cancel_run() temp() else: Output.debug("Button pressed, but Settings.ON_BUTTON_PRESS is None.") else: Output.debug("Button pressed, but we are not waiting for this event.")
def call_photo_thread(number, is_temp_photo=False): """Tells PhotoThread to take a photo and waits for it to return.""" Output.debug("This is call_photo_thread().") global photo_thread global filename_schema Output.debug("photo_thread: " + str(photo_thread)) if is_temp_photo: photo_thread.set_data("temp.jpg", number, fullsize=True) else: photo_thread.set_data(filename_schema.format(number), number) photo_thread.run() while True: Output.debug("Warte auf photo_taken...") if photo_thread.photo_taken: break time.sleep(0.1)
def doPrivateBookingPhase(self): phaseActions = PVTPHASEACTIONS + self.currFreeActions + [ACTPHASESKIP] availableActions = [] while True: availableActions = phaseActions + self._addFreeActions() action = self._choicePrivateBookingPhase(availableActions) Output.updateScreen() if action == ACTPRIVATEBOOK: self.doBookMovie(PRIVATE) elif action == ACTPHASESKIP: Output.updateScreen() return True Output.updateScreen() return True
def getChoiceFromStack(prompt, currStack, noChoices=1): Output.menuWindow.clear() Output.printToWindow(prompt + '\n', Output.menuWindow) count = 1 indexMapping = {} for i, currCard in enumerate(currStack.cards): Output.printToWindow('{0:2d} - {1}\n'.format(count, currCard.visibleName()), Output.menuWindow) indexMapping[count] = currCard.name count += 1 chosenCard = [] while True: for i in range(0, noChoices): Output.printToWindow('%d of %d : '%(i, noChoices), Output.menuWindow) choice = int(Output.menuWindow.getstr(2)) #choice -= 48 if choice >= 1 and choice <= len(currStack.cards): if choice in indexMapping: chosenCard.append(indexMapping[choice]) if len(chosenCard) > 0: return chosenCard
def generate_headers(self): self.generate_dep_headers() for header in self.fixture_files: Output.output("#include \"" + os.path.relpath(header, os.path.dirname(os.path.abspath(self.target))) + "\"", self.file)
def generate_suite_getter(self): suite_getter = suite_getter_template % ( get_suite_getter_name(), get_suite_desc_name(self.suite)) Output.output(suite_getter, self.file)
def generate_dep_headers(self): for header in dep_headers: Output.output("#include <testngpp/" + header + ">", self.file)
def main(args): # get the absolute path of the FastSearch directory fastSearchDir = os.path.abspath(args[0])[:os.path.abspath(args[0]).rfind(os.sep)] + os.sep # instantiate the exit code code = EXIT_CLEAN # instantiate pre-run update condition preRunUpdateCheck = False # declare options list optionsList = FileHandler.initializeOptionsList(fastSearchDir, []) colors = Output.Colors(optionsList) # FastSearch has been updated if len(args) > 3 and args[1] == '-updatesuccess': print colors.alert() + '\nFastSearch has been successfully updated to v' + str(Updater.CURRENT_VERSION) + '!' + colors.end() # display the post update message retrieved from the server if not (args[2] in ('None', '', None)): print colors.alert() + args[2:] + colors.end() # run a QuickSearch and return the results as a list and quit the application if len(args) > 1 and args[1][1:].lower() in ('r', 'return'): if len(args) > 2: optionsList = FileHandler.defaultList if len(args) > 3 and args[2][1:].lower() in ('d', 'deep', 'deepsearch', 'ds'): optionsList[0] = True start = 3 else: start = 2 # if the user requested a deep search but provided no string if args[start][1:] in ('d', 'deep', 'deepsearch', 'ds'): return EXIT_RESULTS_BAD, None string = args[start].lower() for i in range(start + 1, len(args)): string += ' ' + args[i].lower() search = Search.Search(string, optionsList, colors) search.start() search.join() return EXIT_RESULTS, search.finish() else: return EXIT_RESULTS_BAD, None print colors.blue() + '\n::Welcome to FastSearch v' + str(Updater.CURRENT_VERSION) + ' by Alex Laird::' + colors.end() # if arguments are specified, use them as the search string if len(args) > 1 and not args[1] == '-updatesuccess': if args[1].startswith('-'): if len(args) == 2 and not args[1][1:].lower() in ('d', 'debug'): if args[1][1:].lower() in ('help', 'h'): Output.help(colors) elif args[1][1:].lower() in ('update', 'updates', 'u'): runUpdater(fastSearchDir, colors) elif args[1][1:].lower() in ('credit', 'credits', 'c'): Output.credits(colors) elif args[1][1:].lower() in ('option', 'options', 'o', 'pref', 'preferences', 'setting', 'settings'): optionsList = Options.options(fastSearchDir, optionsList, colors) else: print colors.alert() + 'The command-line arguments were not valid. View the help menu for assistance.\n' + colors.end() # run a benchmark comparing a standard os.walk method (with no comparisons) to the FastSearch localWalk method elif args[1][1:].lower() in ('d', 'debug'): try: code = debug(args, colors) except: code = EXIT_DEBUG_ERROR return code else: print colors.alert() + 'The command-line arguments were not valid. View the help menu for assistance.\n' + colors.end() else: string = args[1].lower() for i in range(2, len(args)): string += ' ' + args[i].lower() # the search will be launched immedietly with the current working directory as root code = runSearch(fastSearchDir, string, optionsList, False, colors)[0] # if no arguments were specified elif len(args) == 1: if preRunUpdateCheck: simpleUpdateChecker(colors) looping = True results = None # loop until the user wants out while looping: # retreive a command from the user string = raw_input(colors.blue() + 'Type (s)earch, (o)ptions, (u)pdate, (h)elp, (c)redits, or (q)uit: ' + colors.end()).lower() # the user entered a number if string.strip('[]').isdigit(): if not results == None: location = int(string.strip('[]')) - 1 ref = 0 # decrement the number as needed to keep it consistent with the correct results subarray if location > len(results[0]) - 1: location -= len(results[0]) ref = 1 if location > len(results[1]) - 1: location -= len(results[1]) ref = 2 # ensure that the location is/was a valid search result if location < 0 or location > len(results[ref]) - 1: print colors.alert() + 'The number entered did not correspond to a search results. Try again.\n' + colors.end() # launch the search result print 'Opening ' + os.path.abspath(results[ref][location]) + ' ...' os.system('open ' + os.path.normpath(os.path.abspath(results[ref][location])).replace(' ', '\\ ')) print '' else: print colors.alert() + '\nThat wasn\'t an option. Try again.\n' + colors.end() continue # the user wants to search if string in ('s', 'search', 'f', 'find'): # retreive the string to search for from the user string = raw_input(colors.blue() + 'Enter a search string: ' + colors.end()).lower() code, results = runSearch(fastSearchDir, string, optionsList, False, colors) # the user wants to check for updates elif string in ('u', 'update', 'updates'): runUpdater(fastSearchDir, colors) # the user wants help elif string in ('h', 'help'): Output.help(colors) # the user wants to see the credits elif string in ('c', 'credit', 'credits'): Output.credits(colors) # the user wants to specify search options elif string in ('o', 'options', 'p', 'pref', 'prefs', 'preferences', 'setting', 'settings'): optionsList = Options.options(fastSearchDir, optionsList, colors) # the user wants to end the program elif string in ('q', 'quit', 'e', 'exit', 'c', 'close', 'end'): # clean exit without errors code = EXIT_CLEAN looping = False # the user is an idiot else: print colors.alert() + '\nThat wasn\'t an option. Try again.\n' + colors.end() if not optionsList[6] == None: optionsList[6].close() if code == None: return EXIT_UNKNOWN_ERROR else: return code