Example #1
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()
Example #2
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)
Example #3
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!")
    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")
Example #5
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)
Example #6
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)
 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))
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
Example #9
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)
Example #10
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')
Example #11
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
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))
Example #13
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()
Example #14
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
Example #15
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)
Example #16
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()
Example #17
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!')
Example #18
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()
Example #19
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()
Example #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)
    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 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())
Example #23
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)
	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)
Example #25
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
Example #26
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)
Example #27
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 = "[email protected]%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()
Example #28
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)
Example #29
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)
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))