def handleCallback(phrase, listner): #speech.say('You said %s' % phrase) if phrase == "jarvis" or phrase == "jaiss": print (phrase) speech.say("Yes Boss") elif phrase == "are you up": speech.say("definitely. at your service sir!") elif phrase == "what is the current time": speech.say(getCurrentTime()) elif phrase == "turn off": print (phrase) speech.say("Turning Off") listner.stoplistening() elif phrase == "how are you": print (phrase) speech.say("I am good. Thank you. How are you.") elif phrase == "read news": print (phrase) feeds = speakWebPage.readFeeds() speech.say(feeds) elif phrase == "show my feeds": print (phrase) speech.say("Launching Google Reader") os.system("C:\Users\kshwetabh\AppData\Local\Google\Chrome\Application\chrome.exe reader.google.com") elif phrase == "how is the weather outside": speech.say("Getting current weather. Please wait...!") print (phrase) speech.say(Weather.getCurrentWather()) elif phrase == "get me the weather forecast": speech.say("Getting weather forecast. Please wait...!") print (phrase) speech.say("This week's weather forecast:") for item in Weather.getWeatherForecast(): speech.say(item) elif phrase == "any new mails": check_mails() print (phrase) elif phrase == "morning greetings": morning_greetings() else: print (phrase) speech.say("Could not understand, please repeat")
def text(): data = extractor.loadStuySite() schedule = extractor.getSchedule(data[1], data[2]) bellDay = extractor.getBellDay(schedule) delays = MTAService.getDelays(MTAService.getSubways()) forecast = Weather.getForecastString(Weather.getForecast()) high = Weather.getHigh() low = Weather.getLow() now = Weather.getTemp() resp = twiml.Response() message = "" #---schedule--- if bellDay == "Closed" : message += "School is closed." elif bellDay == "Weekend" : message += "It's a weekend." elif bellDay == "Unknown" : message += "Schedule unavailable." else : #'a' or 'an' depending on the next word: #B1/B2 ('a') or A1/A2/Unknown ('an') gymDay = extractor.getGymDay(schedule) #if gymDay[0] == "B" : article = "a" #else : article = "an" #"Today is %s %s day."%(article, gymDay) shortened for text message += "Schedule: %s. Phys. ed.: %s."%(bellDay, gymDay) #---weather--- message += " Today will be %s. High: %d. Low: %d. Currently %d degrees."%(forecast, high, low, now) #---MTA--- if delays : message += " Delays on the " + delays[0] #account for more than one line with delays if len(delays) > 1 : for i in xrange (len(delays)-1): message += ", %s"%(delays[i+1]) message += " lines." else : message += " line." else : message += " There are no train delays!" resp.sms(message) return str(resp)
def get_weather(request,location): print "getting weather at %s " % location global more_results del more_results[:] try: station = Weather.location2station(location) weather = Weather.Station(station[0]) weather.update(live=True) more_string = "Dew point: %s, Pressure: %s, Humidity: %i%%, Wind: %s " % ( weather.data['dewpoint_string'],weather.data['pressure_string'],weather.data['relative_humidity'],weather.data['wind_string']) more_results.append(more_string) return IRCResponse(request.reply_recipient, "Weather at %s: %s %s %s " % (weather.data['city'],weather.data['weather'],weather.data['temperature_string'],weather.data['observation_time'])) except: return IRCResponse(request.reply_recipient, "Weather at %s is not found." % location)
def maps(id): if not os.path.exists(GPS_DIR + '/GPS_' + id + '.pkl'): abort(404) type = request.args.get('type') if request.args.get('type') else 'single' colorProfile = request.args.get('color') if request.args.get( 'color') else 'gr' settings = MapSettings(colorProfile) mapClass = MapData(id) if type == "multi": startYMD = mapClass.parseYMD() results = query_db('SELECT * FROM CPCFiles WHERE start_date LIKE ?', (str(startYMD) + '%', )) for result in results: settings.addData(MapData(result['id'])) elif type == 'single': settings.addData(mapClass) else: abort(404) settings.getArrayStats() datetime = parse(mapClass.startDate) try: weatherData = Weather.fetchWeatherData(datetime) except: weatherData = False settings.getArrayStats() return render_template('maps/index.html', subd=subd, settings=json.dumps(settings.toJSON(), cls=ComplexEncoder), weather=json.dumps(weatherData))
def add_weather(self, weather): if weather == "Rain": bounds = (-self.height*GC.TILEHEIGHT//4, self.width*GC.TILEWIDTH, -16, -8) self.weather.append(Weather.Weather('Rain', .1, bounds, (self.width, self.height))) elif weather == "Snow": bounds = (-self.height*GC.TILEHEIGHT, self.width*GC.TILEWIDTH, -16, -8) self.weather.append(Weather.Weather('Snow', .125, bounds, (self.width, self.height))) elif weather == "Sand": bounds = (-2*self.height*GC.TILEHEIGHT, self.width*GC.TILEWIDTH, self.height*GC.TILEHEIGHT+16, self.height*GC.TILEHEIGHT+32) self.weather.append(Weather.Weather('Sand', .075, bounds, (self.width, self.height))) elif weather == "Smoke": bounds = (-self.height*GC.TILEHEIGHT, self.width*GC.TILEWIDTH, self.height*GC.TILEHEIGHT, self.height*GC.TILEHEIGHT+16) self.weather.append(Weather.Weather('Smoke', .075, bounds, (self.width, self.height))) elif weather == "Light": bounds = (0, self.width*GC.TILEWIDTH, 0, self.height*GC.TILEHEIGHT) self.weather.append(Weather.Weather('Light', .04, bounds, (self.width, self.height))) elif weather == "Dark": bounds = (0, self.width*GC.TILEWIDTH, 0, self.height*GC.TILEHEIGHT) self.weather.append(Weather.Weather('Dark', .04, bounds, (self.width, self.height))) elif weather == "Fire": bounds = (0, GC.WINWIDTH, GC.WINHEIGHT, GC.WINHEIGHT+16) self.weather.append(Weather.Weather('Fire', .05, bounds, (GC.TILEX, GC.TILEY)))
def ActualBot(sentence): if __name__ == '__main__': WAKE = 'hello' SERVICE = Gcalender.authenticate_google() while True: print("Listening") sentence = CInput.get_command() #sentence = SInput.VoiceCommand() if sentence.count(WAKE) > 0: speak("Im ready") sentence = CInput.get_command() #sentence = SInput.VoiceCommand() if "poweroff" in sentence or "power of" in sentence or "powerdown" in sentence or "power off" in sentence or "power down" in sentence or "powerof" in sentence: break botresponse = MIntegration.MLFunc(sentence) if botresponse == None: pass elif "weather" in botresponse: speak("Which City's weather report should I look for ?") command = input() #command = SInpuy.VoiceCommand() command = command.lower() Weather.weatherreport(command) elif "event" in botresponse: date = Gcalender.get_date(sentence) if date: Gcalender.get_events(date, SERVICE) else: speak("I dont understand") elif "mail" in botresponse: try: speak("Enter the Recipient") to = str(input()) speak("Enter the subject") subject = input() speak("What should I write?") content = input() UserEmail.SendSubEmail(to, subject, content) speak("Email has been sent") except Exception as e: print(e) speak("An Error has occured") #########BUG######## elif "search" in botresponse: speak("What should I search for ?") command = input() #command = SInput.VoiceCommand() CF.searchnet(command) elif "news" in botresponse: CF.shownews() elif "screenshot" in botresponse: CF.takescreenshot() elif "translate" in botresponse: Gtranslate.translatesentence() elif "shutdown" in botresponse: speak("Do you wish to shutdown the system ?") command = CInput.get_command() #command = SInput.VoiceCommand() if (command == 'yes' or command == 'yep' or command == 'sure'): os.system("shutdown /s /t 1") else: pass elif "restart" in botresponse: speak("Do you wish to restart the system ?") command = CInput.get_command() #command = SInput.VoiceCommand() if (command == 'yes' or command == 'yep' or command == 'sure'): os.system("shutdown /r /t 1") else: pass elif "maps" in botresponse: speak("Which place should i search for ?") place = input() #place = SInput.VoiceCommand() webbrowser.open("https://www.google.com/maps/place/" + place) elif "reddit" in botresponse: try: subreddit = input("Which subreddit ?") #subreddit = SInput.VoiceCommand() subreddit = subreddit.replace(" ", "") webbrowser.open_new_tab('www.reddit.com/r/' + subreddit) speak("Opening reddit") except Exception as e: speak("Something Went wrong") elif "note" in botresponse: speak("What should i write down ?") note_text = CInput.get_command() #note_text = SInput.VoiceCommand() Notes.instantnote(note_text) speak("I've made a note of that") elif "console" in botresponse: webbrowser.open_new_tab( "https://play.google.com/console/u/0/developers/5469473923678169464/app-list" ) elif "insta" in botresponse: speak("Initializing") CF.instagram() elif "standby" in botresponse: break elif "wiki" in botresponse: speak("What do you want me to search on wikipedia ?") wikisearch = CInput.get_command() CF.wiki(wikisearch) elif "wolfram" in botresponse: speak("Ask me") wolframquery = CInput.get_command() WRFile.wolframfunc(wolframquery) elif "read" in botresponse: EM.copydata() elif "copy" in botresponse: EM.copy() elif "paste" in botresponse: EM.paste() elif "time" in botresponse: CF.timetoday() elif "date" in botresponse: CF.daytoday() else: print("I dont understand you. Please be more specific") return
def update_weather(team, metric): if team: fig = Weather.temp_chart(df, team, metric) return fig
def schedule(): digit = request.form['Digits'] resp = twiml.Response() audio = [] #---pressed 1: schedule--- if int(digit) == 1 : print "1 case: schedule" data = extractor.loadStuySite() schedule = extractor.getSchedule(data[1], data[2]) bellDay = extractor.getBellDay(schedule) #sentence for schedule type, plus phys. ed. cycle if applicable if bellDay == "Closed" : audio.append("Closed.mp3") elif bellDay == "Weekend" : audio.append("Closed.mp3") elif bellDay == "Unknown" : audio.append("Unknown.mp3") else : gymDay = extractor.getGymDay(schedule) #depends on mp3s with same names as bellDay, gymDay options audio.append("%s.mp3"%(bellDay)) audio.append("cycle.mp3") audio.append("cycle-%s.mp3"%(gymDay)) #---pressed 2: weather--- elif int(digit) == 2 : print "2 case: weather" forecast = Weather.getForecast() temp = Weather.getTemp() high = Weather.getHigh() low = Weather.getLow() adjectives = [20,22,23,24,25,26,27,28,29,30,31,32,33,34,36] nouns = [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,21,35,37,38,39,40,41,42,43,44,45,46,47] #if adjective, e.g. "cold" #"Today it will be __" if forecast in adjectives: audio.append("adjective.mp3") #if noun, e.g. "thunderstorms" #"Today there will be __" elif forecast in nouns: audio.append("noun.mp3") #special cases, e.g. hurricane, have their own intros audio.append("weather-%d.mp3"%(forecast)) #"Today the high will be __ Fahrenheit." audio.append("high.mp3") #one of the number mp3s if high < 0 : audio.append("negative.mp3") audio.append("%d.mp3"%(abs(high))) audio.append("fahrenheit.mp3") #"and the low will be __ Fahrenheit." audio.append("low.mp3") if low < 0 : audio.append("negative.mp3") audio.append("%d.mp3"%(low)) audio.append("fahrenheit.mp3") #"It is now __ Fahrenheit" audio.append("now.mp3") if temp < 0 : audio.append("negative.mp3") audio.append("%d.mp3"%(temp)) audio.append("fahrenheit.mp3") #---pressed 3: MTA--- elif int(digit) == 3 : print "3 case: MTA" delays = MTAService.getDelays(MTAService.getSubways()) if delays : audio.append("delays.mp3") for each in delays : for char in xrange(len(each)) : audio.append("%s.mp3"%(str(each[char]))) audio.append("line.mp3") #---pressed 4: credits--- elif int(digit) == 4 : audio.append("credits.mp3") #---pressed another button--- else : print "Not valid number. Bad user." #"You pressed some other number. Bad user." audio.append("baduser.mp3") #"Press any button to go back." audio.append("back.mp3") #play all queued audio, accepting any button as an interrupt gather = resp.gather(numDigits=1, action="/chance", timeout=10) for each in audio: url = url_for("static", filename=("audio/%s"%(each))) gather.play(url) return str(resp)
def __init__(self): self.weather = Weather.Weather() self.musicPlayer = PlayMusic.PlayMusic() self.speaker = TextToSpeech.TextToSpeech() self.help = Help.Help()
# TODO: add description # TODO: add unittest logging.info('Deleting completed tasks') tasks.delete_completed_tasks(1) if __name__ == "__main__": # init logging logging.basicConfig(filename=LOG_FILE_PATH, level=logging.DEBUG) logging.info("Start Screen Program") # init date and time dt = DateAndTime.DateAndTime() # init weather weather_obj = Weather.Weather() # init tasks tasks = Tasks.Tasks() # init the fonts font18 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 18) font24 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 24) font35 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 35) font68 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 68) schedule.every(1).minutes.do(update_screen, dt=dt, weather=weather_obj.weather_dict, tasks=tasks) schedule.every(1).minutes.do(update_weather, weather_obj=weather_obj)
import Weather Weather.cli()
def weather(player, string): """Summon a weather system by name""" import Weather Weather.weather().toggleRandomWeather(False) Weather.weather().summon(str(string))
def has_weather(text): if text.__contains__("本地天气"): return Weather.main() else: return no_music_distance(text)
async def on_message(message): file = openpyxl.load_workbook("쿨타임.xlsx") sheet = file.active file1 = openpyxl.load_workbook("밴.xlsx") sheet1 = file1.active kk = 0 if "<@249706579912294400>" in message.content: file = openpyxl.load_workbook('상태.xlsx') sheet = file.active if sheet[ "A1"].value != "활동" and message.author.id != '536190598806503435' and message.author.id != '249706579912294400': await client.send_message( message.channel, "지금 관리자는 " + str(sheet["A1"].value) + "중입니다.\n+메시지를 통해 관리자방에 쪽지를 남겨둘수있어요.") if message.content.startswith("!") or message.content.startswith("+"): i = 1 while True: if message.author.id == "249706579912294400": break if sheet["A" + str(i)].value == message.author.id: if int(sheet["B" + str(i)].value) > int( datetime.datetime.today().strftime("%Y%m%d%H%M%S")): a = datetime.datetime.today() + datetime.timedelta( seconds=4) sheet["B" + str(i)].value = a.strftime("%Y%m%d%H%M%S") await client.send_message( message.channel, "<@" + str(message.author.id) + ">" + "명령어를 천천히 입력해주세요. 쿨타임: `4`초") file.save("쿨타임.xlsx") else: a = datetime.datetime.today() + datetime.timedelta( seconds=4) sheet["B" + str(i)].value = a.strftime("%Y%m%d%H%M%S") file.save("쿨타임.xlsx") break if sheet["A" + str(i)].value == None: a = datetime.datetime.today() + datetime.timedelta(seconds=4) sheet["A" + str(i)].value = str(message.author.id) sheet["B" + str(i)].value = a.strftime("%Y%m%d%H%M%S") file.save("쿨타임.xlsx") break i = i + 1 i = 1 while True: if sheet1["A" + str(i)].value == message.author.id: msg = "차단된 회원입니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) break if sheet["A" + str(i)].value == None: kk = 1 break i = i + 1 if kk == 1: if message.content.startswith('+unreal'): await client.send_message( message.channel, ":star: VIP버전 - 20유로 (2만 5,500원) 입니다.:asterisk: Premium버전 - 15유로 (1만 9,100원) 입니다." ) if message.content.startswith('+h4x'): await client.send_message( message.channel, ":star:VIP버전 - 12.99달러 (1만 4,607원) 입니다.") if message.content.startswith('+lolicon'): await client.send_message( message.channel, ":icecream:Ultimate버전 - 69.95유로 (9만 300원) 입니다.:icecream:Professional버전 - 49.95유로 (6만 4,400원) 입니다.:icecream:Lite 버전 - 19.95유로 (2만 5,700원) 입니다." ) if message.content.startswith('+maximus'): await client.send_message( message.channel, ":star:MAX RECOVERY 버전 - 99.90헤알 (3만 200원) 입니다.:star:Premium 버전 - 75.90헤알 (2만 3,000원) 입니다.:star:VIP 버전 - (1만 5,400원) 입니다." ) if message.content.startswith('+maximus 정보'): await client.send_message( message.channel, "```1) 환불 불가능.\n2) 막시무스 계정 공유 금지 \n3) 업데이트는 무료로 진행됨 " "\n4) MAX RECOVERY 버전은 라이센스가 3달로 제한되며, 3달마다 갱신할 수 있다." "\n5) VIP, PREMIUM 버전은 라이센스가 1년으로 제한되며, 갱신할 수 있다. " "\n6) VIP, PREMIUM 버전은 당신의 Social ID로 등록되며, " "그 ID로 막시를 사용하는 한 얼마든지 다른 컴퓨터에서도 접속이 가능하다. " "\n7) 막시무스는 GTA 온라인에서의 밴에 대한 어떤 책임도 지지 않는다.```") if message.content.startswith('+cubexis'): await client.send_message( message.channel, ":star:Platinum버전 - 29유로 (3만 7,460원) 입니다.") if message.content.startswith('+requiem'): await client.send_message( message.channel, ":icecream:레퀴엠 키 - 10달러 (약 1만 1,245원), :icecream:VIP 업그레이드 키 - 20달러 (2만 2,490원) 입니다." ) if message.content.startswith('+diablo'): await client.send_message( message.channel, ":star:VIP버전 - 15유로 (약 19,132원) 입니다.") if message.content.startswith('+phantom-x'): await client.send_message( message.channel, ":icecream:Premium+ Edition - 1,990 루블 (약 33,392원), :icecream:Standard Edition - 990 루블 (약 16,612원) 입니다." ) if message.content.startswith('+echo'): await client.send_message( message.channel, ":star:echo menu - 20달러 (약 2만 2600원) 입니다.") if message.content.startswith('+evolve'): await client.send_message(message.channel, "테이크 투 인터렉티브로 인해 막힘(구매 및 사용 불가)") if message.content.startswith('+maverick'): await client.send_message( message.channel, ":star:▪무료버전 : 무료 ▪유료버전 : 한 달에 5달러(약 5600원), 세 달에 10달러(약 11,100원), 평생버전 15달러(약 16,900원) ▪VIP평생버전 : 50달러(약 56,400원)" ) if message.content.startswith('+dynamic'): await client.send_message( message.channel, ":star:Premium 10.35파운드 (1만 5,035원) :star:VIP 15.40파운드 (2만 2,372원)" ) if message.content.startswith('+관리자'): if message.author.id == "249706579912294400": state = message.content.split(" ") file = openpyxl.load_workbook('상태.xlsx') sheet = file.active if sheet["A1"].value == str(state[1]): await client.send_message(message.channel, "이미 말씀하신 상태에요.") else: sheet["A1"].value = str(state[1]) await client.send_message( message.channel, "현재 상태를 " + str(sheet["A1"].value) + "중으로 바꿨습니다.") file.save('상태.xlsx') else: msg = "권한이 없습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) if message.content.startswith('+메시지'): if message.author.id == "249706579912294400": m = message.content[5:] m = m.replace("<@249706579912294400>", "") channel = client.get_channel("536203979428855818") await client.send_message(channel, message.author.name + ": " + m) await client.send_message(message.channel, "관리자방에 메시지를 보냈어요.") else: msg = "권한이 없습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) if message.content.startswith('+추방'): msg = message.content.split(" ") role = "" for i in message.server.roles: if i.id == "507513845225619456": role = i break msgg = msg[1][2:20] mem = message.server.get_member(msgg) if role in message.author.roles: await client.kick(mem) await client.send_message(message.channel, "회원을 추방했습니다.") else: msg = "권한이 없습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) if message.content.startswith('+출근'): msg1 = "출근 하셨습니다." embed = discord.Embed(description=msg1, color=0xf30adc) await client.send_message(message.channel, embed=embed) if message.content.startswith('+퇴근'): msg1 = "퇴근 하셨습니다." embed = discord.Embed(description=msg1, color=0xf30adc) await client.send_message(message.channel, embed=embed) if message.content.startswith('+휴가'): msg1 = "휴가중" embed = discord.Embed(description=msg1, color=0xf30adc) await client.send_message(message.channel, embed=embed) if message.content.startswith('+휴식'): msg1 = "힐링중" embed = discord.Embed(description=msg1, color=0xf30adc) await client.send_message(message.channel, embed=embed) if message.content.startswith('+문의받음'): msg1 = "다시 문의 받아요" embed = discord.Embed(description=msg1, color=0xf30adc) await client.send_message(message.channel, embed=embed) if message.content.startswith( '+공지') and not message.content.startswith('+공지설정'): if message.author.id == "249706579912294400": msg = message.content[23:] content = message.content.split(" ") channel = client.get_channel(content[1]) await client.send_message(channel, msg) msg1 = "공지를 전송했습니다." embed = discord.Embed(description=msg1, color=0x2ef079) await client.send_message(message.channel, embed=embed) else: msg = "권한이 없습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) if message.content.startswith("+전체공지"): if message.author.id == "249706579912294400": content = message.content[6:] file = openpyxl.load_workbook("가입서버.xlsx") sheet = file.active i = 1 while True: if sheet["B" + str(i)].value != None: channel = client.get_channel(sheet["B" + str(i)].value) await client.send_message(channel, content) else: break i += 1 msg = "전체공지를 전송했습니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) else: msg = "권한이 없습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) if message.content.startswith("+플레이중"): if message.author.id == "249706579912294400": await client.change_presence(game=discord.Game( name=str(message.content)[6:], type=1)) else: msg = "권한이 없습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) if message.content.startswith("+강화삭제"): if message.author.id == "249706579912294400": msg = message.content.split(" ") file = openpyxl.load_workbook("강화.xlsx") sheet = file.active i = 1 while True: if sheet["A" + str(i)].value == msg[1]: sheet["A" + str(i)].value = "-" sheet["B" + str(i)].value = "-" sheet["C" + str(i)].value = "-" sheet["D" + str(i)].value = "-" sheet["E" + str(i)].value = "-" file.save('강화.xlsx') if sheet["A" + str(i)].value == None: break i = i + 1 msg = "해당 아이디의 강화목록을 모두 삭제했습니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) else: msg = "권한이 없습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) if message.content.startswith("+강화초기화"): if message.author.id == "249706579912294400": file = openpyxl.load_workbook("강화.xlsx") sheet = file.active i = 1 while True: if sheet["A" + str(i)].value == None: break if sheet["A" + str(i)].value != None: sheet["A" + str(i)].value = None sheet["B" + str(i)].value = None sheet["C" + str(i)].value = None sheet["D" + str(i)].value = None sheet["E" + str(i)].value = None i = i + 1 file.save('강화.xlsx') msg = "강화목록을 초기화했습니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) else: msg = "권한이 없습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) if message.content.startswith( "+안내") and not message.content.startswith("+안내사항"): if message.author.id == "249706579912294400": msg = message.content[4:] f = open('안내.txt', 'w') f.write(msg) f.close() msg = "안내 메시지를 등록했습니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) else: msg = "권한이 없습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) if message.content.startswith('+차단'): if message.author.id == "249706579912294400": msg = message.content.split(" ") i = 1 while True: if sheet1["A" + str(i)].value == msg[1]: sheet1["A" + str(i)].value = "-" file1.save("밴.xlsx") msg = "차단을 해제했습니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) break if sheet1["A" + str(i)].value == None: sheet1["A" + str(i)].value = str(msg[1]) file1.save("밴.xlsx") msg = "이용자를 차단 했습니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) break i += 1 else: msg = "권한이 없습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) if message.content.startswith('+소개'): msg = "__**일반유저**__ 모두가 사용가능한 명령어" \ "\n`+도움말`" \ "\n`+일반명령어`" \ "\n`+음악명령어`" \ "\n`+게임명령어`" \ "\n\n__**서버소유자**__ 만 사용가능한 명령어" \ "\n`+공지설정 <채널명>`" \ "\n\n__**봇 소유자**__ 만 사용가능한 명령어" \ "\n`+관리자 <관리자상태>`" \ "\n`+플레이중 <내용>`" \ "\n`+공지 <채널id> <내용>`" \ "\n`+전체공지 <내용>`" \ "\n`+안내 <내용>`" \ "\n`+강화초기화`" \ "\n`+강화삭제 <유저id>`" \ "\n`+차단 <유저id>`" \ "\n`+서버삭제 <서버id>`" embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith('+도움말'): msg = "`+소개` - 봇을 소개합니다." \ "\n`+일반명령어` - 일반 명령어" \ "\n`+음악명령어` - 음악기능 명령어" \ "\n`+게임명령어` - 강화게임 명령어" \ "\n`+서버소유자명령어` - 서버 소유자 전용 명령어" embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith('+일반명령어'): msg = "**__일반 명령어__**" \ "\n`+안내사항` -> 공지나 안내메시지를 확인할수 있습니다." \ "\n`+회원가입` -> 봇에게 회원가입을 합니다." \ "\n`+가입회원` -> 가입한 회원수를 알려줍니다." \ "\n`+가입서버` -> 가입된 서버의 개수를 알려줍니다." \ "\n`+시간` -> 현재 시각을 알려줍니다." \ "\n`+검색 <내용>` -> 통합검색을 할 수 있습니다." \ "\n`+날씨 <지역>` -> 지역의 날씨를 말해줍니다." \ "\n`+초대` -> 초대링크를 받을수있습니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith('+게임명령어'): msg = "**__게임 명령어__**" \ "\n`+강화 <이름>` -> <이름>을 강화합니다." \ "\n`+강화랭킹` -> 현재서버 강화순위을 알려줍니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith('+음악명령어'): msg = "**__음악 명령어__**" \ "\n`+입장` -> 음성채널에 입장합니다." \ "\n`+재생 (URL 또는 곡명)` -> 노래를 재생합니다." \ "\n`+다음곡` -> 재생중인 노래를 넘기고 다음 노래를 재생합니다." \ "\n`+재생목록` -> 재생목록을 확인합니다." \ "\n`+중지` -> 노래를 일시정지 합니다." \ "\n`+중지해제` -> 일시정지한 노래를 다시 재생합니다." \ "\n`+끄기` -> 노래를 종료하고 음성채널을 나갑니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith('+서버소유자명령어'): msg = "**__서버 소유자 명령어__**" \ "\n`+공지설정 <채널명>` -> 공지가 전송되는 채널을 선택합니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith("+입장"): await client.send_message(message.channel, "보이스채널에 입장합니다.") if message.content.startswith("+끄기"): await client.send_message(message.channel, "보이스채널에서 퇴장합니다.") if message.content.startswith("+안내사항"): f = open("안내.txt") msg = f.read() f.close() embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith("+검색"): ss = message.content[4:] ss = ss.split(" ") loc = ss[0] for i in range(1, len(ss)): loc = loc + "+" + ss[i] search = message.content[ 7:] + "에 대한 검색결과입니다.\n\n[1. 지식백과](https://search.naver.com/search.naver?where=kdic&sm=tab_jum&query=" + loc + ")\n" + Knoledge.get_knoledge( loc )[:50] + "\n\n[2. 지식in](https://search.naver.com/search.naver?where=kin&sm=tab_jum&query=" + loc + ")\n" + AI.get_image( loc )[: 50] + "\n\n[3. 웹사이트](https://search.naver.com/search.naver?where=webkr&sm=tab_jum&query=" + loc + ")\n" + Dictionary.get_deng( loc)[:50] embed = discord.Embed(description=search, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith("+시간"): msg = str(datetime.datetime.today().year) + "년 " + str( datetime.datetime.today().month) + "월 " + str( datetime.datetime.today().day) + "일 " + str( datetime.datetime.today().hour) + "시 " + str( datetime.datetime.today().minute) + "분 " + str( datetime.datetime.today().second) + "초" embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith("+날씨"): loc = message.content.split(" ") temp = Weather.get_weather(loc[1] + " 날씨") embed = discord.Embed(description=temp, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith( "+서버삭제") and message.author.id == "249706579912294400": channel = message.content.split(" ") file = openpyxl.load_workbook("가입서버.xlsx") sheet = file.active i = 1 while True: if sheet["A" + str(i)].value == str(message.server.id): sheet["A" + str(i)].value = "-" sheet["B" + str(i)].value = "-" file.save('가입서버.xlsx') break if sheet["A" + str(i)].value == None: break i += 1 leave = client.get_server(str(channel[1])) await client.leave_server(leave) if message.content.startswith("+회원가입"): file = openpyxl.load_workbook("가입회원.xlsx") sheet = file.active i = 1 while True: if sheet["A" + str(i)].value == str(message.author.id): msg = "이미 가입된 회원입니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) break if sheet["A" + str(i)].value == None: num = int(sheet["C1"].value) + 1 sheet["A" + str(i)].value = str(message.author.id) sheet["C1"].value = int(sheet["C1"].value) + 1 msg = "**환영합니다! " + str(num) + "번째 회원입니다.**" embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) file.save('가입회원.xlsx') break i += 1 if message.content.startswith("+가입회원"): file = openpyxl.load_workbook("가입회원.xlsx") sheet = file.active msg = "현재 " + str(sheet["C1"].value) + "명이 회원가입을 했습니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith("+가입서버"): msg = "현재 가입한 서버는 " + str(len(client.servers)) + "개입니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) if message.content.startswith("+강화랭킹"): file = openpyxl.load_workbook("강화.xlsx") sheet = file.active list = [] i = 1 while True: if sheet["E" + str(i)].value == str(message.server.id): list.append( "Lv.%03d `" % int(sheet["C" + str(i)].value) + str(sheet["B" + str(i)].value) + "` " + discord.utils.get(client.get_all_members(), id=str(sheet[ "A" + str(i)].value)).name) if sheet["A" + str(i)].value == None: break i = i + 1 a, b, c, d, e = "-", "-", "-", "-", "-" list.sort(reverse=True) if len(list) == 0: a, b, c, d, e = "-", "-", "-", "-", "-" if len(list) == 1: a, b, c, d, e = list[0], "-", "-", "-", "-" if len(list) == 2: a, b, c, d, e = list[0], list[1], "-", "-", "-" if len(list) == 3: a, b, c, d, e = list[0], list[1], list[2], "-", "-" if len(list) == 4: a, b, c, d, e = list[0], list[1], list[2], list[3], "-" if len(list) == 5: a, b, c, d, e = list[0], list[1], list[2], list[3], list[4] mm = "1. " + a + "\n2. " + b + "\n3. " + c + "\n4. " + d + "\n5. " + e embed = discord.Embed(description=mm) await client.send_message(message.channel, embed=embed) if message.content.startswith( "+강화" ) and not message.content.startswith( "+강화랭킹") and not message.content.startswith( "+강화삭제") and not message.content.startswith("+강화초기화"): file = openpyxl.load_workbook("강화.xlsx") sheet = file.active item = message.content.split(" ") num = 0 i = 1 while True: if sheet["A" + str(i)].value == message.author.id: num = num + 1 if sheet["B" + str(i)].value == item[1]: if int(sheet["D" + str(i)].value) <= int( datetime.datetime.today().strftime( "%Y%m%d%H%M%S")): time = datetime.datetime.today( ) + datetime.timedelta(seconds=30) sheet["D" + str(i)].value = time.strftime( "%Y%m%d%H%M%S") level = int(sheet["C" + str(i)].value) rank = enforce.enf(level)[1] a = random.randint(1, 100) if a <= enforce.enf(level)[0]: up = random.randint(1, 30) level1 = level + up rank1 = enforce.enf(level + up)[1] sheet["C" + str(i)].value = level1 mm = "강화에 성공하였습니다.\n`%s` Lv.%s -> Lv.%s `%s` -> `%s`" % ( sheet["B" + str(i)].value, str(level), str(level1), rank, rank1) embed = discord.Embed(description=mm, color=0x2037bb) await client.send_message(message.channel, embed=embed) elif a > 95: sheet["C" + str(i)].value = "0" mm = "`%s`가 터졌습니다.\nLv.0 `알`" % sheet[ "B" + str(i)].value embed = discord.Embed(description=mm, color=0xee2f2f) await client.send_message(message.channel, embed=embed) else: down = random.randint(1, 25) level1 = level - down rank1 = enforce.enf(level - down)[1] sheet["C" + str(i)].value = level1 mm = "강화에 실패하였습니다.\n`%s` Lv.%s -> Lv.%s `%s` -> `%s`" % ( sheet["B" + str(i)].value, str(level), str(level1), rank, rank1) embed = discord.Embed(description=mm, color=0xee2f2f) await client.send_message(message.channel, embed=embed) file.save('강화.xlsx') break else: mm = "30초 쿨타임이 지나지 않았습니다." embed = discord.Embed(description=mm, color=0xee2f2f) await client.send_message(message.channel, embed=embed) break if sheet["A" + str(i)].value == None: if num == 2: msg = "강화 개수 제한이 꽉 찼습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed) else: sheet["A" + str(i)].value = str(message.author.id) sheet["B" + str(i)].value = item[1] sheet["C" + str(i)].value = 0 sheet["D" + str(i)].value = 0 sheet["E" + str(i)].value = str(message.server.id) mm = "`%s`를 새로 만들었습니다." % item[1] embed = discord.Embed(description=mm, color=0x2ef079) await client.send_message(message.channel, embed=embed) file.save('강화.xlsx') break i = i + 1 if message.content.startswith("+공지설정"): if message.author == message.server.owner: file = openpyxl.load_workbook("가입서버.xlsx") sheet = file.active msg = message.content.split(" ") channel = discord.utils.get(message.server.channels, name=msg[1]) i = 1 while True: if sheet["A" + str(i)].value == str( message.server.id) or sheet[ "A" + str(i)].value == None: sheet["A" + str(i)].value = str(message.server.id) sheet["B" + str(i)].value = str(channel.id) msg = "공지채널을 등록했습니다." embed = discord.Embed(description=msg, color=0x2ef079) await client.send_message(message.channel, embed=embed) file.save('가입서버.xlsx') break i += 1 else: msg = "권한이 없습니다." embed = discord.Embed(description=msg, color=0xee2f2f) await client.send_message(message.channel, embed=embed)
import sys import pickle from Weather import * from TestUtils import * # Track failures fails = 0 # DATA READ # Take first 100 entries for testing weatherFile = 'data/sample.txt' fileSlice = 100 weather = Weather(weatherFile, fileSlice) # DATA TREATMENT # zero any null gust measurements newG = ['0' if g == '-99999' else g for g in weather.getFeatureData('Gust')] weather.modify('Gust', newG) # remove any data with remaining null observations. weather.discard() # generate new pressure trend values pTType = ['F', 'S', 'R'] newPT = [ str(pTType.index(p) - 1) for p in weather.getFeatureData('Pressure Trend') ] weather.modify('Pressure Trend', newPT)
return (np.array(res[['coordsNowX','coordsNowY']])) disk_engine = sa.create_engine('sqlite:///c:\\tmp\\ais.db') fig, ax = plt.subplots() m = Basemap(projection='aeqd',lat_0=72,lon_0=29, resolution='l', llcrnrlon=15, llcrnrlat=69, urcrnrlon=38, urcrnrlat=74.6,area_thresh = 100,ax=ax) #matplotlib.pyplot.ion(); weatherData = Weather.loadWeather(m) numScenarios = 2920 #f = np.load("C:\\tmp\\w.npz") #wd = f['arr_0'][:numScenarios] #wsp = f['arr_1'][:numScenarios] #hs = f['arr_2'][:numScenarios] #print wsp[23,4,5],wd[23,4,5],hs[23,4,5] #print weatherData[23,4,5] minx, maxx, miny, maxy = (27686.0,848650.0,56061.0,645608.0)
def main(): data = extractor.loadStuySite() news = extractor.getNews(data[0]) schedule = extractor.getSchedule(data[1], data[2]) bellDay = extractor.getBellDay(schedule) gymDay = extractor.getGymDay(schedule) date = extractor.getDate() temp = Weather.getTemp() forecastCode = Weather.getForecast() forecastURL = url_for("static", filename="images/" + Weather.getForecastURL(forecastCode)) forecastString = Weather.getForecastString(forecastCode) delays = [] # MTAService.getDelays(MTAService.getSubways()) # detecting a mobile device user_agent_string = request.user_agent.string mobile_user_agent_families = [ "Firefox Mobile", "Opera Mobile", "Opera Mini", "Mobile Safari", "webOS", "IE Mobile", "Playstation Portable", "Nokia", "Blackberry", "Palm", "Silk", "Android", "Maemo", "Obigo", "Netfront", "AvantGo", "Teleca", "SEMC-Browser", "Bolt", "Iris", "UP.Browser", "Symphony", "Minimo", "Bunjaloo", "Jasmine", "Dolfin", "Polaris", "BREW", "Chrome Mobile", "UC Browser", "Tizen Browser", ] mobile_os_families = ["Windows Phone 6.5", "Windows CE", "Symbian OS", "iOS"] ua_family = user_agent_parser.ParseUserAgent(user_agent_string)["family"] os_family = user_agent_parser.ParseOS(user_agent_string)["family"] if ua_family in mobile_user_agent_families or os_family in mobile_os_families: return render_template( "mobile.html", news=news, schedule=schedule, bellDay=bellDay, gymDay=gymDay, date=date, temp=temp, forecastURL=forecastURL, forecastString=forecastString, delays=delays, ) else: return render_template( "home.html", news=news, schedule=schedule, bellDay=bellDay, gymDay=gymDay, date=date, temp=temp, forecastURL=forecastURL, forecastString=forecastString, delays=delays, )
def getReport(self): newWeather = Weather.Weather() self.weather = newWeather.getWeather() self.precipitation = newWeather.getPrecipitation() self.temperature = newWeather.getTemperature() del newWeather
import sys import tkinter as tk import weather as Weather w = Weather() avg_temp = lambda: w.query("SELECT AVG(temp) FROM weather")[0][0] min_temp = lambda: w.query("SELECT MIN(temp) FROM weather")[0][0] max_temp = lambda: w.query("SELECT MAX(temp) FROM weather")[0][0] all_temp = lambda: w.query("SELECT temp FROM weather") def gui(): root = tk.Tk() w.get_forecast_plot(root) avgL = tk.Label(root) avgL.pack() minL = tk.Label(root) minL.pack() maxL = tk.Label(root) maxL.pack() def set_labels(): avgL.config(text=f"Averge temperature: {avg_temp():.2f}") minL.config(text=f"Minimum temperature: {min_temp():.2f}") maxL.config(text=f"Maximum temperature: {max_temp():.2f}") def on_request_click():
def ambient(player, string): """Set the ambient colour""" import Weather Weather.weather().ambient(getV4FromString(string))
csv_path = './data/darksky_weather.csv' ################################################################ if __name__ == "__main__": config_path = locate_config(sys.argv) config = ConfigParser() config.read(config_path) api_key = config.get('Darksky', 'key') for c in city_names: city = City.City(c, state_name) forecast_handle = Weather.Weather(api_key) weather_forecast = forecast_handle.get_hourly_weather( city, start_date, end_date, True) if not os.path.isfile( r'/Users/sravichandran/Desktop/Sindu/Traffic/Data Scraping /output/weather_data_2015/darksky_2015.csv' ): weather_forecast.to_csv( r'/Users/sravichandran/Desktop/Sindu/Traffic/Data Scraping /output/weather_data_2015/darksky_2015.csv', index=None, header=True) else: weather_forecast.to_csv( r'/Users/sravichandran/Desktop/Sindu/Traffic/Data Scraping /output/weather_data_2015/darksky_2015.csv', mode='a', header=False)
# -*- coding: utf-8 -*- # Document as UTF-8 Document. import sys import time sys.path.append("Functions/Weather") import Weather sys.path.append("Functions/Logger") import logit sys.path.append("Functions/getProfileData") import profileData print("------------------------ Check Weather -----------------------") print("") location = "Haifa" weather = Weather.main(location) print("") print weather print("") logit.logger("Info","Test Module run out. ") print("") print ("--------------------------------------------------------------") print("") IMEI = "356516040249414" Fake_IMEI = "35651604000000" print ("------------ Get Profile Full Name by IMEI ------------------") print("")
# ''' This will be the main script to run, it will call the other scripts from here and do the layout''' # Import packages from tkinter import * from PIL import Image, ImageTk import os # Import scripts import Weather import DateTime import Location # Classes location = Location.Location() weather = Weather.Weather() date_time = DateTime.Date_Time() # tries to get the location, if it can't it'll return [None, None] lat_long = location.geo_location() # weather_currently = weather.get_weather(lat_long[0], lat_long[1])#if weather can't be fetched, return will be 'unknown' # print(weather_currently) print(date_time.get_date_time()) # text sizes xlarge_text_size = 94 large_text_size = 48 medium_text_size = 28 small_text_size = 18 # Colours
def Issue(eventId, eventArg=0): #ESP32_Server.EventHandler(eventId, eventArg) WifiSocket.EventHandler(eventId, eventArg) BluetoothSocket.EventHandler(eventId, eventArg) Weather.EventHandler(eventId, eventArg)
openGMail.openSiteGMail() elif 'time' in command: tellTime.sayTime() elif 'who are you' in command: defineYourself.defineYou() elif "camera" in command or "take a photo" in command: ec.capture(0, "robo camera", "img.jpg") elif 'on youtube' in command or 'from youtube' in command: ytSearch.searchingVideo(command) elif 'weather' in command: Weather.GetWeather() elif "restart" in command: restart.Logout() elif "hibernate" in command or "sleep" in command: hibernate.Logout() elif "log off" in command or "sign out" in command: LogOff.Logout() elif "where is" in command or "locate" in command: Maps.Maps(command) elif 'shutdown' in command or 'power off' in command: shutdown.Logout()
def update_weather(team, metric): if team: fig = Weather.start_time_chart(df, team, metric) return fig
fh.close() return chars def skewTime(h, m, s): return (h,m,s) # main loop chars = parseChars("clock_chars.txt") colon = chars[":"] display = Display() # load messenger module messenger = Messenger.Messenger(display) weather = Weather.Weather(messenger) #weather.showToday() #messenger.showNews() prev_min = 0 next_pos = 1 + (int)(random.random() * 10) counter = 0 off_x = 0 off_y = 0 while(1): counter = counter + 1 if counter == next_pos: if counter % 3 == 0: weather.showTemperature()
Plotting error versus estimation length (day of year) Created on Fri Nov 10 19:27:07 2017 @author: dan """ import matplotlib.pyplot as plt import datetime as dt import pandas as pd import numpy as np import Weather as wx plt.style.use('weather') df = wx.WxDF() fig = plt.figure(16) fig.clear() ax = fig.add_subplot(111) yr = 2016 col = df.columns[8] actual = df.loc[df.Year == yr, col].mean() ax.axhline(actual, ls='--', lw=1, color='C1', label='Actual Average Temperature') df['dy'] = df.index.dayofyear
def morning_greetings(): speech.say ("Good Morning.") speech.say(" It is "+''.join(getCurrentTime())) speech.say(Weather.getCurrentWather()) check_mails()
# houses pipe houses_pipes = [multiprocessing.Pipe() for i in range(numberOfHouses)] ###MAIN choice = input( "If you want to follow the evolution of all the houses during the simulation, type y.\n>" ) marketProcess = Market.Market(externalFactors, lockExternal, globalNeed, lockGlobalNeed, payableEnergyBank, lockPayable, clocker, weather, market_conn) print("Starting market") marketProcess.start() weatherProcess = Weather.Weather(weather, clocker, day) print("Starting weather") weatherProcess.start() houses = [ House.House(i, clocker, weather, lockHouse, houses_pipes[i][1]) for i in range(numberOfHouses) ] print("Starting every Houses") for k in houses: k.start() tickProcess = Clock.Clock(clocker) print("Starting the clock") tickProcess.start()
def search(): if request.method == 'POST': active = Database.ActiveUser() id = active.getActiveUser() logstate = "" if id == "None": logstate = False else: logstate = True location = request.form['search'] value = request.form['Gender'] geocode = Geocoding.Geocoding() latlon = geocode.getLocation(location) lat = str(latlon["lat"]) long = str(latlon["lng"]) weather = Weather.Weather() weather.getAllInfo(lat, long) day = datetime.datetime.now().strftime("%A") t = datetime.datetime.now().time().strftime("%I:%M %p") date = str(day) + " " + str(t) description = weather.getDescription() # "Mostly Cloudy" description_list = description.split(" ") new_description = "" for word in description_list: word = word[0:1].upper() + word[1:] new_description = new_description + word + " " description = new_description current = weather.getCurrent() high = weather.getHigh() # "58 F" low = weather.getLow() # "39 F" humidity = weather.getHumidity() # "55%" wind = weather.getWind() # "20 mph" icon = weather.getIcon() if value == "Men": alchemy = AlchemyOutlook.Alchemy(location, value) pictures = alchemy.getPictures() return render_template("search.html", location=location.upper(), date=date, description=description, current=current, high=high, low=low, humidity=humidity, wind=wind, icon=icon, pictures=pictures, logstate=logstate) elif value == "Women": alchemy = AlchemyOutlook.Alchemy(location, value) pictures = alchemy.getPictures() return render_template("search.html", location=location.upper(), date=date, description=description, current=current, high=high, low=low, humidity=humidity, wind=wind, icon=icon, pictures=pictures, logstate=logstate) else: return render_template("search.html", test=value, t=t)
def Forecast(self): return Weather.GetWeather(city_code1) # get weather data
def __millis(): dt = datetime.now() ms = (dt.day * 24 * 60 * 60 + dt.second) * 1000 + dt.microsecond / 1000.0 return ms gpsDevice = '/dev/ttyUSB0' arduinoDevice = "/dev/ttyUSB1" gps = Devices.GPS(gpsDevice) arduino = Devices.Arduino(arduinoDevice) location = '/home/pi/Thesis/data/' file = "configlist.csv" rain = Weather.Rainfall() envdata = Weather.OWMData() owndata = Weather.OwnWeather('http://192.168.1.53:500') rownum = 2 ##todo check if file exists ##todo also check if 2.csv exists. Exit on both cases with open(location + file, "a+") as writefile: configFile = csv.writer(writefile, delimiter=",") ConfigMaker = Configs.RandomConfig(offlineOnly=False) # Note: all thoughout this file I didn't use f formatting/any normal string formatting # There was a reason that I did this, but I can't remember why on reflection # I'm pretty sure it was because what I was doing kept changing, and I never went back to pretty it up. completeheaders = str( "Row") + "," + ConfigMaker.returnHeaders() + ",owntemp,ownhumidity"+\
def main(): greet() while True: userQuery = input_command().lower() # if "What can you do?" in userQuery: # speak("I can send email for you, check weather of any city you want, play any song or check your internet " # "speed") if 'thank you' in userQuery: speak("You're Welcome. I am happy to assist you") elif 'internet speed' in userQuery: speed = SpeedTest.check_speed() speak(speed) elif 'how are you' in userQuery: speak('I am very well.') speak('What can i do for you?') print( 'try speaking \'send email\', \'tell me a joke\', \'latest news\', ' ) # noinspection SpellCheckingInspection elif 'wikipedia' in userQuery: userQuery = userQuery.replace("wikipedia", "") if userQuery == "": speak("what exactly do you want to search") else: result = wikipedia.summary(userQuery, sentences=3) speak("According to wikipedia") print(result) speak(result) elif 'launch' in userQuery: regex = re.search('launch (.*)', userQuery) if regex: app = regex.group(1) if 'vs code' in userQuery: speak("Opening VS Code") os.startfile('C:\\Users\\path to\\Code.exe') elif 'pycharm' in userQuery: speak("Opening Pycharm") os.startfile('"C:\\Program Files\\path to\\pycharm64.exe"') else: os.startfile(f'C:\\{app}.exe') elif 'time' in userQuery: time = datetime.datetime.now().strftime('%H:%M') speak('current time in 24 hour format is:' + time) elif 'open reddit' in userQuery: regex = re.search('open reddit (.*)', userQuery) url = 'https://www.reddit.com/' if regex: subreddit = regex.group(1) url = url + 'r/' + subreddit webbrowser.open(url) speak('The Reddit content has been opened for you.') # opening any website elif 'open' in userQuery: regex = re.search('open (.+)', userQuery) if regex: domain = regex.group(1) if '.com' in domain: url = 'https://www.' + domain webbrowser.open(url) speak(f'Opening {domain}...') else: url = 'https://www.' + domain + '.com' webbrowser.open(url) speak(f'Opening {domain}.com...') elif 'send email' in userQuery: conn = sqlite3.connect('Database.db') c = conn.cursor() c.execute( ''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='contacts' ''' ) if c.fetchone()[0] != 1: c.execute( '''CREATE TABLE contacts (name text primary key, email text)''' ) conn.commit() speak('Who do you want to send an email to?') user = input_command().lower() try: c.execute('SELECT * FROM contacts WHERE name =?', (user, )) name = c.fetchone() if name: speak(f"What do you want to say to {user}") message = input_command() send_email(users[user], message) speak(f'email sent to {user}') else: raise Exception except: speak( "email account of this user is not available, please type the email below" ) email = input("Email: ") speak(f"What do you want to say to {user}") message = input_command() send_email(email, message) speak(f'email sent to {user}') speak("do you want me to save this email for future usage?") ch = input_command() if "yes" in ch.lower(): c.execute('INSERT INTO contacts values(?, ?)', (user, email)) conn.commit() else: speak('email is not saved') elif "weather" in userQuery: speak("Which city?") city = input_command() speak("Current weather in " + city + Weather.weather(city)) elif 'play a song' in userQuery or 'play song': speak('What song do you want to play?') mySong = input_command() speak(f"Searching {mySong} on youtube...") # noinspection SpellCheckingInspection if mySong: flag = 0 url = "https://www.youtube.com/results?search_query=" + mySong.replace( ' ', '+') html = urllib.request.URLopener.urlopen(url) soup1 = re.findall(r"watch\?v=(\S{11})", html.read().decode()) url_list = [] # for vid in soup1: vid = soup1[0] print(vid) if ('https://www.youtube.com/watch?v=' + vid).startswith("https://www.youtube.com/watch?v="): flag = 1 final_url = 'https://www.youtube.com/watch?v=' + vid url_list.append(final_url) url = final_url # ydl_opts = {} # os.chdir(r'C:\Users\aakas\desktop') # with youtube_dl.YoutubeDL(ydl_opts) as ydl: # ydl.download([url]) # # vlc.play(os.path) if flag == 0: speak('I have not found anything on Youtube ') else: speak(f"playing {mySong} on youtube") webbrowser.open(url) exit() else: speak("Sorry didn't get that") input_command()
def get_weather_code_for_location(lat, lon, unix_time): result = Weather.get_weather_for_location(lat, lon, unix_time) return result[0]
class Rounds(object): def __init__(self,our_tm,enemy_tm): self.our_tm=our_tm self.enemy_tm=enemy_tm self.our_skill=None self.enemy_skill=None self.our_life_line=True self.enemy_life_line=True self.weather=Weather() self.first=True self.ml=music_list() def Run(self): ''' 回合制战斗 ''' Console.start_game(self.our_tm,self.enemy_tm) while True: #检查结束 if self._CheckTeam(): self._Exit() break # print('start') self._Start() # print('choose') if self._Choose()=='END': self._Exit() break # print('fight') self._Fight() self._End() # rest() def _Exit(self): self.ml.pause_music() music_manager.stop() def _Start(self): if self.first: self.first=False self.ml.append_music(pk_path+'Global/music/golden_fight_start.mp3') self.ml.append_music(pk_path+'Global/music/golden_fight_repeat.mp3',True) rest(1.5) Console.msg('开战了!') rest(1.5) self._Admission(self.our_tm) rest(1.5) self._Admission(self.enemy_tm) else: our_pm=self.our_tm.pm_list.Front() enemy_pm=self.enemy_tm.pm_list.Front() is_enemy_admission=False is_our_admission=False if not our_pm.IsAlive(): is_our_admission=True if not enemy_pm.IsAlive(): is_enemy_admission=True if is_our_admission or is_enemy_admission: if our_pm.IsAlive(): self._ReduceCondRound(our_pm) elif enemy_pm.IsAlive(): self._ReduceCondRound(enemy_pm) while(True): if self.our_tm.pm_list.SwitchPM(): is_our_admission=True break if not is_our_admission: break if is_enemy_admission: for pm in self.enemy_tm.pm_list: if pm.IsAlive() and TypeChart.TypeVSType(our_pm.type,pm.type)[0]<=2: self.enemy_tm.pm_list.Choose(pm) is_enemy_admission=True break #如果没有合适的属性的宝可梦,则让第一只活着的宝可梦上场 if not self.enemy_tm.pm_list.Front().IsAlive(): self.enemy_tm.pm_list.Choose(self.enemy_tm.pm_list.FirstAlive()) if is_our_admission: self._Admission(self.our_tm) if is_enemy_admission: self._Admission(self.enemy_tm) def _Choose(self): ''' 选择攻击、道具或者交换宝可梦 ''' self.our_skill=None self.enemy_skill=None our_pm = self.our_tm.pm_list.FirstAlive() enemy_pm=self.enemy_tm.pm_list.FirstAlive() #我方选择 if our_pm.special_cond.Check(SpecialCondEnum.FORCED): self.our_skill=our_pm.last_round.src_skill else: while(True): Console.refresh(is_clean_total=True) Console.msg('[1] 战斗') Console.msg('[2] 背包') Console.msg('[3] 精灵') Console.msg('[4] 逃跑') choice=input('请选择你要进行的操作:') choice=a2i(choice,1,4) if choice<4 and choice>=0: if choice == 0: retval = SkillChoose(our_pm) if retval!=None: self.our_skill=retval break elif choice == 1: if self.our_tm.package.Open(self.our_tm.pm_list): break elif choice == 2: if our_pm.special_cond.Check(SpecialCondEnum.BOUND): Console.msg(our_pm.GetName()+'被束缚,无法下场') continue if self.our_tm.pm_list.SwitchPM(): self._Admission(self.our_tm) break elif choice == 3: if ToBeSure('逃跑'): return 'END' else: pass #敌方选择 self._EnemyScriptChoose() Console.refresh(is_clean_total=True) return '' # print('Skills') # print(self.our_skill) # print(self.enemy_skill) def _Admission(self,team): ''' 宝可梦入场 ''' # rest() pokemon=team.pm_list.FirstAlive() if pokemon!=None: team.player.Speak('就决定是你了(゜-゜)つロ— '+pokemon.GetName()+'!') return pokemon def _UseProps(self): ''' 道具使用阶段 ''' pass def _Fight(self): ''' 1.使用招式阶段 2.判断宝可梦状态 3.招式负面效果发动 ''' our_pm = self.our_tm.pm_list.FirstAlive() enemy_pm=self.enemy_tm.pm_list.FirstAlive() if self.our_skill==None: if self.enemy_skill==None: pass else: self._CheckAndApplySkill(self.enemy_skill,enemy_pm,our_pm,self.weather,self.enemy_tm,self.our_tm) else: if self.enemy_skill==None: self._CheckAndApplySkill(self.our_skill,our_pm,enemy_pm,self.weather,self.our_tm,self.enemy_tm) else: if self.enemy_skill.GetPriority()>self.our_skill.GetPriority(): self._CheckAndApplySkill(self.enemy_skill,enemy_pm,our_pm,self.weather,self.enemy_tm,self.our_tm) self._CheckAndApplySkill(self.our_skill,our_pm,enemy_pm,self.weather,self.our_tm,self.enemy_tm) elif self.enemy_skill.GetPriority()<self.our_skill.GetPriority(): self._CheckAndApplySkill(self.our_skill,our_pm,enemy_pm,self.weather,self.our_tm,self.enemy_tm) self._CheckAndApplySkill(self.enemy_skill,enemy_pm,our_pm,self.weather,self.enemy_tm,self.our_tm) else: our_speed = our_pm.Speed() enemy_speed = enemy_pm.Speed() if our_speed*our_pm.stage.Get(StageEnum.SPEED) > enemy_speed*enemy_pm.stage.Get(StageEnum.SPEED): self._CheckAndApplySkill(self.our_skill,our_pm,enemy_pm,self.weather,self.our_tm,self.enemy_tm) self._CheckAndApplySkill(self.enemy_skill,enemy_pm,our_pm,self.weather,self.enemy_tm,self.our_tm) elif enemy_pm.status_cond==StatusCondEnum.PARALYSIS: self._CheckAndApplySkill(self.our_skill,our_pm,enemy_pm,self.weather,self.our_tm,self.enemy_tm) self._CheckAndApplySkill(self.enemy_skill,enemy_pm,our_pm,self.weather,self.enemy_tm,self.our_tm) elif our_pm.status_cond==StatusCondEnum.PARALYSIS: self._CheckAndApplySkill(self.enemy_skill,enemy_pm,our_pm,self.weather,self.enemy_tm,self.our_tm) self._CheckAndApplySkill(self.our_skill,our_pm,enemy_pm,self.weather,self.our_tm,self.enemy_tm) elif our_speed*our_pm.stage.Get(StageEnum.SPEED) < enemy_speed*enemy_pm.stage.Get(StageEnum.SPEED): self._CheckAndApplySkill(self.enemy_skill,enemy_pm,our_pm,self.weather,self.enemy_tm,self.our_tm) self._CheckAndApplySkill(self.our_skill,our_pm,enemy_pm,self.weather,self.our_tm,self.enemy_tm) else: if our_speed > enemy_speed: self._CheckAndApplySkill(self.our_skill,our_pm,enemy_pm,self.weather,self.our_tm,self.enemy_tm) self._CheckAndApplySkill(self.enemy_skill,enemy_pm,our_pm,self.weather,self.enemy_tm,self.our_tm) elif our_speed < enemy_speed: self._CheckAndApplySkill(self.enemy_skill,enemy_pm,our_pm,self.weather,self.enemy_tm,self.our_tm) self._CheckAndApplySkill(self.our_skill,our_pm,enemy_pm,self.weather,self.our_tm,self.enemy_tm) else: self._CheckAndApplySkill(self.our_skill,our_pm,enemy_pm,self.weather,self.our_tm,self.enemy_tm) self._CheckAndApplySkill(self.enemy_skill,enemy_pm,our_pm,self.weather,self.enemy_tm,self.our_tm) our_pm = self.our_tm.pm_list.Front() enemy_pm=self.enemy_tm.pm_list.Front() #招式负面效果发动 if our_pm.IsAlive(): self._NegativeEffect(our_pm,enemy_pm) if enemy_pm.IsAlive(): self._NegativeEffect(enemy_pm,our_pm) def _NegativeEffect(self,pm,opposite_pm): if pm.status_cond.Check(StatusCondEnum.POISON): Console.msg(pm.GetName()+pm.status_cond.Discription()) ApplyDamage(pm,pm.HP()*1/8) elif pm.status_cond.Check(StatusCondEnum.BADLYPOISON): Console.msg(pm.GetName()+pm.status_cond.Discription()) time=pm.status_cond.LastTime()+1 if time>15: time=15 ApplyDamage(pm,pm.HP()*time/16) elif pm.status_cond.Check(StatusCondEnum.BURN): Console.msg(pm.GetName()+pm.status_cond.Discription()) ApplyDamage(pm,pm.HP()*1/16) if pm.special_cond.Check(SpecialCondEnum.PARASITIC): Console.msg(pm.GetName()+SpecialCondEnum.Discription(SpecialCondEnum.PARASITIC)) ApplyDamage(pm,pm.HP()*1/16) if opposite_pm.IsAlive(): Console.msg(opposite_pm.GetName()+'吸收了力量,回复了'+RecoverHP(opposite_pm,pm.HP()*1/16)+'点HP') def _End(self): ''' 1.天气变化 2.回合结束 ''' our_pm = self.our_tm.pm_list.Front() enemy_pm=self.enemy_tm.pm_list.Front() #状态数减1 self._ReduceCondRound(our_pm) self._ReduceCondRound(enemy_pm) if self.weather!=None: last_weather=self.weather.Get() self.weather.Reduce() if self.weather!=last_weather: Console.msg(self.weather.Discription()) else: if self.weather.IsNormal(): pass else: Console.msg(self.weather.Discription()) def _ReduceCondRound(self,pm): if pm.IsAlive(): retval=pm.status_cond.Reduce() if retval!='': Console.msg(pm.GetName()+retval) is_forced_before=pm.special_cond.Check(SpecialCondEnum.FORCED) retval=pm.special_cond.Reduce() if retval!='': Console.msg(pm.GetName()+retval) is_forced_later=pm.special_cond.Check(SpecialCondEnum.FORCED) if is_forced_before and not is_forced_later and pm.last_round.src_skill !=None and pm.last_round.src_skill.GetName()=='大闹一番': Console.msg(pm.GetName()+'闹得头晕目眩') SkillBase.CauseSpecialCond(pm,1,SpecialCondEnum.CONFUSION) def _CheckTeam(self): ''' 检查战斗是否结束 ''' end=True for pm in self.enemy_tm.pm_list: if pm.hp>0: end=False if end==True: music_name=self.ml.top().get_music() music_name=music_name[music_name.rfind('/')+1:] if music_name == 'golden_fight_start.mp3': self.ml.play_next() self.ml.append_music(pk_path+'Global/music/golden_fight_win.mp3') self.ml.play_next() Console.msg('***************',sleep_time=0.5) Console.msg('你赢得了胜利!',sleep_time=0.5) Console.msg('***************',sleep_time=0.5) return True end=True for pm in self.our_tm.pm_list: if pm.hp>0: end=False if end==True: Console.msg('你输了...') return True return end def _CheckAndApplySkill(self,skill,src,target,weather,src_tm,target_tm): status=src.status_cond damage=0 apply_flag=True if not(src.IsAlive() and target.IsAlive()): return False if not StatusCondEnum.IsNormal(status): if status==StatusCondEnum.PARALYSIS: if np.random.rand()<0.25: Console.msg(src.GetName()+src.status_cond.Discription()) apply_flag=False elif status==StatusCondEnum.SLEEP: Console.msg(src.GetName()+src.status_cond.Discription()) apply_flag=False elif status==StatusCondEnum.FREEZE: Console.msg(src.GetName()+src.status_cond.Discription()) apply_flag=False special_cond=src.special_cond if special_cond.Check(SpecialCondEnum.STIFF): Console.msg(src.GetName()+SpecialCondEnum.Discription(SpecialCondEnum.STIFF)) apply_flag=False elif special_cond.Check(SpecialCondEnum.CONFUSION): Console.msg(src.GetName()+'混乱了') if np.random.rand()<0.5: Console.msg(src.GetName()+SpecialCondEnum.Discription(SpecialCondEnum.CONFUSION)) damage=SelfHarm().Apply(src,src,weather,is_print=False) apply_flag=False if apply_flag: damage=skill.Apply(src,target,weather) if target.IsAlive(): if target.last_round.src_skill!=None and damage>0 and target.last_round.src_skill.GetName()=='愤怒': Console.msg(target.GetName()+'被激怒了') Console.msg(target.GetName()+target.stage.Up(StageEnum.ATTACK,1)) target.last_round.target_skill=skill target.last_round.suffer_damage=damage if src.IsAlive(): src.last_round.src_skill=skill if skill.GetName()=='吹飞' or skill.GetName()=='吼叫': Console.msg(target.GetName()+'被强制下场') target_tm.pm_list.Choose(target_tm.pm_list.LastAlive()) self._Admission(target_tm) def _EnemyScriptChoose(self): our_pm = self.our_tm.pm_list.FirstAlive() enemy_pm=self.enemy_tm.pm_list.FirstAlive() effect,effect_str=TypeChart.TypeVSType(our_pm.type,enemy_pm.type) if np.random.rand()<0.33333: self.enemy_tm.player.MockingOnFighting() if enemy_pm.special_cond.Check(SpecialCondEnum.FORCED): self.enemy_skill=enemy_pm.last_round.src_skill return True else: #优先换精灵 if effect>2 and np.random.rand()<0.6: if not enemy_pm.special_cond.Check(SpecialCondEnum.BOUND): for i,pm in enumerate(self.enemy_tm.pm_list): if pm.IsAlive() and TypeChart.TypeVSType(our_pm.type,pm.type)[0]<=2: self.enemy_tm.player.Speak('下来吧'+self.enemy_tm.pm_list.FirstAlive().GetName()) self.enemy_tm.pm_list.Swap(0,i) self._Admission(self.enemy_tm) enemy_pm=pm return True #其次是使用药物 if enemy_pm.IsAlive() and enemy_pm.hp<enemy_pm.HP()*0.25 and np.random.rand()<1/3: medicine=FullRestore(1) self.enemy_tm.player.Speak('对'+enemy_pm.GetName()+'使用了'+medicine.GetName()) medicine.Use(enemy_pm) return True #最后是选择招式 self.enemy_skill=self._EnemyScriptSkillChoose() return True def _EnemyScriptSkillChoose(self): our_pm = self.our_tm.pm_list.FirstAlive() enemy_pm=self.enemy_tm.pm_list.FirstAlive() choice=[0 for i in range(len(enemy_pm.skills))] struggle_flag=True for i,skill in enumerate(enemy_pm.skills): if skill.pp>0: struggle_flag=False income=0 if skill.IsHit(enemy_pm,our_pm,self.weather): if skill.GetPower()>0: income=skill.DamageCal(enemy_pm,our_pm,self.weather,is_print=False)*skill.GetHit()/100 if isinstance(skill,ReboundSkill) or isinstance(skill,SelfLossSkill): income=income-enemy_pm.hp*skill.percent elif isinstance(skill,FixDamageSkill): income=skill.damage*skill.GetHit()/100 elif isinstance(skill,StockpileSkill): income=income/2 elif isinstance(skill,MustKillSkill): income=our_pm.hp*(30+enemy_pm.level-our_pm.level)/100 elif isinstance(skill,MultiHitSkill): income=income*3.168 elif isinstance(skill,AbsorbSkill): income=income+income*skill.percent else: obj_of_action=skill.GetObjOfAction() if obj_of_action & ObjOfAction.SRC: if skill.GetPower()>0: income = income-30*np.random.randint(50,100)/100 else: income = income+30*np.random.randint(50,100)/100 if obj_of_action & ObjOfAction.SRC_ABL: if enemy_pm.stage.Mean()<=0: income = income+30*np.random.randint(50,100)/100*skill.effect else: income = income+15*np.random.randint(50,100)/100*skill.effect if obj_of_action & ObjOfAction.TAR_ABL: if our_pm.stage.Mean()>=0: income = income+30*np.random.randint(50,100)/100 else: income = income+15*np.random.randint(50,100)/100 choice[i]=income*np.random.randint(80,100)/100 else: choice[i]=-1 if struggle_flag: return Struggle() else: return enemy_pm.skills[np.argmax(choice)]
import datetime import mraa import time import json #outfit chooser from Outfit import * #weather finder from Weather import * #email import emailBot w = Weather("toronto", "canada") wDict = w.getDict() print(wDict) o = Outfit(wDict) print(o.outfit) buzz = mraa.Gpio(31) button = mraa.Gpio(29) buzz.dir(mraa.DIR_OUT) button.dir(mraa.DIR_IN) buzz.write(0)
- Example routines to add new secondary features to the observation list """ # Weather data is accessed through an instantation of the provided `Weather` class. from Weather import * # Create a new object (e.g. `weather`) of type `Weather`. # # As part of the instantiation provide: # - weatherFile: The filename (either basic.txt or advanced.txt) # - fileSlice: The number of lines to read from the chosen input file (0 is all) # # Use the fileSlice to limit the sample size for early evaluation weatherFile = 'data/sample.txt' fileSlice = 0 weather = Weather(weatherFile, fileSlice) # Recovering Incomplete Data # # Some of the observation values have a value of `-99999` # This is a default value I inserted to indicate that the feature data was either not collected # at the time of the observation or had a null value. # # Any data points that contain null observations need to be corrected to avoid problems # with subsequent filtering and modifications. # # In some cases null values can either be interpolated or set to a default value. # # The large majority of null data is from the `Gust` measurement. # Here I assume than no observation is the same as a zero value
def assistant(command): "if statements for executing commands" if 'open reddit' in command: reg_ex = re.search('open reddit (.*)', command) url = 'https://www.reddit.com/' if reg_ex: subreddit = reg_ex.group(1) url = url + 'r/' + subreddit webbrowser.open(url) print('Done!') elif 'open website' in command: reg_ex = re.search('open website (.+)', command) if reg_ex: domain = reg_ex.group(1) url = 'https://www.' + domain webbrowser.open(url) print('Done!') else: pass elif 'what\'s up' in command: talkToMe('Just doing my thing') 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)) elif 'email' in command: talkToMe('Who is the recipient?') recipient = myCommand() if 'John' in recipient: 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 mail.login('username', 'password') #send message mail.sendmail('John Fisher', '*****@*****.**', content) #end mail connection mail.close() talkToMe('Email sent.') elif 'open youtube' in command: webbrowser.open("youtube.com") elif 'exit program' in command: talkToMe('Goodbye, I am shutting down.') sys.exit() else: talkToMe('I don\'t know what you mean!')
def fog(player, string): """Set the fog colour and density, from 1 (normal) to 10 (very dense)""" import Weather Weather.weather().fog(getV4FromString(string))
from Weather import * ## Step 2 - Load Weather data # # Create a new object (e.g. `weather`) of type `Weather`. # # As part of the instantiation provide: # - weatherFile: The filename (either basic.txt or advanced.txt) # - fileSlice: The number of lines to read from the chosen input file (0 is all) # # Use the fileSlice to limit the sample size for early evaluation weatherFile = 'data/basic.txt' fileSlice = 0 weather = Weather(weatherFile, fileSlice) ## Step 3 - Inspect the Data print '#' * 50 print '# Step 3: Inspect the Data' print '#' * 50 print '\n' # print data print 'Weather Data:' print weather.data # print number of entries print 'Number of entries: %s' % (weather.getNrEntries())
def sunlight(player, string): """Set the sunlight colour""" import Weather Weather.weather().sun(getV4FromString(string))
import subprocess as sp import random import os import Weather import datetime # test t_delta = datetime.timedelta(hours=9) JST = datetime.timezone(t_delta, 'JST') now = datetime.datetime.now(JST) print(now) # print('直近の天気を調べるね') order = 0 wd = Weather.Weather() Say = wd.getLocation()+'の'+wd.getDate(order)+'の天気は['+wd.getWeathers(order)+']だよ' if(wd.getDate(0)=='None' or wd.getWeathers(order)=='None'): Say = '何もみえないよ。' #Say = '天気予報機能は現在メンテナンス中だよ' Num = str(random.randint(0,1)) #Python3;.9~ #dirname=os.path.dirname(__file__) #Python~3.8 dirname=os.path.dirname(os.path.abspath(__file__)) shellpath=dirname+'/ShikimiShellArt.sh' sp.Popen([shellpath,Num,Say],cwd=dirname)
def rain(player, string): """Set the rain amount, from 0 to 1""" import Weather Weather.weather().rain(float(string))
HOSTNAME = 'inductor.eecs.umich.edu' PORT = 4001 HOUR = 3600 print os.getcwd() while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', 10002)) pid = 'nghjDMLmHY' while True: Weather.fetch() station = Weather.Station('KARB') m = dict(station.items()) s.sendto(pid + json.dumps(m), (HOSTNAME, PORT)) time.sleep(HOUR) except Exception, e: print "Suppressed excpetion", e time.sleep(5)