def assert_yesno(self, user_input, expected, default=None): with mock.patch('sys.stdout', new_callable=StringIO) as mock_out: with mock.patch('sys.stdin', new=StringIO(user_input)): if default is None: self.assertEqual(expected, yesno('asdf_prompt')) else: self.assertEqual(expected, yesno('asdf_prompt', default)) self.assertIn('asdf_prompt', mock_out.getvalue()) self.assertIn('[y/n]', mock_out.getvalue().lower()) if default is not None: self.assertIn('[Y/n]' if default else '[y/N]', mock_out.getvalue())
def tag(version): """ Updates the version related files and tag """ repo = Repo(".") version = Version(version) if not validate_environment(version, repo): return update_init_py_version(version) update_run_sh_version(version) input( 'Please add the release notes to the CHANGELOG.md file, then press Enter to continue.' ) proceed = False while not proceed: print(repo.git.diff()) proceed = yesno('Are these changes ok? y/N ', default=False) if repo.git.diff(): create_bump_commit(repo.git, version) else: print('No changes to commit. Exiting...') return repo.create_tag(version) print( 'Please, check the changes. If everything is OK, you just need to push with:\n' '$ git push --tags upstream {}'.format(version.branch_name()))
def checkInstalled(): import path exists = path.getPath(utils.ADDON.getSetting('OS'), silent=True) if not exists: if utils.yesno('Do you want to install the VPN application now'): import install install.install(silent=False)
def checkPrevious(): if not downloaded(): return utils.flagUpdate() if utils.yesno(1, 19, 20, 21): reboot()
def format(self): #utils.log("******************* format *******************") if not utils.yesno(1, 7, 0, 8): self.setInfoBox(utils.getString(4)) return self.timerOff() self.setInfoBox(utils.getString(9)) self.sleep(INFOSECS) #1 second response = self.flirc.format() self.timerOn() self.setInfoBox(utils.getString(response)) self.sleep(INFOSECS) #1 second
def main(): args = parse_args() if args.dir: if not check_dir_exists(args.dir): if utils.yesno(f'{args.dir} does not exist. Create it?'): create_dir(args.dir) os.chdir(args.dir) print(args.title) result = download(args.url, codec=args.codec, bitrate=args.bitrate, title=args.title, quiet=not(args.verbose)) handle_download(result, args.notify)
def sync(args: argparse.Namespace) -> None: """Prompt user for each change towards getting hot dir, cold dir and cold index synced :param args: must have attrs hot_dir:str and cold_dir: str """ hot_dir, cold_dir = Path(args.hot_dir), Path(args.cold_dir) assert hot_dir.is_dir(), "hot_dir not found!" assert cold_dir.is_dir(), "cold_dir not found!" index = Index(cold_dir) # inv_index = defaultdict(list) # for k, v in index.items(): # inv_index[v].append(k) # Set up progress bar total = 0 for file in itertools.chain(walk(hot_dir, []), walk(cold_dir, [])): total += file.stat().st_size with tqdm(total=total, unit="B", unit_scale=True) as pbar: # Find all changes required changes = walk_trees(PurePath(), index, hot_dir, cold_dir, [], [], pbar) # TODO: calculate reverse indices recursively for added and removed # TODO: find all moved. Can be also moved into added or out from removed # for file in hot_only: # h = hash_file(os.path.join(args.hot_dir, file), pbar) # if h in inv_index and set(cold_only) & set(inv_index[h]): # print(set(cold_only) & set(inv_index[h]), "moved to", file) # Confirm each change with the user changes.sort(key=attrgetter('name')) actions = [] action_total = 0 for change in changes: if yesno(str(change), default=False): actions.append(change) action_total += change.size # Carry out all confirmed changes with tqdm(total=action_total, unit="B", unit_scale=True) as pbar: for change in actions: change.apply(args.hot_dir, args.cold_dir, index) pbar.update(change.size) index.store() print("OK: Done!")
def performUpdate(response, silent): try: version = response['Version'] link = response['Link'] md5 = response['MD5'] except: return path = getDownloadPath() if utils.generateMD5(path) != md5: if (not silent) and (not utils.yesno(1, 10, 11)): return dp = None if not silent: dp = utils.progress(1, 14, 15) hash = 0 count = 0 nTries = 3 if not silent: nTries = 1 while (count < nTries) and (hash != md5): count += 1 try: download(link, path, dp) hash = utils.generateMD5(path) except Exception, e: utils.deleteFile(path) if str(e) == 'Canceled': return if hash != md5: utils.unflagUpdate() utils.deleteFile(path) utils.setSetting('dVersion', '0.0.0') if not silent: utils.ok(1, 24, 13) return
def performUpdate(response, silent): try: version = response['Version'] link = response['Link'] md5 = response['MD5'] except: return path = getDownloadPath() if utils.generateMD5(path) != md5: if (not silent) and (not utils.yesno(1, 10, 11)): return dp = None if not silent: dp = utils.progress(1, 14, 15) hash = 0 count = 0 nTries = 3 if not silent: nTries = 1 while (count < nTries) and (hash != md5): count += 1 try: download(link,path,version,dp) hash = utils.generateMD5(path) except Exception, e: utils.deleteFile(path) if str(e) == 'Canceled': return if hash != md5: utils.unflagUpdate() utils.deleteFile(path) utils.setSetting('dVersion', '0.0.0') if not silent: utils.ok(1, 24, 13) return
def CheckUsername(): utils.log('================== in CheckUsername ==================') user = USERNAME pwd = PASSWORD if user != '' and pwd != '': return True dlg = utils.yesno('VPNicity requires a subscription.', '', 'Would you like to enter your account details now?') if dlg == 1: user = utils.dialogKB('', 'Enter Your VPNicity Username') pwd = utils.dialogKB('', 'Enter Your VPNicity Password') ADDON.setSetting('USER', user) ADDON.setSetting('PASS', pwd) SetupAccount() return True
def download(url: str, codec: str, bitrate: int, title: str = None, quiet: bool = True): ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': codec, 'preferredquality': str(bitrate), }], 'outtmpl': '%(title)s.%(etx)s', 'quiet': quiet } with youtube_dl.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=False) if check_file_exists(title + OUTPUT_EXT[codec]): if utils.yesno('{} already exists, overwrite it? (y/n)' .format(title)): overwrite = True else: overwrite = False else: overwrite = True if overwrite: # youtube-dl doesn't seem to raise exceptions (further testing # is needed) try: status = ydl.download([url]) except: status = -1 move_file(info.get('title', None) + OUTPUT_EXT[codec], title + OUTPUT_EXT[codec]) return {'status': status, 'info': info} else: return {'status': -2}
def performManualUpdate(response, silent): try: import xbmcgui path = getDownloadPath() select_name=['Cancel'] select_url=['Cancel'] for i in json.loads(response): cVersion = utils.getSetting('cVersion') if not cVersion in i['Version']: select_name.append(i['Version']) select_url.append(i['Link']+'*'+i['Version']+'*'+i['MD5']) link = select_url[xbmcgui.Dialog().select('Your Current Firmware '+ cVersion , select_name)] if 'Cancel' in link: return url = link.split('*')[0] version = link.split('*')[1] md5 = link.split('*')[2] if utils.generateMD5(path) != md5: if (not silent) and (not utils.yesno(1, 11, 0)): return dp = None if silent: dp = utils.progress(1, 14, 15) hash = 0 count = 0 nTries = 3 if not silent: nTries = 1 while (count < nTries) and (hash != md5): count += 1 try: download(url,path,version,dp) hash = utils.generateMD5(path) except Exception, e: utils.deleteFile(path) if str(e) == 'Canceled': return if hash != md5: utils.unflagUpdate() utils.deleteFile(path) utils.setSetting('dVersion', '0.0.0') if not silent: utils.ok(1, 24, 13) return utils.setSetting('dVersion', version) if not utils.okReboot(1, 23, 16, 18, delay = 15): return reboot()
def splitter(originalFile, no_levels=3, zip=False, inichunk=False, demo=False): if demo: print('\nMAPPS Map Spliter **DEMO**, v0.1, 2014.') else: print('\nMAPPS Map Spliter, v0.1, 2014.') sys.stdout.write("\n Importing original image...") sys.stdout.flush() img = Image(filename=originalFile) sys.stdout.write(" complete.\n") sys.stdout.flush() imgwidth = img.width imgheight = img.height if imgwidth / imgheight != 2: print('\n Ooops!!! The Image Width to Height ratio should be 2!!!') return else: stem = originalFile.split('.')[0] if not os.path.exists(stem): os.makedirs(stem) else: print('\n Uh-oh! The directory {} already exists.'.format(stem)) if utils.yesno(' Do you want to replace it?'): shutil.rmtree(stem) os.makedirs(stem) else: return levels = range(1, no_levels + 1) for level in levels: print('\n Processing Level {}'.format(level)) split = 2 ** level segs = range(split) div = 1. / split for h in segs: for w in segs: w1 = int(imgwidth * div * w) w2 = int(imgwidth * div * (w + 1)) h1 = int(imgheight * div * h) h2 = int(imgheight * div * (h + 1)) imgtmp = img[w1:w2, h1:h2] # print(w1, w2, h1, h2) imgtmp.transform(resize='1440x720!') imgtmp.format = 'jpeg' hlevel = '{0:03d}'.format(h + 1) wlevel = '{0:03d}'.format(w + 1) saveas = os.path.join(stem, '{}_{}_{}_{}.jpg'.format( stem, level, hlevel, wlevel)) print(' Writing: {}'.format(saveas)) imgtmp.save(filename=saveas) if imgtmp.width != 1440: print('ERROR: image width = {}\n'.format(imgtmp.width)) if imgtmp.height != 720: print('ERROR: image height = {}\n'.format(imgtmp.height)) # process input image img.transform(resize='1440x720') img.format = 'jpeg' img.save(filename=os.path.join(stem, '{}_0_001_001.jpg'.format( stem))) # create ini file segment if inichunk: utils.inifix(stem, no_levels) # zip output if zip: print('\n Zipping output to {}.zip'.format(stem)) zipf = zipfile.ZipFile('{}.zip'.format(stem), 'w') utils.zipdir('{}/'.format(stem), zipf) zipf.close() shutil.rmtree(stem) print('\nFinished!\n') return
'name']: indicator['unit'] = indicator['name'][indicator['name'].rfind('(') + 1:indicator['name'].rfind(')')] # derive the short unit indicator['shortUnit'] = extract_short_unit(indicator['unit']) return indicator # Create a directory for holding the downloads. if not os.path.exists(DOWNLOADS_PATH): os.makedirs(DOWNLOADS_PATH) excel_filepath = os.path.join(DOWNLOADS_PATH, 'WDIEXCEL.xlsx') if not os.path.isfile(excel_filepath) or yesno( "The spreadsheet has been downloaded before. Download latest version?" ): info("Getting the zip file...") request_header = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' } r = requests.get(ZIP_FILE_URL, stream=True, headers=request_header) if r.ok: zip_filepath = os.path.join(DOWNLOADS_PATH, 'wdi.zip') with open(zip_filepath, 'wb') as out_file: shutil.copyfileobj(r.raw, out_file) info("Saved the zip file to disk.") z = zipfile.ZipFile(zip_filepath) z.extractall(DOWNLOADS_PATH) r = None # we do not need the request anymore
def performManualUpdate(response, silent): try: import xbmcgui path = getDownloadPath() select_name = ['Cancel'] select_url = ['Cancel'] for i in json.loads(response): cVersion = utils.getSetting('cVersion') if not cVersion in i['Version']: select_name.append(i['Version']) select_url.append(i['Link'] + '*' + i['Version'] + '*' + i['MD5']) link = select_url[xbmcgui.Dialog().select( 'Your Current Firmware ' + cVersion, select_name)] if 'Cancel' in link: return url = link.split('*')[0] version = link.split('*')[1] md5 = link.split('*')[2] if utils.generateMD5(path) != md5: if (not silent) and (not utils.yesno(1, 11, 0)): return dp = None if silent: dp = utils.progress(1, 14, 15) hash = 0 count = 0 nTries = 3 if not silent: nTries = 1 while (count < nTries) and (hash != md5): count += 1 try: download(url, path, version, dp) hash = utils.generateMD5(path) except Exception, e: utils.deleteFile(path) if str(e) == 'Canceled': return if hash != md5: utils.unflagUpdate() utils.deleteFile(path) utils.setSetting('dVersion', '0.0.0') if not silent: utils.ok(1, 24, 13) return utils.setSetting('dVersion', version) if not utils.okReboot(1, 23, 16, 18, delay=15): return reboot()