def addImageTextBoxesToDialog(self, query, txtEnd, imageList, oDialogModel): y = 15 #add image checkboxes to the dialog count = 1 x = 105 for img in imageList: print(img) imageFilePath = fh.FileHandler().createImageFilePathForTheQuery( query, img) imageURL = "file:///" + imageFilePath thmbFilePath = fh.FileHandler( ).createThumbImageFilePathForTheQuery(query, img) thumbImageURL = "file:///" + thmbFilePath print(imageURL) im = Image.open(imageFilePath) dim = 150 size = (dim, dim) #create thumbnails im.thumbnail(size, Image.ANTIALIAS) im.save(thmbFilePath) imtb = Image.open(thmbFilePath) self.createCheckBox(oDialogModel, img, img, 150, 75, x, y) self.setCheckBoxImageURL(oDialogModel, img, thumbImageURL) x += 80 count += 1 return x
def __init__(self, filename): self.fileContent = [] self.curr = None self.currIndex = -1 self.tokens = [] if not filename: return if filename[-4:] != "jack": raise TypeError("Type error: Should input a .jack script file!") fileHandler = FileHandler.FileHandler(filename) in_comment = False for s in fileHandler.fileContent: s = self.removeComment(s) if not in_comment and '/*' in s: s = s[:s.index('/*')] in_comment = True elif in_comment and '*/' in s: s = s[s.index('*/') + 2:] in_comment = False elif in_comment: continue if len(s) > 0: self.fileContent.append(s) for content in self.fileContent: self.parse(content)
class GameInterface: fh = handler.FileHandler() walkButtons = [["left", "right"], ["up", "down"]] gameInterface = [ ["loginMenu", ["Username", "Password", "Login"]], ["battleMenu", ["Fight", "Pokemon", "Items", "Run"]], ["itemMenu", ["PokeballTab", "GreatBall"]], ["chatMenu", ["General", "Battle", "Trade", "Global"]], ["gameMenu", ["Toggle", "Return", "Logout", "Exit"]], [ "emoteMenu", ["Toggle", "Heart", "Sleep", "Thumbsup", "Sjpiener", "Sunglasses"] ], ] pixels = [["avatarPixel"], ["battleMenuPixel"], ["loginPixel"], ["shinyPixel"], ["hpBarPixel"]] def __init__(self): print("\nP O K E T I M E M O R E P O W E R\n") print("\nImporting game interface\n" + "_" * 28) self.setCoordinates(self.gameInterface, "menus") print("\nImporting pixels\n" + "_" * 28) self.setCoordinates(self.pixels, "pixels") def setCoordinates(self, interface, folder): for i in interface: i.append(self.fh.readJson(i[0], "\\coordinates\\{}".format(folder)))
def textDetailsAboutFormula( self, query): #get the formual text details from file fileName = fh.FileHandler().createFilePathForTheQuery(query) try: f = open(fileName, 'r') resArray = f.readlines() res = ''.join(resArray) f.close() textList = [] waeqr = wap.WolframAlphaQueryResult(res) #get from titles for pod in waeqr.Pods(): podObject = wap.Pod(pod) for subPod in podObject.Subpods(): subPodObject = wap.Subpod(subPod) if (subPodObject.Plaintext() != [[]]): title = subPodObject.Title() if (title[0] != ''): textList.append(title[0]) else: textList.append(podObject.Title()[0]) return textList except Exception: textList = ["No Text Found"] print("exeption thrown") return textList
def saveFiles(self): # Rewrite config file string = "Directory=" + self.musicDirectory + NEWLINE + \ "Icon=" + self.iconPath + NEWLINE + \ "CurrentSong=" + str(self.currentSong) fileObj = FileHandler(self.directory, "config") fileObj.write(string, "") # Rewrite songs file fileObj = FileHandler(self.directory, "Songs") string = [] for i in range(self.songs.getSongCount()): path = self.songs.getPath(i) title = self.songs.getTitle(i) string.append(path + "," + title) fileObj.write(string, NEWLINE)
def upload_file(login, password): ''' Uploads files ''' db_obj = DataBaseCl() if db_obj.checkauth(login, password): if request.method == 'POST': f = request.files['file_name'] if f: if f.filename.split('.')[1] in ALLOWED_EXTENSIONS: filename = secure_filename(f.filename) path_f = os.path.join(app.config['UPLOAD_FOLDER'], filename) f.save(path_f) req = FileHandler(path_f) res = req.parse_file() return jsonify({'result:': res}) else: return 'not upload' return ''' <!doctype html> <form action="" method=post enctype=multipart/form-data> <p><input type=file name= file_name> <input type=submit value=Upload> </form> ''' else: return ('you have no permissions')
def populateList(self): file = FileHandler("Items") attributes = file.read() tokenizer = StringTokenizer('\n') tokenizer.setString(attributes) while (not tokenizer.atEnd()): self.items.append(Item(tokenizer.getToken())) self.itemCount = self.itemCount + 1
def __init__(self): self.my_console = Console.Console( "(-o-)", """Welcome to the personal pokemon encyclopedia (or pokedex for short) Type help or '?' to see a list of commands""", self) self.my_file_handler = FileHandler.FileHandler() self.my_Calc = StatisticCalculator.StatisticCalculator() self.view = CmdView.CmdView()
def __init__(self, fadezone=20): self.handler = FH.FileHandler() self.fadezone = fadezone self.bigrams = [] ''' combines the short and the long letters to bigrams ''' for i in range(len(self.SHORT_LETTERS)): for a in range(len(self.LONG_LETTERS) - 2): self.bigrams.append(self.SHORT_LETTERS[i] + self.LONG_LETTERS[a])
def logMessage(self, msg): # Pega data e hora locais instantDate = datetime.now() hora = str('{0:02}'.format(instantDate.hour)) minuto = str('{0:02}'.format(instantDate.minute)) segundo = str('{0:02}'.format(instantDate.second)) Log = FileHandler() Log.open(self.logFileName, 'a') Log.write(hora + ":" + minuto + ":" + segundo + " ----> " + msg + '\n') Log.close()
def __init__(self, filename): if str.find(filename, '.') != -1: class_name = str.split(filename, ".")[0] target_name = class_name + ".asm" if not "vm".__eq__(str.split(filename, ".")[1]): print("File type error, .vm file expected.") return else: class_name = str.split(filename, "\\")[-1] target_name = filename + "\\" + class_name + ".asm" file_handler = FileHandler.FileHandler(filename) file_handler.append_enter() file_handler.write(target_name)
def actionPerformed(self, actionEvent): oControl = actionEvent.Source #get the name of the object which created the event name = oControl.getModel().getPropertyValue("Name") if (name == "SelectFormulaButton" ): #if the event is from the select formula button query = self.eventObject.getControl( "selectFormulaList").getSelectedItem() query = query.split("\n")[0] #get the formula selected txtList = FormulaListDialog().textDetailsAboutFormula(query) #get the text details related to the formula imgList = FormulaListDialog().imageDetailsAboutFormula(query) #get the image details related to the formula if not (txtList[0][0] == "N"): #if an exception is not thrown oDialog = FormulaListDialog().createAvailableResourcesDialog( query, txtList, imgList) oDialog.execute() #execute the available resources dialog self.eventObject.endExecute() #finish the dialog elif (name == "GetResourcesButton" ): #if the event is created by the get resources button count = 1 selectedItems = [] #initially the selected items is null selectedImages = [] #initially the selected images list is null query = self.eventObject.getControl( "formulaLabel").getModel().getPropertyValue("Label") #retrieve the query name from the parent dialog while (True): #loop until the checkboxes are finished control = self.eventObject.getControl("text" + ` count `) if (control == None): #if no check box is found break break if (control.getState() == 1 ): #if a selected checkbox is found append as true selectedItems.append(True) else: selectedItems.append( False ) #if a non selected check box is found append as false count += 1 count = 0 while (True): #do the same thing for image check boxes control = self.eventObject.getControl("image" + ` count `) if (control == None): break if (control.getState() == 1): selectedImages.append(True) else: selectedImages.append(False) count += 1 fh.FileHandler().addDetailsFileData(query, selectedItems, selectedImages) #add details to the file self.eventObject.endExecute() #finish executing the dialog
def populateFromFile(self): self.songs = [] self.songCount = 0 fileObj = FileHandler(self.directory, "Songs") fileString = fileObj.read() tokenizer = StringTokenizer(NEWLINE) tokenizer.setString(fileString) while not tokenizer.atEnd(): self.songCount = self.songCount + 1 token = tokenizer.getToken() index = token.index("/,") name = token[index + 2:] path = token[:index + 1] self.songs.append(Song(name, path))
def backup_file_svn(self): '''备份文件到svn(备份的svn)''' file_handler = FileHandler.FileHandler() backup_rep = file_handler.getBackupRepository() if len(backup_rep) > 0: try: loggingHandler.logger.info('开始移动备份工程项目文件至本地备份服务器!') file_handler.backupRepository(backup_rep) loggingHandler.logger.info('完成移动备份工程项目文件至本地备份服务器!') loggingHandler.logger.info('开始本地SVN备份服务器内容提交!') file_handler.svn_commit(backup_rep) loggingHandler.logger.info('完成本地SVN备份服务器内容提交!') except (KeyboardInterrupt, SystemExit) as e: loggingHandler.logger.exception('备份文件到svn出现异常!')
def sendFile(): response='' acceptable_extensions = ['csv','txt','xls'] if request.method == "POST": render_form() upload = request.files['file'] file_handler = FileHandler(secure_filename(upload.filename)) if file_handler.validate_file(): upload.save(secure_filename(upload.filename)) create_graph(upload.filename) nodes = [nodes for nodes in graph.nodes] return render_template('graph.html', body="<div id='graphHolder'></div>", nodes=nodes) else: response = 'The file you have uploaded is not supported' else: response = 'File not uploaded' return response
def configFile(self): fileObj = FileHandler(self.directory, "config") configArray = fileObj.read() tokenizer = StringTokenizer(NEWLINE) tokenizer.setString(configArray) # Directory token = tokenizer.getToken() index = token.index('=') + 1 self.musicDirectory = token[index:] # Icon token = tokenizer.getToken() index = token.index('=') + 1 self.iconPath = token[index:] # LastSong token = tokenizer.getToken() index = token.index('=') + 1 self.currentSong = int(token[index:])
def main(): handler = fh.FileHandler(INPUT_FOLDER, INCORRECT_FOLDER, PROCESSED_FOLDER) handler.remove_invalid_files_from_folder() parser = p.Parser(handler.get_fb2_file()) bookname = parser.get_book_name() number_of_paragraph = parser.get_number_of_paragraph() number_of_words = parser.get_number_of_words() number_of_letters = parser.get_number_of_letters() word_Upper = parser.get_words_in_uppercase() word_lower = parser.get_words_in_lower() words = parser.get_words_stats() db = sql.SqlDatabase(DB_FOLDER, DB_NAME) db.create_book_stat_table() db.create_input_file_stat_table() db.insert_book_stat_values(bookname[0], number_of_paragraph[0], number_of_words[0], number_of_letters[0], word_Upper, word_lower) for items in words.items(): db.insert_input_file_stat_values(items[0], items[1][0], items[1][1]) handler.remove_processed_files_from_input_folder() print("Ok")
def imageDetailsAboutFormula( self, query): #get the formula image details from file fileName = fh.FileHandler().createFilePathForTheQuery(query) try: f = open(fileName, 'r') resArray = f.readlines() res = ''.join(resArray) f.close() imageList = [] waeqr = wap.WolframAlphaQueryResult(res) #get from images count = 0 for pod in waeqr.Pods(): podObject = wap.Pod(pod) for subPod in podObject.Subpods(): subPodObject = wap.Subpod(subPod) if (subPodObject.Img() != [[]]): imageList.append("image" + ` count `) count += 1 return imageList except Exception: imageList = ["No Text Found"] print("exeption thrown") return imageList
sys.path.append('redes\ II') from Package import * from Convert import * from Log import * from FileHandler import * from Transmition import * if len(sys.argv) != 2: print "Uso correto: %s <porta>" % sys.argv[0] sys.exit(1) """ Get local machine name """ host = socket.gethostname() """ Create instance of Log Class """ ProcessServerLog = Log("ProcessServerLog_" + host + ".txt") filep = FileHandler() """ Create a socket object """ try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) ProcessServerLog.logMessage(host + ": criado socket") except socket.error, (errno, errmsg): ProcessServerLog.logMessage("Erro ao criar socket: " + str(errno) + ": " + str(errmsg)) sys.exit(1) """ Reserve a port for your service """ port = int(sys.argv[1]) """ Bind to the port """ try: s.bind((host, port)) ProcessServerLog.logMessage(host + ": realizado bind() na porta: " + str(port))
def exportFilter(self): # 1.0 = first line character 0. end-1c = end minus return # carriage text = self.rightFrame.editArea.get("1.0", 'end-1c') fileObj = FileHandler(FILTER_NAME) fileObj.write(text, "")
return arguments if __name__ == "__main__": # Get the command line arguments. Run in IDE for demo tweaking. stime = time() try: args = getargs() if args is None: sys.exit() except: raise try: FileHandler = FileHandler.FileHandler() objs = FileHandler.load_mesh(args.inputfile) if objs is None: sys.exit() except (KeyboardInterrupt, SystemExit): raise SystemExit("Error, loading mesh from file failed!") # Start of tweaking. if args.verbose: print("Calculating the optimal orientation:\n {}".format( args.inputfile.split(os.sep)[-1])) c = 0 info = dict() for part, content in objs.items(): mesh = content["mesh"]
from FileHandler import * import os import subprocess import shutil # clean up shutil.rmtree("./latex", ignore_errors=True) shutil.rmtree("./html", ignore_errors=True) # run doxygen os.system("\"C:\\Program Files\\doxygen\\bin\\doxygen\" doxy_config") # modify latex src texHandler = FileHandler("./latex/refman.tex") texHandler.addAfter("\\renewcommand{\\numberline}[1]{#1~}", FileHandler("./src/packages.tex").getContent(), 1) texHandler.addAfter("%--- Begin generated contents ---", FileHandler("./src/additional_Sections.tex").getContent(), 1) texHandler.addBefore( "\\end{document}", "\\bibliography{../src/ref}{}" + "\n" + "\\bibliographystyle{plain}", 1) texHandler.reprint("./latex/refman.tex") # modify compile latex script docGenHandler = FileHandler("./latex/make.bat") docGenHandler.addBefore("setlocal enabledelayedexpansion", "bibtex refman") docGenHandler.replaceLine("set count=8", "set count=4") docGenHandler.addBefore("cd /D %Dir_Old%", "COPY refman.pdf \"../MT-RRT.pdf\"") docGenHandler.replaceLine("cd /D %Dir_Old%", "") docGenHandler.replaceLine("set Dir_Old=", "")
def output_tokens(self, filename): file = FileHandler.FileHandler(None) file.fileContent.append('<tokens>') file.fileContent.extend([x.to_xml() for x in self.tokens]) file.fileContent.append('</tokens>') file.write(filename)
class PauperBot: fh = handler.FileHandler() mouse = mouse.MouseInput() ui = interface.GameInterface() encounters = 0 totalEncounters = 0 shinyEncounters = 0 shinyTime = 0 sessionStart = 0 save = "" def test(self): cursorPosition = pyautogui.position() screenSize = pyautogui.size() print("Cursor position: {} Screensize: {}".format( cursorPosition, screenSize)) def typeinChat(self, text): pyautogui.typewrite("\n{}\n".format(text), interval=0.09) def humanizer(self): roll = random.randint(1, 10000) if roll <= 100: delay = random.randint(5, 180) print("\nAFK for {} seconds, BRB!!\n".format(delay)) time.sleep(delay) elif roll == 9999: self.typeinChat("I love this game guys!") def getGameState(self): gameState = False while not gameState: # print(gameState) if self.checkFixedPixel("avatarPixel"): gameState = True return "hunting" elif self.checkFixedPixel("hpBarPixel"): gameState = True return "encounter" elif self.checkFixedPixel("loginPixel"): gameState = True return "disconnected" time.sleep(1) def getPixelData(self, pixelName, pixels): for pixel in pixels: if pixel[0] == pixelName: return pixel[1] def menuClick(self, button, interface): for menu in interface: for menuItem in menu[2]: if menuItem["button"] == button: startX = menuItem["coordinates"]["start"]["x"] startY = menuItem["coordinates"]["start"]["y"] endX = menuItem["coordinates"]["end"]["x"] endY = menuItem["coordinates"]["end"]["y"] randomX = random.randint(startX, endX) randomY = random.randint(startY, endY) # print(randomX, randomY) pyautogui.click(randomX, randomY) time.sleep(random.randint(50, 90) / 100) def walkSteps(self, button, minStep, maxStep): for i in range(random.randint(minStep, maxStep)): pyautogui.keyDown(button) time.sleep(0.1) pyautogui.keyUp(button) def walkSeconds(self, button, seconds): # print("Button {}\t{} seconds".format(button, seconds)) pyautogui.keyDown(button) time.sleep(seconds) pyautogui.keyUp(button) def walkRoute(self, route): for direction in route: print(direction[0]) if direction[0] == "delay": time.sleep(float(direction[1])) else: self.walkSeconds(direction[0], float(direction[1])) def waitForPixel(self, pixelName): pixel = False while not pixel: self.checkIfDisconnected() print("Searching for {}".format(pixelName)) if self.checkFixedPixel(pixelName): pixel = True time.sleep(0.5) def checkFixedPixel(self, pixelName): pixelReference = self.getPixelData(pixelName, self.ui.pixels) xRef = pixelReference["coordinates"]["x"] yRef = pixelReference["coordinates"]["y"] rgbRef = (pixelReference["color"]["r"], pixelReference["color"]["g"], pixelReference["color"]["b"]) detectedPixelColor = pyautogui.pixel(xRef, yRef) # print("Detected {} color: {} x:{} y:{}".format(pixelName, detectedPixelColor, xRef, yRef)) pixelMatch = pyautogui.pixelMatchesColor(xRef, yRef, rgbRef, tolerance=20) return pixelMatch def loadSaveFile(self): print("\nLoading save file\n" + "_" * 28) save = self.fh.readJson("save", "") print( " | Encounters:\t{}\n | Shinies:\t{}\n | Runtime:\t{}\n | Last shiny:\t{}" .format(save["encounters"], save["shinyEncounters"], datetime.timedelta(seconds=save["runTime"]), save["lastShinyDate"])) return save def saveProgress(self): save = { "encounters": self.totalEncounters, "shinyEncounters": self.shinyEncounters, "lastShinyDate": self.shinyTime, "runTime": self.save["runTime"] + (time.time() - self.sessionStart) } self.fh.writeJson("save", "", save) def idle(self): while True: time.sleep(random.random(75, 550)) self.checkIfDisconnected() def autocatch(self): encounter = True while encounter: print("Catching pokemon!") time.sleep(1) self.menuClick("Items", self.ui.gameInterface) time.sleep(1) self.menuClick("PokeballTab", self.ui.gameInterface) time.sleep(1) self.menuClick("GreatBall", self.ui.gameInterface) time.sleep(13) state = self.getGameState() print(state) if state != "encounter": encounter = False def login(self): time.sleep(1) print("Log in") self.menuClick("Login", self.ui.gameInterface) time.sleep(1) def checkIfDisconnected(self): if self.checkFixedPixel("loginPixel"): print("\nDisconnected") self.login() def randomDirection(self): direction = random.randint(1, 100) if direction > 50: return 1 else: return 0 def hunt(self, direction): time.sleep(3) self.save = self.loadSaveFile() shiny = False self.totalEncounters = self.save["encounters"] self.sessionStart = time.time() print("\nStart the hunt!\n" + "_" * 28) while shiny == False: gameState = self.getGameState() if gameState == "hunting": button = random.randint(0, 1) seconds = random.randint(150, 400) / 1000 self.walkSeconds( self.ui.walkButtons[direction][self.randomDirection()], seconds) elif gameState == "encounter": # print("\nEncounter check") self.encounters += 1 self.totalEncounters += 1 pyautogui.screenshot("Zemmel{}.jpg".format(self.encounters)) if self.checkFixedPixel("shinyPixel"): print("Shiny gevonden in {} encounters".format( self.encounters)) # self.idle() self.autocatch() shiny = True else: print("Encounter {}: geen shiny".format(self.encounters)) time.sleep(0.5) self.menuClick("Run", self.ui.gameInterface) time.sleep(1.5) self.humanizer() elif gameState == "disconnected": self.login()
def __init__(self, window): self.fileHandler = FileHandler.FileHandler() self.window = window
def InitFileHander(self): self.fileHander = FileHandler.FileHandler(self.everything) # 初始化一个FileHander的实例 pass
def to_file(self, filename): xml = self.to_xml() file = FileHandler.FileHandler(None) file.refresh_content(xml) file.write(filename)
import FastQC as fq import SortMeRNA as smr import yaml with open("config.yml", 'r') as confile: cfg = yaml.load(confile) """ for section in cfg: print(section) for element in cfg[section]: print(" " + element + " > " + str(cfg[section][element])) """ # Creates a filehandler from a folder data = fh.FileHandler(cfg["config"]["reads_dir"], cfg["config"]["work_dir"], clean=cfg["config"]["clean"]) # Checks order : order = cfg["config"]["test_order"] # Creates script accordingly for element in order: if element == "fastqc": # Creates a fastqc object depending on the config in fastqc qc = fq.FastQC(data, cfg["fastqc"]["directory"], zip_extract=cfg["fastqc"]["zipextract"]) # Runs the generated script run = rnr.Runner(data) elif element == "sortmerna": # Creates a smr object
def cli(): global FileHandler # Get the command line arguments. Run in IDE for demo tweaking. stime = time() try: args = getargs() if args is None: sys.exit() except: raise try: FileHandler = FileHandler.FileHandler() objs = FileHandler.load_mesh(args.inputfile) if objs is None: sys.exit() except (KeyboardInterrupt, SystemExit): raise SystemExit("Error, loading mesh from file failed!") # Start of tweaking. if args.verbose: print("Calculating the optimal orientation:\n {}".format( args.inputfile.split(os.sep)[-1])) c = 0 info = dict() for part, content in objs.items(): mesh = content["mesh"] info[part] = dict() if args.convert: info[part]["matrix"] = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] else: try: cstime = time() x = Tweak(mesh, args.extended_mode, args.verbose, args.show_progress, args.favside, args.volume) info[part]["matrix"] = x.matrix info[part]["tweaker_stats"] = x except (KeyboardInterrupt, SystemExit): raise SystemExit("\nError, tweaking process failed!") # List tweaking results if args.result or args.verbose: print("Result-stats:") print(" Tweaked Z-axis: \t{}".format(x.alignment)) print(" Axis {}, \tangle: {}".format(x.rotation_axis, x.rotation_angle)) print(""" Rotation matrix: {:2f}\t{:2f}\t{:2f} {:2f}\t{:2f}\t{:2f} {:2f}\t{:2f}\t{:2f}""".format(x.matrix[0][0], x.matrix[0][1], x.matrix[0][2], x.matrix[1][0], x.matrix[1][1], x.matrix[1][2], x.matrix[2][0], x.matrix[2][1], x.matrix[2][2])) print(" Unprintability: \t{}".format(x.unprintability)) print("Found result: \t{:2f} s\n".format(time() - cstime)) if not args.result: try: FileHandler.write_mesh(objs, info, args.outputfile, args.output_type) except FileNotFoundError: raise FileNotFoundError("Output File '{}' not found.".format( args.outputfile)) # Success message if args.verbose: print("Tweaking took: \t{:2f} s".format(time() - stime)) print("Successfully Rotated!")
from Student import * from FileHandler import * import os fileHandler = FileHandler() fileHandler.readStudentFile("CES3063_Fall2020_rptSinifListesi.XLS") fileHandler.readAnswerSheet( "CSE3063 OOSD Weekly Session 1 - Monday Quizzes ANSWER KEY.txt") entries = os.listdir('Polls') for entry in entries: print(entry) fileHandler.readPollFile("Polls/" + entry) fileHandler.writeAttendence() ## The only output we get the overall attendance. You can find the result in the AttendanceOutput.xls file.