def get_libs_remote_source(lib=remote_lib_file): libraries={} libtfile=lib with open(libtfile,'rt',encoding='utf8') as csvfile: readCSV = csv.reader(csvfile, delimiter='|') i=0;up=False;tdn=False; for row in readCSV: if i==0: csvheader=row i=1 if 'library_name' and 'path' and 'TD_name' and 'Update' in csvheader: lb=csvheader.index('library_name') pth=csvheader.index('path') tdn=csvheader.index('TD_name') up=csvheader.index('Update') else: if 'library_name' and 'path' and 'TD_name' in csvheader: lb=csvheader.index('library_name') tdn=csvheader.index('TD_name') pth=csvheader.index('path') else:break else: try: update=False library=str(row[lb]) route=str(row[pth]) if tdn!=False: try: TD=str(row[tdn]) if TD=='': TD=None except: TD=None else: TD=None if up!=False: try: update=str(row[up]) if update.upper()=="TRUE": update=True else: update=False except: update=True else: update=False libraries[library]=[route,TD,update] except BaseException as e: Print.error('Exception: ' + str(e)) pass if not libraries: return False return libraries
def plotProfile(address, runIndex, space): # Uses traing profiles at the moment # space will be 'depth', 'original' or 'uncentred' print("Plot.plotProfileClass "+str(space)) # Load depth depth = None depth = Print.readDepth(address, runIndex) # depth_array = None depth_array = depth X_profiles = None if space == 'uncentred' or space == 'depth': # Load profiles lon_train, lat_train, dynHeight_train, X_train, X_train_centred, varTime_train = None, None, None, None, None, None lon_train, lat_train, dynHeight_train, X_train, X_train_centred, varTime_train = \ Print.readReconstruction(address, runIndex, depth, True) """ lon_train, lat_train, dynHeight_train, Tint_train_array, X_train_array, \ Sint_train_array, varTime_train = None, None, None, None, None, None, None lon_train, lat_train, dynHeight_train, Tint_train_array, X_train_array, \ Sint_train_array, varTime_train = Print.readLoadFromFile_Train(address, runIndex, depth) X_train_centred = X_train_array """ if space == 'uncentred': X_profiles = X_train if space == 'depth': X_profiles = X_train_centred elif space == 'original': lon_train, lat_train, dynHeight_train, Tint_train_array, X_train_array, \ Sint_train_array, varTime_train = None, None, None, None, None, None, None lon_train, lat_train, dynHeight_train, Tint_train_array, X_train_array, \ Sint_train_array, varTime_train = Print.readLoadFromFile_Train(address, runIndex, depth) X_profiles = Tint_train_array fig, ax1 = plt.subplots() for d in range(np.ma.size(X_profiles, axis=0)): ax1.plot(X_profiles[d,:], depth_array, lw = 1, alpha = 0.01, color = 'grey') if space == 'depth': ax1.set_xlabel("Normalized Temperature Anomaly /degree") ax1.set_ylabel("Depth") elif space == 'uncentred': ax1.set_xlabel("Temperature /degrees") ax1.set_ylabel("Depth") ax1.invert_yaxis() ax1.grid(True) ax1.legend(loc='best') #ax1.set_title("Profiles with Depth in SO - "+space) ax1.set_xlabel("Temperature /degrees") ax1.set_ylabel("Depth /dbar") filename = address+"Plots/Profiles_"+space+".pdf" plt.savefig(filename,bbox_inches="tight",transparent=True)
def isUpdateAvailable(self): nsp = self.getLatestFile() if not nsp: return True try: if int(nsp.version) < int(self.lastestVersion()): return True except BaseException as e: Print.error('isUpdateAvailable exception: ' + str(e)) pass return False
def unlockAll(): initTitles() initFiles() for k,f in Nsps.files.items(): if f.isUnlockable(): try: Print.info('unlocking ' + f.path) f.open(f.path, 'r+b') f.unlock() f.close() except BaseException as e: Print.info('error unlocking: ' + str(e))
def organize(): initTitles() initFiles() #scan() Print.info('organizing') for k, f in Nsps.files.items(): #print('moving ' + f.path) #Print.info(str(f.hasValidTicket) +' = ' + f.path) f.move() Print.info('removing empty directories') Nsps.removeEmptyDir('.', False) Nsps.save()
def postTinfoilSetInstalledApps(request, response): try: serial = request.bits[2] path = 'switch/' + serial + '' Print.info('path: ' + path) os.makedirs(path, exist_ok=True) with open(path + '/installed.json', 'wb') as f: f.write(request.post) return success(request, response, "OK") except: raise
def ret_tikname(self,titleid,keygeneration): tikname=False if int(keygeneration,16)>9: keygeneration=str(hex(int(keygeneration,16)))[2:] try: # print(len(str(keygeneration))) if len(str(keygeneration))==1: tikname=str(titleid).lower()+'000000000000000'+keygeneration+'.tik' elif len(str(keygeneration))==2: tikname=str(titleid)+'00000000000000'+keygeneration+'.tik' except BaseException as e: Print.error('Exception: ' + str(e)) return tikname
def verify(self): success = True for f in self: if not isinstance(f, Nca): continue hash = str(f.sha256()) if hash[0:16] != str(f._path)[0:16]: Print.error('BAD HASH %s = %s' % (str(f._path), str(f.sha256()))) success = False return success
def unlock(self): #if not self.isOpen(): # self.open('r+b') if not Titles.contains(self.titleId): raise IOError('No title key found in database!') self.ticket().setTitleKeyBlock(int(Titles.get(self.titleId).key, 16)) Print.info('setting title key to ' + Titles.get(self.titleId).key) self.ticket().flush() self.close() self.hasValidTicket = True self.move()
def setGameCard(self, isGameCard = False): if isGameCard: targetValue = 1 else: targetValue = 0 for nca in self: if type(nca) == Nca: if nca.header.getIsGameCard() == targetValue: continue Print.info('writing isGameCard for %s, %d' % (str(nca._path), targetValue)) nca.header.setIsGameCard(targetValue)
def get_biggest_file(path): try: objects = os.listdir(path) sofar = 0 name = "" for item in objects: size = os.path.getsize(os.path.join(path, item)) if size > sofar: sofar = size name = item return os.path.join(path, name) except Exception as e: Print.error(e)
def open(self, path=None, mode='rb', cryptoType=-1, cryptoKey=-1, cryptoCounter=-1): r = super(BaseFs, self).open(path, mode, cryptoType, cryptoKey, cryptoCounter) self.rewind() self.magic = self.read(0x4) if self.magic != b'HFS0': raise IOError('Not a valid HFS0 partition ' + str(self.magic)) fileCount = self.readInt32() stringTableSize = self.readInt32() self.readInt32() # junk data self.seek(0x10 + fileCount * 0x40) stringTable = self.read(stringTableSize) stringEndOffset = stringTableSize headerSize = 0x10 + 0x40 * fileCount + stringTableSize self.files = [] for i in range(fileCount): i = fileCount - i - 1 self.seek(0x10 + i * 0x40) offset = self.readInt64() size = self.readInt64() nameOffset = self.readInt32() # just the offset name = stringTable[nameOffset:stringEndOffset].decode( 'utf-8').rstrip(' \t\r\n\0') stringEndOffset = nameOffset self.readInt32() # junk data #if name in ['update', 'secure', 'normal']: if name == 'update': Print.info('Parsing update partition, please wait') f = uHfs0(None) #f = factory(name) else: f = Fs.factory(name) f._path = name f.offset = offset f.size = size self.files.append(self.partition(offset + headerSize, f.size, f)) self.files.reverse()
def run(shipCount): """ implements every method of battleship game and checks for winner every turn shipCount: number of ships(potentially of various sizes) that each player has. Precondition: player variable initialized. Postcondition: checks win condition every turn and declares winner when one player has no ships remaining. """ endGame = False player = 1 print() print("Player 1:") print() shipPlacement2.placeShip(0, shipCount) player = 2 input("Press Enter and then switch players to continue...") print(chr(27) + "[2J") print("Player 2:") print() shipPlacement2.placeShip(1, shipCount) player = 1 input("Press Enter and then switch players to continue...") print(chr(27) + "[2J") scoreBoardLogic.initializeScore(shipPlacement2.playArr[0], shipPlacement2.playArr[1]) while not endGame: if player == 1: print("Player 1:") elif player == 2: print("Player 2:") Print.printTopMap(player) print() Print.printBottomMap(player) shotDetection.shot(player) #check win condition and switch players if not if player == 1: if shotDetection.p1shotCount >= winCount: endGame = True print("\nPlayer 1 Wins!\n") else: player = 2 print(chr(27) + "[2J") elif player == 2: if shotDetection.p2shotCount == winCount: endGame = True print("\nPlayer 2 Wins!\n") else: player = 1 print(chr(27) + "[2J")
def display(): Print.clear() print() Print.yellow('You have just experienced one part of the e-waste cycle.') Print.cyan('\nWrite the next part of the cycle to help finish the game.\n') Print.green( "E.T. thanks you. Maybe he'll be able to call more friends with some re-purposed e-waste next time." + Print.yellowf(" (Don't worry. That's the same finger.)")) print() drawET()
def printInfo(self, maxDepth=3, indent=0): tabs = '\t' * indent Print.info('\n%sNacp\n' % (tabs)) super(Nacp, self).printInfo(maxDepth, indent) Print.info(tabs + 'Application Id = ' + hex(self.getApplicationId())) for i in range(15): Print.info(tabs + str(NacpLanguageType(i)) + ' Title = ' + self.getTitle(i)) Print.info(tabs + str(NacpLanguageType(i)) + ' Developer = ' + self.getDeveloper(i)) Print.info(tabs + 'Startup User Account = ' + str(self.getStartupUserAccount()))
def loadCsv(self, line, map=['id', 'path', 'version', 'timestamp', 'hasValidTicket']): split = line.split('|') for i, value in enumerate(split): if i >= len(map): Print.info('invalid map index: ' + str(i) + ', ' + str(len(map))) continue i = str(map[i]) methodName = 'set' + i[0].capitalize() + i[1:] method = getattr(self, methodName, lambda x: None) method(value.strip())
def postTinfoilSetInstalledApps(request, response): try: serial = "XAJ70002712345" path = 'switch/' + serial + '' Print.info('path: ' + path) if not os.makedirs(path, exist_ok=True): Print.error('Failed to create ' + path) with open(path + '/installed.json', 'wb') as f: f.write(request.post) return success(request, response, "OK") except: raise
def parte4(): Print.warning( "*** Dependendo dos valores dos parametros, o tempo de execucao pode ser muito alto. ***\n" ) parte4_teste1() voltar = False while not voltar: escolher = input("Deseja escolher valores para os parametros? (s/n): ") if escolher == "s": parte4_escolher() elif escolher == "n": voltar = True else: Print.fail("Opcao invalida! Tente novamente.")
def updateDb(url): initTitles() Print.info("Downloading new title database " + url) try: if url == '' or not url: return if "http://" not in url and "https://" not in url: try: url = base64.b64decode(url) except Exception as e: Print.info("\nError decoding url: ", e) return r = requests.get(url) r.encoding = 'utf-8-sig' if r.status_code == 200: Titles.loadTitleBuffer(r.text, False) else: Print.info('Error updating database: ', repr(r)) except Exception as e: Print.info('Error downloading:' + str(e)) raise
def gen_sx_autoloader_files(folder,type='hdd',push=False,no_colide=False): gamelist=folder_to_list(folder,['xci','xc0']) if type=='hdd': SD_folder=os.path.join(sx_autoloader_db, 'hdd') else: SD_folder=os.path.join(sx_autoloader_db, 'sd') if not os.path.exists(sx_autoloader_db): os.makedirs(sx_autoloader_db) if not os.path.exists(SD_folder): os.makedirs(SD_folder) for f in os.listdir(SD_folder): fp = os.path.join(SD_folder, f) try: shutil.rmtree(fp) except OSError: os.remove(fp) print(' * Generating autoloader files') try: for g in gamelist: fileid,fileversion,cctag,nG,nU,nD,baseid=parsetags(g) if fileid=='unknown': continue tfile=os.path.join(SD_folder,fileid) fileparts=Path(g).parts if type=='hdd': new_path=g.replace(fileparts[0],'"usbhdd:/') else: new_path=g.replace(fileparts[0],'"sdmc:/') new_path=new_path.replace('\\','/') with open(tfile,'w') as text_file: text_file.write(new_path) print(' DONE') if push==True: if not is_switch_connected(): sys.exit("Can't push files. Switch device isn't connected.\nCheck if mtp responder is running!!!") print(' * Pushing autoloader files') if type=='hdd': destiny="1: External SD Card\\sxos\\titles\\00FF0012656180FF\\cach\\hdd" else: destiny="1: External SD Card\\sxos\\titles\\00FF0012656180FF\\cach\\sd" process=subprocess.Popen([nscb_mtp,"TransferFolder","-ori",SD_folder,"-dst",destiny,"-fbf","true"]) while process.poll()==None: if process.poll()!=None: process.terminate(); if no_colide==True: cleanup_sx_autoloader_files() except BaseException as e: Print.error('Exception: ' + str(e)) pass
def runAcorner(self, cornerPY, cornerName): cLen = len(cornerPY) lcycle = int(dic['Std_Loop_Numb']) print cornerPY self.runAcase(cornerPY[0], cornerName, loopName=1) if cLen > 1: for id in range(0, lcycle): Time = datetime.datetime.now() Lpth = id + 1 Cnth = cornerName pt.LoopBegin(Time, Lpth, Cnth) for idx in range(1, cLen): self.runAcase(cornerPY[idx], Cnth, loopName=Lpth) pt.LoopEnd(Lpth, Cnth)
def loadTitlesJson(filePath='titledb/titles.json'): newTitles = {} confLock.acquire() if os.path.isfile(filePath): timestamp = time.clock() with open(filePath, encoding="utf-8-sig") as f: for i, k in json.loads(f.read()).items(): newTitles[i] = Title.Title() newTitles[i].__dict__ = k Print.info('loaded ' + filePath + ' in ' + str(time.clock() - timestamp) + ' seconds') confLock.release() return newTitles
def plotPostZonal(address, run, n_comp, dtype, plotFronts=False): print("Plot.plotPostZonal") # Load lat, lon and labels lon, lat, varTime, labels = None, None, None, None lon, lat, labels = Print.readLabels(address, run) # Load the posterior probabilities for each class class_number_array = None class_number_array = np.arange(0, n_comp).reshape(-1, 1) lon_pp, lat_pp, post_prob = Print.readPosteriorProb( address, run, class_number_array) #print(lat_pp) #print('post_prob: ',info(post_prob),np.shape(post_prob)) #print(type(post_prob),type(lat_pp)) minla, maxla = -60, 75 # only goes to 75 with 15 step zstep = 15.0 zex = np.arange(minla, maxla, zstep) + zstep / 2.0 print('zex ', zex) nzonz = int( (maxla - minla) / zstep) # above 3 defined in collate_raw.ipynb lb = [str(i) for i in zex] zonalz = np.zeros([n_comp, nzonz]) for z in range(nzonz): # calculate fraction of data points that fall into each class in each zonal band zdex = np.logical_and(lat >= minla + zstep * z, lat < minla + zstep * (z + 1)) for c in range(n_comp): zonalz[c, z] = np.size(np.where(labels[zdex] == c)) / np.size( (labels[zdex])) #print(np.mean(zonalz)) import matplotlib.cm as cm figz, axz = plt.subplots() for c in range(n_comp): axz.plot(zonalz[c, :], zex[:nzonz], lw=1.5, label="Class " + str(c + 1)) #, \ axz.legend(loc='best') axz.set_title("Zonal class frequencies") axz.set_xlabel("Frequency") axz.set_ylabel("Latitude") axz.grid(True) finam = 'Plots/zonal.' + str( n_comp) + 'classes' + pver + '.' + dtype + '.png' plt.savefig(finam, bbox_inches="tight", transparent=True, dpi=300)
def ativabotoes(botoes_jogo, errados, alterados, jogo, mat, strart_time, times, n_select, linha, coluna, ecra, tempo, best_results, dificuldade): result = False if botoes_jogo[0]: errados = Logic.constroi_errados(alterados, jogo, mat) strart_time = time.time() botoes_jogo[0] = False else: actual_time = time.time() - strart_time if actual_time >= times: errados = [] if botoes_jogo[1]: jogo = Logic.copia_matriz(mat) botoes_jogo[1] = False if botoes_jogo[2] and n_select: jogo[linha][coluna] = mat[linha][coluna] botoes_jogo[2] = False if botoes_jogo[3]: ecra = 5 tempo = time.time() - tempo result = Print.correto(jogo) if result: Results.adiciona_lista(tempo, dificuldade, best_results) Results.gravar_resultados(best_results) botoes_jogo[3] = False return errados, strart_time, jogo, ecra, tempo, best_results, result
def start(self): measures = self.getPrint() p = Print.getPrint2() # choose iterations iterations = self.iters.get() # choose deletion method randomOrNeighbour = "n" reMaking = True shortFirst = True successRates = [] for connections in range(49, 51): # provide a .csv file name self.fileName = "print" + self.printvar.get( ) + "\\" + self.printvar.get() + "_" + str(connections) + ".csv" # [success, total iterations] (not being used at the moment) successRate = [0, 0] for i in range(iterations): nets = netlists.getRandomNetlist(p, connections) netlist = nets[0] gates = nets[1] success = astar3D.executeAlgorithm(measures, netlist, gates, 1, self.fileName, randomOrNeighbour, reMaking, shortFirst) successRate[1] += 1 if success: successRate[0] += 1 successRates.append(successRate)
def showGrid(self): plotInfo = self.readData(self.cons.get()) self.paths = ast.literal_eval(plotInfo[4]) # if the user never asked to show the grid before or asks for a new grid if self.pathsSet == 0 or self.selectedNetlist != self.cons.get(): self.enableShowPaths() self.pathsSet = 1 # remember the selected netlist self.selectedNetlist = self.cons.get() # prepare for the grid visualization measures = self.getPrint() printObject = Print.Print() defToCall = "getPrint" + self.printvar.get() gates = getattr(printObject, defToCall)() self.v = [measures[0], measures[1], measures[2], self.paths, gates] # select only the paths with the selected lengths newPaths = [] for element in self.paths: if len(element[0]) >= self.showPathsFrom.get() and len( element[0]) <= self.showPathsTo.get(): newPaths.append(element) self.visualizeGrid(self.v[0], self.v[1], self.v[2], newPaths, self.v[4])
def plotPCAcomponents(address, runIndex, n_comp): # space will be 'depth', 'reduced' or 'uncentred' print("Plot.plotPCAcomponents") # get depths pressures = Print.readDepth(address, runIndex) # read PCA object with open('../Objects/PCA_object.pkl','rb') as input: pca_object = pickle.load(input) # get number of components n_pca_comp = pca_object.n_components_ pca_comp = pca_object.components_ # define colormap colorname = 'Dark2' colormap = plt.get_cmap(colorname, n_pca_comp) cNorm = colors.Normalize(vmin = 0, vmax = n_pca_comp) scalarMap = cmx.ScalarMappable(norm = cNorm, cmap = colormap) colorVal = scalarMap.to_rgba # line plot for k in range(0, n_pca_comp): fig = plt.figure(figsize=(7,7)) x = np.transpose(pca_comp[k]) y = pressures plt.plot(x, y, color=colorVal(k), linestyle='solid', linewidth=5.0) plt.show()
def unlockAll(): initTitles() initFiles() for k,f in Nsps.files.items(): if f.isUnlockable(): try: if f.title().isBase() and not blockchain.verifyKey(f.titleId, f.title().key): raise IOError('Could not verify title key! %s / %s - %s' % (f.titleId, f.title().key, f.title().name)) continue Print.info('unlocking ' + f.path) f.open(f.path, 'r+b') f.unlock() f.close() except BaseException as e: Print.info('error unlocking: ' + str(e))
def start(self): measures = self.getPrint() p = Print.getPrint2() # choose iterations iterations = self.iters.get() # choose deletion method randomOrNeighbour = "n" reMaking = True shortFirst = True successRates = [] for connections in range(49, 51): # provide a .csv file name self.fileName = "print" + self.printvar.get() + "\\" + self.printvar.get() + "_" + str(connections) + ".csv" # [success, total iterations] (not being used at the moment) successRate = [0, 0] for i in range(iterations): nets = netlists.getRandomNetlist(p, connections) netlist = nets[0] gates = nets[1] success = astar3D.executeAlgorithm(measures, netlist, gates, 1, self.fileName, randomOrNeighbour, reMaking, shortFirst) successRate[1] += 1 if success: successRate[0] += 1 successRates.append(successRate)
def generate(self,titleid=None,titlekey=None,keygeneration=None,outfolder=None): try: if outfolder != None: if int(keygeneration,16)>9: keygeneration=str(hex(keygeneration))[2:] if len(str(keygeneration))==1: certname=str(titleid).lower()+'000000000000000'+keygeneration+'.cert' elif len(str(keygeneration))==2: certname=str(titleid)+'00000000000000'+keygeneration+'.cert' certpath=os.path.join(outfolder, certname) chain='00010004969FE8288DA6B9DD52C7BD63642A4A9AE5F053ECCB93613FDA37992087BD9199DA5E6797618D77098133FD5B05CD8288139E2E975CD2608003878CDAF020F51A0E5B7692780845561B31C61808E8A47C3462224D94F736E9A14E56ACBF71B7F11BBDEE38DDB846D6BD8F0AB4E4948C5434EAF9BF26529B7EB83671D3CE60A6D7A850DBE6801EC52A7B7A3E5A27BC675BA3C53377CFC372EBCE02062F59F37003AA23AE35D4880E0E4B69F982FB1BAC806C2F75BA29587F2815FD7783998C354D52B19E3FAD9FBEF444C48579288DB0978116AFC82CE54DACB9ED7E1BFD50938F22F85EECF3A4F426AE5FEB15B72F022FB36ECCE9314DAD131429BFC9675F58EE000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000526F6F742D4341303030303030303300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015853303030303030323000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D21D3CE67C1069DA049D5E5310E76B907E18EEC80B337C4723E339573F4C664907DB2F0832D03DF5EA5F160A4AF24100D71AFAC2E3AE75AFA1228012A9A21616597DF71EAFCB65941470D1B40F5EF83A597E179FCB5B57C2EE17DA3BC3769864CB47856767229D67328141FC9AB1DF149E0C5C15AEB80BC58FC71BE18966642D68308B506934B8EF779F78E4DDF30A0DCF93FCAFBFA131A8839FD641949F47EE25CEECF814D55B0BE6E5677C1EFFEC6F29871EF29AA3ED9197B0D83852E050908031EF1ABBB5AFC8B3DD937A076FF6761AB362405C3F7D86A3B17A6170A659C16008950F7F5E06A5DE3E5998895EFA7DEEA060BE9575668F78AB1907B3BA1B7D000100010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010003704138EFBBBDA16A987DD901326D1C9459484C88A2861B91A312587AE70EF6237EC50E1032DC39DDE89A96A8E859D76A98A6E7E36A0CFE352CA893058234FF833FCB3B03811E9F0DC0D9A52F8045B4B2F9411B67A51C44B5EF8CE77BD6D56BA75734A1856DE6D4BED6D3A242C7C8791B3422375E5C779ABF072F7695EFA0F75BCB83789FC30E3FE4CC8392207840638949C7F688565F649B74D63D8D58FFADDA571E9554426B1318FC468983D4C8A5628B06B6FC5D507C13E7A18AC1511EB6D62EA5448F83501447A9AFB3ECC2903C9DD52F922AC9ACDBEF58C6021848D96E208732D3D1D9D9EA440D91621C7A99DB8843C59C1F2E2C7D9B577D512C166D6F7E1AAD4A774A37447E78FE2021E14A95D112A068ADA019F463C7A55685AABB6888B9246483D18B9C806F474918331782344A4B8531334B26303263D9D2EB4F4BB99602B352F6AE4046C69A5E7E8E4A18EF9BC0A2DED61310417012FD824CC116CFB7C4C1F7EC7177A17446CBDE96F3EDD88FCD052F0B888A45FDAF2B631354F40D16E5FA9C2C4EDA98E798D15E6046DC5363F3096B2C607A9D8DD55B1502A6AC7D3CC8D8C575998E7D796910C804C495235057E91ECD2637C9C1845151AC6B9A0490AE3EC6F47740A0DB0BA36D075956CEE7354EA3E9A4F2720B26550C7D394324BC0CB7E9317D8A8661F42191FF10B08256CE3FD25B745E5194906B4D61CB4C2E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000526F6F7400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001434130303030303030330000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007BE8EF6CB279C9E2EEE121C6EAF44FF639F88F078B4B77ED9F9560B0358281B50E55AB721115A177703C7A30FE3AE9EF1C60BC1D974676B23A68CC04B198525BC968F11DE2DB50E4D9E7F071E562DAE2092233E9D363F61DD7C19FF3A4A91E8F6553D471DD7B84B9F1B8CE7335F0F5540563A1EAB83963E09BE901011F99546361287020E9CC0DAB487F140D6626A1836D27111F2068DE4772149151CF69C61BA60EF9D949A0F71F5499F2D39AD28C7005348293C431FFBD33F6BCA60DC7195EA2BCC56D200BAF6D06D09C41DB8DE9C720154CA4832B69C08C69CD3B073A0063602F462D338061A5EA6C915CD5623579C3EB64CE44EF586D14BAAA8834019B3EEBEED3790001000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' chain=bytearray.fromhex(chain) # Hex.dump(chain) return chain except BaseException as e: Print.error('Exception: ' + str(e))
def __init__(self, path=None, mode='rb'): self.path = None self.titleId = None self.hasValidTicket = None self.timestamp = None self.version = None super(Nsp, self).__init__(None, path, mode) if path: self.setPath(path) #if files: # self.pack(files) if self.titleId and self.isUnlockable(): Print.info('unlockable title found ' + self.path)
def run(): while True: print '\n#########################' print '#ArcGIS Database Console#' print '#########################\n' print '\nOptions:\n' print 'f - Print Feature Classes' print 't - Print Tables\n' command = raw_input("Please enter a command\n") if command == 'f': p.featureClasses() elif command == 't': p.tables() elif command == 'q': print 'Quitting' return else: print 'Not a valid option, try again'
def evaluate(line, mode): global _do_block global _looking_for_end_bracket global _record_lines global _lines global _same_string if line == "quit": return 1 sline = line.split(" ") sline = _convert_to_values(1, sline) sline = Arithmetic.do_arithmetic_statements(sline) sline = IfElse.do_boolean_expressions(sline) sline = _booleans_to_ints(sline) # Checking if the line is both from a file and an if statement if mode: if _is_if_statement_true(sline) or _is_else_if_statement_true(sline, _same_string) or _is_else_statement_true(sline, _same_string): _do_block = True _same_string = True elif _is_start_bracket(sline): _record_lines = True _looking_for_end_bracket = True elif _looking_for_end_bracket and _is_end_bracket(sline): _record_lines = False _looking_for_end_bracket = False if _do_block: IfElse.perform_block_statement(_lines, mode) _lines = [] _do_block = False elif _record_lines: _lines.append(line) return 0 elif _is_else_if_statement(sline) or _is_else_statement(sline) or _do_block: pass else: _same_string = False # Checking if the line is a variable set statement if _is_variable_set_statement(sline): val = Variable.variable_set_statement(sline) if val: return val # Checking if the line is a print statement if _is_print_statement(sline): val = Print.print_statement(sline) if val: return val return 0
# Print.print_lol(man, fh = out_man) # # print(man, file = out_man) # with open('other_data.txt','w') as out_other: # Print.print_lol(other, fh = out_other) # # print(other, file = out_other) # except IOError as err: # print('file error: ' + str(err)) # with open('man_data.txt') as mdf: # print(mdf.readline()) # # Print.print_lol(man, fh = out_man) #=============================================================================== try: with open('man_data.txt','wb') as out_man,open('other_data','wb') as out_other: pickle.dump(man, out_man) pickle.dump(other, out_other) except IOError as err: print('File error: ' + str(err)) except pickle.PickleError as perr: print('PickleError: ' + str(perr)) new_man = [] try: with open('man_data.txt', 'rb') as man_file, open('other_data', 'rb') as other_file: new_man = pickle.load(man_file) except IOError as err: print('File error: ' + str(err)) except pickle.PickleError as perr: print('PickleError: ' + str(perr)) Print.print_lol(new_man) print(new_man)
number_of_questions = int(input('\nNumber of Questions: ')) perfectsq_neg_output = FactorisationGenerator.perfectsq_neg(number_of_questions) else: print('\nInvalid input.') quit() # Preparing output and descriptions output = [] description = [] # Perfect squares - positive description.append('\n\n\\item Factorise the following expressions using the algebraic fact that $(a+b)^2 = a^2 + 2ab + b^2$.') output.append(perfectsq_pos_output) # Perfect squares - negative description.append('\n\n\\item Factorise the following expressions using the algebraic fact that $(a+b)^2 = a^2 - 2ab + b^2$.') output.append(perfectsq_neg_output) file = open("perfect_squares.txt","w") Print.doc_format(title,set_number,date,output,description,file) file.close() print('\n\n\nText file have been produced. Please copy and paste onto LaTeX and compile.') print("\nThank you for using WhyTi's review set maker :)") any_key = input('\n\n\nPress any key to exit.') quit()
import BubbleSort import Print array = [3, -2, 0, 6, 1, 4, -1] BubbleSort.sorter(array) Print.print_array_with_index(array)
def main(): m = Map(steps, height, width, wall, ground, automataSteps) m.createMap() Print.big(m.createMapMatrix()) print "\n\n\n\n\n" Print.big(m.createMapMatrixAutomata())