def verify(fn): ''' verify the implementation of rename() Returns: True, if the implementation is as specified False, otherwise ''' failed = False try: rename(fn) except: print("The function rename() raised an Exception:\n======") traceback.print_exc() print("======") return False with open(fn, 'r') as f: for i,line in enumerate(f): lc = l2n(line) expectedname = "%02d_" % (i,) + lc if not os.path.exists(expectedname): print(" * the file '{}' does not exist in directory '{}'".format(expectedname, os.getcwd())) failed = True if os.path.exists(lc): print(" * the file '{}' still exists in directory '{}'".format(lc, os.getcwd())) failed = True return not failed
def img_actions(keyword): img_dir = os.path.dirname( os.path.abspath(__file__)) + "/downloads/" + keyword count = 250 download.download(keyword, count, img_dir) rename.rename(keyword, img_dir) convert.convert(img_dir) convert.downscale(img_dir)
def rename(self, src, line, col, newname): try: createPackageStructure("pass",src) rename(pkgstructureFile2,line,col,newname) save() return file(pkgstructureFile2).read() finally: removePackageStructure()
def renameMethod(self, src, line, col, newname): try: createPackageStructure(src,MethodTestdata) rename(pkgstructureFile2,line,col,newname) save() return file(pkgstructureFile1).read() finally: removePackageStructure()
def rename(self, src, line, col, newname): try: createPackageStructure("pass",src) rename(pkgstructureFile2,line,col,newname) save() return file(pkgstructureFile2).read() finally: removePackageStructure()
def renameMethod(self, src, line, col, newname): try: createPackageStructure(src,MethodTestdata) rename(pkgstructureFile2,line,col,newname) save() return file(pkgstructureFile1).read() finally: removePackageStructure()
def helper(self, src, classsrc, line, col, newname): try: createPackageStructure(src, classsrc) rename(pkgstructureFile1, line, col, newname) # modify me once save is moved #return readFile(filename) from bike.transformer.save import outputqueue return outputqueue[pkgstructureFile1] finally: removePackageStructure()
def helper(self, src, classsrc, line, col, newname): try: createPackageStructure(src,classsrc) filename = pkgstructureFile1 rename(filename,line,col,newname) # modify me once save is moved #return readFile(filename) from bike.transformer.save import outputqueue return outputqueue[filename] finally: removePackageStructure()
def train(self): print("Image Preprocessing...") rename() print("Re-naming images complete!") resize() print("Re-sizing images complete!") print("Training KNN classifier...") classifier = train("../FakeImageDetection/train", model_save_path="trained_knn_model.clf", n_neighbors=1) print("Training complete!")
def update(args): archive_cfg = read_subcmd_config('archive') rename_cfg = read_subcmd_config('rename') args.archive_dir = args.archive_dir or archive_cfg['archive_dir'] if not os.path.isdir(args.archive_dir): raise RuntimeError("archive-dir {} is not a directory".format( args.archive_dir)) files = filter(tarfile.is_tarfile, collect_files(args.archive_dir)) latest = natsorted(files, reverse=True)[0] args.archive = [latest] args.extract_dir = None archive.extract(args) rename.rename(args) args.path = [rename_cfg['out_dir']] archive.archive(args)
def get_block(filename, a, b): global block global block_str block, k, block_str = rename.rename(filename) # for str in block_str: # print str build_dependency_graph(k) compute_priority(a, b) #build_graphviz() schedule() print_iloc()
def test_rename(self): test_dir = "rename" file_names = ["abc.txt", "bcd.mpg", "(20090101)abc.divx", "(20090102) bcd.mpg", "(20090103) efg.mp4", "[20090101]abc.divx", "[20090102] bcd.mpg", "[20090103] efg.mp4", "[drama] abc (2009.03.22 1440x1080i x264).mp4", "(drama) abc (2009.03.22 1440x1080i x264).mp4", "Nodame Cantabile in Europe SP2 (2009 Version) [720p x.264 AAC][Ueno Juri].mkv", "2009.Shanghai.Super.Concert.091224.SDTV.XViD-DokGoDie.avi", "2009...Shanghai.Super.Concert.091224.SDTV.XViD-DokGoDie.avi", "2009.10.Shanghai.Super.Concert.091224.SDTV.XViD-DokGoDie.avi", "Abc Def (2009.01.01).mp4", "のだめカンタービレ(第5話)「さよなら巨匠!恋の学園祭オケ対決!!」[1920x1080p x.264 AAC].mkv", "(TV バラエティ お笑い) 20091213 スクール革命 #35 東国原知事&神戸蘭子宮崎グルメ旅で大暴走 アンタ山崎・オードリー 内村光良.avi", "【TV バラエティ お笑い】 20091216 #30 爆笑レッドシアター ジョセフィーヌ登場!狩野アゲハに超災難 内村光良 (20091216)", "London Hearts (2009.12.22).mp4", "Asami Mitsuhiko ep09 finale (1280x720 x264).mp4", "Tunnels no Minasan no Okagedeshita [XviD 704x396 mp3].avi" ] os.mkdir(test_dir) for file_name in file_names: f = open(os.path.join(test_dir, file_name), "w") f.close() for (root, dirs, files) in os.walk(test_dir): for file in files: rename.rename(root, file, False) for file_name in file_names: os.remove(os.path.join(test_dir, file_name)) os.rmdir(test_dir)
def GetScriptResultByListItemIdx(self, listIdx, itemIdx, count=0, script=None): if script is None: script = self.parent.EditorPanel.TextCtrl.GetValue() command = "thisItem.%s = self.parent.ListBox.GetItemValueByColumnKey(itemIdx, '%s', listIdx)" thisItem = Struct() for v in self.GetScriptVars(): exec(command % (v[1], v[0])) oldpath = thisItem.FILEPATH thisItem.COUNT = count + 1 syspath = sys.path import rename result = rename.rename(thisItem, script, [self.GetScriptPath()]) syspath = sys.path return thisItem, result
def GetScriptResult(self, script=None): if script is None: script = self.EditorPanel.TextCtrl.GetValue() # scriptpath = self.GetScriptPath() scriptvars = self.GetScriptVars() # listIdx = self.ListBox.GetSelectedListIdx() command = "thisItem.%s = self.ListBox.GetItemValueByColumnKey(itemIdx, '%s', listIdx)" self.preview_result = list() for count, itemIdx in enumerate(self.ListBox.GetSelectedItems()): thisItem = Struct() for v in scriptvars: exec(command % (v[1], v[0])) thisItem.COUNT = count + 1 # syspath = sys.path import rename self.preview_result += [ rename.rename(thisItem, script, [self.GetScriptPath()]) ] # syspath = sys.path return self.preview_result
def renameMethod(self, src, line, col, newname): createPackageStructure(src, MethodTestdata) rename(pkgstructureFile1,line,col,newname,self.callback) save() return file(pkgstructureFile1).read()
#!/usr/bin/env python import test_tweepy import rename # import make_video import vision import os test_tweepy.get_twitter_images('lanadelrey') print("Successfully get images from Twitter!") rename.rename() vision.label_images() mkv_cmd = 'ffmpeg -r 1 -i pic%d.jpg -vcodec mpeg4 test.avi' # read_make_video = make_video.read() mkv_cmd_exe = os.popen(mkv_cmd, 'r', 1) print("Successfully make the video!")
def renameClass(self, src, newname): createPackageStructure(src,TheClassTestdata) rename(pkgstructureFile2,1,6, newname) save() return file(pkgstructureFile1).read()
from rename import rename from param import IMGDIR, NAMEFILE rename(IMGDIR, NAMEFILE)
def task_auto_rename(doc, lines): print print 'TASK: Automatically Renaming Single-Letter Variables' print '===================================================' small_vars = analyze.get_small_vars(doc, 1) N = len(small_vars) if N==1: print print 'There are no single-letter variables!' print 'Auto-renaming will abort' return #first, create new names for vars new_names=[] new_safe=[] n=0 for var in small_vars: n+=1 #new_names.append('%s__%d'%\ # (var.getAttribute('name'), n)) new_names.append('%s'%\ (var.getAttribute('name')*2)) new_safe.append( analyze.check_var_free(var, new_names[-1]) ) #this loop is used while the user is manually renaming the vars char='' while 1: #print vars. to be renamed last_block='' n=0 print print ' The following variables will be renamed' print ' ---------------------------------------' print for var in small_vars: n+=1 block=var.parentNode.getAttribute('name') if block!=last_block: print ' %s %s'%\ (blocks_name[int(var.parentNode.getAttribute('type'))], block) last_block=block name = var.getAttribute('name') new_name = new_names[n-1] if not new_safe[n-1]: new_name += '*' print ' %5s %s -> %-3s :: %s'%\ ('[%d]'%(n), name, new_name,\ var.getAttribute('type')) if not all(new_safe): print print ' (* variable name already used)' print print ' Choose one option:' print ' m - manually configure the name of one variable' print ' A - accept options and rename' print ' q - cancel task' char = raw_input(' ') if char=='q': return elif char=='A': if not all(new_safe): print ' Note: some varible names are already being used.' if raw_input(' Continue [y/n]? ').lower()!='y': continue break #leave loop and fix vars elif char== 'm': pass #we will continue later else: continue #if got here, configure name of variable n=-1 while (n<0 or n>N): char = raw_input(' Choose variable to rename [1-%d, other value to cancel]: '%(N)) try: n = int(char) except: n = 0 if n==0: continue v_name = small_vars[n-1].getAttribute('name') new_name = raw_input(' Enter name for variable %s (leave it empty to cancel): '%(v_name)) if len(new_name): new_names[n-1] = new_name new_safe[n-1] = analyze.check_var_free(var, new_name) #rename renames = dict(zip(small_vars, new_names)) rename.rename(lines, doc, renames) print print ' Rename complete!' #save import os.path fname = doc.childNodes[0].nodeName (head,tail) = os.path.split(fname) tail = 'doendo_'+tail new_fname = os.path.join(head,tail) print ' Writing %s'%(new_fname) fout = open(new_fname,'w') fout.write(''.join(lines)) fout.close()
def renameMethod(self, src, line, col, newname): createPackageStructure(src, MethodTestdata) rename(pkgstructureFile1,line,col,newname,self.callback) save() return file(pkgstructureFile1).read()
def rename(self, src, line, col, newname): writeTmpTestFile(src) rename(tmpfile,line,col, newname) save() return file(tmpfile).read()
#!/usr/bin/env python import re import sys import xml.dom.minidom import analyze import rename if len(sys.argv)<5: print 'Usage: %s file scope orig_var new_var'%(sys.argv[0]) sys.exit(1) fname = sys.argv[1] scope = sys.argv[2] orig_var = sys.argv[3] new_var = sys.argv[4] fin = open(fname) lines = fin.readlines() fin.close() data = ''.join(lines) #analyze doc = analyze.analyze(fname, data) #rename rename.rename(lines, doc, scope, {orig_var:new_var}) print ''.join(lines)
def renameClass(self, src, newname): createPackageStructure(src, TheClassTestdata) rename(pkgstructureFile2, 1, 6, newname) save() return file(pkgstructureFile1).read()
def rename(self, src, line, col, newname): createPackageStructure(src, "pass") rename(pkgstructureFile1, line, col, newname) save() return file(pkgstructureFile1).read()
def copy(string): rename.rename(string, copy=True)
'3) Resize input', '4) Transcode input into an output with another codec' ]), ] exercise = inquirer.prompt(menu)['menu'] if '1)' in exercise: getData() elif '2)' in exercise: print('Enter the path of the file you want to rename:') input_file = str(input()) print('\nEnter the new name:') new_name = str(input()) rename(input_file, new_name) elif '3)' in exercise: print('Enter the path of the input you want to resize:') input_file = str(input()) print( '\nDefine the width and height as (360x240) or the resolution as (720p):' ) while 1: size = str(input()) if 'p' in size or 'x' in size: print('\nSize: ', size) resize(size, input_file) break else: print('Invalid option, choose another size')
def sentsavedata(file_name, temp_file, url, vers): createfile('temp.csv') line = 0 with open(file_name, 'r') as inp, open(temp_file, 'a') as out: writer = csv.writer(out) for row in csv.reader(inp): print(line) if line != 0: data = { "uvid": row[0], "slave": row[1], "pv1_voltage": row[2], "pv2_voltage": row[3], "pv3_voltage": row[4], "pv1_current": row[5], "pv2_current": row[6], "pv3_current": row[7], "pv1_power": row[8], "pv2_power": row[9], "pv3_power": row[10], "daily_energy": row[11], "total_energy": row[12], "annual_energy": 0, "other": str({ "month_0": row[13], "month_1": row[14], "month_2": row[15], "month_3": row[16], "month_4": row[17], "month_5": row[18], "month_6": row[19], "month_7": row[20], "month_8": row[21], "month_9": row[22], "month_10": row[23], "month_11": row[24], "month_12": row[25], "apparent_power": row[26], "vers": row[27] }), "offline": 1, "recordedAt": row[28], } headers = {'Content-type': 'application/json'} try: print(data) if not GSM: r = requests.post(url, data=json.dumps(data), headers=headers, timeout=1) else: r = gsm.requests.post(url=url, data=json.dump(data)) print(r) print(r.content) time.sleep(2) except requests.ConnectionError: writer.writerow(row) print('no net') except requests.exceptions.ReadTimeout: writer.writerow(row) print('timeout') line += 1 delete.delete(file_name) rename(temp_file, file_name)
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ # 更新順・時間順でpdfの作成を行う # dファイルを作成しなければならない # # # """ from img2pdf import img2pdf from file_order import order from remove import rmPdf, rmJpg from rename import rename from pdfmerge import pdfmerge import os if __name__ == '__main__': os.chdir('./d') rename() img2pdf('./') order('./','p') pdfmerge('./p','01') os.chdir('./p') rmJpg() rmPdf() os.chdir('../') os.rmdir('./p')
def rename(self, src, line, col, newname): createPackageStructure(src,"pass") rename(pkgstructureFile1,line,col, newname) save() return file(pkgstructureFile1).read()
def handleUserInput(userInput, prevDir, prevCommand, clipboard, recursiveTransfer): handleOutput = 0 passedInput = "" passedOutput = "" shouldForwardData = False if userInput == "?": out.displayHelp() elif userInput == "?clip": out.displayClipboardHelp() elif userInput == "?ren": out.displayRenamingHelp() elif userInput == ":-": if len(prevCommand) == 0: print("No shell command previously executed") else: result = cmd.executeCommandWithStatus(prevCommand, True) shouldForwardData = True elif userInput == ":": result = cmd.editAndExecPrevCmd(prevCommand) if prevCommand != "" else cmd.editAndExecPrevCmd() handleOutput = 2 if result[0] == 0 else handleOutput shouldForwardData = True elif userInput == ":clearcommands": cmd.clearCommandHistory() elif userInput == ":<": result = cmd.visitCommandMenu("--execute", previousCommand = prevCommand) handleOutput = 2 if result[0] == 0 else 1 if result[0] == 1 else handleOutput shouldForwardData = True elif len(userInput) > 2 and userInput[0:2] == ":<": result = cmd.visitCommandMenu("--execute", userInput[2:], prevCommand) handleOutput = 2 if result[0] == 0 else 1 if result[0] == 1 else handleOutput shouldForwardData = True elif userInput == "::": result = cmd.visitCommandMenu("--edit", previousCommand = prevCommand) handleOutput = 2 if result[0] == 0 else 1 if result[0] == 1 else handleOutput shouldForwardData = True elif len(userInput) > 2 and userInput[0:2] == "::": result = cmd.visitCommandMenu("--edit", userInput[2:], prevCommand) handleOutput = 2 if result[0] == 0 else 1 if result[0] == 1 else handleOutput shouldForwardData = True elif userInput == "<": result = nav.executeGoToFromMenu("-h", prevDir, previousCommand = prevCommand) handleOutput = 4 if result[0] <= 0 else 1 if result[0] == 1 else handleOutput shouldForwardData = True if result[0] == -1: recursiveTransfer.setTargetDir(result[1]) elif userInput == ">": result = nav.executeGoToFromMenu("-f", prevDir, previousCommand = prevCommand) handleOutput = 4 if result[0] <= 0 else 1 if result[0] == 1 else handleOutput shouldForwardData = True if result[0] == -1: recursiveTransfer.setTargetDir(result[1]) elif len(userInput) >= 2 and userInput[0:2] == "<<": if (len(userInput) == 2): print("No filter keyword entered. Cannot filter navigation history.") else: result = nav.executeGoToFromMenu("-fh", prevDir, userInput[2:], prevCommand) handleOutput = 4 if result[0] <= 0 else 1 if result[0] == 1 else handleOutput shouldForwardData = True if result[0] == -1: recursiveTransfer.setTargetDir(result[1]) elif len(userInput) > 1 and userInput[0] == "<": result = nav.executeGoToFromMenu("-h", prevDir, userInput[1:]) handleOutput = 4 if result[0] == 0 else 1 if (result[0] == 1 or result[0] == 4) else handleOutput #forward user input if history menu is empty and the user enters <[entry_nr] (result == 4) shouldForwardData = True elif len(userInput) > 1 and userInput[0] == ">": result = nav.executeGoToFromMenu("-f", prevDir, userInput[1:]) handleOutput = 4 if result[0] == 0 else 1 if (result[0] == 1 or result[0] == 4) else handleOutput #forward user input if favorites menu is empty and the user enters >[entry_nr] (result == 4) shouldForwardData = True elif userInput == ",": result = nav.goTo(prevDir, os.getcwd()) handleOutput = 4 if result[0] == 0 else handleOutput shouldForwardData = True elif userInput == "+>": nav.addDirToFavorites() elif userInput == "->": result = nav.removeDirFromFavorites() handleOutput = 1 if result[0] == 1 else handleOutput shouldForwardData = True elif userInput == ":clearnavigation": nav.clearVisitedDirsMenu() elif userInput == ":c": clipboard.createAction() elif userInput == ":m": clipboard.createAction(False) elif userInput == ":y": clipboard.applyAction() elif userInput == ":ec": clipboard.erase(True) elif userInput == ":dc": clipboard.display() elif userInput == ":td": recursiveTransfer.setTargetDir() elif userInput == ":M": recursiveTransfer.transferItemsToTargetDir(False) elif userInput == ":C": recursiveTransfer.transferItemsToTargetDir() elif userInput == ":etd": recursiveTransfer.eraseTargetDir(True) elif userInput == ":dtd": recursiveTransfer.displayTargetDir() elif userInput.startswith(":") and userInput[1:] in renaming_commands: rn.rename(renaming_translations[userInput[1:]]) elif len(userInput) > 1 and userInput[len(userInput)-1] == ":": print("Input cancelled, no action performed!") elif userInput == "!": print("You exited the navigation app.") print("") print("Last visited directory: " + os.getcwd()) print("Last executed shell command: ", end='') print(prevCommand) if len(prevCommand) > 0 else print("none") print("") else: if userInput != "" and userInput[0] == ":": result = cmd.executeCommandWithStatus(userInput[1:]) handleOutput = 2 else: result = nav.goTo(userInput, prevDir) handleOutput = 4 if result[0] == 0 else handleOutput shouldForwardData = True if shouldForwardData: passedInput = result[1] passedOutput = result[2] return (handleOutput, passedInput, passedOutput)
def renameFunction(self, src, newname): createPackageStructure(src,FunctionTestdata) rename(pkgstructureFile2,1,4, newname) save() return file(pkgstructureFile1).read()
print("\n\n\t*** Select Function ***") if menu == 1: menu = correlation_test elif menu == 2: print("1. train") print("2. test") menu = int(input("\nSelect > ")) if menu == 1: menu = SVM_train elif menu == 2: menu = SVM_test else: raise ValueError("Invalid menu number!") elif menu == 3: print("1. train") print("2. test") menu = int(input("\nSelect > ")) if menu == 1: menu = MLP_train elif menu == 2: menu = MLP_test else: raise ValueError("Invalid menu number!") model, log = menu("") rename(model, log) except Exception as ex: _, _, tb = sys.exc_info() print("[main:" + str(tb.tb_lineno) + "] " + str(ex) + "\n\n")
# Revisar archivos ya leidos server.select('INBOX') typ, [response] = server.search(None, 'SEEN') if typ != 'OK': raise RuntimeError(response) # Copiar los mensajes a 2019 y validar typ, create_response = server.create('2019') msg_ids = ','.join(response.split(' ')) if not msg_ids: print('No hay facturas nuevas') else: server.copy(msg_ids, '2019') server.select('2019') typ, [response] = server.search(None, 'ALL') print 'COPIED:', msg_ids, ' to folder 2019' # Correos a eliminar de Inbox? server.select('INBOX', readonly=False) typ, [msg_ids] = server.search(None, 'ALL') msg_ids = ','.join(msg_ids.split(' ')) typ, response = server.store(msg_ids, '+FLAGS', r'(\Deleted)') typ, response = server.expunge() print 'Correos eliminados de Inbox:', response zextract.zextract() rename.rename(SAVED_DIR) # TODO: extraccion de *.zip # TODO: separar carpetas por mes en correo y hd
import rename dir = '/Users/michaelishmael/Dev/Projects/baby-flashcard-app/media/ipadretina' find = r'*.jpg' replace = r'_ipadr' rename.rename(dir, find, replace)