def authentication(mode):
    """
    Authenticates a username against a stored password, if any, otherwise
    requires a password is to be entered.

    :Args:
        - cfg (:class:`.Configuration`): an instance of class Configuration as
          returned by create_config()

    :Returns:
        - a :class:`.Credentials` instance object
    """

    try:
        return AzureOAuth.get_unattended_session(config=mode)

    except (AuthenticationException, InvalidConfigException) as e:
        print("Could not get unattended session: {0}".format(e))
        
    try:
        auth_url = AzureOAuth.get_authorization_url(config=mode)[0]
        webbrowser.open(auth_url)
        redirect_url = input("Please enter authentication url: ")
        return AzureOAuth.get_authorization_token(redirect_url,
                                                  config=mode)

    except (AuthenticationException, InvalidConfigException) as e:
        print("Failed to get authorization: {0}".format(e))
示例#2
0
    def link(self, type='auth'):
        if type == 'auth':
            # link with code
            url = self.build_authorize_url()
            webbrowser.open(url)
            urlinfo = urlparse.urlparse(self.callback)
            if urlinfo.hostname in ['localhost', '127.0.0.1']:
                print "Please authorize in the browser."
                code = local.receive_code(urlinfo.port is None and '80' or urlinfo.port)
                if code == False:
                    print "Authorization failed."
                    return
                else:
                    print "Authorization succeeded."
            else:
                print "url:", url
                print "Please authorize in the browser, and input authorization code below."
                code = raw_input("Authorization code: ")
                
            token = self.access_token_with_code(code)        
        else:
            # not supported yet
            username = raw_input("Username: "******"Password: ")
            token = self.access_token_with_password(username, password)

        self.token = token['access_token']
        self.write_creds(self.token)
示例#3
0
    def OnButton(self, evt):
        """Handles button events
        @param evt: event that called this handler
        @postcondition: Dialog is closed
        @postcondition: If Report Event then email program is opened

        """
        e_id = evt.GetId()
        if e_id == wx.ID_CLOSE:
            self.Close()
        elif e_id == ID_SEND:
            msg = "mailto:%s?subject=Error Report&body=%s"
            addr = "bugs@%s" % (ed_glob.HOME_PAGE.replace("http://", '', 1))
            msg = msg % (addr, self.err_msg)
            msg = msg.replace("'", '')
            webbrowser.open(msg)
            self.Close()
        elif e_id == wx.ID_ABORT:
            ErrorDialog.ABORT = True
            # Try a nice shutdown first time through
            wx.CallLater(500, wx.GetApp().OnExit, 
                         wx.MenuEvent(wx.wxEVT_MENU_OPEN, ed_glob.ID_EXIT),
                         True)
            self.Close()
        else:
            evt.Skip()
示例#4
0
def main():
    # change path to launcher
    global __file__
    __file__ = os.path.abspath(__file__)
    if os.path.islink(__file__):
        __file__ = getattr(os, 'readlink', lambda x: x)(__file__)
    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    launcher_log.info("start XX-Net %s", update_from_github.current_version())

    web_control.confirm_xxnet_exit()

    setup_win_python.check_setup()

    module_init.start_all_auto()

    web_control.start()


    if has_desktop and config.get(["modules", "launcher", "popup_webui"], 1) == 1:
        host_port = config.get(["modules", "launcher", "control_port"], 8085)
        webbrowser.open("http://127.0.0.1:%s/" % host_port)

    update.start()

    if config.get(["modules", "launcher", "show_systray"], 1):
        sys_tray.serve_forever()
    else:
        while True:
            time.sleep(100)

    module_init.stop_all()
    sys.exit()
示例#5
0
def handle(text, mic, profile):
    baseurl= "http://www.wikihow.com/"
    wiki = MediaWiki('http://www.wikihow.com/api.php')
    #wiki.login("*****@*****.**", "david1234")
    params = {'action':'query','list':'search','srsearch':text,'srprop':'redirecttitle','limit':'1', 'format':'json'}

    response = wiki.call(params)
    #r = json.dumps(response, sort_keys=True, indent=4, separators=(',', ': '))

    flag = 0
    flag_title = "none"
    pos= response['query']['search']
    query = getRequest(text)
    wiki.logout()
#Getting the article with the best score
    for key in pos:
        val = fuzz.ratio(key['title'],query)
        print(str(val) + "% " + key['title'])
        if val > flag:
            flag = val
            flag_title = key['title']
    if flag !=0:
        answer = flag_title
        mic.say(answer)

        #rWH = renderWH.renderWikihow()
        #url = baseurl + answer
        #print url
        #url_ = rWH.getContent(str(url))
        #rWH.renderContent(url_)
        webbrowser.open(baseurl + flag_title)
    else:
        mic.say("I could not find anything bro!")
示例#6
0
def ppm2bmp(ppm_file_name):
    import os
    import webbrowser
    import sys

    bmp_file_name, extension = os.path.splitext(ppm_file_name)
    # FIXME: horrible hacks!!!
    if (extension == ".ppm"):
        bmp_file_name += ".bmp"

        # BL says: need to do some wired stuff to make sure cmd/system works with
        # space in file name , e.g. ' & " thingys
        cmd = 'ppm2bmp "'
        ppm2bmp_call = cmd + ppm_file_name + '"'
        major, minor, micro, releaselevel, serial = sys.version_info
        if (major >= 2 and minor >=4):
            import subprocess
            status = subprocess.call(ppm2bmp_call, shell=True)
            if status:
                # something went wrong with raster3d
                # maybe same for system call?!?
                print "BL WARNING:: some error in ppm2bmp"
                return
        else:
            os.system(ppm2bmp_call)
    if (extension == ".png"):
        bmp_file_name = ppm_file_name
    if (not os.path.isfile(bmp_file_name)):
        print "BL WARNING:: Cannot find png/bmp file ", bmp_file_name
    else:
        print "calling display..."
        try:
            webbrowser.open(bmp_file_name,1,1)
        except OSError:
            print "BL WARNING:: We can't open screendump file ",bmp_file_name
示例#7
0
    def open_location(self, locations):
        """
        Try to open one of the specified locations in a new window of the default
        browser. See webbrowser module for more information.

        locations should be a tuple.
        """
        # CB: could have been a list. This is only here because if locations is set
        # to a string, it will loop over the characters of the string.
        assert isinstance(locations,tuple),"locations must be a tuple."

        for location in locations:
            try:
                existing_location = resolve_path(location)
                webbrowser.open(existing_location,new=2,autoraise=True)
                self.messageBar.response('Opened local file '+existing_location+' in browser.')
                return ###
            except:
                pass

        for location in locations:
            if location.startswith('http'):
                try:
                    webbrowser.open(location,new=2,autoraise=True)
                    self.messageBar.response('Opened remote location '+location+' in browser.')
                    return ###
                except:
                    pass

        self.messageBar.response("Could not open any of %s in a browser."%locations)
示例#8
0
def grep(pattern, html, limit, fields, view, new):
    """
    Read trees from stdin and print those who match the pattern.
    If 'html' is False, print CoNLL trees.
    If 'html' is True and 'view' is False, print HTML to stdout.
    If 'html' is True and 'view' is True, view HTML in browser.
    """
    if not html:
        _grep_text(pattern)
        return

    if not view:
        _grep_html(pattern, limit, fields, file=sys.stdout)
        return

     # Create temporary file.
    f = tempfile.NamedTemporaryFile(delete=False, suffix='.html')
    filename = f.name
    f.close()

    # Write HTML to temporary file.
    with codecs.open(filename, 'wb', encoding='utf-8') as f:
        _grep_html(pattern, limit, fields, file=f)

    # Open that file.
    webbrowser.open('file://' + filename, new=new*2)
示例#9
0
def gdb(scripts_filename, fields, view, new):
    """
    Debug-print trees from stdin and either write HTML to stdout or open in
    browser.

    scripts_filename: path to scripts
    fields: CoNLL fields to print in trees
    view: if True, open in browser, otherwise print HTML to stdout
    new: if True, don't try to reuse old browser tabs (when viewing)
    """

    # If need not view in browser, write HTML to stdout.
    if not view:
        _gdb(scripts_filename, fields, file=sys.stdout)
        return

    # Create temporary file.
    f = tempfile.NamedTemporaryFile(delete=False, suffix='.html')
    filename = f.name
    f.close()

    # Write HTML to temporary file.
    with codecs.open(filename, 'wb', encoding='utf-8') as f:
        _gdb(scripts_filename, fields, file=f)

    # Open that file.
    webbrowser.open('file://' + filename, new=new*2)
    def run(self, edit):
        template_filename = self.view.file_name()
        self.dissect_filename(template_filename)
        if not template_filename:
            return sublime.error_message("You have to provide a template path.")
        if not self.action.startswith("eton"):
            return sublime.error_message("Invalid eton template %s" % template_filename)
        if not os.path.exists(template_filename):
            return sublime.error_message("File does not exist")

        self.url = get_url(self.settings) + self.COMMAND_URL+self.partner+'/'+self.action.replace('eton_','')
        # get file names
        file_names = json.dumps(self.generate_file_list())
        use_cache = self.settings.get('use_cache', DEFAULT_USE_CACHE_SETTING)

        print("Attempting to render %s for %s" % (self.action, self.partner))
        print("url is %s" % self.url)

        params = dict(partner=self.partner,
                    action=self.action,
                    templates= json.dumps(self.generate_file_map()))
        try:
            response = urlopen(self.url, urllib.parse.urlencode(params).encode("utf-8"))
        except urllib.error.URLError as e:
            print(e)
            return str(e)

        temp = tempfile.NamedTemporaryFile(delete=False, suffix=".html")
        temp.write(response.read())
        temp.close()
        webbrowser.open("file://"+temp.name)
    def open_websession(self):
        """
        Open a web browser session to prompt the user to authenticate via their
        AAD credentials.
        This method of authentication is the 'last resort' after
        auto-authentication and unattended authentication have failed.

        :Raises:
            - :class:`RuntimeError` if authentication fails, which will fail
              the loading of the addon as all auth routes have failed. This
              could be due to either an 
              :class:`batchapps.exceptions.AuthenticationException` of a
              :class:`batchapps.exceptions.InvalidConfigException`.
        """
        session = bpy.context.scene.batchapps_session

        try:
            url, state = AzureOAuth.get_authorization_url(config=session.cfg)
            webbrowser.open(url)

            session.log.info("Opened web browser for authentication "
                             "and waiting for response.")

            self.wait_for_request()

        except (AuthenticationException, InvalidConfigException) as exp:
            session.log.error("Unable to open Web UI auth session: "
                              "{0}".format(exp))

            raise RuntimeError("Failed to authorize addon")
示例#12
0
def authenticate():
    """Authenticate with facebook so you can make api calls that require auth.

    Alternatively you can just set the ACCESS_TOKEN global variable in this
    module to set an access token you get from facebook.

    If you want to request certain permissions, set the AUTH_SCOPE global
    variable to the list of permissions you want.
    """
    global ACCESS_TOKEN
    needs_auth = True
    if os.path.exists(ACCESS_TOKEN_FILE):
        data = json.loads(open(ACCESS_TOKEN_FILE).read())
        expires_at = data.get('expires_at')
        still_valid = expires_at and (expires_at == 'never' or expires_at > time.time())
        if still_valid and set(data['scope']).issuperset(AUTH_SCOPE):
            ACCESS_TOKEN = data['access_token']
            needs_auth = False

    if needs_auth:
        webbrowser.open('https://www.facebook.com/dialog/oauth?' +
                        urlencode({'client_id':APP_ID,
                                   'redirect_uri':'http://127.0.0.1:%s/' % SERVER_PORT,
                                   'response_type':'token',
                                   'scope':','.join(AUTH_SCOPE)}))

        httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', SERVER_PORT), _RequestHandler)
        while ACCESS_TOKEN is None:
            httpd.handle_request()
示例#13
0
 def setSource(self, url):
     """Called when user clicks on a URL"""
     name = unicode(url.toString())
     if name.startswith(u'http'):
         webbrowser.open(name, True)
     else:
         QtGui.QTextBrowser.setSource(self, QtCore.QUrl(name))
示例#14
0
def do_args(arg, quoted_output, output):
  if not quoted_output:
    cmd = '{}://x-callback-url/'.format(arg)
  else:
    if arg == 'onewriter':
      # Replace 'Notepad.txt' with the name of your open doc in 1Writer
      cmd = '{}://x-callback-url/append?path=Documents%2F&name=Notepad.txt&type=Local&text={}'.format(arg, quoted_output)
    if arg == 'editorial':
      clipboard.set(output)
      '''
      'Append Open Doc' is an Editorial workflow
      available here:
      http://www.editorial-workflows.com/workflow/5278032428269568/g2tYM1p0OZ4
      '''
      cmd = '{}://?command=Append%20Open%20Doc'.format(arg)
    if arg == 'drafts4':
      '''
      Append gps data to open Draft doc using the
      2nd argument from calling URL as the UUID of
      the open doc
      '''
      cmd = '{}://x-callback-url/append?uuid={}&text={}'.format(arg, sys.argv[2], quoted_output)

  webbrowser.open(cmd)
  sys.exit('Finished!')
示例#15
0
def browse_remote(pep):
    import webbrowser
    file = find_pep(pep)
    if file.startswith('pep-') and file.endswith((".txt", '.rst')):
        file = file[:-3] + "html"
    url = PEPDIRRUL + file
    webbrowser.open(url)
示例#16
0
    def post_process(self):
        """
        Upload results if possible
        """
        super(BlazeMeterUploader, self).post_process()

        if not self.client.active_session_id:
            self.log.debug("No feeding session obtained, not uploading artifacts")
            return

        if len(self.kpi_buffer):
            self.__send_data(self.kpi_buffer, False)
            self.kpi_buffer = []

        try:
            self.__upload_artifacts()
        except IOError as _:
            self.log.warning("Failed artifact upload: %s", traceback.format_exc())
        finally:
            try:
                self.client.end_online()
            except KeyboardInterrupt:
                raise
            except BaseException as exc:
                self.log.warning("Failed to finish online: %s", exc)

        if self.client.results_url:
            if self.browser_open in ('end', 'both'):
                webbrowser.open(self.client.results_url)
            self.log.info("Online report link: %s", self.client.results_url)
示例#17
0
 def inner_run():
     print "Validating models..."
     self.validate(display_num_errors=True)
     print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
     print "Development server is running at http://%s:%s/" % (addr, port)
     print "Using the Werkzeug debugger (http://werkzeug.pocoo.org/)"
     print "Quit the server with %s." % quit_command
     path = options.get('admin_media_path', '')
     if not path:
         admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin')
         if os.path.isdir(admin_media_path):
             path = admin_media_path
         else:
             path = os.path.join(django.__path__[0], 'contrib/admin/media')
     handler = WSGIHandler()
     if USE_ADMINMEDIAHANDLER:
         handler = AdminMediaHandler(handler, path)
     if USE_STATICFILES:
         use_static_handler = options.get('use_static_handler', True)
         insecure_serving = options.get('insecure_serving', False)
         if use_static_handler and (settings.DEBUG or insecure_serving):
             handler = StaticFilesHandler(handler)
     if open_browser:
         import webbrowser
         url = "http://%s:%s/" % (addr, port)
         webbrowser.open(url)
     run_simple(addr, int(port), DebuggedApplication(handler, True),
                use_reloader=use_reloader, use_debugger=True, threaded=threaded)
示例#18
0
	def _send_to_working_copy(self, action, payload, x_callback_enabled=True):
		x_callback = 'x-callback-url/' if x_callback_enabled else ''
		payload['key'] = self.key
		payload = urllib.urlencode(payload).replace('+', '%20')
		fmt = 'working-copy://{x_callback}{action}/?{payload}'
		url = fmt.format(x_callback=x_callback, action=action, payload=payload)
		wb.open(url)
示例#19
0
	def on_navigate(self, url):
		if self.view.is_popup_visible():
			self.view.hide_popup()
			if url[0:4] == 'http':
				webbrowser.open(url)
			else:
				self.view.window().open_file(url, sublime.ENCODED_POSITION | sublime.TRANSIENT)
示例#20
0
def song(karaoke=False):
    """
    Listen to the Gammapy song.

    Make sure you listen on good headphones or speakers. You'll be not disappointed!

    Parameters
    ----------
    karaoke : bool
        Print lyrics to sing along.
    """
    import webbrowser
    import sys

    webbrowser.open("https://gammapy.org/gammapy_song.mp3")

    if karaoke:
        lyrics = (
            "\nGammapy Song Lyrics\n"
            "-------------------\n\n"
            "Gammapy, gamma-ray data analysis package\n"
            "Gammapy, prototype software CTA science tools\n\n"
            "Supernova remnants, pulsar winds, AGN, Gamma, Gamma, Gammapy\n"
            "Galactic plane survey, pevatrons, Gammapy, Gamma, Gammapy\n"
            "Gammapy, github, continuous integration, readthedocs, travis, "
            "open source project\n\n"
            "Gammapy, Gammapy\n\n"
            "Supernova remnants, pulsar winds, AGN, Gamma, Gamma, Gammapy\n"
        )

        centered = "\n".join("{:^80}".format(s) for s in lyrics.split("\n"))
        sys.stdout.write(centered)
示例#21
0
    def OnLinkClicked(self, link):
        self.link = wx.TextDataObject(link.GetHref())
        if link.GetEvent().ShiftDown():
            if wx.TheClipboard.Open():
                wx.TheClipboard.SetData(self.link)
                wx.TheClipboard.Close()
            else:
                dlg = wx.MessageDialog(self, "Couldn't open clipboard!\n", wx.OK)
                wx.Bell()
                dlg.ShowModal()
                dlg.Destroy()
        else:
            if 0:  # Chris's original code...
                if sys.platform not in ["windows", "nt"]:
                    # TODO: A MORE APPROPRIATE COMMAND LINE FOR Linux
                    # [or rather, non-Windows platforms... as of writing,
                    # this MEANS  Linux, until wxPython for wxMac comes along...]
                    command = "/usr/bin/netscape"
                else:
                    command = "start"
                command = '%s "%s"' % (command, self.link.GetText())
                os.system(command)

            else:  # My alternative
                import webbrowser

                webbrowser.open(link.GetHref())
示例#22
0
 def link(self, event):
     "opens browser with linked page"
     link = "http://www.gnu.org/licenses/gpl-3.0.html"
     try:
         webbrowser.open(link)
     except Exception:
         self.bell()
def open_url(url, quiet = True):
    try:
        webbrowser.open(url)
    except webbrowser.Error as ex: 
        log.error('Failed to open URL "{0}" in default browser, because "{1}".'.format(url, ex))
        if not quiet:
            raise
示例#24
0
def process_html(htmlPart):
    # Example using BeautifulSoup
    #soup = BeautifulSoup(htmlPart.get_payload(decode=True))
    #for link in soup.findAll('a'):
    #   if link['href']:
    #       url = link['href']

    # BeautifulSoup is a better way to extract links, but isn't
    # guaranteed to be installed. Use custom HTMLParser class instead.
    parser = UrlParser()
    parser.feed(htmlPart.get_payload(decode=True))
    parser.close()
    urls = parser.get_urls()

    if any(urls):
        for url in urls:
            logging.info("!!! Found a URL: " + url)
            # Attempt to open the url in the default browser
            # Use a new window to de-conflict other potential exploits
            # new=0 -> same window
            # new=1 -> new window
            # new=2 -> new tab
            logging.debug("Opening URL " + url)
            webbrowser.open(url, 1)

    filename = htmlPart.get_filename()
    if filename:
        # We have an HTML attachment
        # Attempt to save and open it.
        process_attachment(htmlPart, '.html')
示例#25
0
    def goURL(self, event):
	try:
	    webbrowser.open(self.noteDescrip.GetValue())
	except:
	    dial = wx.MessageDialog(None, 'Unable to launch internet browser', 'Error', wx.OK | wx.ICON_ERROR)
	    dial.ShowModal()  
	    return
示例#26
0
    def test_access_token_acquisition(self):
        """
        This test is commented out because it needs user-interaction.
        """
        if not self.RUN_INTERACTIVE_TESTS:
            return
        oauth_authenticator = scapi.authentication.OAuthAuthenticator(self.CONSUMER, 
                                                                      self.CONSUMER_SECRET,
                                                                      None, 
                                                                      None)

        sca = scapi.ApiConnector(host=self.API_HOST, authenticator=oauth_authenticator)
        token, secret = sca.fetch_request_token()
        authorization_url = sca.get_request_token_authorization_url(token)
        webbrowser.open(authorization_url)
        oauth_verifier = raw_input("please enter verifier code as seen in the browser:")
        
        oauth_authenticator = scapi.authentication.OAuthAuthenticator(self.CONSUMER, 
                                                                      self.CONSUMER_SECRET,
                                                                      token, 
                                                                      secret)

        sca = scapi.ApiConnector(self.API_HOST, authenticator=oauth_authenticator)
        token, secret = sca.fetch_access_token(oauth_verifier)
        logger.info("Access token: '%s'", token)
        logger.info("Access token secret: '%s'", secret)
        # force oauth-authentication with the new parameters, and
        # then invoke some simple test
        self.AUTHENTICATOR = "oauth"
        self.TOKEN = token
        self.SECRET = secret
        self.test_connect()
示例#27
0
def info_command():
  i = listbox.curselection()
  try:
    item = listbox.get(i)
  except Tkinter.TclError:
    return
  webbrowser.open("http://en.wikipedia.org/wiki/%s" % armor(item))
示例#28
0
def main():
  parser = Parser()

  # Parse the input files.
  for src in FLAGS.sources:
    if src == '-':
      parser.parse_file(sys.stdin)
    else:
      with open(src, mode='r') as infile:
        parser.parse_file(infile)

  # Print the csv.
  if not FLAGS.open:
    parser.print_csv()
  else:
    dirname = tempfile.mkdtemp()
    basename = FLAGS.name
    if os.path.splitext(basename)[1] != '.csv':
      basename += '.csv';
    pathname = os.path.join(dirname, basename)
    with open(pathname, mode='w') as tmpfile:
      parser.print_csv(outfile=tmpfile)
    fileuri = urlparse.urljoin('file:', urllib.pathname2url(pathname))
    print('opening %s' % fileuri)
    webbrowser.open(fileuri)
示例#29
0
 def on_navigation_policy(self, webview, frame, request, action, decision):
     uri = request.get_uri()
     if not uri.startswith('gir://'):
         webbrowser.open(uri)
         decision.ignore()
         return True
     parts = uri.split('/')[2:]
     gir = parts.pop(0)
     if gir:
         for namespace in self.get_namespaces():
             if namespace.name == gir:
                 self._set_namespace(namespace)
                 if not parts:
                     self._show_namespace(namespace)
                     decision.ignore()
                     return True
                 break
         name = parts.pop(0) if parts else None
         if name:
             for klass in namespace.classes:
                 if name == klass.name:
                     self._set_class(klass)
                     if not parts:
                         self._show_class(namespace, klass)
                         decision.ignore()
                         return True
     return False
示例#30
0
def webgui(args):
    os.environ["FWDB_CONFIG"] = json.dumps(get_lp(args).to_dict())
    from fireworks.flask_site.app import app
    if args.wflowquery:
        app.BASE_Q_WF = json.loads(args.wflowquery)
    if args.fwquery:
        app.BASE_Q = json.loads(args.fwquery)
        if "state" in app.BASE_Q:
            app.BASE_Q_WF["state"] = app.BASE_Q["state"]

    if not args.server_mode:
        from multiprocessing import Process
        p1 = Process(
            target=app.run,
            kwargs={"host": args.host, "port": args.port, "debug": args.debug})
        p1.start()
        import webbrowser
        time.sleep(2)
        webbrowser.open("http://{}:{}".format(args.host, args.port))
        p1.join()
    else:
        from fireworks.flask_site.app import bootstrap_app
        try:
            from fireworks.flask_site.gunicorn import (
                StandaloneApplication, number_of_workers)
        except ImportError:
            import sys
            sys.exit("Gunicorn is required for server mode. "
                     "Install using `pip install gunicorn`.")
        options = {
            'bind': '%s:%s' % (args.host, args.port),
            'workers': number_of_workers(),
        }
        StandaloneApplication(bootstrap_app, options).run()
示例#31
0
 def open_download(self):
     """Open download page in web browser."""
     webbrowser.open(self.app.settings['download_link'])
     self.goto_next.emit()
示例#32
0
async def _run(
        provider,
        # AWS
        profile,
        aws_access_key_id,
        aws_secret_access_key,
        aws_session_token,
        # Azure
        cli,
        user_account,
        user_account_browser,
        msi,
        service_principal,
        file_auth,
        tenant_id,
        subscription_ids,
        all_subscriptions,
        client_id,
        client_secret,
        username,
        password,
        # GCP
        service_account,
        project_id,
        folder_id,
        organization_id,
        all_projects,
        # Aliyun
        access_key_id,
        access_key_secret,
        # GitHub
        repositories,
        # General
        report_name,
        report_dir,
        timestamp,
        services,
        skipped_services,
        list_services,
        result_format,
        database_name,
        host_ip,
        host_port,
        regions,
        excluded_regions,
        fetch_local,
        update,
        ip_ranges,
        ip_ranges_name_key,
        ruleset,
        exceptions,
        force_write,
        debug,
        quiet,
        log_file,
        no_browser,
        programmatic_execution,
        **kwargs):
    """
    Run a scout job.
    """

    # Configure the debug level
    set_logger_configuration(debug, quiet, log_file)

    print_info('Launching Scout')

    print_info('Authenticating to cloud provider')
    auth_strategy = get_authentication_strategy(provider)

    try:
        credentials = auth_strategy.authenticate(
            profile=profile,
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key,
            aws_session_token=aws_session_token,
            user_account=user_account,
            user_account_browser=user_account_browser,
            service_account=service_account,
            cli=cli,
            msi=msi,
            service_principal=service_principal,
            file_auth=file_auth,
            tenant_id=tenant_id,
            client_id=client_id,
            client_secret=client_secret,
            username=username,
            password=password,
            access_key_id=access_key_id,
            access_key_secret=access_key_secret)

        if not credentials:
            return 101
    except Exception as e:
        print_exception(f'Authentication failure: {e}')
        return 101

    # Create a cloud provider object
    try:
        cloud_provider = get_provider(
            provider=provider,
            # AWS
            profile=profile,
            # Azure
            subscription_ids=subscription_ids,
            all_subscriptions=all_subscriptions,
            # GCP
            project_id=project_id,
            folder_id=folder_id,
            organization_id=organization_id,
            all_projects=all_projects,
            # GitHub
            repositories=repositories,
            # Other
            report_dir=report_dir,
            timestamp=timestamp,
            services=services,
            skipped_services=skipped_services,
            programmatic_execution=programmatic_execution,
            credentials=credentials)
    except Exception as e:
        print_exception(f'Initialization failure: {e}')
        return 102

    # Create a new report
    try:
        report_name = report_name if report_name else cloud_provider.get_report_name(
        )
        report = ScoutReport(cloud_provider.provider_code,
                             report_name,
                             report_dir,
                             timestamp,
                             result_format=result_format)

        if database_name:
            database_file, _ = get_filename('RESULTS',
                                            report_name,
                                            report_dir,
                                            file_extension="db")
            Server.init(database_file, host_ip, host_port)
            return
    except Exception as e:
        print_exception('Report initialization failure: {}'.format(e))
        return 103

    # If this command, run and exit
    if list_services:
        available_services = [
            x for x in dir(cloud_provider.services)
            if not (x.startswith('_') or x in ['credentials', 'fetch'])
        ]
        print_info('The available services are: "{}"'.format(
            '", "'.join(available_services)))
        return 0

    # Complete run, including pulling data from provider
    if not fetch_local:

        # Fetch data from provider APIs
        try:
            print_info('Gathering data from APIs')
            await cloud_provider.fetch(regions=regions,
                                       excluded_regions=excluded_regions)
        except KeyboardInterrupt:
            print_info('\nCancelled by user')
            return 130
        except Exception as e:
            print_exception(
                'Unhandled exception thrown while gathering data: {}'.format(
                    e))
            return 104

        # Update means we reload the whole config and overwrite part of it
        if update:
            try:
                print_info('Updating existing data')
                current_run_services = copy.deepcopy(cloud_provider.services)
                last_run_dict = report.encoder.load_from_file('RESULTS')
                cloud_provider.services = last_run_dict['services']
                for service in cloud_provider.service_list:
                    cloud_provider.services[service] = current_run_services[
                        service]
            except Exception as e:
                print_exception('Failure while updating report: {}'.format(e))

    # Partial run, using pre-pulled data
    else:
        try:
            print_info('Using local data')
            # Reload to flatten everything into a python dictionary
            last_run_dict = report.encoder.load_from_file('RESULTS')
            for key in last_run_dict:
                setattr(cloud_provider, key, last_run_dict[key])
        except Exception as e:
            print_exception('Failure while updating report: {}'.format(e))

    # Pre processing
    try:
        print_info('Running pre-processing engine')
        cloud_provider.preprocessing(ip_ranges, ip_ranges_name_key)
    except Exception as e:
        print_exception(
            'Failure while running pre-processing engine: {}'.format(e))
        return 105

    # Analyze config
    try:
        print_info('Running rule engine')
        finding_rules = Ruleset(cloud_provider=cloud_provider.provider_code,
                                environment_name=cloud_provider.environment,
                                filename=ruleset,
                                ip_ranges=ip_ranges,
                                account_id=cloud_provider.account_id)
        processing_engine = ProcessingEngine(finding_rules)
        processing_engine.run(cloud_provider)
    except Exception as e:
        print_exception('Failure while running rule engine: {}'.format(e))
        return 106

    # Create display filters
    try:
        print_info('Applying display filters')
        filter_rules = Ruleset(cloud_provider=cloud_provider.provider_code,
                               environment_name=cloud_provider.environment,
                               filename='filters.json',
                               rule_type='filters',
                               account_id=cloud_provider.account_id)
        processing_engine = ProcessingEngine(filter_rules)
        processing_engine.run(cloud_provider)
    except Exception as e:
        print_exception('Failure while applying display filters: {}'.format(e))
        return 107

    # Handle exceptions
    if exceptions:
        print_info('Applying exceptions')
        try:
            exceptions = RuleExceptions(exceptions)
            exceptions.process(cloud_provider)
            exceptions = exceptions.exceptions
        except Exception as e:
            print_exception(f'Failed to load exceptions: {e}')
            exceptions = {}
    else:
        exceptions = {}

    # Finalize
    try:
        print_info('Running post-processing engine')
        run_parameters = {
            'services': services,
            'skipped_services': skipped_services,
            'regions': regions,
            'excluded_regions': excluded_regions,
        }
        cloud_provider.postprocessing(report.current_time, finding_rules,
                                      run_parameters)
    except Exception as e:
        print_exception(
            'Failure while running post-processing engine: {}'.format(e))
        return 108

    # Save config and create HTML report
    try:
        html_report_path = report.save(cloud_provider, exceptions, force_write,
                                       debug)
    except Exception as e:
        print_exception('Failure while generating HTML report: {}'.format(e))
        return 109

    # Open the report by default
    if not no_browser:
        print_info('Opening the HTML report')
        url = 'file://%s' % os.path.abspath(html_report_path)
        webbrowser.open(url, new=2)

    if ERRORS_LIST:  # errors were handled during execution
        return 200
    else:
        return 0
示例#33
0
 def open_browser(self, url):        
     webbrowser.open(url)
示例#34
0
	def new_account(__):
		web.open("http://progject.free.fr/pages/inscription.php")
示例#35
0
import webbrowser
import time

count = 1

while (count <= 3):
    time.sleep(10)
    webbrowser.open('https://www.youtube.com/watch?v=B35SXSVNMmI')
    count = count + 1
示例#36
0
    def __init__(self, width=600, height=200, background='gray'):
        self.w = width
        self.h = height
        self.bg = background
        self.title = '哆啦A梦屁股大  一个马桶装不下'
        self.root = tk.Tk(className=self.title)
        self.url = tk.StringVar()
        self.v = tk.IntVar()
        self.v.set(1)
        # 定义3个frame,frame 默认按从上往下排列
        # Frame空间
        frame_1 = tk.Frame(self.root)
        frame_2 = tk.Frame(self.root)
        frame_3 = tk.Frame(self.root)

        # menu 菜单
        menu = tk.Menu(self.root)
        self.root.config(menu=menu)
        menu1 = tk.Menu(menu, tearoff=0)
        menu.add_cascade(label='Menu', menu=menu1)
        menu1.add_command(label='about me',
                          command=lambda: webbrowser.open(
                              'https://blog.csdn.net/zwx19921215'))
        menu1.add_command(label='exit', command=lambda: self.root.quit())

        # 控件内容设置
        # frame1 ,每个frame标签元素默认按从左只有排列
        group = tk.Label(frame_1, text='视频解析选项(默认Part 1)', padx=14, pady=14)
        tb1 = tk.Radiobutton(frame_1,
                             text='Part 1',
                             variable=self.v,
                             value=1,
                             width=10,
                             height=3)
        tb2 = tk.Radiobutton(frame_1,
                             text='Part 2',
                             variable=self.v,
                             value=2,
                             width=10,
                             height=3)
        # frame2
        label1 = tk.Label(frame_2, text="小仙女请输入网址:")
        entry = tk.Entry(frame_2,
                         textvariable=self.url,
                         highlightcolor='Fuchsia',
                         highlightthickness=1,
                         width=35)
        label2 = tk.Label(frame_2, text=" ")
        play = tk.Button(frame_2,
                         text="PLAY",
                         font=('楷体', 12),
                         fg='black',
                         width=3,
                         height=-1,
                         command=self.video_play)
        label3 = tk.Label(frame_2, text=" ")
        # frame3
        label_explain = tk.Label(frame_3,
                                 fg='black',
                                 font=('楷体', 14),
                                 text='\nTip:小仙女(帆帆)专用')

        # 控件布局
        frame_1.pack()
        frame_2.pack()
        frame_3.pack()
        group.grid(row=0, column=0)
        tb1.grid(row=0, column=1)
        tb2.grid(row=0, column=2)
        label1.grid(row=0, column=0)
        entry.grid(row=0, column=1)
        label2.grid(row=0, column=2)
        play.grid(row=0, column=3, ipadx=10, ipady=10)
        label3.grid(row=0, column=4)
        label_explain.grid(row=1, column=0)
示例#37
0
 def show_help(self):
     """Open webbrowser with application help."""
     webbrowser.open(self.settings['help_link'])
示例#38
0
 def openYoutube(self):
     webbrowser.open('https://www.youtube.com/')
示例#39
0
# coding: utf-8

# http://unapologetic.io/posts/2013/10/30/the-parse-reminders-in-fantastical-action/

import webbrowser
import urllib
import sys

reminders = sys.argv[1]
i = 0
while i < len(reminders):
    if reminders[i] == ',':
        reminders = reminders[0:i] + '\n\n' + reminders[i+1:len(reminders)]
    i += 1

reminders = reminders.encode('utf-8')
reminders = urllib.quote(reminders, safe='')

base = 'drafts4://x-callback-url/create?text=' + reminders + '&action=Parse%20Reminders%20In%20Fantastical'


webbrowser.open(base)
示例#40
0
文件: pic.py 项目: elileo1/python
import Screenshot
import io
import webbrowser
import requests
import base64
from PIL import Image


api_key = 'ZpGGVxrMn6VMZUyDHLg7mxwz'
api_secret = '4vyGw9aVsxEee5xIM1AsuaP3KyvBltMG '
token = '24.894a366bafda51d8d0528bf810dd8a65.2592000.1518230663.282335-10672403'

if __name__ == "__main__":
    print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    Screenshot.check_screenshot()
    print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    im = Image.open("./answer.png")
    region = im.crop((0, 200, 1280, 300))
    imgByteArr = io.BytesIO()
    region.save(imgByteArr, format='PNG')
    image_data = imgByteArr.getvalue()
    base64_data = base64.b64encode(image_data)
    r = requests.post('https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic',
                      params={'access_token': token}, data={'image': base64_data})
    result = ''
    for i in r.json()['words_result']:
        result += i['words']
    print result
    # result = urllib.parse.quote(result)
    webbrowser.open('https://baidu.com/s?wd=' + result)
示例#41
0
folder_path_resursi=folder_path+resource
sys.path.insert(1, folder_path_resursi)
record='\Rekord.txt'
record_path=folder_path_resursi+record
bruh=open(record_path,'r')

if int(bruh.read())==0:
    bruh.close()
    print('Instalacija modula u tijeku. Pričekajte...')
    import Videoplayer
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "webbrowser"])
    except:
        None
    import webbrowser
    webbrowser.open('Upute za korištenje\PRAVILA I KONTROLE.txt')
    subprocess.check_call([sys.executable, "-m", "pip", "install", "pathlib"])
    subprocess.check_call([sys.executable, "-m", "pip", "install", "pygame"])
    subprocess.check_call([sys.executable, "-m", "pip", "install", "opencv-python"])
    subprocess.check_call([sys.executable, "-m", "pip", "install", "pywin32"])
    subprocess.check_call([sys.executable, "-m", "pip", "install", "winshell"])
    import os, winshell
    from win32com.client import Dispatch
    desktop = winshell.desktop()
    path = os.path.join(desktop, "Super Mario.lnk")
    target = r"{}\Super Mario.py".format(pathlib.Path().absolute())
    wDir = r"{}".format(pathlib.Path().absolute())
    icon = r"{}\mario python ikona.ico".format(folder_path_resursi)
    shell = Dispatch('WScript.Shell')
    shortcut = shell.CreateShortCut(path)
    shortcut.Targetpath = target
示例#42
0
def dateSelector(FILES):
    """Limits downloads to a date range"""
    ### find the first date
    first = FILES[0][-12:-4]  #need to slice it to just include the date
    ### find the last date
    last = FILES[-1][-12:-4]  #again need to slice it
    ### GET USER INPUT
    #need to contain it to ensure error checking, do that later
    selFirst = 'NONE'
    selLast = "NONE"

    print(
        'PLEASE SELECT A DATE BETWEEN %s AND %s\nPLEASE VERIFY DATES AT WEBSITE\nPRESS ENTER TO DOWNLOAD ALL AVAILABLE DATES\n\nFORMAT IS YYYYMMDD'
        % (first, last))  #maybe change later
    #open NEMWEB archive to ensure dates are cross referenced
    SCADAurl = 'http://nemweb.com.au/Reports/Archive/Dispatch_SCADA/'  #SCADA ARCHIVE
    DEMANDurl = 'http://nemweb.com.au/Reports/Archive/Operational_Demand/Actual_HH/'  #DEMAND ARCHIVE
    webbrowser.open(SCADAurl)
    webbrowser.open(DEMANDurl)

    while True:
        selFirst = input("\nSTART DATE: ")  #first date
        selFirst = selFirst.upper()  #sanitise input
        #contain user input
        if selFirst == '' or len(selFirst) == 8:
            break
        else:
            print("\nPLEASE INPUT A CORRECT DATE OR PRESS ENTER'")

    while True:
        selLast = input("END DATE: ")  #last date
        selLast = selLast.upper()  #sanitise input
        if selLast == "" or len(selLast) == 8:
            break
        else:
            print("\nPLEASE INPUT A CORRECT DATE OR PRESS ENTER")

    #if NULL is entered, make the selected date a wildcard
    if selFirst == '':  #every date
        selFirst = "(.*)"  #regex wildcard
    if selLast == '':  #every date
        selLast = "(.*)"  #regex wildcard

    ## SET UP PATTERNS
    firstDatePattern = "(.*)_" + selFirst + "(.*)"  #used to find the actual first date
    lastDatePattern = "(.*)_" + selLast + "(.*)"  #used to find the actual last date
    toDel = []  #array to hold files to delete
    for dates in FILES:  #iterate downwards
        result = re.search(firstDatePattern, dates)
        if not result:  #ie, not found
            toDel.append(dates)  #append name to a new list to delete later
        elif result:  #found the date
            #delete the lists
            FILES = [x for x in FILES if x not in toDel
                     ]  #remove unwanted files from the list to download
            break
    toDel = []  #array to hold files to delete
    for dates in reversed(FILES):  #iterate from the bottom
        result = re.search(lastDatePattern, dates)
        if not result:  #ie, not found
            toDel.append(dates)  #append name to a new list to delete later
        elif result:  #found
            FILES = [x for x in FILES if x not in toDel
                     ]  #remove unwanted files from the list to download
            break

    noteSaver(selFirst, selLast)
    return FILES
示例#43
0
#! python3
# lucky.py - Google検索結果をいくつか開く

import requests, sys, webbrowser, bs4

print("Googling...")  # Googleページをダウンロード中にテキストを表示
res = requests.get("http://google.com/search?q=" + " ".join(sys.argv[1:]))
res.raise_for_status()

# TODO: 上位の検索結果のリンクを取得する
soup = bs4.BeautifulSoup(res.text, 'lxml')
link_elems = soup.select('.r a')

# TODO : 各結果をブラウザのタブで開く
num_open = min(5, len(link_elems))
for i in range(num_open):
    webbrowser.open("http://google.com" + link_elems[i].get("href"))
示例#44
0
文件: tasks.py 项目: zetayue/pymatgen
def open_doc(ctx):
    pth = os.path.abspath("docs/_build/html/index.html")
    webbrowser.open("file://" + pth)
 def help_button_clicked(self):
     import webbrowser
     webbrowser.open("https://neutronimaging.pages.ornl.gov/en/tutorial/notebooks/registration/")
示例#46
0
def show_stack(frame=None, slient=False):
    if not frame:
        frame = sys._getframe().f_back

    g = pgv.AGraph(strict=False, directed=True)

    stack = []

    node_set = set()
    subgraph_set = {}

    while frame:
        filename = frame.f_code.co_filename
        firstlineno = frame.f_code.co_firstlineno
        function = frame.f_code.co_name

        node = '{0}:{1}:{2}'.format(filename, firstlineno, function)
        if node not in node_set:
            node_set.add(node)
            if filename not in subgraph_set:
                subgraph_set[filename] = g.add_subgraph(name='cluster' +
                                                        filename,
                                                        label=filename)
            subgraph = subgraph_set[filename]
            subgraph.add_node(node,
                              label='{0}:{1}'.format(firstlineno, function))

        stack.append(frame)
        frame = frame.f_back

    stack.reverse()

    len_stack = len(stack)

    for index, start in enumerate(stack):

        if index + 1 < len_stack:
            start_filename = start.f_code.co_filename
            start_firstlineno = start.f_code.co_firstlineno
            start_function = start.f_code.co_name
            start_lineno = start.f_lineno
            start_subgraph = subgraph_set[start_filename]

            end = stack[index + 1]
            end_filename = end.f_code.co_filename
            end_firstlineno = end.f_code.co_firstlineno
            end_function = end.f_code.co_name
            end_subgraph = subgraph_set[end_filename]

            if index == 0:
                color = 'green'
            elif index == len_stack - 2:
                color = 'red'
            else:
                color = 'black'

            g.add_edge('{0}:{1}:{2}'.format(start_filename, start_firstlineno,
                                            start_function),
                       '{0}:{1}:{2}'.format(end_filename, end_firstlineno,
                                            end_function),
                       color=color,
                       ltail=start_subgraph.name,
                       lhead=end_subgraph.name,
                       label='#{0} at {1}'.format(index + 1, start_lineno))

    file = os.path.abspath('stack.png')
    open(file, 'w').close()
    g.draw(file, prog='dot')
    g.close()
    if not slient:
        webbrowser.open('file://' + file)

    return file
示例#47
0
    def OnEnter(self, event):
        put = self.txt.GetValue()
        self.txt.SetValue("")
        put = put.lower()
        put = put.strip()
        put = re.sub(r'[?|$|.|!]', r'', put)
        link = put.split()

        identity_keywords = ["who are you", "who r u", "what is your name"]
        youtube_keywords = ["play", "stream", "queue"]
        launch_keywords = ["open", "launch"]
        search_keywords = ["search", "google"]
        wikipedia_keywords = ["wikipedia", "wiki"]

        if put == '':
            m = sr.Recognizer()
            with sr.Microphone() as srm:
                audio = m.listen(srm)
            try:
                self.txt.SetValue("Listening...")
                put = m.recognize_google(audio)
                put = put.lower()
                link = put.split()
                self.txt.SetValue(put)
            except sr.UnknownValueError:
                print("BENJI could not understand audio")
            except sr.RequestError as RE:
                print("could not request results from IMF archives;{0}".format(
                    RE))
            except:
                print("Unknown error occurred, while taking speech input!")

    #Play song on  Youtube
        elif any(word in put for word in youtube_keywords):
            try:
                link = '+'.join(link[1:])
                #                    print(link)
                say = link.replace('+', ' ')
                url = 'https://www.youtube.com/results?search_query=' + link
                #                    webbrowser.open('https://www.youtube.com'+link)
                fhand = urllib.request.urlopen(url).read()
                soup = BeautifulSoup(fhand, "html.parser")
                songs = soup.findAll('div', {'class': 'yt-lockup-video'})
                hit = songs[0].find('a')['href']
                #                    print(hit)
                self.say("playing " + say)

                webbrowser.open('https://www.youtube.com' + hit)
            except:
                print('Sorry Ethan. Looks like its not working!')
    #Who are you?
        elif any(word in put for word in identity_keywords):
            try:
                self.say(
                    "I am BENJI, a digital assistant declassified for civilian use. Previously I was used by the Impossible Missions Force"
                )

            except:
                print('Error. Try reading the ReadMe to know about me!')
    #Open a webpage
        elif any(word in put for word in launch_keywords):
            try:
                self.say("opening " + link[1])

                webbrowser.open('http://www.' + link[1] + '.com')
            except:
                print(
                    'Sorry Ethan,unable to access it. Cannot hack either-IMF protocol!'
                )
    #Google search
        elif any(word in put for word in search_keywords):
            try:
                link = '+'.join(link[1:])
                say = link.replace('+', ' ')
                self.say("searching google for " + say)

                webbrowser.open('https://www.google.com/search?q=' + link)
            except:
                print('Nope, this is not working.')
    #Wikipedia
        elif any(word in put for word in wikipedia_keywords):
            try:
                link = '+'.join(link[1:])
                say = link.replace('+', ' ')
                wikisearch = wikipedia.page(say)
                self.say("Opening wikipedia page for" + say)

                webbrowser.open(wikisearch.url)
            except:
                print(
                    'Wikipedia could not either find the article or your Third-world connection is unstable'
                )
#Lock the device
        elif put.startswith('secure '):
            try:
                self.say("locking the device")

                ctypes.windll.user32.LockWorkStation()
            except:
                print('Cannot lock device')

    #News of various press agencies
        elif put.startswith('aljazeera '):
            try:
                aljazeeraurl = (
                    'https://newsapi.org/v1/articles?source=al-jazeera-english&sortBy=latest&apiKey=571863193daf421082a8666fe4b666f3'
                )
                newsresponce = requests.get(aljazeeraurl)
                newsjson = newsresponce.json()
                self.say('Our agents from Al-Jazeera report this')

                print('  =====Al Jazeera===== \n')
                i = 1
                for item in newsjson['articles']:
                    print(str(i) + '. ' + item['title'] + '\n')
                    print(item['description'] + '\n')
                    i += 1
            except:
                print('Qatari agents have refused to share this intel, Ethan')
        elif put.startswith('bbc '):
            try:
                bbcurl = (
                    'https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=571863193daf421082a8666fe4b666f3'
                )
                newsresponce = requests.get(bbcurl)
                newsjson = newsresponce.json()
                self.say('Our agents from BBC report this')

                print('  =====BBC===== \n')
                i = 1
                for item in newsjson['articles']:
                    print(str(i) + '. ' + item['title'] + '\n')
                    print(item['description'] + '\n')
                    i += 1
            except:
                print('MI6 is going crazy! Not allowing this!')
        elif put.startswith('cricket '):
            try:
                cricketurl = (
                    'https://newsapi.org/v1/articles?source=espn-cric-info&sortBy=latest&apiKey=571863193daf421082a8666fe4b666f3'
                )
                newsresponce = requests.get(cricketurl)
                newsjson = newsresponce.json()
                self.say('Our agents from ESPN Cricket report this')

                print('  =====CRICKET NEWS===== \n')
                i = 1
                for item in newsjson['articles']:
                    print(str(i) + '. ' + item['title'] + '\n')
                    print(item['description'] + '\n')
                    i += 1
            except:
                print('Connection not secure')
        elif put.startswith('hindus '):
            try:
                hindusurl = (
                    'https://newsapi.org/v1/articles?source=the-hindu&sortBy=latest&apiKey=571863193daf421082a8666fe4b666f3'
                )
                newsresponce = requests.get(hindusurl)
                newsjson = newsresponce.json()
                self.say('Our agents from Hindu News report this')

                print('  =====HINDU NEWS===== \n')
                i = 1
                for item in newsjson['articles']:
                    print(str(i) + '. ' + item['title'] + '\n')
                    print(item['description'] + '\n')
                    i += 1
            except:
                print('R&A W is blocking our reports, Ethan. Sorry! ')
示例#48
0
 def helpDocumentation(self):
     """
     Displays the help documentation
     """
     webbrowser.open("gui_help.html", new=1)
示例#49
0
	def open_help(self):
		currentDir = unicode(os.path.abspath( os.path.dirname(__file__)))
		webbrowser.open(os.path.join(currentDir,"data.html"))
		webbrowser.open("http://maplab.alwaysdata.net/SSAM.html")
示例#50
0
if __name__ == "__main__":
    speak("JAI MATA DI")
    wishMe()
    while (True):
        query = takecommand().lower()
        if "wikipedia" in query:
            speak("Searching wikipedia....")
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            speak("according to wikipedia")
            speak(results)
            print(results)

        elif "open youtube" in query:
            webbrowser.open("youtube.com")

        elif "open google" in query:
            webbrowser.open("google.com")
        elif "open geeksforgeeks" in query:
            webbrowser.open("geeksforgeeks.org")

        elif "open stack overflow" in query:
            webbrowser.open("stackoverflow.com")
        elif "the time" in query:
            strtime = datetime.datetime.now().strftime("%H:%M:%S")
            speak(f"sir the time is (strtime)")
            print(strtime)
        elif " open code" in query:
            cp = "C:\\Users\\saksh\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            os.startfile(cp)
 def githubLink(self):
     webbrowser.open("https://www.github.com/reinhart1010/computerun-2020")
示例#52
0
def daq_home():
    webbrowser.open("http://localhost:80") # the Apache2 server
    return # placeholder
 def openInDesktop():
     webbrowser.open(qrPayload)
 def websiteLink(self):
     webbrowser.open("http://computerun.id")
示例#55
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/11/9
# @Author  : RookieDay
# @Site    : 
# @File    : README
# @Github  : https://github.com/rookieday
# @Software: PyCharm Community Edition

# pyaudio 参考
# http://people.csail.mit.edu/hubert/pyaudio/
# 百度语音识别
# https://cloud.baidu.com/product/speech
# 以及查看接口文档
# 需要申请ID
""" 你的 APPID AK SK """
# APP_ID = '你的 App ID'
# API_KEY = '你的 Api Key'
# SECRET_KEY = '你的 Secret Key'
# 打开浏览器 webbrowser模块

# webbrowser.open(url, new=0, autoraise=True)
# 在系统的默认浏览器中访问url地址,如果new=0,url会在同一个浏览器窗口中打开;如果new=1,新的浏览器窗口会被打开;new=2新的浏览器tab会被打开。
import webbrowser
webbrowser.open('www.baidu.com',new=2,autoraise=True)
 def openLink(self, url):
     webbrowser.open(url)
示例#57
0
	def githubOpener(self):
		webbrowser.open('https://github.com/Hydr4/')
示例#58
0
async def open_url (url):
    webbrowser.open(url)
示例#59
0
	def facebookOpener(self):
		webbrowser.open('https://www.facebook.com/The.Hydra.Python.Programmer')
示例#60
0
	def mailOpener(self):
		webbrowser.open('mailto:[email protected]')