예제 #1
0
def plot_sys_tree(system, outfile=None, fmt='pdf'):
    """
    Generate a plot of the system tree and bring it up in a browser.
    (requires graphviz).

    Args
    ----
    system : `System`
        Starting node of the System tree to be plotted.

    outfile : str, optional
        Name of the output file.  Default is 'system_tree.<fmt>'

    fmt : str, optional
        Format for the plot file. Any format accepted by dot should work.
        Default is 'pdf'.
    """
    if outfile is None:
        outfile = 'system_tree.'+fmt

    dotfile = os.path.splitext(outfile)[0]+'.dot'

    _write_system_dot(system, dotfile)

    os.system("dot -T%s -o %s %s" % (fmt, outfile, dotfile))

    if sys.platform == 'darwin':
        os.system('open %s' % outfile)
    else:
        webbrowser.get().open(outfile)

    try:
        os.remove(dotfile)
    except:
        pass
예제 #2
0
 def start(self):
     # Create a web server and define the handler to manage the incoming
     # request
     self._sserver = ThreadedHTTPServer((self._address, self._sport), self._gui, self._auth,
                                        self._multiple_instance, self._enable_file_cache,
                                        self._update_interval, self._websocket_timeout_timer_ms,
                                        self._pending_messages_queue_length, self._title, 
                                        self, self._certfile, self._keyfile, self._ssl_version, *self._userdata)
     shost, sport = self._sserver.socket.getsockname()[:2]
     self._log.info('Started httpserver http://%s:%s/'%(shost,sport))
     # when listening on multiple net interfaces the browsers connects to localhost
     if shost == '0.0.0.0':
         shost = '127.0.0.1'
     self._base_address = 'http://%s:%s/' % (shost,sport)
     if self._start_browser:
         try:
             import android
             android.webbrowser.open(self._base_address)
         except ImportError:
             # use default browser instead of always forcing IE on Windows
             if os.name == 'nt':
                 webbrowser.get('windows-default').open(self._base_address)
             else:
                 webbrowser.open(self._base_address)
     self._sth = threading.Thread(target=self._sserver.serve_forever)
     self._sth.daemon = False
     self._sth.start()
예제 #3
0
파일: plotting.py 프로젝트: grogs84/nwspa
def plot(L, scale=4, dot_size = 3, browser=None):
    """ plot takes a list of points, optionally a scale (relative to a 200x200 frame),
        optionally a dot size (diameter) in pixels, and optionally a browser name.
        It produces an html file with SVG representing the given plot,
        and opens the file in a web browser. It returns nothing.
    """
    scalar = 200./scale
    origin = (210, 210)
    hpath = create_temp('.html')
    with open(hpath, 'w') as h:
        h.writelines(
            ['<!DOCTYPE html>\n'
            ,'<head>\n'
            ,'<title>plot</title>\n'
            ,'</head>\n'
            ,'<body>\n'
            ,'<svg height="420" width=420 xmlns="http://www.w3.org/2000/svg">\n'
            ,'<line x1="0" y1="210" x2="420" y2="210"'
            ,'style="stroke:rgb(0,0,0);stroke-width:2"/>\n'
            ,'<line x1="210" y1="0" x2="210" y2="420"'
            ,'style="stroke:rgb(0,0,0);stroke-width:2"/>\n'])
        for pt in L:
            if isinstance(pt, Number):
                x,y = pt.real, pt.imag
            else:
                if isinstance(pt, tuple) or isinstance(pt, list):
                    x,y = pt
                else:
                    raise ValueError
            h.writelines(['<circle cx="%d" cy="%d" r="%d" fill="red"/>\n'
                          % (origin[0]+scalar*x,origin[1]-scalar*y,dot_size)])
        h.writelines(['</svg>\n</body>\n</html>'])
    if browser is None:
        browser = _browser
    webbrowser.get(browser).open('file://%s' % hpath)
예제 #4
0
    def VisualizeToHTML(self):
        var_nodes = ',\n'.join(
            ["            {{id: {}, label: '{}', group: '{}'}}".format(node.id, node.name, node.type)   #.type[1:-1]
             for node in self.tree.GetAllNodes()])

        var_edges = ',\n'.join(
            ["            {{from: {}, to: {}}}".format(str(i), str(j)) for (i, j) in self.tree.GetAllEdges()])

        code = '<html>\n<head>\n<script type="text/javascript" src="lib/vis/dist/vis.js"></script>\n' \
            '<link href="lib/vis/dist/vis.css" rel="stylesheet" type="text/css" />\n\n<style type="text/css">' \
            '\n\t#mynetwork {\n\t\twidth: 100%;\n\t\theight: 100%;\n\t\tborder: 1px solid lightgray;\n\t}\n</style>' \
            '\n</head>\n<body>\n<div id="mynetwork"></div>\n\n<script type="text/javascript">\nvar nodes = new vis.DataSet([\n' + \
            var_nodes + '\n\t\t]);\n\n\t\tvar edges = new vis.DataSet([\n' + var_edges + \
            '\n\t\t]);\n\n// create a network\nvar container = document.getElementById(\'mynetwork\');' + \
            '\nvar data = {\nnodes: nodes,\nedges: edges\n};\nvar options = {\n\t\tnodes: {\n\t\t\tfont: {size: 10},' + \
            '\n\t\t\tborderWidth: 0.3,\n\t\t\tborderWidthSelected: 0.5,\n\t\t\tcolor: {background:\'#F0F5FA\'},\n\t\t\tshape: ' + \
            '\'dot\',\n\t\t\tsize: 10\n\t\t},\n\t\tedges: {\n\t\t\twidth: 0.5,\n\t\t\tarrows: {\n\t\t\t\tto: {\n\t\t\t\t\tenabled: ' + \
            'true,\n\t\t\t\t\tscaleFactor: 0.3\n\t\t\t\t}\n\t\t\t},\n\t\t\tselectionWidth: 0.5\n\t\t},\n\t\tgroups: {\n\t\t\ti: ' + \
            '{\n\t\t\t\tcolor: {background:\'#fddddd\'},\n\t\t\t\tedges: {dashes:true}\n\t\t\t},\n\t\t\tc: {\n\t\t\t\tcolor: ' + \
            '{background:\'#c7e3f9\'},\n\t\t\t\tshape: \'dot\',\n\t\t\t\tsize: 10\n\t\t\t},\n\t\t\ta: {\n\t\t\t\tcolor: {\n\t\t\t\t' + \
            '\tbackground:\'#f5fafe\',\n\t\t\t\t\topacity: 0.5\n\t\t\t\t},\n\t\t\t},\n\t\t\te: {\n\t\t\t\tcolor: {background:\'#e6eeee\'},' + \
            '\n\t\t\t\tshape: \'dot\',\n\t\t\t\tsize: 10\n\t\t\t}\n\t\t}\n\t};\nvar network = new vis.Network(container, data, options);' + \
            '\n</script>\n\n<script src="../googleAnalytics.js"></script>\n</body>\n</html>\n\t\t'

        html_file_name = 'treee.html'
        with c_open(html_file_name, 'w', 'utf-8') as f:
            f.write(code)
            try:
                webbrowser.get('windows-default').open('file://{}'.format(os.path.abspath(html_file_name)))
            except Exception:
                webbrowser.open('file://{}'.format(os.path.abspath(html_file_name)))
        '''
예제 #5
0
파일: plotting.py 프로젝트: grogs84/nwspa
def plot_line(L, scale=10, dot_size = 3, browser=None):
    """ plot takes a list of points, optionally a scale (relative to a 200x200 frame),
        optionally a dot size (diameter) in pixels, and optionally a browser name.
        It produces an html file with SVG representing the given plot,
        and opens the file in a web browser. It returns nothing.
    """
    scalar = 200./scale
    # origin = (210, 210)
    origin = 210
    hpath = create_temp('.html')
    with open(hpath, 'w') as h:
        h.writelines(
            ['<!DOCTYPE html>\n'
            ,'<head>\n'
            ,'<title>plot</title>\n'
            ,'</head>\n'
            ,'<body>\n'
            ,'<svg height="420" width=420 xmlns="http://www.w3.org/2000/svg">\n'
            ,'<line x1="0" y1="210" x2="420" y2="210"'
            ,'style="stroke:rgb(0,0,0);stroke-width:2"/>\n'
            ,'<line x1="210" y1="0" x2="210" y2="420"'
            ,'style="stroke:rgb(0,0,0);stroke-width:2"/>\n'])
        for line in L:
            pt1, pt2 = line
            x1, y1 = pt1
            x2, y2 = pt2
            h.writelines(['<line x1="%d" y1="%d" x2="%d" y2="%d" style="stroke:rgb(0,0,0);stroke-width:2"/>\n'
                          % (origin+x1*scalar,origin-y1*scalar,origin+x2*scalar,origin-y2*scalar)])
        h.writelines(['</svg>\n</body>\n</html>'])
    if browser is None:
        browser = _browser
    webbrowser.get(browser).open('file://%s' % hpath)
예제 #6
0
    def start(self):
        ip = self.ip if self.ip else '[all ip addresses on your system]'
        proto = 'https' if self.certfile else 'http'
        info = self.log.info
        info("The IPython Notebook is running at: %s://%s:%i%s" %
             (proto, ip, self.port,self.base_project_url) )
        info("Use Control-C to stop this server and shut down all kernels.")

        if self.open_browser:
            ip = self.ip or '127.0.0.1'
            if self.browser:
                browser = webbrowser.get(self.browser)
            else:
                browser = webbrowser.get()

            if self.file_to_run:
                filename, _ = os.path.splitext(os.path.basename(self.file_to_run))
                for nb in self.notebook_manager.list_notebooks():
                    if filename == nb['name']:
                        url = nb['notebook_id']
                        break
                else:
                    url = ''
            else:
                url = ''
            b = lambda : browser.open("%s://%s:%i%s%s" % (proto, ip,
                                        self.port, self.base_project_url, url),
                                    new=2)
            threading.Thread(target=b).start()
        try:
            ioloop.IOLoop.instance().start()
        except KeyboardInterrupt:
            info("Interrupted...")
        finally:
            self.cleanup_kernels()
예제 #7
0
파일: plotting.py 프로젝트: grogs84/nwspa
 def show(self, browser=None):
     scalar = 200./10
     # origin = (210, 210)
     dot_size = 3
     origin = 210
     hpath = create_temp('.html')
     with open(hpath, 'w') as h:
         h.writelines(
             ['<!DOCTYPE html>\n'
             ,'<head>\n'
             ,'<title>plot</title>\n'
             ,'</head>\n'
             ,'<body>\n'
             ,'<svg height="420" width=420 xmlns="http://www.w3.org/2000/svg">\n'
             ,'<line x1="0" y1="210" x2="420" y2="210"'
             ,'style="stroke:rgb(0,0,0);stroke-width:2"/>\n'
             ,'<line x1="210" y1="0" x2="210" y2="420"'
             ,'style="stroke:rgb(0,0,0);stroke-width:2"/>\n'])
         for line in self.lines:
             pt1, pt2 = self.lines[line][0]
             c = self.lines[line][1]
             x1, y1 = pt1
             x2, y2 = pt2
             h.writelines(['<line x1="%d" y1="%d" x2="%d" y2="%d" style="stroke:%s";stroke-width:2"/>\n'
                           % (origin+x1*scalar,origin-y1*scalar,origin+x2*scalar,origin-y2*scalar,c)])
         for pts in self.points:
             pt = self.points[pts]
             x,y = pt
             h.writelines(['<circle cx="%d" cy="%d" r="%d" fill="red"/>\n'
                         % (origin+scalar*x,origin-scalar*y,dot_size)])
         h.writelines(['</svg>\n</body>\n</html>'])
     if browser is None:
         browser = _browser
     webbrowser.get(browser).open('file://%s' % hpath)
예제 #8
0
def helpdesk():
    """Open the NEST helpdesk in browser.

    Use the system default browser.

    KEYWORDS: info
    """

    if sys.version_info < (2, 7, 8):
        print("The NEST helpdesk is only available with Python 2.7.8 or "
              "later. \n")
        return

    if 'NEST_DOC_DIR' not in os.environ:
        print(
            'NEST help needs to know where NEST is installed.'
            'Please source nest_vars.sh or define NEST_DOC_DIR manually.')
        return

    helpfile = os.path.join(os.environ['NEST_DOC_DIR'], 'help',
                            'helpindex.html')

    # Under Windows systems webbrowser.open is incomplete
    # See <https://bugs.python.org/issue8232>
    if sys.platform[:3] == "win":
        os.startfile(helpfile)

    # Under MacOs we need to ask for the browser explicitly.
    # See <https://bugs.python.org/issue30392>.
    if sys.platform[:3] == "dar":
        webbrowser.get('safari').open_new(helpfile)
    else:
        webbrowser.open_new(helpfile)
예제 #9
0
    def run(self):
        
        # Create a new manager object
        self.manager = BrowserManager()

        # Save the changes to the browser
        self.manager.saveFile()
                
        print "File saved\n"

        self.browserList = ["Internet Explorer", "FireFox", "Chrome", "Opera", "Safari"]
        self.window.show_quick_panel(self.browserList, None)

        print sublime.platform()

        # Get the domain to open
        for title, domain in self.manager.getDomainConfig().items():
            if self.manager.getSelectedDomain() == domain:
                url = domain + self.window.active_view().file_name()[16:len(self.window.active_view().file_name())]

        # Check to see if the file can be displayed in the browser
        if self.window.active_view().file_name().endswith(self.manager.getExtList()):
            if sublime.platform() == "windows":
                webbrowser.get('windows-default').open(url)
            else:
                webbrowser.open(url)
        else:
            print "\nThis is not a browsable file\n"
예제 #10
0
 def prefs(self):
     daemon = xmlrpclib.ServerProxy("http://localhost:7080/")
     try:
         daemon.is_running()
         webbrowser.get('safari').open("lbry://settings")
     except:
         rumps.notification(title='LBRY', subtitle='', message="Couldn't connect to lbrynet daemon", sound=True)
예제 #11
0
def show_plot():
    l = get_csv()
    f = len(l)-1
    value = []
    pro = []
    for r in range(0, 20):
        print l[r]
        value.append(l[r][1])
        pro.append(l[r][0])

    # 写入json
    data = {}
    data["categories"] = pro
    data["data"] = value
    j = json.dumps(data)
    print j

    with open('./html/data.js', 'wb') as f:
        co = 'var c=' + j
        f.write(co)

    # 写入图片
    '''
    pos = np.arange(len(value))
    plt.bar(pos, value, color=getColors(value), alpha=1)
    plt.show()
    '''

    # 打开网页
    webbrowser.get('C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chrome.exe %s').open('../html/py.html')
예제 #12
0
def main():
    try:
        buildServer = run_local_build_server()
        while not is_build_server_running():
            print "[build server] BOOTING"
        print "[build server] ONLINE"

        appInventor = start_appinventor()
        while not is_app_inventor_running():
            print "[app inventor] BOOTING"
        print "[app inventor] ONLINE"

        print "[app inventor] OPENING"
        try:
            browser = webbrowser.get("chrome")
        except webbrowser.Error:
            try:
                webbrowser.register("firefox", None, webbrowser.GenericBrowser(os.environ["ProgramFiles"] + r"\Mozilla Firefox\firefox.exe"), 1)
                browser = webbrowser.get("firefox")
            except webbrowser.Error:
                browser = webbrowser.get()
        browser.open("http://localhost:8888/_ah/login?continue=http://localhost:8888/")
    except Exception as e:
        print type(e)
        print e
    finally:
        taskkill(buildServer.pid)
        taskkill(appInventor.pid)
예제 #13
0
파일: server.py 프로젝트: motleytech/remi
 def start(self, *userdata):
     # here the websocket is started on an ephemereal port
     self._wsserver = ThreadedWebsocketServer((self._address, 0), WebSocketsHandler, self._multiple_instance)
     wshost, wsport = self._wsserver.socket.getsockname()[:2]
     debug_message('Started websocket server %s:%s' % (wshost, wsport))
     self._wsth = threading.Thread(target=self._wsserver.serve_forever)
     self._wsth.daemon = True
     self._wsth.start()
     
     # Create a web server and define the handler to manage the incoming
     # request
     self._sserver = ThreadedHTTPServer((self._address, self._sport), self._gui,
                                        (wshost, wsport), self._multiple_instance, self._enable_file_cache,
                                        self._update_interval, *userdata)
     shost, sport = self._sserver.socket.getsockname()[:2]
     # when listening on multiple net interfaces the browsers connects to localhost
     if shost == '0.0.0.0':
         shost = '127.0.0.1'
     base_address = 'http://%s:%s/' % (shost,sport)
     debug_message('Started httpserver %s' % base_address)
     if self._start_browser:
         try:
             import android
             android.webbrowser.open(base_address)
         except:
             # use default browser instead of always forcing IE on Windows
             if os.name == 'nt':
                 webbrowser.get('windows-default').open(base_address)
             else:
                 webbrowser.open(base_address)
     self._sth = threading.Thread(target=self._sserver.serve_forever)
     self._sth.daemon = True
     self._sth.start()
예제 #14
0
	def play(self):
		self.start_time = time()

		""" Add game name to database after it's been started at least once """
		does_it_exist = dbase.execute("SELECT Name FROM games WHERE Name = '%s'" % self.game_name).fetchone()
		if does_it_exist is None:
			database.execute("INSERT INTO games (Name,Timewatched,AltName) VALUES ('%s',0,NULL)" % self.game_name)

		""" For conky output - Populate the miscellaneous table with the display name and start time """
		database.execute("INSERT INTO miscellaneous (Name,Value) VALUES ('%s','%s')" % (self.display_name, self.start_time))
		database.commit()

		if self.show_chat is True:
			try:
				webbrowser.get('chromium').open_new('--app=http://www.twitch.tv/%s/chat?popout=' % self.final_selection)
			except:
				webbrowser.open_new('http://www.twitch.tv/%s/chat?popout=' % self.final_selection)

		if self.channel_name_if_vod is None:
			print(' ' + Colors.WHITE + self.display_name + Colors.ENDC + ' | ' + Colors.WHITE + self.stream_quality.title() + Colors.ENDC)
			player_final = Options.player_final + ' --title ' + self.display_name.replace(' ', '')
			self.args_to_subprocess = "livestreamer twitch.tv/'{0}' '{1}' --player '{2}' --hls-segment-threads 3 --http-header Client-ID=guulhcvqo9djhuyhb2vi56wqnglc351".format(self.final_selection, self.stream_quality, player_final)
		else:
			print(' ' + Colors.WHITE + self.display_name + ': ' + self.video_title_if_vod + Colors.ENDC + ' | ' + Colors.WHITE + self.stream_quality.title() + Colors.ENDC)
			player_final = Options.player_final + ' --title ' + self.display_name
			self.args_to_subprocess = "livestreamer '{0}' '{1}' --player '{2}' --hls-segment-threads 3 --player-passthrough=hls --http-header Client-ID=guulhcvqo9djhuyhb2vi56wqnglc351".format(self.final_selection, self.stream_quality, player_final)

		self.args_to_subprocess = shlex.split(self.args_to_subprocess)
		self.livestreamer_process = subprocess.Popen(self.args_to_subprocess, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
예제 #15
0
def uriToBrowser(uri=None):
    ''' 
        Method that launches the URI in the default browser of the system. This returns no new entity.

        :param uri:    uri to open.
    '''
    # Temporally deactivating standard ouptut and error:
    #   Source: <https://stackoverflow.com/questions/2323080/how-can-i-disable-the-webbrowser-message-in-python>

    # Cloning stdout (1) and stderr (2)
    savout1 = os.dup(1)
    savout2 = os.dup(2)

    # Closing them
    os.close(1)
    os.close(2)
    os.open(os.devnull, os.O_RDWR)

    try:
        # Opening the Tor URI using onion.cab proxy
        if ".onion" in uri:
            wb.get().open(uri.replace(".onion", ".onion.cab"), new=2)    
        else:
            wb.get().open(uri, new=2)
    finally:
        # Reopening them...
        os.dup2(savout1, 1)
        os.dup2(savout2, 2)
예제 #16
0
파일: config.py 프로젝트: huntrar/cliquery
def set_config():
    """Set optional API keys, browser, and bookmarks in CONFIG."""
    for key, val in iteritems(read_config()):
        CONFIG[key] = val

    if 'browser' in CONFIG and CONFIG['browser'] != 'Automatically detected':
        try:
            CONFIG['browser_obj'] = webbrowser.get(CONFIG['browser'])
            return
        except webbrowser.Error as err:
            sys.stderr.write('{} at {}\n'.format(str(err), CONFIG['browser']))
            CONFIG['browser_obj'] = None
            pass
        except IndexError:
            CONFIG['browser_obj'] = None
            pass

    # If no valid browser found then use webbrowser to automatically detect one
    try:
        supported_platforms = {'win32': 'windows-default', 'cygwin': 'cygstart', 'darwin': 'macosx'}
        if sys.platform not in supported_platforms:
            browser_name = 'Automatically detected'
            browser_obj = webbrowser.get()
        else:
            browser_name = supported_platforms[sys.platform]
            if browser_name == 'cygstart':
                # Cygwin requires us to register browser type (or export BROWSER='cygstart')
                webbrowser.register(browser_name, None, webbrowser.GenericBrowser(browser_name))
            browser_obj = webbrowser.get(browser_name)

        CONFIG['browser'] = browser_name
        CONFIG['browser_obj'] = browser_obj
    except webbrowser.Error:
        pass
예제 #17
0
    def resource_usage(self, address=None, port=None, browser=None):
        import webbrowser
        from mozbuild.html_build_viewer import BuildViewerServer

        last = self._get_state_filename("build_resources.json")
        if not os.path.exists(last):
            print(
                "Build resources not available. If you have performed a "
                "build and receive this message, the psutil Python package "
                "likely failed to initialize properly."
            )
            return 1

        server = BuildViewerServer(address, port)
        server.add_resource_json_file("last", last)
        try:
            webbrowser.get(browser).open_new_tab(server.url)
        except Exception:
            print("Cannot get browser specified, trying the default instead.")
            try:
                browser = webbrowser.get().open_new_tab(server.url)
            except Exception:
                print("Please open %s in a browser." % server.url)

        print("Hit CTRL+c to stop server.")
        server.run()
예제 #18
0
def main():
    # configure server
    static_dirs = PELICAN_SETTINGS['STATIC_PATHS'] + [PELICAN_SETTINGS['THEME']]
    config = {
        '/' + static_dir: {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.join(OUTPUT_PATH, static_dir)}
        for static_dir in static_dirs}
    cherrypy.config.update({'engine.autoreload.on': False})
    if not DEBUG:
        cherrypy.config.update({'log.screen': False})
    cherrypy.tree.mount(CherrypyServer(), '/', config=config)

    # configure observer
    global OBSERVER
    OBSERVER = PausingObserver()
    OBSERVER.schedule(PelicanUpdater(), PELICAN_PATH, recursive=True)

    # start threads
    cherrypy.engine.start()
    OBSERVER.start()
    if BROWSER:
        webbrowser.get(BROWSER).open('http://127.0.0.1:8080')

    # control loop
    while True:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            break

    # teardown
    OBSERVER.stop()
    os._exit(0)
예제 #19
0
def main():
  url_path = 'http://merlin.hrm.local/jira/secure/IssueNavigator.jspa?mode=hide&requestId=15370'
  # url_path = 'http://merlin/jira/secure/Dashboard.jspa'
  if len(sys.argv) > 1:
    url_path = JIRA_PATH + sys.argv[1]

  webbrowser.get(WEBBROWSER).open_new_tab(url_path)
예제 #20
0
def ScrapeRangeWeekly(keyword, startmonth, startyear, endmonth, endyear):
    months = 11-startmonth + (endyear - startyear - 1)*12 + endmonth
    print 'Scraping weekly data from '+month_list[startmonth-1]+' '+str(startyear)+' to '+month_list[endmonth-1]+' '+str(endyear)
    
    URL_start = "http://www.google.com/trends/trendsReport?&q="
    URL_end = "&cmpt=q&content=1&export=1"
    
    queries = keyword[0]
    if len(keyword) > 1:
        queries_list = []
        for i in range(0,len(keyword)):
            queries_list.append(keyword[i])
        queries = '%20'.join(queries_list)

    date = '&date='+str(startmonth)+'%2F'+str(startyear)+'%20'+str(months)+'m'
    
    URL = URL_start+queries+date+URL_end

    print(URL)
    
    # webbrowser.open(URL)
    webbrowser.get('safari').open(URL) 

    time.sleep(7)
    
    oldname = path+'/'+'report.csv'
    newname = path+'/'+'weekly_data.csv'
    os.rename(oldname,newname)

    shutil.move(newname,path+'/'+scrapings_dir)
예제 #21
0
def ScrapeTwoMonths(keyword, country, region, city, year, startmonth):
    print 'Scraping '+month_list[startmonth-1]+' and '+month_list[startmonth]+' in '+str(year)
    URL_start = "http://www.google.com/trends/trendsReport?&q="
    URL_end = "&cmpt=q&content=1&export=1"
  
    # Geographic restrictions
    if country is not None:
        geo = "&geo="
        geo = geo + country
        if region is not None:
            geo = geo + "-" + region

    queries = keyword[0] #keyword is a list
    if len(keyword) > 1:
        queries_list = []
        for i in range(0,len(keyword)):
            queries_list.append(keyword[i])
        queries = '%20'.join(queries_list)
        
    date = '&date='+str(startmonth)+'%2F'+str(year)+'%202m'
    
    URL = URL_start+queries+ geo + date+URL_end
    print(URL)

    # webbrowser.open(URL)  
    webbrowser.get('safari').open(URL)  
예제 #22
0
def launch_browser(port,preferred_browser=None):
    ''' try to use preferred browser if specified, fall back to default 
    '''
    url = 'http://localhost:'+str(port)    
    print 'Opening URL in browser: '+url+' (pid='+str(os.getpid())+')'
    
    # webbrowser doesn't know about chrome, so try to find it (this is for win7)
    if preferred_browser and preferred_browser.lower() == 'chrome':
        USERPROFILE = os.getenv("USERPROFILE")
        if USERPROFILE:
            CHROMEPATH = USERPROFILE+'\AppData\Local\Google\Chrome\Application\chrome.exe'
       	    if os.path.isfile(CHROMEPATH):
                preferred_browser = CHROMEPATH.replace('\\','\\\\')+' --app=%s'
    
    # try to get preferred browser, fall back to default
    if preferred_browser:
        try:
            browser = webbrowser.get(preferred_browser);
        except:
            print "Couldn't get preferred browser ("+preferred_browser+"), using default..."
            browser = webbrowser.get()
    else:
        browser = webbrowser.get()
    
    # open new browser window (may open in a tab depending on user preferences, etc.)
    if browser:
        browser.open(url,1,True)
        print "Opened in",browser.name
    else:
        print "Couldn't launch browser: "+str(browser)
예제 #23
0
def treeherder(ui, repo, tree=None, rev=None, **opts):
    """Open Treeherder showing build status for the specified revision.

    The command receives a tree name and a revision to query. The tree is
    required because a revision/changeset may existing in multiple
    repositories.
    """
    if not tree:
        raise util.Abort('A tree must be specified.')

    if not rev:
        raise util.Abort('A revision must be specified.')

    tree, repo_url = resolve_trees_to_uris([tree])[0]
    if not repo_url:
        raise util.Abort("Don't know about tree: %s" % tree)

    r = MercurialRepository(repo_url)
    node = repo[rev].hex()
    push = r.push_info_for_changeset(node)

    if not push:
        raise util.Abort("Could not find push info for changeset %s" % node)

    push_node = push.last_node

    url = treeherder_url(tree, push_node[0:12])

    import webbrowser
    webbrowser.get('firefox').open(url)
예제 #24
0
def launchBrowser():
    # wait for server to start starting...
    while not serverStarted:
        time.sleep(0.001)

    # wait for server to finish starting
    time.sleep(1.0)

    # search for port in server's config file
    serverPort = DEFAULT_PORT
    with open("server.cfg", 'r') as f:
        contents = f.read()
        position = string.find(contents, "port=")
        if position != -1:
            position += 5
            portStr = contents[position:].split()[0]
            try:
                serverPort = int(portStr)
            except:
                serverPort = DEFAULT_PORT

    # open the web browser (Firefox in Linux, user's preferred on Windows)
    if os.name == "posix":
        # will return default system's browser if Firefox is not installed
        controller = webbrowser.get('Firefox')
    else:
        controller = webbrowser.get('windows-default')

    url = "http://localhost"
    if serverPort != 80: url += ":" + str(serverPort)
    controller.open_new_tab(url)
예제 #25
0
    def callback(self, index):
        if index == -1:
            return

        command = self.cmds[index]
        self.view.run_command(command)

        if protocol and command == 'xdebug_listen':
            url = get_project_setting('url')
            if url:
                webbrowser.get(browser).open(url + '?XDEBUG_SESSION_START=sublime.xdebug')
            else:
                sublime.status_message('Xdebug: No URL defined in project settings file.')

            global original_layout
            global debug_view
            window = sublime.active_window()
            original_layout = window.get_layout()
            debug_view = window.active_view()
            window.set_layout({
                "cols": [0.0, 0.5, 1.0],
                "rows": [0.0, 0.7, 1.0],
                "cells": [[0, 0, 2, 1], [0, 1, 1, 2], [1, 1, 2, 2]]
            })

        if command == 'xdebug_clear':
            url = get_project_setting('url')
            if url:
                webbrowser.get(browser).open(url + '?XDEBUG_SESSION_STOP=sublime.xdebug')
            else:
                sublime.status_message('Xdebug: No URL defined in project settings file.')
            window = sublime.active_window()
            window.run_command('hide_panel', {"panel": 'output.xdebug_inspect'})
            window.set_layout(original_layout)
예제 #26
0
 def keypress(self, size, key):
     if key in {'down', 'n', 'N'}:
         self.answer_text.next_ans()
     elif key in {'up', 'b', 'B'}:
         self.answer_text.prev_ans()
     elif key in {'o', 'O'}:
         import webbrowser
         if sys.platform.startswith('darwin'):
             browser = webbrowser.get('safari')
         else:
             browser = webbrowser.get()
         print_warning("Opening in your browser...")
         browser.open(self.url)
     elif key == 'left':
         global question_post
         global question_page
         question_post = None
         if question_page is None:
             sys.exit(0)
         else:
             LOOP.widget = question_page
     elif key == 'window resize':
         screenHeight, screenWidth = subprocess.check_output(['stty', 'size']).split()
         if self.screenHeight != screenHeight:
             self._invalidate()
             answer_frame = self.makeFrame(self.data)
             urwid.WidgetWrap.__init__(self, answer_frame)
예제 #27
0
    def open_url(self, url):
        # It looks like the maximum URL length is about 2k. I can't
        # seem to find the exact value
        if len(url) > 2047:
            url = url[:2047]
        try:
            webbrowser.get("windows-default").open_new(url)
        except:
            logging.warn("Error opening URL: %r\n%s", url,
                    traceback.format_exc())
            recommendURL = app.config.get(prefs.RECOMMEND_URL)

            if url.startswith(app.config.get(prefs.VIDEOBOMB_URL)):
                title = _('Error Bombing Item')
            elif url.startswith(recommendURL):
                title = _('Error Recommending Item')
            else:
                title = _("Error Opening Website")

            scheme, host, path, params, query, fragment = urlparse(url)
            shortURL = '%s:%s%s' % (scheme, host, path)
            msg = _(
                "There was an error opening %(url)s.  Please try again in a few "
                "seconds",
                {"url": shortURL}
            )
            dialogs.show_message(title, msg, dialogs.WARNING_MESSAGE)
예제 #28
0
def pwned_edi():
    data=read_pw(target, port)
    if data != None:
        data=data[365:377]
        pw=data.strip("\x00")
        webbrowser.get("/Applications/Firefox.app/Contents/MacOS/firefox-bin %s" ).open('http://*****:*****@'+target+'/index.asp')
    else:
        print "Socket timeOut or not Vulnerable"
예제 #29
0
 def callbackLookup(self, sender=None):
     lookupThese = []
     if self.currentSelection:
         if len(self.currentSelection)!=1: return
         for glyph in self.currentSelection:
             lookupThese.append(glyph)
     url = self.lookupURL + urlencode(dict(s=",".join([a.asU() for a in lookupThese])))
     webbrowser.get().open(url)
예제 #30
0
    def test_get(self):
        webbrowser = support.import_fresh_module('webbrowser')
        self.assertIsNone(webbrowser._tryorder)
        self.assertFalse(webbrowser._browsers)

        with self.assertRaises(webbrowser.Error):
            webbrowser.get('fakebrowser')
        self.assertIsNotNone(webbrowser._tryorder)
def action_go1():
    wb.get().open_new("https://www.News18.com")
def action_go2():
    wb.get().open_new("https://www.sarkariresult.com")
예제 #33
0
파일: flink.py 프로젝트: Taibe4/DeviantSoft
 def labworks():
     webbrowser.get(using=None).open_new_tab('http://labworks.mpt.ru/')
예제 #34
0
def html_open(name):
    data_path = path()
    new_cwd = os.chdir(data_path)
    data_path = data_path + name
    chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
    webbrowser.get(chrome_path).open_new(data_path)
예제 #35
0
파일: web.py 프로젝트: lhon/dappled-core
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=8008)
    parser.add_argument('--server', action="store_true")

    args = parser.parse_args()

    http_server = HTTPServer(application)

    # if connecting over SSH, then require server mode
    if ('SSH_CONNECTION' in os.environ
            or 'SSH_CLIENT' in os.environ) and not args.server:
        print('SSH connection detected; using --server')
        args.server = True
        # TODO: password....

    if args.server:
        ip = '0.0.0.0'
    else:
        ip = 'localhost'

    # based on notebook/notebookapp.py
    success = False
    for port in range(args.port, args.port + 10):
        try:
            http_server.listen(port, ip)
        except socket.error as e:
            if e.errno == errno.EADDRINUSE:
                print('The port %i is already in use, trying another port.' %
                      port)
                continue
            elif e.errno in (errno.EACCES,
                             getattr(errno, 'WSAEACCES', errno.EACCES)):
                print("Permission to listen on port %i denied" % port)
                continue
            else:
                raise
        else:
            success = True
            break
    if not success:
        print('ERROR: the notebook server could not be started because '
              'no available port could be found.')
        sys.exit(1)

    global PORT
    PORT = port

    if args.server:
        print('Serving from:')
        ip_addresses = get_ip_addresses()
        for ip in ip_addresses:
            print('  http://%s:%d' % (ip, port))
    else:
        url = 'http://%s:%d' % (ip, port)
        print('Opening browser at:', url)
        try:
            browser = webbrowser.get(None)
        except webbrowser.Error as e:
            browser = None
        if browser:
            b = lambda: browser.open(url, new=2)
            threading.Thread(target=b).start()

    # allows unbuffered() in parent process to catch ctrl-c on Windows
    # http://stackoverflow.com/questions/25965332/subprocess-stdin-pipe-does-not-return-until-program-terminates
    def ping():
        print('ping-%#@($')

    tornado.ioloop.PeriodicCallback(ping, 1000).start()

    tornado.ioloop.IOLoop.instance().start()
예제 #36
0
    engine.say('The available sizes are')
    engine.say(SIZE)


with sr.Microphone() as source:
    print('Say Something!')
    engine.say('Are you bored! Want to have a look at different shirts?')
    engine.runAndWait()
    audio = r.listen(source)
    print('Done!')
try:

    text = r.recognize_google(audio)
    print('You said:\n' + text)
    if('yes' in text ):
     wb.get(chrome_path).open('https://www.amazon.in/Mens-Shirts/b/ref=sd_allcat_sbc_mfashion_shirts?ie=UTF8&node=1968093031')
     engine.say('Here are your shirts! Happy shopping!')
     engine.runAndWait()

    elif ('no' in text):
        engine.say('So you want to look at a specific shirt to buy!')
        engine.runAndWait()
        with sr.Microphone() as source:
            audio = r.listen(source)


        try:
            text1 = r.recognize_google(audio)

            if ('yes' in text1):
                engine.say('Then please tell me what do you want to buy and also specify the price criteria if needed')
def assistant(command):
    if 'open gmail' in command:
        chrome_path = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
        url = 'https://mail.google.com/mail/u/0/#inbox'
        webbrowser.get(chrome_path).open(url)

    elif 'what\'s up' in command:
        TalkToMe('i am great, wassup with you.')

    elif "what time is it" in data:
        speak(ctime())

    elif "where is" in data:
        data = data.split(" ")
        location = data[2]
        speak("Hold on, I will show you where " + location + " is.")
        os.system("chromium-browser https://www.google.nl/maps/place/" + location + "/&amp;")

    elif 'send email' in command:
        TalkToMe('who do you want to send ?')
        recipiant = myCommand()
        if '<RECIEVER NAME>' in recipiant:
            TalkToMe('what should i say')
            content = myCommand()          
            #init gmail SMTP
            mail = smtplib.SMTP('smtp.gmail.com',587)            
            #identify to server
            mail.ehlo()            
            #encrypt session 
            mail.starttls()           
            #login using gmail
            mail.login('<SENDER'S EMAIL ID>', '<SENDER'S EMAIL PASSWORD')           
            #send mail
            mail.sendmail('<RECIEVER NAME>', '<RECIEVER EMAIL ID>'.content)           
            #close connection
            mail.colse()
            TalkToMe('EMAIL SENT')
    
    elif 'joke' in command:
        res = requests.get(
                'https://icanhazdadjoke.com/',
                headers={"Accept":"application/json"}
                )
        if res.status_code == requests.codes.ok:
            talkToMe(str(res.json()['joke']))
        else:
            talkToMe('oops!I ran out of jokes')

    elif 'current weather in' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            weather = Weather()
            location = weather.lookup_by_location(city)
            condition = location.condition()
            talkToMe('The Current weather in %s is %s The tempeture is %.1f degree' % (city, condition.text(), (int(condition.temp())-32)/1.8))

    elif 'weather forecast in' in command:
        reg_ex = re.search('weather forecast in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            weather = Weather()
            location = weather.lookup_by_location(city)
            forecasts = location.forecast()
            for i in range(0,3):
                talkToMe('On %s will it %s. The maximum temperture will be %.1f degree.'
                         'The lowest temperature will be %.1f degrees.' % (forecasts[i].date(), forecasts[i].text(), (int(forecasts[i].high())-32)/1.8, (int(forecasts[i].low())-32)/1.8))
예제 #38
0
파일: flink.py 프로젝트: Taibe4/DeviantSoft
 def duck():
     webbrowser.get(using=None).open_new_tab('https://duckduckgo.com')
예제 #39
0
def respond(voice_data):
    # 1: greeting
    if there_exists(['hey', 'hi', 'hello']):
        greetings = [
            f"hey, how can I help you {person_obj.name}",
            f"hey, what's up? {person_obj.name}",
            f"I'm listening {person_obj.name}",
            f"how can I help you? {person_obj.name}",
            f"hello {person_obj.name}"
        ]
        greet = greetings[random.randint(0, len(greetings) - 1)]
        speak(greet)

    # 2: name
    if there_exists(
        ["what is your name", "what's your name", "tell me your name"]):
        if person_obj.name:
            speak("my name is Amon")
        else:
            speak("my name is Amon. what's your name?")

    if there_exists(["my name is"]):
        person_name = voice_data.split("is")[-1].strip()
        speak(f"okay, i will remember that {person_name}")
        person_obj.setName(person_name)  # remember name in person object

    # 3: greeting
    if there_exists(["how are you", "how are you doing"]):
        speak(f"I'm very well, thanks for asking {person_obj.name}")

    # 4: time
    if there_exists(["what's the time", "tell me the time",
                     "what time is it"]):
        time = ctime().split(" ")[3].split(":")[0:2]
        if time[0] == "00":
            hours = '12'
        else:
            hours = time[0]
        minutes = time[1]
        time = f'{hours} {minutes}'
        speak(time)

    # 5: search google
    if there_exists(["search for"]) and 'youtube' not in voice_data:
        search_term = voice_data.split("for")[-1]
        url = f"https://google.com/search?q={search_term}"
        webbrowser.get().open(url)
        speak(f'Here is what I found for {search_term} on google')

    # 6: search youtube
    if there_exists(["youtube"]):
        search_term = voice_data.split("for")[-1]
        url = f"https://www.youtube.com/results?search_query={search_term}"
        webbrowser.get().open(url)
        speak(f'Here is what I found for {search_term} on youtube')

    # 7: get stock price
    if there_exists(["price of"]):
        search_term = voice_data.lower().split(" of ")[-1].strip(
        )  #strip removes whitespace after/before a term in string
        stocks = {
            "apple": "AAPL",
            "microsoft": "MSFT",
            "facebook": "FB",
            "tesla": "TSLA",
            "bitcoin": "BTC-USD"
        }
        try:
            stock = stocks[search_term]
            stock = yf.Ticker(stock)
            price = stock.info["regularMarketPrice"]

            speak(
                f'price of {search_term} is {price} {stock.info["currency"]} {person_obj.name}'
            )
        except:
            speak('oops, something went wrong')
    if there_exists(["exit", "quit", "goodbye"]):
        speak("going offline")
        exit()
예제 #40
0
파일: flink.py 프로젝트: Taibe4/DeviantSoft
 def google():
     webbrowser.get(using=None).open_new_tab('https://google.com')
def mainframe():
    """Logic for execution task based on query"""
    SR.scrollable_text_clearing()
    greet()
    query_for_future = None
    try:
        while (True):
            query = SR.takeCommand().lower(
            )  #converted the command in lower case of ease of matching

            #wikipedia search
            if there_exists(['search wikipedia for', 'from wikipedia'], query):
                SR.speak("Searching wikipedia...")
                if 'search wikipedia for' in query:
                    query = query.replace('search wikipedia for', '')
                    results = wikipedia.summary(query, sentences=2)
                    SR.speak("According to wikipedia:\n")
                    SR.speak(results)
                elif 'from wikipedia' in query:
                    query = query.replace('from wikipedia', '')
                    results = wikipedia.summary(query, sentences=2)
                    SR.speak("According to wikipedia:\n")
                    SR.speak(results)
            elif there_exists(['wikipedia'], query):
                SR.speak("Searching wikipedia....")
                query = query.replace("wikipedia", "")
                results = wikipedia.summary(query, sentences=2)
                SR.speak("According to wikipedia:\n")
                SR.speak(results)

            #jokes
            elif there_exists([
                    'tell me joke', 'tell me a joke', 'tell me some jokes',
                    'i would like to hear some jokes',
                    "i'd like to hear some jokes",
                    'can you please tell me some jokes',
                    'i want to hear a joke', 'i want to hear some jokes',
                    'please tell me some jokes',
                    'would like to hear some jokes', 'tell me more jokes'
            ], query):
                SR.speak(pyjokes.get_joke(language="en", category="all"))
                query_for_future = query
            elif there_exists([
                    'one more', 'one more please', 'tell me more',
                    'i would like to hear more of them', 'once more',
                    'once again', 'more', 'again'
            ], query) and (query_for_future is not None):
                SR.speak(pyjokes.get_joke(language="en", category="all"))

            #asking for name
            elif there_exists([
                    "what is your name", "what's your name",
                    "tell me your name", 'who are you'
            ], query):
                SR.speak("My name is Heisenberg and I'm here to serve you.")
            #How are you
            elif there_exists(['how are you'], query):
                conn = sqlite3.connect('Heisenberg.db')
                mycursor = conn.cursor()
                mycursor.execute('select sentences from howareyou')
                result = mycursor.fetchall()
                temporary_data = random.choice(result)[0]
                SR.updating_ST_No_newline(temporary_data + '😃\n')
                SR.nonPrintSpeak(temporary_data)
                conn.close()
            #what is my name
            elif there_exists([
                    'what is my name', 'tell me my name',
                    "i don't remember my name"
            ], query):
                SR.speak("Your name is " + str(getpass.getuser()))

            #calendar
            elif there_exists(['show me calendar', 'display calendar'], query):
                SR.updating_ST(calendar.calendar(2021))

            #google, youtube and location
            #playing on youtube
            elif there_exists(['open youtube and play', 'on youtube'], query):
                if 'on youtube' in query:
                    SR.speak("Opening youtube")
                    pywhatkit.playonyt(query.replace('on youtube', ''))
                else:
                    SR.speak("Opening youtube")
                    pywhatkit.playonyt(
                        query.replace('open youtube and play ', ''))
                break
            elif there_exists([
                    'play some songs on youtube',
                    'i would like to listen some music',
                    'i would like to listen some songs',
                    'play songs on youtube'
            ], query):
                SR.speak("Opening youtube")
                pywhatkit.playonyt('play random songs')
                break
            elif there_exists(['open youtube', 'access youtube'], query):
                SR.speak("Opening youtube")
                webbrowser.get(chrome_path).open("https://www.youtube.com")
                break
            elif there_exists(['open google and search', 'google and search'],
                              query):
                url = 'https://google.com/search?q=' + query[query.find('for'
                                                                        ) + 4:]
                webbrowser.get(chrome_path).open(url)
                break
            #image search
            elif there_exists(
                ['show me images of', 'images of', 'display images'], query):
                url = "https://www.google.com/search?tbm=isch&q=" + query[
                    query.find('of') + 3:]
                webbrowser.get(chrome_path).open(url)
                break
            elif there_exists([
                    'search for', 'do a little searching for',
                    'show me results for', 'show me result for',
                    'start searching for'
            ], query):
                SR.speak("Searching.....")
                if 'search for' in query:
                    SR.speak(
                        f"Showing results for {query.replace('search for','')}"
                    )
                    pywhatkit.search(query.replace('search for', ''))
                elif 'do a little searching for' in query:
                    SR.speak(
                        f"Showing results for {query.replace('do a little searching for','')}"
                    )
                    pywhatkit.search(
                        query.replace('do a little searching for', ''))
                elif 'show me results for' in query:
                    SR.speak(
                        f"Showing results for {query.replace('show me results for','')}"
                    )
                    pywhatkit(query.replace('show me results for', ''))
                elif 'start searching for' in query:
                    SR.speak(
                        f"Showing results for {query.replace('start searching for','')}"
                    )
                    pywhatkit(query.replace('start searching for', ''))
                break

            elif there_exists(['open google'], query):
                SR.speak("Opening google")
                webbrowser.get(chrome_path).open("https://www.google.com")
                break
            elif there_exists([
                    'find location of', 'show location of',
                    'find location for', 'show location for'
            ], query):
                if 'of' in query:
                    url = 'https://google.nl/maps/place/' + query[
                        query.find('of') + 3:] + '/&amp'
                    webbrowser.get(chrome_path).open(url)
                    break
                elif 'for' in query:
                    url = 'https://google.nl/maps/place/' + query[
                        query.find('for') + 4:] + '/&amp'
                    webbrowser.get(chrome_path).open(url)
                    break
            elif there_exists([
                    "what is my exact location", "What is my location",
                    "my current location", "exact current location"
            ], query):
                url = "https://www.google.com/maps/search/Where+am+I+?/"
                webbrowser.get().open(url)
                SR.speak("Showing your current location on google maps...")
                break
            elif there_exists(["where am i"], query):
                Ip_info = requests.get(
                    'https://api.ipdata.co?api-key=test').json()
                loc = Ip_info['region']
                SR.speak(f"You must be somewhere in {loc}")

            #who is searcing mode
            elif there_exists([
                    'who is', 'who the heck is', 'who the hell is',
                    'who is this'
            ], query):
                query = query.replace("wikipedia", "")
                results = wikipedia.summary(query, sentences=1)
                SR.speak("According to wikipdedia:  ")
                SR.speak(results)

            #play music
            elif there_exists([
                    'play music', 'play some music for me',
                    'like to listen some music'
            ], query):
                SR.speak("Playing musics")
                music_dir = 'D:\\Musics\\vishal'
                songs = os.listdir(music_dir)
                # print(songs)
                indx = random.randint(0, 50)
                os.startfile(os.path.join(music_dir, songs[indx]))
                break

            # top 5 news
            elif there_exists([
                    'top 5 news', 'top five news', 'listen some news',
                    'news of today'
            ], query):
                news = Annex.News(scrollable_text)
                news.show()

            #whatsapp message
            elif there_exists([
                    'open whatsapp messeaging', 'send a whatsapp message',
                    'send whatsapp message', 'please send a whatsapp message'
            ], query):
                whatsapp = Annex.WhatsApp(scrollable_text)
                whatsapp.send()
                del whatsapp
            #what is meant by
            elif there_exists(['what is meant by', 'what is mean by'], query):
                results = wikipedia.summary(query, sentences=2)
                SR.speak("According to wikipedia:\n")
                SR.speak(results)

            #taking photo
            elif there_exists([
                    'take a photo', 'take a selfie', 'take my photo',
                    'take photo', 'take selfie', 'one photo please',
                    'click a photo'
            ], query):
                takephoto = Annex.camera()
                Location = takephoto.takePhoto()
                os.startfile(Location)
                del takephoto
                SR.speak("Captured picture is stored in Camera folder.")

            #bluetooth file sharing
            elif there_exists([
                    'send some files through bluetooth',
                    'send file through bluetooth', 'bluetooth sharing',
                    'bluetooth file sharing', 'open bluetooth'
            ], query):
                SR.speak("Opening bluetooth...")
                os.startfile(r"C:\Windows\System32\fsquirt.exe")
                break

            #play game
            elif there_exists([
                    'would like to play some games', 'play some games',
                    'would like to play some game', 'want to play some games',
                    'want to play game', 'want to play games', 'play games',
                    'open games', 'play game', 'open game'
            ], query):
                SR.speak("We have 2 games right now.\n")
                SR.updating_ST_No_newline('1.')
                SR.speak("Stone Paper Scissor")
                SR.updating_ST_No_newline('2.')
                SR.speak("Snake")
                SR.speak("\nTell us your choice:")
                while (True):
                    query = SR.takeCommand().lower()
                    if ('stone' in query) or ('paper' in query):
                        SR.speak("Opening stone paper scissor...")
                        sps = Annex.StonePaperScissor()
                        sps.start(scrollable_text)
                        break
                    elif ('snake' in query):
                        SR.speak("Opening snake game...")
                        import Snake
                        Snake.start()
                        break
                    else:
                        SR.speak(
                            "It did not match the option that we have. \nPlease say it again."
                        )

            #makig note
            elif there_exists([
                    'make a note', 'take note', 'take a note', 'note it down',
                    'make note', 'remember this as note',
                    'open notepad and write'
            ], query):
                SR.speak("What would you like to write down?")
                data = SR.takeCommand()
                n = Annex.note()
                n.Note(data)
                SR.speak("I have a made a note of that.")
                break

            #flipping coin
            elif there_exists(["toss a coin", "flip a coin", "toss"], query):
                moves = ["head", "tails"]
                cmove = random.choice(moves)
                playsound.playsound('quarter spin flac.mp3')
                SR.speak("It's " + cmove)

            #time and date
            elif there_exists(['the time'], query):
                strTime = datetime.datetime.now().strftime("%H:%M:%S")
                SR.speak(f"Sir, the time is {strTime}")
            elif there_exists(['the date'], query):
                strDay = datetime.date.today().strftime("%B %d, %Y")
                SR.speak(f"Today is {strDay}")
            elif there_exists([
                    'what day it is', 'what day is today',
                    'which day is today', "today's day name please"
            ], query):
                SR.speak(f"Today is {datetime.datetime.now().strftime('%A')}")

            #opening software applications
            elif there_exists(['open chrome'], query):
                SR.speak("Opening chrome")
                os.startfile(
                    r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
                )
                break
            elif there_exists([
                    'open notepad plus plus', 'open notepad++',
                    'open notepad ++'
            ], query):
                SR.speak('Opening notepad++')
                os.startfile(r'C:\Program Files\Notepad++\notepad++.exe')
                break
            elif there_exists(['open notepad', 'start notepad'], query):
                SR.speak('Opening notepad')
                os.startfile(r'C:\Windows\notepad.exe')
                break
            elif there_exists([
                    'open ms paint', 'open mspaint', 'open microsoft paint',
                    'start microsoft paint', 'start ms paint'
            ], query):
                SR.speak("Opening Microsoft paint....")
                os.startfile('C:\Windows\System32\mspaint.exe')
                break
            elif there_exists([
                    'show me performance of my system',
                    'open performance monitor', 'performance monitor',
                    'performance of my computer',
                    'performance of this computer'
            ], query):
                os.startfile("C:\Windows\System32\perfmon.exe")
                break
            elif there_exists(
                ['open snipping tool', 'snipping tool', 'start snipping tool'],
                    query):
                SR.speak("Opening snipping tool....")
                os.startfile("C:\Windows\System32\SnippingTool.exe")
                break
            elif there_exists(
                ['open code', 'open visual studio ', 'open vs code'], query):
                SR.speak("Opeining vs code")
                codepath = r"C:\Users\Vishal\AppData\Local\Programs\Microsoft VS Code\Code.exe"
                os.startfile(codepath)
                break
            elif there_exists([
                    'open file manager', 'file manager', 'open my computer',
                    'my computer', 'open file explorer', 'file explorer',
                    'open this pc', 'this pc'
            ], query):
                SR.speak("Opening File Explorer")
                os.startfile("C:\Windows\explorer.exe")
                break
            elif there_exists(['powershell'], query):
                SR.speak("Opening powershell")
                os.startfile(
                    r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
                )
                break
            elif there_exists([
                    'cmd',
                    'command prompt',
                    'command prom',
                    'commandpromt',
            ], query):
                SR.speak("Opening command prompt")
                os.startfile(r'C:\Windows\System32\cmd.exe')
                break
            elif there_exists(['open whatsapp'], query):
                SR.speak("Opening whatsApp")
                os.startfile(
                    r'C:\Users\Vishal\AppData\Local\WhatsApp\WhatsApp.exe')
                break
            elif there_exists([
                    'open settings', 'open control panel',
                    'open this computer setting Window',
                    'open computer setting Window', 'open computer settings',
                    'open setting', 'show me settings',
                    'open my computer settings'
            ], query):
                SR.speak("Opening settings...")
                os.startfile('C:\Windows\System32\control.exe')
                break
            elif there_exists([
                    'open your setting', 'open your settings',
                    'open settiing window', 'show me setting window',
                    'open voice assistant settings'
            ], query):
                SR.speak("Opening my Setting window..")
                sett_wind = Annex.SettingWindow()
                sett_wind.settingWindow(root)
                break
            elif there_exists(['open vlc', 'vlc media player', 'vlc player'],
                              query):
                SR.speak("Opening VLC media player")
                os.startfile(r"C:\Program Files\VideoLAN\VLC\vlc.exe")
                break

            #password generator
            elif there_exists([
                    'suggest me a password', 'password suggestion',
                    'i want a password'
            ], query):
                m3 = Annex.PasswordGenerator()
                m3.givePSWD(scrollable_text)
                del m3
            #screeshot
            elif there_exists([
                    'take screenshot', 'take a screenshot',
                    'screenshot please', 'capture my screen'
            ], query):
                SR.speak("Taking screenshot")
                SS = Annex.screenshot()
                SS.takeSS()
                SR.speak('Captured screenshot is saved in Screenshots folder.')
                del SS

            #voice recorder
            elif there_exists(
                ['record my voice', 'start voice recorder', 'voice recorder'],
                    query):
                VR = Annex.VoiceRecorer()
                VR.Record(scrollable_text)
                del VR

            #text to speech conversion
            elif there_exists(['text to speech', 'convert my notes to voice'],
                              query):
                SR.speak("Opening Text to Speech mode")
                TS = Annex.TextSpeech()
                del TS

            #weather report
            elif there_exists(['weather report', 'temperature'], query):
                Weather = Annex.Weather()
                Weather.show(scrollable_text)

            #shutting down system
            elif there_exists([
                    'exit', 'quit', 'shutdown', 'shut up', 'goodbye',
                    'shut down'
            ], query):
                SR.speak("shutting down")
                sys.exit()

            elif there_exists(['none'], query):
                pass
            elif there_exists([
                    'stop the flow', 'stop the execution', 'halt',
                    'halt the process', 'stop the process', 'stop listening',
                    'stop the listening'
            ], query):
                SR.speak("Listening halted.")
                break
            #it will give online results for the query
            elif there_exists([
                    'search something for me', 'to do a little search',
                    'search mode', 'i want to search something'
            ], query):
                SR.speak('What you want me to search for?')
                query = SR.takeCommand()
                SR.speak(f"Showing results for {query}")
                try:
                    res = app.query(query)
                    SR.speak(next(res.results).text)
                except:
                    print(
                        "Sorry, but there is a little problem while fetching the result."
                    )

            #what is the capital
            elif there_exists(
                ['what is the capital of', 'capital of', 'capital city of'],
                    query):
                try:
                    res = app.query(query)
                    SR.speak(next(res.results).text)
                except:
                    print(
                        "Sorry, but there is a little problem while fetching the result."
                    )

            elif there_exists(['temperature'], query):
                try:
                    res = app.query(query)
                    SR.speak(next(res.results).text)
                except:
                    print("Internet Connection Error")
            elif there_exists([
                    '+', '-', '*', 'x', '/', 'plus', 'add', 'minus',
                    'subtract', 'divide', 'multiply', 'divided', 'multiplied'
            ], query):
                try:
                    res = app.query(query)
                    SR.speak(next(res.results).text)
                except:
                    print("Internet Connection Error")

            else:
                SR.speak(
                    "Sorry it did not match with any commands that i'm registered with. Please say it again."
                )
    except Exception as e:
        pass
예제 #42
0
파일: flink.py 프로젝트: Taibe4/DeviantSoft
 def youtube():
     webbrowser.get(using=None).open_new_tab('https://youtube.com')
def youtube(textToSearch):
    query = urllib.parse.quote(textToSearch)
    url = "https://www.youtube.com/results?search_query=" + query
    webbrowser.get('chrome').open_new_tab(url)
예제 #44
0
 def _open_browser():
     webbrowser.get().open('http://%s:%s/%s' % (ip, port, file_path))
예제 #45
0
        elif 'send email' in query:
            try:
                speak("What is the message ?")
                content = takeCommand()
                speak(content)
                to = '*****@*****.**'  # Email to which mail has to be sent
                send_Email(to, content)
                speak("Email has been sent successfully! ")
            except Exception as e:
                print(e)
                speak("There was an error sending the email !")

        elif 'open website in chrome' in query:
            speak("Which website should i open ? ")
            search = takeCommand().lower()
            wb.get(chrome_path).open_new_tab(search + ".com")

        elif 'open youtube in chrome' in query:
            wb.get(chrome_path).open_new_tab('https://youtube.com')

        elif 'open google in chrome' in query:
            wb.get(chrome_path).open_new_tab('https://google.com')

        elif 'open stack overflow in chrome' in query:
            wb.get(chrome_path).open_new_tab('https://stackoverflow.com')

        elif 'search in chrome' in query:
            speak('What do you want to search for?')
            search = takeCommand()
            url = 'https://google.com/search?q=' + search
            wb.get(chrome_path).open_new_tab(url)
import webbrowser
import time

text = clipboard.get_selection()
time.sleep(0.01)

site = "https://synonyme.woxikon.de/synonyme/" + text + ".php"
webbrowser.get('google-chrome').open_new_tab(site)
예제 #47
0
def mymain():

    wishme()
    while True:
        query = takeCommand().lower()
        if "time" in query:
            time()
        elif "date" in query:
            date()
        elif 'wikipedia' in query:
            speak("Searching.....")
            query = query.replace("wikipedia", "")
            result = wikipedia.summary(query, sentences=2)
            print(result)
            speak(result)
        elif 'send email' in query:
            try:
                speak('what should I say?')
                content = takeCommand()
                to = ''
                sendEmail(to, content)
                speak("Email Has been sent!")
            except Exception as e:
                print(e)
                speak("Unable To Send Your Email Try again")
        elif "search in web" in query:
            speak("what should I search ?")
            path = 'C:\\Program Files\\Mozilla Firefox\\firefox.exe'
            search = takeCommand().lower()
            wb.register('firefox', None, wb.BackgroundBrowser(path))
            wb.get('firefox').open_new_tab('https://www.' + search + '.com')
            speak("opening Firefox")
        elif "how are you" in query:
            speak("I'm Fine My Friend Thank You..")
        elif "your name" in query:
            speak("My Name is Ninja...")
        elif "your job" in query:
            speak(
                "I'm personal assistance....assists you with their daily personal tasks"
            )
        elif "my name" in query:
            speak("Your name is omar... the developer who create me..")
        elif "human" in query:
            speak("No I'm Nothing.... I'm AI System")
        elif "log out" in query:
            os.system("shutdown -l")
            speak("Signing Out")
            quit()
        elif "shut down" in query:
            os.system("shutdown /s /t 1")
            speak("Shutdown Computer")
            quit()
        elif "restart" in query:
            os.system("shutdown /r /t 1")
            speak("restart Computer")
            quit()
        elif "play songs" in query:
            songs_dir = "F:\\Audio"
            songs = os.listdir(songs_dir)
            os.startfile(os.path.join(songs_dir, songs[0]))
            speak("Opening musics")
        elif "remember" in query:
            speak("What should i remember?")
            data = takeCommand().strip().upper()
            speak("you said me to remember" + data)
            r = open('gui\\data.txt', 'w')
            r.write(str(data))
            r.close()
        elif "reminder" in query:
            r = open('gui\\data.txt', 'r')
            speak("you said me to remind you about.." + r.read())
        elif "screenshot" in query:
            screenShoot()
            speak("Screenshot Saved..")
        elif ("cpu") in query:
            cpu()
        elif ("battery") in query:
            cpu()
        elif ("joke") in query:
            jokes()
        elif "go to hell" in query:
            speak("Goodbye My Friend... see you again soon...")
            quit()
예제 #48
0
파일: weburl.py 프로젝트: weisongf/study
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import webbrowser
import time

print("start" + time.ctime())
count = 0
firefoxPath = r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe'
webbrowser.register('Firefox', None, webbrowser.BackgroundBrowser(firefoxPath))
webbrowser.get('Firefox').open('www.baidu.com', new=1, autoraise=True)
while (count < 3):
    time.sleep(5)
    #webbrowser.open("http://blog.csdn.net/ko_tin/article/details/72466012")
    #webbrowser.Chrome.open("http://blog.csdn.net/ko_tin/article/details/72466012")
    webbrowser.get('Firefox').open_new_tab(
        'http://edu.inspur.com/login.htm?fromurl=%2fsty%2findex.htm')
    count = count + 1

# chromePath = r'你的浏览器目录'            #  例如我的:C:\***\***\***\***\Google\Chrome\Application\chrome.exe
# webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chromePath))  #这里的'chrome'可以用其它任意名字,如chrome111,这里将想打开的浏览器保存到'chrome'
# webbrowser.get('chrome').open('www.baidu.com',new=1,autoraise=True)
예제 #49
0
# USEFUL JARVIS ============================================================================================================= BRAIN 2

        if ('wi-fi') in message:
            REMOTE_SERVER = "www.google.com"
            speekmodule.wifi()
            rand = ['We are connected']
            speekmodule.speek(rand, n, mixer)

        if ('.com') in message:
            rand = ['Opening' + message]
            Chrome = (
                "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
            )
            speekmodule.speek(rand, n, mixer)
            webbrowser.get(Chrome).open('http://www.' + message)
            print('')

        if ('google maps') in message:
            query = message
            stopwords = ['google', 'maps']
            querywords = query.split()
            resultwords = [
                word for word in querywords if word.lower() not in stopwords
            ]
            result = ' '.join(resultwords)
            Chrome = (
                "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
            )
            webbrowser.get(Chrome).open("https://www.google.be/maps/place/" +
                                        result + "/")
def action_go3():
    wb.get().open_new("https://www.amazon.com")
예제 #51
0
파일: user.py 프로젝트: visnix/WebKit
 def can_open_url(self):
     try:
         webbrowser.get()
         return True
     except webbrowser.Error:
         return False
예제 #52
0
파일: flink.py 프로젝트: Taibe4/DeviantSoft
 def Habr():
     webbrowser.get(using=None).open_new_tab('https://habr.com/ru/')
예제 #53
0
#opens several google search requests

import requests, sys, webbrowser, bs4


print('Googling...') # display text while downloading the Google page
res = requests.get('http://google.com/search?q=' + ' '.join(sys.argv[1:]))
res.raise_for_status()

# TODO: Retrieve top search result links.
soup = bs4.BeautifulSoup(res.text)

# TODO: Open a browser tab for each result.
linkElems = soup.select('.r a')
numOpen = min(5, len(linkElems))
for i in range(numOpen):
    webbrowser.get('chrome').open('http://google.com' + linkElems[i].get('href'))
        if word is None:
            break
        in_text += ' ' + word
        if word == 'end':
            break
    return in_text


#path = 'Flicker8k_Dataset/111537222_07e56d5a30.jpg'
max_length = 32
tokenizer = load(open("tokenizer.p", "rb"))
model = load_model('models/model_9.h5')
xception_model = Xception(include_top=False, pooling="avg")

photo = extract_features(img_path, xception_model)
img = Image.open(img_path)

description = generate_desc(model, tokenizer, photo, max_length)
print("\n\n")
print(description)
plt.imshow(img)

description += '.'

find = RemoveBannedWords(description, bannedWord)
print(find)

chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
url = "https://www.google.com.tr/search?q={}".format(find)
webbrowser.get(chrome_path).open(url)
예제 #55
0
 def __call__(self, a):
     print("Opening URl: " + self.url)
     webbrowser.get(chrome_path).open(self.url)
with sr.Microphone() as source:
    print('[search edureka:search youtube]')
    print('speak now')
    audio = r3.listen(source)

if 'edureka' in r2.recognize_google(audio):
    r2 = sr.Recognizer()
    url = 'http://www.google.com/'
    with sr.Microphone() as source:
        print('search your query')
        audio = r2.listen(source)

        try:
            get = r2.recognize_google(audio)
            print(get)
            wb.get().open_new(url + get)
        except sr.UnknownValueError:
            print('error')
        except sr.RequestError as e:
            print('failed'.format(e))

if 'video' in r1.recognize_google(audio):
    r1 = sr.Recognizer()
    url = 'https://www.youtube.com/results?search_query='
    with sr.Microphone() as source:
        print('search your query')
        audio = r1.listen(source)

        try:
            get = r1.recognize_google(audio)
            print(get)
예제 #57
0
import mlfinlab.filters.filters as filters
import mlfinlab.labeling.labeling as labeling
import mlfinlab.features.fracdiff as fracdiff
import mlfinlab.sample_weights as sample_weights
import mlfinlab.sampling as sampling
import mlfinlab.bet_sizing as bet_sizing
import mlfinlab.util as util
import mlfinlab.structural_breaks as structural_breaks
import mlfinlab.feature_importance as feature_importance
import mlfinlab.ensemble as ensemble
import mlfinlab.portfolio_optimization as portfolio_optimization
import mlfinlab.clustering as clustering

# Sponsorship notification
try:
    webbrowser.get('google-chrome').open_new(
        'https://www.patreon.com/HudsonThames')
except webbrowser.Error as error:
    try:
        webbrowser.get('firefox').open_new(
            'https://www.patreon.com/HudsonThames')
    except webbrowser.Error as error:
        try:
            webbrowser.get('windows-default').open_new(
                'https://www.patreon.com/HudsonThames')
        except webbrowser.Error as error:
            print(
                'Support us on Patreon: https://www.patreon.com/HudsonThames')

print()
print()
print(
예제 #58
0
def submit(args: 'argparse.Namespace') -> None:
    # guess url
    history = onlinejudge._implementation.download_history.DownloadHistory()
    if args.file.parent.resolve() == pathlib.Path.cwd():
        guessed_urls = history.get()
    else:
        log.warning(
            'cannot guess URL since the given file is not in the current directory'
        )
        guessed_urls = []
    if args.url is None:
        if len(guessed_urls) == 1:
            args.url = guessed_urls[0]
            log.info('guessed problem: %s', args.url)
        else:
            log.error('failed to guess the URL to submit')
            log.info('please manually specify URL as: $ oj submit URL FILE')
            sys.exit(1)

    # parse url
    problem = onlinejudge.dispatch.problem_from_url(args.url)
    if problem is None:
        sys.exit(1)

    # read code
    with args.file.open('rb') as fh:
        code = fh.read()  # type: bytes
    format_config = {
        'dos2unix': args.format_dos2unix or args.golf,
        'rstrip': args.format_dos2unix or args.golf,
    }
    code = format_code(code, **format_config)

    # report code
    log.info('code (%d byte):', len(code))
    log.emit(
        utils.make_pretty_large_file_content(code,
                                             limit=30,
                                             head=10,
                                             tail=10,
                                             bold=True))

    with utils.with_cookiejar(utils.new_session_with_our_user_agent(),
                              path=args.cookie) as sess:
        # guess or select language ids
        language_dict = {
            language.id: language.name
            for language in problem.get_available_languages(session=sess)
        }  # type: Dict[LanguageId, str]
        matched_lang_ids = None  # type: Optional[List[str]]
        if args.language in language_dict:
            matched_lang_ids = [args.language]
        else:
            if args.guess:
                kwargs = {
                    'language_dict': language_dict,
                    'cxx_latest': args.guess_cxx_latest,
                    'cxx_compiler': args.guess_cxx_compiler,
                    'python_version': args.guess_python_version,
                    'python_interpreter': args.guess_python_interpreter,
                }
                matched_lang_ids = guess_lang_ids_of_file(
                    args.file, code, **kwargs)
                if not matched_lang_ids:
                    log.info('failed to guess languages from the file name')
                    matched_lang_ids = list(language_dict.keys())
                if args.language is not None:
                    log.info(
                        'you can use `--no-guess` option if you want to do an unusual submission'
                    )
                    matched_lang_ids = select_ids_of_matched_languages(
                        args.language.split(),
                        matched_lang_ids,
                        language_dict=language_dict)
            else:
                if args.language is None:
                    matched_lang_ids = None
                else:
                    matched_lang_ids = select_ids_of_matched_languages(
                        args.language.split(),
                        list(language_dict.keys()),
                        language_dict=language_dict)

        # report selected language ids
        if matched_lang_ids is not None and len(matched_lang_ids) == 1:
            args.language = matched_lang_ids[0]
            log.info('chosen language: %s (%s)', args.language,
                     language_dict[LanguageId(args.language)])
        else:
            if matched_lang_ids is None:
                log.error('language is unknown')
                log.info('supported languages are:')
            elif len(matched_lang_ids) == 0:
                log.error('no languages are matched')
                log.info('supported languages are:')
            else:
                log.error('Matched languages were not narrowed down to one.')
                log.info('You have to choose:')
            for lang_id in sorted(matched_lang_ids or language_dict.keys()):
                log.emit('%s (%s)', lang_id,
                         language_dict[LanguageId(lang_id)])
            sys.exit(1)

        # confirm
        guessed_unmatch = ([problem.get_url()] != guessed_urls)
        if guessed_unmatch:
            samples_text = ('samples of "{}'.format('", "'.join(guessed_urls))
                            if guessed_urls else 'no samples')
            log.warning(
                'the problem "%s" is specified to submit, but %s were downloaded in this directory. this may be mis-operation',
                problem.get_url(), samples_text)
        if args.wait:
            log.status('sleep(%.2f)', args.wait)
            time.sleep(args.wait)
        if not args.yes:
            if guessed_unmatch:
                problem_id = problem.get_url().rstrip('/').split(
                    '/')[-1].split('?')[-1]  # this is too ad-hoc
                key = problem_id[:3] + (problem_id[-1]
                                        if len(problem_id) >= 4 else '')
                sys.stdout.write('Are you sure? Please type "{}" '.format(key))
                sys.stdout.flush()
                c = sys.stdin.readline().rstrip()
                if c != key:
                    log.info('terminated.')
                    return
            else:
                sys.stdout.write('Are you sure? [y/N] ')
                sys.stdout.flush()
                c = sys.stdin.read(1)
                if c.lower() != 'y':
                    log.info('terminated.')
                    return

        # submit
        try:
            submission = problem.submit_code(code,
                                             language_id=LanguageId(
                                                 args.language),
                                             session=sess)
        except NotLoggedInError:
            log.failure('login required')
            sys.exit(1)
        except SubmissionError:
            log.failure('submission failed')
            sys.exit(1)

        # show result
        if args.open:
            browser = webbrowser.get()
            log.status('open the submission page with browser')
            opened = browser.open_new_tab(submission.get_url())
            if not opened:
                log.failure(
                    'failed to open the url. please set the $BROWSER envvar')
예제 #59
0
파일: flink.py 프로젝트: Taibe4/DeviantSoft
 def mpt():
     webbrowser.get(using=None).open_new_tab("https://mpt.ru/")
                speak("According to Wikipedia")
                print(results)
                speak(results)
            except wikipedia.exceptions.DisambiguationError as e:
                s = random.choice(e.options)
                print(s)
                speak(s)
            except wikipedia.exceptions.WikipediaException as e:
                print('Search not include, try again wikipedia and your search')
            else:
                continue

        if 'search' in query:
            search = takeCommand('what do you want to search {person.name}?')
            url = 'https://google.com/search?q=' + search
            webbrowser.get().open(url)
            print('here is what i found for/t' + search)

        if 'find location for' in query:
            location = takeCommand('what is the location')
            url = 'https://www.google.com/maps/place/'+ location + '/&amp;'
            webbrowser.get().open(url)
            print(f"here is the location of/t" + location)

        elif "open facebook" in query:
            webbrowser.open_new_tab("https://sl-si.facebook.com/")
            print("Facebook is open now")
            speak("Facebook is open now")


        elif 'news' in query: