def __return_building_list( lista_immobili ): """ Return the building list adding the center and the zoom factor. Comma separated buildings list + [lat, lan, zoom ] """ lat = 0.00 lan = 0.00 list_lat = [] list_lan = [] response = "" n = lista_immobili.__len__() if n != 0 : for i in lista_immobili : if response.__len__() != 0 : response = response + "#" lat = lat + i['lat'] lan = lan + i['lan'] list_lan.append( i['lan'] ) list_lat.append( i['lat'] ) response = response + """ "%s","%s","%s","%s","%s","%s" """ % ( i['lat'], i['lan'], i['mq'], i['desc'], i['prz'], i['id'] ) # get the zoom factor # pack the data in the answer print " (%s %s) (%s %s)" % ( min(list_lat), min(list_lan), max(list_lat), max(list_lan) ) d = Google.point_distance( min(list_lat), min(list_lan), max(list_lat), max(list_lan) ) zoom = Google.get_zoom_value( d ) # immobile was an empty list, building custom values else: zoom = 9 lat = 42.4424572 lan = 14.2096282 n = 1 response = response + "[%f,%f,%d]" % (lat/n, lan/n, zoom) return response
def upload_to_google(service, filename, folder_id, log): for num in range(max_upload_retries): try: log.info('Uploading file to google "{file}"'.format(file=filename)) metadata = { 'name': filename, 'mimeType': Google.mime_types['json'], 'parents': [folder_id], 'supportsTeamDrives': True, } media = MediaFileUpload(filename, mimetype=Google.mime_types['json'], resumable=True) http = service.files().create(body=metadata, media_body=media, supportsTeamDrives=True, fields='id') response = Google.call_api(http, log) log.info( 'Successfully uploaded file: "{filename}" (ID: {id})'.format( filename=filename, id=response['id'])) return except: log.error('Google upload failed for some reason:') log.error(traceback.format_exc()) sleep(5) continue log.error("Google upload failed!")
def generate_calendar_audit_report(service, log): log.info("Querying calendar audit data...") # Result will likely be long / paginated. results = list() page_token = None num_pages = 0 while True: http = service.activities().list(pageToken=page_token, userKey='all', applicationName='calendar') response = Google.call_api(http, log) activities = response.get('items', []) if len(activities) > 0: results.extend(activities) num_pages += 1 page_token = response.get('nextPageToken', None) if page_token is None: break log.info("Downloaded {a} calendar audit entries ({b} pages)".format( a=len(results), b=num_pages)) return results
def generateResponse(self, module, operation): response = Response() if module == 'google': response.texts.append(Google.getResult(operation)) if module == 'wikipedia': response.texts.append(Wikipedia.getSummary(operation)) if module == 'imdb': response.texts = IMDB.getMovieInfo(operation) if module == 'releases': response.texts.append(Releases.getReleaseDate(operation)) if module == 'lyrics': response.texts.append(Lyrics.getLyrics(operation)) if module == 'reddit': response.texts = self.handleReddit(operation) if module == 'wolfram': response.images = Wolfram.getImages(operation) if module == 'network': response.text = network.scan() if module == 'hltb': response.text = (hltb.getTimes(opertaion)) if module == 'hltr': response.texts.append(hltr.getInfo(operation)) if module == 'espeak': espeak.speak(operation) response.texts.append('Done, sir') if not response.texts and not response.images and not response.audios: response.texts = ['I\'m sorry dave, I\'m afraid I can\'t do that'] return response
def generateResponse(self, module, operation): response = Response() if module == 'google': response.texts.append(Google.getResult(operation)) if module == 'wikipedia': response.texts.append(Wikipedia.getSummary(operation)) if module == 'imdb': response.texts = IMDB.getMovieInfo(operation) if module == 'releases': response.texts.append(Releases.getReleaseDate(operation)) if module == 'lyrics': response.texts.append(Lyrics.getLyrics(operation)) if module == 'reddit': response.texts = self.handleReddit(operation) if module == 'wolfram': response.images = Wolfram.getImages(operation) if module == 'network': response.text = network.scan() if module == 'hltb': response.text = (hltb.getTimes(opertaion)) if module == 'hltr': response.texts.append(hltr.getInfo(operation)) if module == 'espeak': espeak.speak(operation) response.texts.append('Done, sir') if not response.texts and not response.images and not response.audios: response.texts = ['I\'m sorry dave, I\'m afraid I can\'t do that'] return response
def verify_target_google_folder(service, id, log): http = service.files().get(fileId=id, fields='id,mimeType,name,webViewLink,parents', supportsTeamDrives=True) folder = Google.call_api(http, log=log) if folder is None or folder['mimeType'] != Google.mime_types['folder']: log.error( "Error: Could not find any contents of folder ID: {0}".format(id)) exit(1) log.info("Valid folder ID: {id} ({name})".format(id=id, name=folder['name']))
def main(): g = Google.Google() g.authenticate() l = -1 at_least_one = False for msg in g.search(query): at_least_one = True if g.resultSizeEstimate != l: l = g.resultSizeEstimate print l content = g.GetMimeMessage(msg['id']) print content['subject'] if not at_least_one: print 'No results'
def save(self, force_insert=False, force_update=False): # TODO posiziona gli immobili a caso se il debug è attivo. if VC_DEBUG: list = [random.random() * 45, random.random() * 45, 7] else: # TODO - se la posizione di google esce fuori dall'abruzzo sposta la posizione # sulla sede amministrativa # TODO - se le coordinate sono impostate non devono essere rimpostate list = Google.resolver("%s %s %s " % (self.CAP, self.via, self.n)) if list != 'None': list.pop() self.google_lat = float(list.pop()) self.google_lan = float(list.pop()) super(Posizione, self).save(force_insert, force_update)
def Pronounce (word): try: print "Cambridge: "+Cambridge.lookup_word(word) except AttributeError: print ColorRed("Cambridge does not have a pronunciation") try: print "Dictionary: "+Dictionary.lookup_word(word) except AttributeError: print ColorRed("Dictionary does not have a pronunciation") try: print "FreeDictionary: "+FreeDictionary.lookup_word(word) except AttributeError: print ColorRed("FreeDictionary does not have a pronunciation") try: print "Google: "+Google.lookup_word(word) except AttributeError: print ColorRed("Google does not have a pronunciation") try: print "Merriam: "+Merriam.lookup_word(word) except AttributeError: print ColorRed("Merriam does not have a pronunciation")
# -*- coding: utf-8 -*- import Google sheet = Google( "https://www.googleapis.com/auth/spreadsheets" ) # read-write, use 'spreadsheets.readonly' if you lack the authorizations sheet.open( 'My Sheet', '<GOOGLE SHEET ID>' ) # store the id in memory for easier use. replace '<GOOGLE SHEET ID>' with the sheet id (easily found in the url= print(sheet.read('My Sheet', 'Page1!A3:C200') ) # example, reading the cells A3 to C200 from the sub sheet 'Page 1' sheet.write('My Sheet', 'Page2!A2:C3', [['test1', 'test2', 'test3'], ['test4', 'test5', 'test6'] ]) # write 2 rows with these test strings in the specified range sheet.close('My Sheet') # remove from memory
def determineCommand(self): # self.command_split[0] is the key word to determine what jarvis should do cmd_key = self.command_split[0].lower() if cmd_key == "quit": Dialogue.selfDestruct() sys.exit() elif cmd_key == "help": Dialogue.printHelpScreen(self.program_names) elif cmd_key == "rerun": self.setCommand(self.lastCommand) self.determineCommand() elif cmd_key == "find": flag = self.command_split[1] if flag == "-f": # find a file print("Looking for files '{}'".format( Find.prepareName(2, self.command_split))) Dialogue.fileResults( Find.findFile(expanduser("~"), Find.prepareName(2, self.command_split))) elif flag == "-d": # find a directory print("Looking for files '{}'".format( Find.prepareName(2, self.command_split))) Dialogue.fileResults( Find.findDirectory(expanduser("~"), Find.prepareName(2, self.command_split))) else: Dialogue.printWithColor( "Jarvis didn't recognize the flag for the 'find' command.", 'red') Dialogue.printWithColor( "The syntax should look like $find -f|-d.. file_name'", 'red') Dialogue.printWithColor( "For more information please type help", 'red') elif cmd_key == "open": try: subprocess.check_call( ['open', Find.prepareName(1, self.command_split)]) except RuntimeError as e: Dialogue.printWithColor( "subprocess.check_call() ran into an error.", 'red') Dialogue.printWithColor(e, 'red') elif cmd_key == "google": webbrowser.open(Google.commandToURL(self.command_split)) elif cmd_key == "close": name = Find.prepareName(1, self.command_split) display_results = [] Dialogue.printWithColor( "Searching for processes that contain {}".format(name), 'cyan') for process in psutil.process_iter(): process_pid = process.pid process_name = process.name() process_status = process.status() if name in process_name.lower(): display_results.append( [process_pid, process_name, process_status]) if len(display_results) > 1: Dialogue.printWithColor("Jarvis found multiple results", 'cyan') for results in display_results: Dialogue.printWithColor( "PID: {}\t Name: {}\t Status: {}\t".format( results[0], results[1], results[2]), 'yellow') response = input( "Please enter the PID you would like to close: ") if response.lower() == "all": for results in display_results: try: print("Jarvis is killing PID {}".format( results[0])) os.kill(results[0], signal.SIGKILL) except ProcessLookupError as e: print( "Jarvis ran into a runtime error trying to kill {}" .format(results)) else: for results in display_results: if str(results[0]) == response: try: print("Jarvis is killing PID {}".format( results[0])) os.kill(results[0], signal.SIGKILL) except RuntimeError as e: print( "Jarvis ran into a runtime error trying to kill {}" .format(results)) return elif len(display_results) == 1: try: print("Jarvis is killing PID {}".format( display_results[0])) os.kill(display_results[0][0], signal.SIGKILL) except RuntimeError as e: print("Jarvis ran into a runtime error trying to kill {}". format(display_results[0])) return else: Dialogue.noResultsFound(name) else: print("Error command not found")
from bs4 import BeautifulSoup import requests import Google from PriceScrapers import priceToDB keywords = [ 'iphone 5s kieskeurig', 'htc one zilver kieskeurig' ] products = [] for keyword in keywords: link = Google.getLink(keyword) products.append(link) itemList = [] # Loop array for product in products: r=requests.get(product) pageHTML=r.text soup=BeautifulSoup("".join(pageHTML)) sAll=soup.findAll("td", { "class" : "prijs" }) # Scrape product name from title text = soup.title.text
def cmndBlk(msg): if msg['cmd'] == 'chat': if msg['text'].lower().strip() == '|eb': _thread.start_new_thread(runBear, (0, )) elif msg['text'].lower().strip() == '|eb -s': _thread.start_new_thread(runBear, (1, )) elif msg['text'].lower()[:9] == '|eb -say ' and len(msg['text']) > 9: _thread.start_new_thread(runBear, ((2, msg['text'][9:]), )) elif msg['text'].lower().strip() == '|source': ws.send( json.dumps({ 'cmd': 'chat', 'text': ('%s') % comm['|source'] })) elif (msg['text'].lower().strip() == '|help' or msg['text'].lower().strip() == '|h'): ws.send(json.dumps({ 'cmd': 'chat', 'text': ('%s') % comm['|help'] })) elif msg['text'].lower()[:3] == '|g ': if len(msg['text'].strip()) > 3: ws.send( json.dumps({ 'cmd': 'chat', 'text': Google.search(msg['text'][3:]) })) else: ws.send( json.dumps({ 'cmd': 'chat', 'text': 'Usage is |g \"string\"' })) elif msg['text'].lower()[:4] == '|ed ': if len(msg['text']) > 4: ws.send( json.dumps({ 'cmd': 'chat', 'text': ED.search(msg['text'][4:]) })) else: ws.send( json.dumps({ 'cmd': 'chat', 'text': 'Usage is |ed \"string\"' })) elif msg['text'].lower() == '|ed': ws.send( json.dumps({ 'cmd': 'chat', 'text': 'Usage is |ed \"string\"' })) elif msg['text'].lower()[:4] == '|wa ': if len(msg['text']) > 4: ws.send( json.dumps({ 'cmd': 'chat', 'text': WA.search(msg['text'][4:]) })) else: ws.send( json.dumps({ 'cmd': 'chat', 'text': 'Usage is |wa \"string\"' })) elif msg['text'].lower() == '|wa': ws.send( json.dumps({ 'cmd': 'chat', 'text': 'Usage is |wa \"string\"' })) elif msg['text'].lower() == '|uptime': ws.send( json.dumps({ 'cmd': 'chat', 'text': '%s' % prsDrtn(time.time() - joined) })) afk(msg) responses(msg)
paragraphs: Iterator[str] = filter(lambda x: x, text.split('\n')) for paragraph in paragraphs: try: detector = Detector(paragraph) except UnknownLanguage: print("无法检测源语言") else: language: str = detector.language.code print(paragraph) print(translator.translate([paragraph], language)) print(u"Detected source language: {}".format( detector.language.name)) if __name__ == '__main__': translators = {"CaiYun": CaiYun.CaiYun(), "Google": Google.Google()} parser = argparse.ArgumentParser( description="use translators to translate text") parser.add_argument("text", type=str, help="the source text you want to translate") parser.add_argument( "-t", "--translator", type=str, default="Google", choices=translators.keys(), help="specify the translator you want to use (default: %(default)s)") args = parser.parse_args() text = args.text.replace('\n', ' ') main(text, translators.get(args.translator))
def OnGoogle(self,event): search_item = self.dy_text2.GetValue() Google.main(frame6.comp_name,search_item,self.response,self.col_headers\ ,frame6.conn,frame6.c) self.Close(True)
def webhook(): city = flask_request.args.get('city') return Google.webhook(flask_request, city)