def on_bot_load(bot): global data global auth_handler data = SaveIO.load(save_subdir, "keys_data") if data == {}: defaults['consumer_secret'] = get_secret() data = defaults SaveIO.save(data, save_subdir, "keys_data") auth_handler = tweepy.OAuthHandler(data['consumer_key'], data['consumer_secret']) if "access_token" in data and "access_token_secret" in data: auth_handler.set_access_token(data['access_token'], data['access_token_secret']) else: try: redirect_url = auth_handler.get_authorization_url() except tweepy.TweepError: print("[oauth] [tweepy] FATAL: Failed to get authorization URL.") sys.exit(503) webbrowser.open_new_tab(redirect_url) verifier = input("[oauth] Type the verification code from Twitter: ") try: access_token, access_token_secret = auth_handler.get_access_token(verifier) except tweepy.TweepError: print("[oauth] [tweepy] FATAL: Could not fetch access token with provided verifier code.") sys.exit(504) data['access_token'], data['access_token_secret'] = access_token, access_token_secret SaveIO.save(data, save_subdir, "keys_data") auth_handler.set_access_token(access_token, access_token_secret)
def GenerateRefreshToken(): """Prompt the user for information to generate and output a refresh token.""" print ('Please enter your OAuth 2.0 Client ID and Client Secret.\n' 'These values can be generated from the Google APIs Console, ' 'https://code.google.com/apis/console under the API Access tab.\n' 'Please use a Client ID for installed applications.') client_id = '800523524577.apps.googleusercontent.com' client_secret = '4AoEFfQChNlQOuY4H6MRcsHE' product = ChooseProduct() flow = client.OAuth2WebServerFlow( client_id=client_id, client_secret=client_secret, scope=PRODUCT_TO_OAUTH_SCOPE[product], user_agent='Ads Python Client Library', redirect_uri='urn:ietf:wg:oauth:2.0:oob') authorize_url = flow.step1_get_authorize_url() print ('Log into the Google Account you use to access your %s account and go ' 'to the following URL: \n%s\n' % (product, authorize_url)) webbrowser.open_new_tab(authorize_url) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() try: credential = flow.step2_exchange(code) except client.FlowExchangeError, e: print 'Authentication has failed: %s' % e sys.exit(1)
def do_GET(self): parsedurl = urlparse(self.path) authed = type(liw.authentication.token) is not NoneType if parsedurl.path == '/code': self.json_headers() liw.authentication.authorization_code = params_to_d(self.path).get('code') self.wfile.write(dumps({'access_token': liw.authentication.get_access_token(), 'routes': filter(lambda d: not d.startswith('_'), dir(liw.application))})) elif parsedurl.path == '/routes': self.json_headers() self.wfile.write(dumps({'routes': filter(lambda d: not d.startswith('_'), dir(liw.application))})) elif not authed: self.json_headers() if not globals()['run_already']: open_new_tab(liw.authentication.authorization_url) globals()['run_already'] = True self.wfile.write(dumps({'path': self.path, 'authed': type(liw.authentication.token) is NoneType})) elif authed and len(parsedurl.path) and parsedurl.path[1:] in dir(liw.application): self.json_headers() self.wfile.write(dumps(getattr(liw.application, parsedurl.path[1:])())) else: self.json_headers(501) self.wfile.write(dumps({'error': 'NotImplemented'}))
def serve_markdown_on_some_available_port(cfg,first_file_url): # try opening on a bunch of ports until we find one that is available attempt = 0 while True: try: port = int(cfg.port) if (cfg.port is not None) else random.randint(5000,9999) server_address = ('127.0.0.1', port) httpd = http_md_server(cfg, server_address, http_md_handler) except: attempt += 1 if attempt == 1000: raise else: break sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." #httpd.serve_forever() cfg.tickle_time = time.time() threading.Thread(target=httpd.serve_forever).start() webbrowser.open_new_tab( "http://%s:%d/%s" % (server_address[0],server_address[1],first_file_url) ) return httpd
def openBrowser(): path = conf.OUTPUT_FILE_PATH try: webbrowser.open_new_tab(path) except Exception: errMsg = '\n[ERROR] Fail to open file with web browser: %s' % path raise ToolkitSystemException(errMsg)
def SearchFor(view, text, searchurl): if not searchurl: # see if we have an extension match first, then use default settings = sublime.load_settings(__name__ + '.sublime-settings') filename, ext = os.path.splitext(view.file_name()) typesettings = settings.get('searchanywhere_type_searchengine', []) foundsetting = False for typesetting in typesettings: if typesetting['extension'] == ext: foundsetting = True searchurl = typesetting['searchurl'] if not foundsetting: if settings.has('searchanywhere_searchurl'): searchurl = settings.get('searchanywhere_searchurl') else: sublime.error_message(__name__ + ': No Search Engine selected') return else: # search url is provided by the caller pass url = searchurl.replace('{0}', text.replace(' ','%20')) webbrowser.open_new_tab(url)
def search_bare_weblink_and_open(self, start, end): # expand selection to nearest stopSymbols view_size = self.view.size() stopSymbols = ['\t', ' ', '\"', '\'', '>', '<', ','] # move the selection back to the start of the url while (start > 0 and not self.view.substr(start - 1) in stopSymbols and self.view.classify(start) & sublime.CLASS_LINE_START == 0): start -= 1 # move end of selection forward to the end of the url while (end < view_size and not self.view.substr(end) in stopSymbols and self.view.classify(end) & sublime.CLASS_LINE_END == 0): end += 1 # grab the URL url = self.view.substr(sublime.Region(start, end)) # optional select URL self.view.sel().add(sublime.Region(start, end)) exp = re.search(self.URL_REGEX, url, re.X) if exp and exp.group(0): strUrl = exp.group(0) if strUrl.find("://") == -1: strUrl = "http://" + strUrl webbrowser.open_new_tab(strUrl) else: sublime.status_message("Looks like there is nothing to open")
def checkUpdates(): try: print "\n\nchecking for updates..." import urllib f=urllib.urlopen("http://www.swharden.com/vdlabs/version/stack.txt") raw=f.read();f.close() print "RAW:",raw data = eval(raw) if data==version: # site worked, no update print "you have the most current version" return False else: # site worked, update available print "contacted site, UPDATE AVAILABLE!!!" message="A newer version is available!\n\n" message+="You are running version: "+str(version)+"\n" message+="The newer version is: "+str(data)+"\n\n" message+="Do you want to update now?" dialog = gtk.MessageDialog(None, 0, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, message) response = dialog.run() dialog.destroy() if response==-8: webbrowser.open_new_tab('http://www.swharden.com/blog/vd-labs-software-by-aj4vd/') return True except: # site didn't work! print "couldn't connect to site..." return False
def __plot_points_on_map(self, locations, is_locations=True): if is_locations: points = self.__convert_locations_to_points(locations) else: points = locations zoom_level = 16 p_count = len(points) center = points[int(p_count / 2)] mymap = pygmaps.pygmaps.maps(center[0], center[1], zoom_level) # mymap.setgrids(37.42, 37.43, 0.001, -122.15, -122.14, 0.001) # mymap.addradpoint(37.429, -122.145, 95, "#FF0000") # create range of colors for the points hex_colors = [] for val in range(1, p_count + 1): col = self.__pseudo_color(val, 0, p_count) hex_colors.append(self.__rgb_to_hex(col)) # draw marks at the points p_count = 0 for pnt, col in zip(points, hex_colors): p_count += 1 mymap.addpoint(pnt[0], pnt[1], col, title=str(p_count)) # draw path using the points then show the map path_color = "#0A6491" mymap.addpath(points, path_color) mymap.draw('mymap.draw.html') url = 'mymap.draw.html' webbrowser.open_new_tab(url)
def openInBrowserTab(url): if sys.platform[:3] in ("win", "dar"): webbrowser.open_new_tab(url) else: # some Linux OS pause execution on webbrowser open, so background it cmd = "import webbrowser;" 'webbrowser.open_new_tab("{0}")'.format(url) subprocess.Popen([sys.executable, "-c", cmd], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
def test_draw_html(self): with tempfile.NamedTemporaryFile(suffix='.html') as f: f.write(webhive.build_string()) f.flush() print f.name webbrowser.open_new_tab('file://'+f.name) time.sleep(100)
def main(): """Run the app.""" # NOTE(jk0): Disable unnecessary requests logging. requests.packages.urllib3.disable_warnings() endpoint = os.environ.get("PASTE_ENDPOINT") parser = argparse.ArgumentParser(version=__VERSION__) parser.add_argument("-f", "--file", help="upload a file") #parser.add_argument("-k", "--key", help="encrypt the pastee with a key") #parser.add_argument("-l", "--lexer", default="text", # help="use a particular lexer (default: text)") #parser.add_argument("-t", "--ttl", default=30, # help="days before paste expires (default: 30)") parsed_args = parser.parse_args() if parsed_args.file: with open(parsed_args.file, "r") as fp: paste = fp.read() else: paste = sys.stdin.read() #paste = PasteeClient(endpoint).create( # paste, # key=parsed_args.key, # lexer=parsed_args.lexer, # ttl=parsed_args.ttl) paste = PyholeClient(endpoint).create(paste) webbrowser.open_new_tab(paste.url)
def check_update(self): # 强制更新 u""" * 功能 * 检测更新。 * 若在服务器端检测到新版本,自动打开浏览器进入新版下载页面 * 网页请求超时或者版本号正确都将自动跳过 * 输入 * 无 * 返回 * 无 """ print u"检查更新。。。" try: updateTime = urllib2.urlopen(u"http://zhihuhelpbyyzy-zhihu.stor.sinaapp.com/ZhihuHelpUpdateTime.txt", timeout=10) except: return time = updateTime.readline().replace(u'\n', '').replace(u'\r', '') url = updateTime.readline().replace(u'\n', '').replace(u'\r', '') updateComment = updateTime.read() if time == SettingClass.UPDATETIME: return else: print u"发现新版本,\n更新说明:{}\n更新日期:{} ,点按回车进入更新页面".format(updateComment, time) print u'新版本下载地址:' + url raw_input() import webbrowser webbrowser.open_new_tab(url) return
def serve(port): Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(('', port), Handler) print('Serving on port: {0}'.format(port)) webbrowser.open_new_tab('http://localhost:{0}/' 'output/classify.html'.format(port)) httpd.serve_forever()
def do_open(args, _): """usage: open cluster[/role[/env/job]] Opens the scheduler page for a cluster, role or job in the default web browser. """ cluster_name = role = env = job = None args = args[0].split("/") if len(args) > 0: cluster_name = args[0] if len(args) > 1: role = args[1] if len(args) > 2: env = args[2] if len(args) > 3: job = args[3] else: # TODO(ksweeney): Remove this after MESOS-2945 is completed. die('env scheduler pages are not yet implemented, please specify job') if not cluster_name: die('cluster is required') api = make_client(cluster_name) import webbrowser webbrowser.open_new_tab( synthesize_url(api.scheduler_proxy.scheduler_client().url, role, env, job))
def execute(self, context): # Check for negative max_total_failures option - negative is an error. # for per-instance failures, negative means "no limit", so it's allowed. if context.options.max_total_failures < 0: context.print_err( "max_total_failures option must be >0, but you specified %s" % context.options.max_total_failures ) return EXIT_INVALID_PARAMETER job = context.options.instance_spec.jobkey instances = ( None if context.options.instance_spec.instance == ALL_INSTANCES else context.options.instance_spec.instance ) if instances is not None and context.options.strict: context.get_active_instances_or_raise(job, instances) api = context.get_api(job.cluster) config = context.get_job_config_optional(job, context.options.config) restart_settings = RestartSettings( batch_size=context.options.batch_size, watch_secs=context.options.watch_secs, max_per_instance_failures=context.options.max_per_instance_failures, max_total_failures=context.options.max_total_failures, health_check_interval_seconds=context.options.healthcheck_interval_seconds, ) resp = api.restart(job, instances, restart_settings, config=config) context.log_response_and_raise(resp, err_msg="Error restarting job %s:" % str(job)) context.print_out("Job %s restarted successfully" % str(job)) if context.options.open_browser: webbrowser.open_new_tab(get_job_page(api, job)) return EXIT_OK
def run(t): while(True): # response = requests.get(URL) # response.encoding = 'gb2312' # text = response.text[1:-1] # test = json.loads(text) html = urllib2.urlopen(Json_URL) context = json.loads(html.read()) tag = False for store in context.keys(): if store != "updated": for model in context[store].keys(): # print util.getStore(store)+util.getMode(model) if context[store][model] == True: tag = True print store+''+model print util.getStore(store)+' '+util.getMode(model) webbrowser.open_new_tab(Output_URL) message.send_mail(mail_list,"iphone",util.getStore(store)+' '+util.getMode(model)) if tag: time.sleep(120) time.sleep(float(t))
def colorbrewer2(self): """ View this color map at colorbrewer2.org. This will open colorbrewer2.org in your default web browser. """ webbrowser.open_new_tab(self.colorbrewer2_url) # pragma: no cover
def execute(self, context): config = context.get_job_config(context.options.jobspec, context.options.config_file) if config.raw().has_cron_schedule(): raise context.CommandError( EXIT_COMMAND_FAILURE, 'Cron jobs may only be scheduled with "aurora cron schedule" command' ) api = context.get_api(config.cluster()) resp = api.create_job(config) context.log_response_and_raise(resp, err_code=EXIT_COMMAND_FAILURE, err_msg="Job creation failed due to error:") if context.options.open_browser: webbrowser.open_new_tab(get_job_page(api, context.options.jobspec)) wait_until(context.options.wait_until, config.job_key(), api) # Check to make sure the job was created successfully. status_response = api.check_status(config.job_key()) if ( status_response.responseCode is not ResponseCode.OK or status_response.result.scheduleStatusResult.tasks is None or status_response.result.scheduleStatusResult.tasks == [] ): context.print_err("Error occurred while creating job %s" % context.options.jobspec) return EXIT_COMMAND_FAILURE else: context.print_out("Job create succeeded: job url=%s" % get_job_page(api, context.options.jobspec)) return EXIT_OK
def on_hover_navigate(self, href): if href == "#enable_globally": self.window.run_command("code_intel_enable_language_server_globally") elif href == "#enable_project": self.window.run_command("code_intel_enable_language_server_in_project") else: webbrowser.open_new_tab(href)
def identy(self): " Identification of the input .PSD file " print('\n WAIT!!!, WORKING . . . ') self.statusBar().showMessage('WAIT!!!, WORKING . . . ') arg3 = unicode(open('.cmyk2rgb-cmyk-psd.txt', 'r').read()) # print arg3 cmd1 = commands.getoutput('identify -verbose ' + arg3) # print cmd1 filename = "cmyk2rgb_report.txt" try: # write Report print(' Saving Report to ' + filename + "...") self.statusBar().showMessage('Saving Report to ' + filename) fout = open(filename, "w") fout.write(cmd1) fout.close() # open Report print(' Opening Report ' + filename + "...") self.statusBar().showMessage('Opening Report ' + filename + "...") webbrowser.open_new_tab(filename) self.statusBar().showMessage('Done.') print(' INFO: Done. ') # except if IO has an error, print an error except IOError: print " ERROR: File %s could not be saved!" % filename self.statusBar().showMessage("ERROR: File could not be saved!")
def save_list(): f = open('index.html','w') text = source.get() message = "<html><head></head><body><p>%s</p></body></html>" % text f.write(message) f.close() webbrowser.open_new_tab('index.html')
def main(): parser = argparse.ArgumentParser(description='Download videos\ from various video hosting sites\ (youtube, vimeo, bliptv, dailymotion,...)') parser.add_argument("-cli", help="Download link on the command line instead\ of opening link in the system's default browser ", action='store_true') parser.add_argument("url", help="The url of the file you wish to download") args = parser.parse_args() links = get_download_links(args.url) if links is not None: print "Choose File you wish to Download" for i, link in enumerate(links): print "[%d] : %s" % (i, link[1]) chosen_link = int(raw_input('> ')) if args.cli: download_video(links[chosen_link][0]) else: open_new_tab(links[chosen_link][0]) else: print "Service unavailable please try again"
def open_web_link(url): if not url: return try: webbrowser.open_new_tab(url) except: log_e('Could not open URL in browser')
def success(): action = 'created' if new else 'updated' print '\nYour stream "{}" has been {}!'.format(stream['Title'], action) if goto: webbrowser.open_new_tab(playlist.permalink_url) print '\nThank you for using soundcloud-streams' raise SystemExit
def preview(self): """Preview the reponse in your browser. """ fd, fname = tempfile.mkstemp() with os.fdopen(fd, 'w') as f: f.write(self.content) webbrowser.open_new_tab(fname)
def create_html_for_cluster(list_baskets, num_cluster): """Create a html with the Freesound embed""" # This list contains the begining and the end of the embed # Need to insert the id of the sound embed_blocks = ['<iframe frameborder="0" scrolling="no" src="https://www.freesound.org/embed/sound/iframe/', '/simple/medium/" width="481" height="86"></iframe>'] # Create the html string message = """ <html> <head></head> <body> """ for idx, ids in enumerate(list_baskets[num_cluster].ids): message += embed_blocks[0] + str(ids) + embed_blocks[1] if idx > 50: break message += """ </body> </html> """ # Create the file f = open('result_cluster'+ str(num_cluster) +'.html', 'w') f.write(message) f.close() # Open it im the browser webbrowser.open_new_tab('result_cluster'+ str(num_cluster) +'.html')
def show_shortcuts(): hotkeys_html = resources.doc(N_('hotkeys.html')) try: from qtpy import QtWebEngineWidgets except (ImportError, qtpy.PythonQtError): # redhat disabled QtWebKit in their qt build but don't punish the users webbrowser.open_new_tab('file://' + hotkeys_html) return html = core.read(hotkeys_html) parent = qtutils.active_window() widget = QtWidgets.QDialog() widget.setWindowModality(Qt.WindowModal) widget.setWindowTitle(N_('Shortcuts')) web = QtWebEngineWidgets.QWebEngineView(parent) web.setHtml(html) layout = qtutils.hbox(defs.no_margin, defs.spacing, web) widget.setLayout(layout) widget.resize(800, min(parent.height(), 600)) qtutils.add_action(widget, N_('Close'), widget.accept, hotkeys.QUESTION, *hotkeys.ACCEPT) widget.show() widget.exec_()
def execute(self): response = utilities.call_srclib(self.view, self.view.sel()[0], ['--no-examples']) if 'Def' not in response: utilities.StatusTimeout(self.view, 'definition not found') return definition = response['Def'] if 'Repo' in definition: # TODO: Resolve to local file - waiting for Src API to expose method for this url = utilities.BASE_URL + "/%s/.%s/%s/.def/%s" % (definition['Repo'], definition['UnitType'], definition['Unit'], definition['Path']) webbrowser.open_new_tab(url) utilities.StatusTimeout(self.view, 'definition is opened in browser') return file_path = definition['File'] if not os.path.isfile(file_path): utilities.StatusTimeout(self.view, 'definition found but file %s does ' + 'not exist.' % file_path) return view = self.view.window().open_file(file_path) sublime.set_timeout(lambda: utilities.show_location(view, definition['DefStart'], definition['DefEnd']), 10) utilities.StatusTimeout(self.view, 'definition found')
def run(self, edit): v = self.view pos = gs.sel(v).begin() inscope = lambda p: v.score_selector(p, 'path.9o') > 0 if not inscope(pos): pos -= 1 if not inscope(pos): return path = v.substr(v.extract_scope(pos)) if URL_PATH_PAT.match(path): try: if not URL_SCHEME_PAT.match(path): path = 'http://%s' % path gs.notice(DOMAIN, 'open url: %s' % path) webbrowser.open_new_tab(path) except Exception: gs.notice(DOMAIN, gs.traceback()) else: wd = v.settings().get('9o.wd') or active_wd() m = SPLIT_FN_POS_PAT.match(path) path = gs.apath((m.group(1) if m else path), wd) row = max(0, int(m.group(2))-1 if (m and m.group(2)) else 0) col = max(0, int(m.group(3))-1 if (m and m.group(3)) else 0) if os.path.exists(path): gs.focus(path, row, col, win=self.view.window()) else: gs.notice(DOMAIN, "Invalid path `%s'" % path)
print(pixel_r,pixel_b,pixel_g) requested_colour = (pixel_r,pixel_g,pixel_b) #closest_name=webcolors.rgb_to_name((pixel_r,pixel_g,pixel_b)) closest_name = get_colour_name(requested_colour) print (closest_name) translator = Translator() t=translator.translate(closest_name,dest='ta') english="THE COLOR IDENTIFIED BY OUR DEVICE IS "+closest_name tamil="எங்கள் சாதனத்தால் அடையாளம் காணப்பட்ட வண்ணம்"+t.text if(lang=="en"): speech.speak(english,"en") else: speech.speak(tamil,"ta") f = open('naveen.html','w+') wrapper = """<html > <head> <title> color identifier device </title></head> <body><h1 style="font-size:70px">THE LIQUID COLOR IS <span style="color:%s;text-transform:uppercase">%s</span></h1></body> <footer style="text-align:center;color:%s;position: fixed;right: 0;bottom: 0;font-size:50px">done by naveen and ramanathan</footer> </html>""" whole = wrapper % (closest_name,closest_name,closest_name) f.write(whole) f.close() webbrowser.open_new_tab('naveen.html') if(lang=="en"): speech.speak("thank you {} for using our device".format(name),"en") else: speech.speak("எங்கள் சாதனத்தைப் பயன்படுத்தியதற்கு நன்றி,{}".format(name),"ta")
tourdictionaryfixdupe.write(dict_filename + " = {\n") for key, val in tour.items(): dictline = '\t' + '"' + key + '"' + ': ' + str(val) + ',' + '\n' tourdictionaryfixdupe.write(dictline) tourdictionaryfixdupe.write("}") os.remove(operating_filename) os.rename(r'tourdictionaryDupeFixed.py', operating_filename) # OPENING WEB-BROWSER choice_open_web_browser = input("Do you want to search about " + golden_boot_winner + "? (y/n): ").lower().strip() if choice_open_web_browser == 'y' or choice_open_web_browser == '': try: url = "https://www.google.com.tr/search?q={}".format( golden_boot_winner) webbrowser.open_new_tab(url) time.sleep(0.5) except: print("\nError in opening the webbrowser") # CREATING `tour_complete.py` AS A BACKUP script_helper.edit_tour_complete() # FUTURE PLANS """ 1. Copy to clipboard 2. Image resizing with OPENCV 3. --Github Readme.md updation-- [complete] """
def _open_browser(*_): webbrowser.open_new_tab(get_sso_url())
def register(*_): webbrowser.open_new_tab('https://{}/#register'.format( settings.frontend_domain))
def open_google(event): webbrowser.open_new_tab("https://google.com")
def open_cp(event): webbrowser.open_new_tab("https://cleverprogrammer.com")
return "Unable to reach %s (%s)" % (url, exc) # Start an instance of Tor configured to only exit through Russia. This prints # Tor's bootstrap information as it starts. Note that this likely will not # work if you have another Tor instance running. def print_bootstrap_lines(line): if "Bootstrapped " in line: print(term.format(line, term.Color.BLUE)) print(term.format("Starting Tor:\n", term.Attr.BOLD)) tor_process = stem.process.launch_tor_with_config ( config = { 'SocksPort': str(SOCKS_PORT), 'ExitNodes': '{ru}', #Russian country code for Stem }, init_msg_handler = print_bootstrap_lines, ) print(term.format("\nChecking our endpoint:\n", term.Attr.BOLD)) print(term.format(query("https://www.atagar.com/echo.php"), term.Color.BLUE)) print('To Russia with Love...') tor_process.kill() webbrowser.open_new_tab('https://www.youtube.com/watch?v=VmkySNDX4dU&t=176s') #Something special
def OnAide(self, e): try: import webbrowser webbrowser.open_new_tab('aide.html') except: pass
if not server.check_api_version(): die("Unable to log in with the supplied username and password.") # Let's begin. server.login() review_url = tempt_fate(server, tool, changenum, diff_content=diff, parent_diff_content=parent_diff, submit_as=options.submit_as) # Load the review up in the browser if requested to: if options.open_browser: try: import webbrowser if 'open_new_tab' in dir(webbrowser): # open_new_tab is only in python 2.5+ webbrowser.open_new_tab(review_url) elif 'open_new' in dir(webbrowser): webbrowser.open_new(review_url) else: os.system('start %s' % review_url) except: print 'Error opening review URL: %s' % review_url if __name__ == "__main__": main()
def start(self): self.ui.build_menu(self.datatype, self.title, self.datalist, self.offset, self.index, self.step) self.stack.append([self.datatype, self.title, self.datalist, self.offset, self.index]) while True: datatype = self.datatype title = self.title datalist = self.datalist offset = self.offset idx = index = self.index step = self.step stack = self.stack djstack = self.djstack key = self.screen.getch() self.ui.screen.refresh() # term resize if key == -1: self.ui.update_size() self.player.update_size() # 退出 if key == ord('q'): break # 退出并清除用户信息 if key == ord('w'): self.account = {} break # 上移 elif key == ord('k'): self.index = carousel(offset, min(len(datalist), offset + step) - 1, idx - 1) # 下移 elif key == ord('j'): self.index = carousel(offset, min(len(datalist), offset + step) - 1, idx + 1) # 数字快捷键 elif ord('0') <= key <= ord('9'): if self.datatype == 'songs' or self.datatype == 'djchannels' or self.datatype == 'help': continue idx = key - ord('0') self.ui.build_menu(self.datatype, self.title, self.datalist, self.offset, idx, self.step) self.ui.build_loading() self.dispatch_enter(idx) self.index = 0 self.offset = 0 # 向上翻页 elif key == ord('u'): if offset == 0: continue self.offset -= step # e.g. 23 - 10 = 13 --> 10 self.index = (index - step) // step * step # 向下翻页 elif key == ord('d'): if offset + step >= len(datalist): continue self.offset += step # e.g. 23 + 10 = 33 --> 30 self.index = (index + step) // step * step # 前进 elif key == ord('l') or key == 10: if self.datatype == 'songs' or self.datatype == 'djchannels' or self.datatype == 'help': continue self.ui.build_loading() self.dispatch_enter(idx) self.index = 0 self.offset = 0 # 回退 elif key == ord('h'): # if not main menu if len(self.stack) == 1: continue up = stack.pop() self.datatype = up[0] self.title = up[1] self.datalist = up[2] self.offset = up[3] self.index = up[4] # 搜索 elif key == ord('f'): # 8 is the 'search' menu self.dispatch_enter(8) # 播放下一曲 elif key == ord(']'): if len(self.presentsongs) == 0: continue self.player.next() time.sleep(0.1) # 播放上一曲 elif key == ord('['): if len(self.presentsongs) == 0: continue self.player.prev() time.sleep(0.1) # 增加音量 elif key == ord('='): if len(self.presentsongs) == 0: continue self.player.volume_up() # 减少音量 elif key == ord('-'): if len(self.presentsongs) == 0: continue self.player.volume_down() # 随机播放 elif key == ord('?'): if len(self.presentsongs) == 0: continue self.player.shuffle() time.sleep(0.1) # 播放、暂停 elif key == ord(' '): if datatype == 'songs': self.presentsongs = ['songs', title, datalist, offset, index] elif datatype == 'djchannels': self.presentsongs = ['djchannels', title, datalist, offset, index] self.player.play(datatype, datalist, idx) time.sleep(0.1) # 加载当前播放列表 elif key == ord('p'): if len(self.presentsongs) == 0: continue self.stack.append([datatype, title, datalist, offset, index]) self.datatype = self.presentsongs[0] self.title = self.presentsongs[1] self.datalist = self.presentsongs[2] self.offset = self.presentsongs[3] self.index = self.presentsongs[4] if self.resume_play: self.player.play(self.datatype, self.datalist, self.index) self.resume_play = False # 添加到打碟歌单 elif key == ord('a'): if datatype == 'songs' and len(datalist) != 0: self.djstack.append(datalist[idx]) elif datatype == 'artists': pass # 加载打碟歌单 elif key == ord('z'): self.stack.append([datatype, title, datalist, offset, index]) self.datatype = 'songs' self.title = '网易云音乐 > 打碟' self.datalist = self.djstack self.offset = 0 self.index = 0 # 添加到收藏歌曲 elif key == ord('s'): if (datatype == 'songs' or datatype == 'djchannels') and len(datalist) != 0: self.collection.append(datalist[idx]) # 加载收藏歌曲 elif key == ord('c'): self.stack.append([datatype, title, datalist, offset, index]) self.datatype = 'songs' self.title = '网易云音乐 > 收藏' self.datalist = self.collection self.offset = 0 self.index = 0 # 从当前列表移除 elif key == ord('r'): if datatype != 'main' and len(datalist) != 0: self.datalist.pop(idx) self.index = carousel(offset, min(len(datalist), offset + step) - 1, idx) # 当前项目下移 elif key == ord("J"): if datatype != 'main' and len(datalist) != 0 and idx + 1 != len(self.datalist): song = self.datalist.pop(idx) self.datalist.insert(idx + 1, song) self.index = idx + 1 # 翻页 if self.index >= offset + step: self.offset = offset + step # 当前项目上移 elif key == ord("K"): if datatype != 'main' and len(datalist) != 0 and idx != 0: song = self.datalist.pop(idx) self.datalist.insert(idx - 1, song) self.index = idx - 1 # 翻页 if self.index < offset: self.offset = offset - step elif key == ord('m'): if datatype != 'main': self.stack.append([datatype, title, datalist, offset, index]) self.datatype = self.stack[0][0] self.title = self.stack[0][1] self.datalist = self.stack[0][2] self.offset = 0 self.index = 0 elif key == ord('g'): if datatype == 'help': webbrowser.open_new_tab('https://github.com/darknessomi/musicbox') self.ui.build_menu(self.datatype, self.title, self.datalist, self.offset, self.index, self.step) self.player.stop() sfile = file(Constant.conf_dir + "/flavor.json", 'w') data = { 'account': self.account, 'collection': self.collection, 'presentsongs': self.presentsongs } sfile.write(json.dumps(data)) sfile.close() curses.endwin()
help= 'CSV File where to save the exported data. Default: (current path)/export.csv', type=str, required=False, default="export.csv", metavar="path/to/file.csv") args = parser.parse_args() return args def shutdown_server(): func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not running with the Werkzeug Server') func() if __name__ == '__main__': args = parse_args() if args.save_requests: os.makedirs(args.save_requests, exist_ok=True) url = "http://localhost:65010" webbrowser.open_new_tab(make_authorization_url()) #webbrowser.open(make_authorization_url()) app.run(debug=False, port=65010)
def showTutorialDialog(self): webbrowser.open_new_tab("https://youtu.be/p0nR2YsCY_U")
def open_browser_for_ffmpeg(): import webbrowser webbrowser.open_new_tab( 'https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-essentials.7z' )
def submit_issue(self, event): webbrowser.open_new_tab( "https://github.com/10se1ucgo/DisableWinTracking/issues/new")
def open_cart_url(self): log.info("Opening cart.") params = {"token": self.access_token} url = furl(DIGITAL_RIVER_CHECKOUT_URL).set(params) webbrowser.open_new_tab(url.url) return url.url
def CreateOptimalRouteHtmlFile(optimal_route, distance, display=True): optimal_route = list(optimal_route) optimal_route += [optimal_route[0]] Page_1 = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta name="description" content="Randy Olson uses machine learning to find the optimal road trip across the U.S."> <meta name="author" content="Randal S. Olson"> <title>The optimal road trip across the U.S. according to machine learning</title> <style> html, body, #map-canvas { height: 100%; margin: 0px; padding: 0px } #panel { position: absolute; top: 5px; left: 50%; margin-left: -180px; z-index: 5; background-color: #fff; padding: 10px; border: 1px solid #999; } </style> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script> <script> var routes_list = [] var markerOptions = {icon: "http://maps.gstatic.com/mapfiles/markers2/marker.png"}; var directionsDisplayOptions = {preserveViewport: true, markerOptions: markerOptions}; var directionsService = new google.maps.DirectionsService(); var map; function initialize() { var center = new google.maps.LatLng(39, -96); var mapOptions = { zoom: 5, center: center }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); for (i=0; i<routes_list.length; i++) { routes_list[i].setMap(map); } } function calcRoute(start, end, routes) { var directionsDisplay = new google.maps.DirectionsRenderer(directionsDisplayOptions); var waypts = []; for (var i = 0; i < routes.length; i++) { waypts.push({ location:routes[i], stopover:true}); } var request = { origin: start, destination: end, waypoints: waypts, optimizeWaypoints: false, travelMode: google.maps.TravelMode.DRIVING }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } }); routes_list.push(directionsDisplay); } function createRoutes(route) { // Google's free map API is limited to 10 waypoints so need to break into batches route.push(route[0]); var subset = 0; while (subset < route.length) { var waypointSubset = route.slice(subset, subset + 10); var startPoint = waypointSubset[0]; var midPoints = waypointSubset.slice(1, waypointSubset.length - 1); var endPoint = waypointSubset[waypointSubset.length - 1]; calcRoute(startPoint, endPoint, midPoints); subset += 9; } } """ Page_2 = """ createRoutes(optimal_route); google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <div id="map-canvas"></div> </body> </html> """ localoutput_file = output_file.replace('.html', '_' + str(distance) + '.html') with open(localoutput_file, 'w') as fs: fs.write(Page_1) fs.write("\t\t\toptimal_route = {0}".format(str(optimal_route))) fs.write(Page_2) if display: webbrowser.open_new_tab(localoutput_file)
def open_url(self, url): """Opens the specified URL in the user's default web browser.""" if url is not None: webbrowser.open_new_tab(url)
def tbtnUrlGoTo_clicked(self, btn): if self.itrUrlSelected is not None: url = self.itemurls.store.get_value(self.itrUrlSelected, self.URLCOL_URL) if url: webbrowser.open_new_tab(url)
def action(self, arg): query = self.__baseURL % urllib.quote_plus( arg.split()[0].encode('utf-8')) webbrowser.open_new_tab(query)
import webbrowser google = raw_input('What do you want to search google for:') webbrowser.open_new_tab('http://www.google.com/search?btnG=1&q=%s' % google)
def codigo_fuente_accion(self, widget): webbrowser.open_new_tab( 'https://github.com/MariajoseChinchilla/Proyecto_final/blob/master/ProyectoFinalTerminado.py' )
df[df.columns[-1]] = (df[df.columns[4]] - df[df.columns[3]]) ## 重新計算 #new_m = df[['108年07月24日成交量前二十名證券']].columns.remove_unused_levels() #print(df.columns) df_title = df.columns.get_level_values(0)[0] df.columns = df.columns.get_level_values(1) ## remove mutiple index[0] #df['漲幅%'] = ((df[df.columns[4]] - df[df.columns[3]])/df[df.columns[3]]).map(lambda x:format (x , '.2%')) df['漲幅%'] = ((df[df.columns[4]] - df[df.columns[3]]) / df[df.columns[3]]) ##證券代號', '證券名稱', '成交張數', '開盤價', '收盤價', '漲跌(+/-)', '漲跌價差', '漲幅%' df = df.iloc[:, [0, 1, 2, 3, 4, 6, 7]] #dfs = df.style.applymap(color_negative_red_1,subset=pd.IndexSlice[:,['漲幅%']]) #dfs = df.style.applymap(color_negative_red,subset=['漲跌價差','漲幅%']).format({'漲幅%': "{:.2%}"}) dfs = df.style.applymap(color_negative_red, subset=['漲跌價差', '漲幅%']).format({ '漲幅%': "{:.2%}" }).set_table_styles(styles) dfs_style = dfs.render() try: with open('Top20_Trade_Amount.html', 'w') as f: f.write(df_title) f.write(dfs_style) finally: f.close() time.sleep(random.randrange(1, 2, 1)) filename = 'file:///' + os.getcwd() + '/' + 'Top20_Trade_Amount.html' webbrowser.open_new_tab(filename)
def test(url = (request_url)): webbrowser.open_new_tab(url)
def run(self, edit): word = self.view.substr(self.view.word((self.view.sel()[0].b))) webbrowser.open_new_tab("http://www.csounds.com/manual/html/%s" % word)
if not isinstance(obj, unicode): obj = unicode(obj, encoding) return obj flickr = flickrapi.FlickrAPI(config.api_key, config.api_secret) print('Step 1: authenticate') # Only do this if we don't have a valid token already if not flickr.token_valid( perms=u'write'): #notice the letter u. It's important. # Get a request token flickr.get_request_token(oauth_callback='oob') # Open a browser at the authentication URL. Do this however # you want, as long as the user visits that URL. authorize_url = flickr.auth_url( perms=u'write') #notice the letter u. It's important. webbrowser.open_new_tab(authorize_url) # Get the verifier code from the user. Do this however you # want, as long as the user gives the application the code. verifier = toUnicodeOrBust(raw_input('Verifier code: ')) # Trade the request token for an access token flickr.get_access_token(verifier) #print('Step 2: use Flickr') flickr.upload(filename=fileToUpload, tags=tagsToTag)
import webbrowser f = open('helloworld.html','w') x = "yo yo yo " message = """<html> <head></head> <body><p>Hello World!""" + x + """</p></body> </html>""" f.write(message) f.close() webbrowser.open_new_tab('helloworld.html')
timeBefore = timedelta(days=7) # 7 dni searchDate = datetime.today() - timeBefore # różnica obecnego czasu i 7 dni #print("Czas przed: ",timeBefore) #print("Obecny czas: ",datetime.today()) #print("Różnica obydwu: ",searchDate) #timestamp - data w sekundach parameters = { "site": "stackoverflow", "sort": "votes", "order": "desc", "fromdate": int(searchDate.timestamp()), "tagged": "python", "min": 15 } r = requests.get("https://api.stackexchange.com/2.2/questions/", parameters) if r.status_code == 200: print("Page is existing.") else: print("Page isn't existing.") exit(1) try: get_json = r.json() except json.decoder.JSONDecoderError: print("Something is wrong with decoding of json from this page. :(") exit(1) for question in get_json["items"]: webbrowser.open_new_tab(question["link"])
def _open_tab(url): time.sleep(1.5) webbrowser.open_new_tab(url)
def write_html(intext=''): f=open('info.htm','w',encoding='utf-8') f.write(intext) f.close webbrowser.open_new_tab('info.htm')
def report(self, tasks=None, out=None, open_it=False, out_format="html"): """Generate report file for specified task. :param task_id: UUID, task identifier :param tasks: list, UUIDs od tasks or pathes files with tasks results :param out: str, output file name :param open_it: bool, whether to open output file in web browser :param out_format: output format (junit, html or html_static) """ tasks = isinstance(tasks, list) and tasks or [tasks] results = [] message = [] processed_names = {} for task_file_or_uuid in tasks: if os.path.exists(os.path.expanduser(task_file_or_uuid)): with open(os.path.expanduser(task_file_or_uuid), "r") as inp_js: tasks_results = json.load(inp_js) for result in tasks_results: try: jsonschema.validate(result, api.Task.TASK_RESULT_SCHEMA) except jsonschema.ValidationError as e: print( _("ERROR: Invalid task result format in %s") % task_file_or_uuid, file=sys.stderr) print(six.text_type(e), file=sys.stderr) return 1 elif uuidutils.is_uuid_like(task_file_or_uuid): tasks_results = map( lambda x: { "key": x["key"], "sla": x["data"]["sla"], "result": x["data"]["raw"], "load_duration": x["data"]["load_duration"], "full_duration": x["data"]["full_duration"] }, api.Task.get(task_file_or_uuid).get_results()) else: print(_("ERROR: Invalid UUID or file name passed: %s") % task_file_or_uuid, file=sys.stderr) return 1 for task_result in tasks_results: if task_result["key"]["name"] in processed_names: processed_names[task_result["key"]["name"]] += 1 task_result["key"]["pos"] = processed_names[ task_result["key"]["name"]] else: processed_names[task_result["key"]["name"]] = 0 results.append(task_result) if out_format.startswith("html"): result = plot.plot(results, include_libs=(out_format == "html_static")) elif out_format == "junit": test_suite = junit.JUnit("Rally test suite") for result in results: if isinstance(result["sla"], list): message = ",".join([ sla["detail"] for sla in result["sla"] if not sla["success"] ]) if message: outcome = junit.JUnit.FAILURE else: outcome = junit.JUnit.SUCCESS test_suite.add_test(result["key"]["name"], result["full_duration"], outcome, message) result = test_suite.to_xml() else: print(_("Invalid output format: %s") % out_format, file=sys.stderr) return 1 if out: output_file = os.path.expanduser(out) with open(output_file, "w+") as f: f.write(result) if open_it: webbrowser.open_new_tab("file://" + os.path.realpath(out)) else: print(result)