예제 #1
0
    def test_get_weather(self):
        """
        The 'weather' variable is manually written each day to match with 
            getWeather() return value
        """
        curr_forecast = getWeather(zipcode)
        weather = "The weather in Greenville, NC is clear sky.\nThe temperature is currently 49 *F with a high of 50 *F and a low of 28 *F.\nThe wind speed is 6 MPH.\n"

        self.assertEqual(weather, getWeather(zipcode))
        self.assertNotEqual("The weather today is", curr_forecast)
예제 #2
0
def pogoda():
    if (0, 0, 0) == weather.getWeather(weather.place):
        print("Нет погоды")
        return
    temp, perc, wind = weather.getWeather(weather.place)
    print(
        "Сегодняшняя средняя погода: T: %.1f  Осадки: %.1f  Ветер: %.1f м/c" %
        (temp, perc, wind))
    #print("погода в Сочи: T: {:.1f}  Осадки: {:.1f} Ветер: {:.1f} м/c".format(weather.getWeather(weather.place2)))
    print("Запишу погоду на сегодня для статистики в ~/weather.cvs")
    dmy = exc('date +%d.%m.%Y')
    with open(weather_csv, 'at') as fout:
        fout.write(dmy + "|%.1f|%.1f|%.1f\n" % (temp, perc, wind))
예제 #3
0
def alert(classList):
    global alarmRangDate
    isTrueEating = list(filter(lambda x: x == 1, classList))
    alarmDidNotRingToday = True if (
        alarmRangDate != datetime.today().date()) else False
    if (alarmDidNotRingToday and (len(isTrueEating) > 4)):
        alarmRangDate = datetime.today().date()
        log([
            'Alert sound............', 'classList=', classList,
            'isTrueEating=', isTrueEating
        ])
        play_mp3()
        weather.getWeather()
예제 #4
0
 def get_data(self):
     data_set = np.empty([self.id_time_map[1].shape[0], 3])
     for i in range(0, data_set[:,0].size):
         data_set[i,0] = weekday(self.id_time_map[1][i])
         data_set[i,1] = hour_of_day(self.id_time_map[1][i])
         data_set[i,2] = getWeather(self.id_time_map[1][i],'London')
     return data_set
예제 #5
0
def format_status():
	symbolLookup = {
	    'clear':u'\u263C',
	    'partly sunny':u'\u2600',
	    'scattered thunderstorms':u'\u2602',
	    'showers':u'\u2602',
	    'scattered showers':u'\u2602',
	    'overcast':u'\u2601',
	    'chance of rain':u'\u2601',
	    'sunny':u'\u2600',
	    'mostly sunny':u'\u2600',
	    'partly cloudy':u'\u2601',
	    'mostly cloudy':u'\u2601',
	    'chance of storm':u'\u2601',
	    'rain':u'\u2602',
	    'chance of snow':u'\u2603',
	    'cloudy':u'\u2601',
	    'mist':u'\u2601',
	    'storm':u'\u2601',
	    'thunderstorm':u'\u2602',
	    'chance of tstorm':u'\u2602',
	    'light rain':u'\u2602'
	}

	weatherString = weather.getWeather("Kochi")
	return symbolLookup[weatherString.lower()]
예제 #6
0
    def update_weather(self):
        _translate = QtCore.QCoreApplication.translate
        dict_weather = None 
        try:
            dict_weather = getWeather()
        except Exception as err:
            print(repr(err))

        if dict_weather:
            self.today_temp.setText(_translate("MainWindow",dict_weather['now']['tmp']+chr(0x2103)))  # python2:unichr()
            self.curr_city.setText(_translate("MainWindow",dict_weather['city']))
            self.today_weather.setText(_translate("MainWindow",dict_weather['now']['cond_txt']))
            self.today_weather_2.setText(_translate("MainWindow",dict_weather['now']['tmp_min']+'/'+ \
                    dict_weather['now']['tmp_max']+' '+dict_weather['now']['wind_dir']+' '+ \
                    dict_weather['now']['wind_sc']))
            for i in range(len(dict_weather['three_day'])):
                if i == 0:
                    self.day_1.setText(_translate("MainWindow", dict_weather['three_day'][i]['date']+' '+ \
                        dict_weather['three_day'][i]['cond_txt_d']+' '+ \
                        dict_weather['three_day'][i]['tmp_min']+'/'+ \
                        dict_weather['three_day'][i]['tmp_max']+' '+ \
                        dict_weather['three_day'][i]['wind_dir']+ \
                        dict_weather['three_day'][i]['wind_sc']))
                elif i == 1:
                    self.day_2.setText(_translate("MainWindow", dict_weather['three_day'][i]['date']+' '+ \
                        dict_weather['three_day'][i]['cond_txt_d']+' '+ \
                        dict_weather['three_day'][i]['tmp_min']+'/'+ \
                        dict_weather['three_day'][i]['tmp_max']+' '+ \
                        dict_weather['three_day'][i]['wind_dir']+ \
                        dict_weather['three_day'][i]['wind_sc']))
        timer3 = threading.Timer(3600, self.update_weather)
        timer3.start()
예제 #7
0
파일: service.py 프로젝트: frannale/solar
def insertarDatos(filename):
    # SETEOS
    cargados, fallidos = 0, 0
    last_date = ''
    # BUSCO ULTIMOS DATOS
    query = "SELECT * FROM SOLAR.MEDICION ORDER BY FECHA DESC,HORA DESC LIMIT 1"
    data = db.makeQuery(query)
    print(data[0]["HORA"])
    data_anterior = {
        'AccumulatedDischargerPower': data[0]["ACM_DESCARGA"],
        'AccumulatedLoadPower': data[0]["ACM_CARGA"],
        'AccumulatedSelfusePower': data[0]["ACM_USO_PROPIO"],
        'AccumulatedPvPower': data[0]["ACM_PV"]
    }
    #ABRO EL CSV FILE
    dir_path = os.getcwd() + '/CSVFiles' + "/" + filename
    with open(dir_path, newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        # PROCESO CADA REGISTRO
        for row in reader:
            # SI CAMBIA EL DIA PEGALE A LA API-WEATHER
            current_date = row['RecordTime'][0:21].replace("\n", "")
            if last_date != current_date[0:10]:
                clima_por_hora = weather.getWeather(current_date)
            last_date = current_date[0:10]
            try:
                # PROCESO DE A 1 REGISTRO
                data_anterior = procesarUno(row, clima_por_hora, data_anterior)
                cargados += 1
            except:
                fallidos += 1

    return cargados, fallidos
예제 #8
0
def index(request):
    if "userID" not in request.session:
        # Prevent user from going to the success page if not logged in.
        return redirect(reverse('useradmin:index'))

    # User is logged in.
    userID = request.session['userID']
    # userCity = request.session['userCity']

    #questionable....maybe use session? Up for discussion
    current_weather = {}
    try:
        current_weather = weather.getWeather(User.objects.get(id=userID).city)
    except Exception as e:
        # This might fail due to an API key issue.
        # Ignoring errors for now.
        pass

    context = {
        "name": User.objects.get(id=userID).name,
        "stories": [],
        "city": User.objects.get(id=userID).city,
        "weather_status": current_weather[2],
        "weather_temp": current_weather[3],
        "weather_humidity": current_weather[4],
        "coords": [current_weather[5], current_weather[6]]
    }

    return render(request, 'infohub/index.html', context)
예제 #9
0
 def showWeather(self):
     logger.info("Getting weather")
     weatherForecast = weather.getWeather()
     if weatherForecast:
         (weatherData, rainData) = weatherForecast
         weatherCode = int(weatherData['W'])
         weatherType = weather.getWeatherType(
             weatherCode)  #returns tuple of name and image filename
         self.weatherGraphic.SetBitmap(wx.Bitmap(weatherType[1]))
         weatherText = "{0} - {1}℃ (feels like {2}℃) - {3}MPH {4} - {5}%".format(
             weatherType[0], weatherData['T'], weatherData['F'],
             weatherData['S'], weatherData['D'], weatherData['H'])
         self.weatherText.SetLabelText(weatherText)
         chanceOfRain = rainData[1]
         if chanceOfRain > 0:
             logger.debug("Rain: {0}% at {1}".format(
                 chanceOfRain, rainData[0]))
             if (rainData[0] - datetime.datetime.now()).days == 1:
                 day = "tomorrow"
             else:
                 day = "today"
             rainLabel = "{0}% chance of rain predicted {1} at {2}".format(
                 chanceOfRain, day, rainData[0].strftime('%H:%M'))
         else:
             rainLabel = "No rain predicted"
         self.rainText.SetLabelText(rainLabel)
     else:
         logger.error("Unable to display weather")
예제 #10
0
 def evaluate(self, csvFile=''):
     #get the weather dictionary
     yourMom.update(self.getLocation())
     wDict = yourMom.getWeather()
     ##        weatherJson = "./jsons/" + str(self.getLocation()) + "weather.json"
     ##        with open (weatherJson,'w') as f:
     ##            f.write(jsonify(wDict))
     return jsonify(wDict)
예제 #11
0
파일: ircbot.py 프로젝트: avesanen/ircbot
 def c_weather(self,data,sender,channel):
     city = "Tampere"
     if len(data.split(" ",1)) > 1:
         city = data.split(" ",1)[1]
         city = city.title()
     w = weather.getWeather(city)
     if w is not None:
         self.say(w,channel)
     else:
         self.say("Can't get weather, sorry.",channel)
예제 #12
0
def handle_get_weather(message):
    cityWeatherList = weather.getWeather(message.text)
    if cityWeatherList[0] == "404":
        bot.send_message(message.chat.id, "City not found")
        return True

    cityWeather = ""
    for i in cityWeatherList:
        cityWeather += i
    bot.send_message(message.chat.id, cityWeather)
예제 #13
0
def say_hello():
    #
    #Return a suitable greeting, along with weather.
    print("say hello message is triggered...")
    card_title = "Greeting Message"
    greeting_string = "Hello Abhinav and Vidhyuth. How are you doing?" + weather.getWeather(
    )
    return build_response({},
                          build_speechlet_response(card_title, greeting_string,
                                                   "Ask me to greet the kids",
                                                   True))
예제 #14
0
def sendWeatherMsg():
    data = weather.getWeather()
    msg = '''======{}======
播报今天的天气情况:
天气:{}
温度:{}
湿度:{}
温馨提醒:{}
=========天气播报========='''.format(nowDate, data['skycon'], data['temperature'],
                                 data['humidity'], data['forecast_keypoint'])
    sendSMS.postData("3151351506", msg)
예제 #15
0
def handle_message(event):
	
	word = event.message.text
	if(word=="weather" or word=="Weather"):
		result = weather.getWeather()
	else:
		result = dictionary.getMeaning(word)

	line_bot_api.reply_message(
		event.reply_token,
		TextSendMessage(text=result)
	)
예제 #16
0
def tick():
    #print(database.addMessage("sendDM.py", "online", "Script sendDM.py is still working."))
    global tryCounter
    tryCounter = tryCounter + 1
    print("Next event triggers at " + str(getNextTime(True)))
    pause.until(getNextTime(True))
    event = database.nextEvent()
    if getNextTime(False) < datetime.datetime.now():
        print(event)
        try:
            if (event["eventType"] == "localWeather"):
                print(event["location"])
                sendDM(event["twitterAccount"],
                       weather.getWeather(str(event["location"])))
                database.updateEventTimeAuto(event["id"])
                print("Run localWeather event #" + event["id"])
            elif (event["eventType"] == "dailyStock"):
                #TODO Call dailyStock function
                print("Run dailyStock #" + event["id"])
            elif (event["eventType"] == "dailyQuote"):
                print(int(event["twitterAccount"]))
                sendDM(event["twitterAccount"],
                       getDailyQuote.get_daily_quote())
                database.updateEventTimeAuto(event["id"])
                print("Run daily quote #" + event["id"])
            elif (event["eventType"] == "dailyWord"):
                sendDM(event["twitterAccount"], word.getWordOfDay())
                database.updateEventTimeAuto(event["id"])
                print("Run word event #" + event["id"])
            elif (event["eventType"] == "remindMe"):
                sendDM(event["twitterAccount"],
                       "REMINDER: " + event["message"])
                database.updateEventTimeAuto(event["id"])

            tryCounter = 0
            database.addMessage("sendDM.py", "online",
                                "Event #" + event["id"] + " was sent.")

        except Exception:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            lines = traceback.format_exception(exc_type, exc_value,
                                               exc_traceback)
            print(lines)
            if tryCounter <= 3:
                time.sleep(10)
            else:
                database.updateEventTimeAuto(event["id"])
                print("Event " + event["id"] +
                      " failed 3 times.  It was skipped.")
                database.addMessage(
                    "sendDM.py", "error", "Event #" + event["id"] +
                    " failed 3 times.  It was skipped.")
예제 #17
0
def callback_inline(call):
	try:
		if call.message:
			if call.data == 'good':
				bot.send_message(call.message.chat.id, 'Вот и отличненько 😊')
			elif call.data == 'weather.home':
				weather.getWeather(call.message, 'Киевский', bot)
			elif call.data == 'weather.another':
				weather.getWeather(call.message, 'Красноярск', bot)
			elif call.data == 'bad':
				bot.send_message(call.message.chat.id, 'Бывает 😢')
 
			# remove inline buttons
			# bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="😊 Как дела?",
				# reply_markup=None)
 
			# show alert
			# bot.answer_callback_query(callback_query_id=call.id, show_alert=False,
				# text="ЭТО ТЕСТОВОЕ УВЕДОМЛЕНИЕ!!11")
 
	except Exception as e:
		print(repr(e))
예제 #18
0
파일: main.py 프로젝트: nvblueboy/Work-TV
	def __init__(self, **kwargs):
		super(AppContainer, self).__init__(**kwargs)
		self.runTime = 0
		self.oldTime = 0

		self.captionBox = None

		self.weatherString = weather.getWeather(self.weatherLocation)

		self.appWidgets = {}
		self.slideWidgets = {}

		self.frameStartTime = 0
예제 #19
0
def handletxt(txt):
    txt = txt.strip()
    try:
        txt = txt.decode("utf-8")
    except:
        pass
    if txt.find(u"天气") > 1 and len(txt) < 8:
        ret = weather.getWeather(txt)
    elif txt.find(u"行情") > 0:
        ret = ""
    elif txt.find(u"几点") >= 0 or txt.find(u"报时") >= 0:
        ret = timeai.showtime()
    else:
        ret = ""
    return ret
예제 #20
0
 def __init__(self, **kwargs):
     super(MainScreen, self).__init__(**kwargs)
     self.info_prompt = "Take a picture to login!"
     self.logged_in = False
     self.img1 = "main_blank.png"
     self.img2 = "main_blank.png"
     self.ig_img1 = "main_blank.png"
     self.ig_img2 = "main_blank.png"
     self.ig_img3 = "main_blank.png"
     self.ig_img4 = "main_blank.png"
     w = weather.getWeather()
     self.weather_info = "Weather: " + w['weather'] + "\n" + \
                         "Temperature (now): " + str(w['temp']) + "\n" + \
                         "Temperature (min): " + str(w['temp_min']) + "\n" + \
                         "Temperature (max): " + str(w['temp_max']) + "\n"
예제 #21
0
def main():
        data=open('keys','r').readlines()
        sdata=[]
        for x in data:
            sdata.append(x.rstrip('\n'))
#        print(sdata)
        weathr=weather.getWeather(sdata[0])
        forcast=weathr.getreq()
        weathr.parseweather(forcast)
        weathr.getcode()
        text=weathr.createtext()
        password=sdata[1]
        eserver=emaill.emaill(text,password,sdata[2])
#        print('ok')
        eserver.sendmsg()
예제 #22
0
def getOutfit():
    weather_data = weather.getWeather()
    print(weather_data)

    clothing_encode = []
    clothing_weather = []
    clothing_type = []
    clothing_db = db.getClothingDatabase()
    for _, entry in clothing_db.items():
        img = cv2.imread(entry['path'])
        enc = style.getStyleEncodeFromImg(img)
        clothing_encode.append(enc)

        if 'pants' in entry['tags']:
            clothing_type.append('lower')
        elif 'shirt' in entry['tags']:
            clothing_type.append('upper')
        else:
            clothing_type.append('-----')

        if 'pants' in entry['tags']:
            clothing_weather.append('cold')
        elif 'shorts' in entry['tags']:
            clothing_weather.append('hot')
        else:
            clothing_weather.append('warm')

    ig_clothing_encode = []
    ig_clothing_type = []
    follow = db.getIgFollowing()
    for user in follow:
        img_files = os.listdir('ig_img/' + user + '/')
        for img_file in img_files:
            path = 'ig_img/' + user + '/' + img_file
            img = cv2.imread(path)
            img_upper, img_lower = img_util.split_clothing(img)
            enc = style.getStyleEncodeFromImg(img_upper)
            ig_clothing_encode.append(enc)
            ig_clothing_type.append('upper')
            enc = style.getStyleEncodeFromImg(img_lower)
            ig_clothing_encode.append(enc)
            ig_clothing_type.append('lower')

    print(clothing_encode)
    print(clothing_type)
    print(ig_clothing_encode)
    print(ig_clothing_type)
def home():
        #trains = [mta2.ott(), mta2.ffs(), mta2.seven(), mta2.ace(), mta2.bdfm(), mta2.g(), mta2.jz(), mta2.l(), mta2.nqr(), mta2.s(), mta2.sir()]
        temp = weather.getTemp()
        sky = weather.getWeather()
	events = utils.upNext(session["username"])
        events = events[:5]        
        if "username" in session: #if logged in already
                nick = utils.getNickName(session["username"])
                return render_template("homepage.html", nickname = nick, 
				       temperature = temp, weather = sky, ott = mta2.ott(),
				       ffs = mta2.ffs(), seven = mta2.seven(), ace = mta2.ace(),
				       bdfm = mta2.bdfm(), g = mta2.g(), jz = mta2.jz(), l = mta2.l(), 
				       nqr = mta2.nqr(), s = mta2.s(), sir = mta2.sir(), events=events)
                                                      #greeting = utils.getName(username)                                                       
         #if not logged in
        else:
                return redirect("/")
예제 #24
0
    def on_post(self, req, resp, userId):

        try:
            result = weather.getWeather(
                req.media["postalCode"], req.media["measurement"]
            )
        except:
            logger.error(
                f"Exception. userId: {userId}",
                exc_info=True,
                extra={"area": "weather"},
            )
            raise falcon.HTTPBadRequest(
                "Bad Request", "The request can not be completed."
            )

        resp.media = result
def handleClientMessage(address, message, action):
	# Register client
	if action == 104:
		origin = message['origin']
		if origin in ServerData.clients:
			sock.sendto(createJsonStr(106, 'Invalid', message['destiny'], message['id'], 'Invalid User Name'), address)
		else:
			ServerData.clients[origin] = address[0] + ':' + str(address[1])
			# Send ACK
			sock.sendto(createJsonStr(105, message['origin'], message['destiny'], message['id'], message['payload']), address)
	else:
		# Send ACK
		sock.sendto(createJsonStr(105, message['origin'], message['destiny'], message['id'], message['payload']), address)
		# Private message
		if action == 101:
			to = message['destiny']
			for key, gen in ServerData.clients.items():
				if key == to:
					parts = ServerData.clients[to].split(':')
					sock.sendto(data, (parts[0], int(parts[1])))
		# Public message
		elif action == 100:
			origin = message['origin']
			for key, gen in ServerData.clients.items():
				if key != origin:
					parts = ServerData.clients[key].split(':')
					sock.sendto(data, (parts[0], int(parts[1])))
		# Disconnect message
		elif action == 103:
			sock.sendto(data, address)
			ServerData.clients.pop(message['origin'])
		# List users message
		elif action == 102:
			users = ''
			for key, gen in ServerData.clients.items():
				users += key + ', '
			sock.sendto(createJsonStr(102, 'SERVER', message['destiny'], message['id'], users[:-2]), address)
		elif action == 107:
			weather = getWeather()
			gdlWeather = 'Check your internet connection and try again.'
			if weather is not None:
				gdlWeather = 'The wind for GDL is going to have a speed of: ' + weather['query']['results']['channel']['wind']['speed']
			sock.sendto(createJsonStr(107, 'SERVER', message['destiny'], message['id'], gdlWeather), address)
		elif action == 108:
			response = postTwitter(message['origin'] + ': ' + message['payload'])
			sock.sendto(createJsonStr(108, 'SERVER', message['destiny'], message['id'], response), address)
예제 #26
0
    def update_info(self):
        _translate = QtCore.QCoreApplication.translate
        # data weather
        # August 16, Wednesday
        weather_data = getWeather()
        now_tmp = "   " + weather_data[-1] + "° "
        rangeoftemp = " " + weather_data[0][4] + "°/ " + weather_data[0][
            3] + "°"
        self.td_temp.setText(_translate("MainWindow", now_tmp))
        self.today_weather.setText(_translate("MainWindow",
                                              weather_data[0][0]))
        self.today_weather_2.setText(_translate("MainWindow", rangeoftemp))
        self.td.setText(_translate("MainWindow", weather_data[0][1][5:19]))
        self.tmr.setText(_translate("MainWindow", weather_data[1][1][5:19]))
        self.dat.setText(_translate("MainWindow", weather_data[2][1][5:19]))

        self.td_weather.setText(_translate("MainWindow", weather_data[0][0]))
        self.td_tmp.setText(
            _translate("MainWindow",
                       weather_data[0][4] + "/" + weather_data[0][3] + "°"))
        self.td_wind.setText(_translate("MainWindow",
                                        weather_data[0][2] + "%"))

        self.tmr_weather.setText(_translate("MainWindow", weather_data[1][0]))
        self.tm_tmp.setText(
            _translate("MainWindow",
                       weather_data[1][4] + "/" + weather_data[1][3] + "°"))
        self.tm_wind.setText(_translate("MainWindow",
                                        weather_data[1][2] + "%"))

        self.dat_weather.setText(_translate("MainWindow", weather_data[2][0]))
        self.dat_tmp.setText(
            _translate("MainWindow",
                       weather_data[2][4] + "/" + weather_data[2][3] + "°"))
        self.dat_wind.setText(
            _translate("MainWindow", weather_data[2][2] + "%"))

        day_information = getDate()
        self.label_day.setText(_translate("MainWindow", day_information))

        timer1 = threading.Timer(14400, self.update_info)
        timer1.start()
예제 #27
0
파일: main.py 프로젝트: sarthfrey/Texty
def texty():
	"""Respond to incoming calls with a simple text message."""
 
	#from_number = request.values.get('From', None)
	from_body = request.values.get('Body', None)
	body_string = str(from_body)
	actual_content = re.split('\s*@',body_string)

	message = "unchanged"
	if len(actual_content) > 1:
		if actual_content[1].lower() == "translate":
			lang_from = actual_content[2]
			lang_to = actual_content[3]
			text = actual_content[4]
			message = "0" + translate.filler(lang_from, lang_to, text)
			#message = lang_from + " " + lang_to + " " + text
		elif actual_content[1].lower() == "currency":
			conversion_rate = currency.getConversionRate(actual_content[2], actual_content[3])
			converted_amount = float(conversion_rate) * float(actual_content[4])
			message = "1" + str(format(converted_amount, '.2f'))
		elif actual_content[1].lower() == "weather" or actual_content[1].lower() == "temperature":
			city = re.split(',\s*',actual_content[3].lower())
			message =  "2" + weather.getWeather(actual_content[2], city[0])
		elif actual_content[1].lower() == "stock":
			message = "3" + str(stocks.getQuote(actual_content[2].upper()))
		elif actual_content[1].lower() == "define":
			message = "4" + str(dictionaryDef.getDefinition(actual_content[2].lower()))
		elif actual_content[1].lower() == "time":
			message = timezone.getTime(actual_content[2].lower())
		elif actual_content[1].lower() == "thesaurus":
			message = "5" + str(thesaurus.getSynonyms(actual_content[2]))
		elif actual_content[1].lower() == "help":
			message = "Available commands:\n\n@currency @(convert-from) @(convert-to) @(amount)\n\n@weather @(units) @(city)\n\n@stock @(stock ticker)\n\n@define @(word)\n\n@time @(city)\n\n@thesaurus @(word)"
		else:
			message = "Please type in @help for a list of commands!"
	else:
		message = "Please type in @help for a list of commands!"

	resp = twilio.twiml.Response()
	resp.message(str(message))
	return str(resp)
예제 #28
0
def mainLoop():
	GPIO.setmode(GPIO.BOARD)
	GPIO.setup(SENSOR_PORT, GPIO.IN)

	lights.setRandom()
	printLED()

	try:
		while True:
			if GPIO.input(SENSOR_PORT):
				if tod.checkTimer():
					time_of_day = tod.getTOD()
					weather_conditions = weather.getWeather()
					greet_text = greetText(time_of_day, weather_conditions["current_observation"]["weather"])
					print(greet_text + "\n")
					speech.playText(greet_text)
					lights.fade(weather.getColor(weather_conditions))
					printLED()
				tod.setTimer(10)
	except KeyboardInterrupt:
		GPIO.cleanup()
예제 #29
0
def generate_image():
    weather_data = weather.getWeather(_LATITUDE, _LONGITUDE)
    nextbus_data = []
    nextbus_data.append(
        nextbus.getPredictions(_NEXTBUS_AGENCY, _NEXTBUS_LINE1,
                               _NEXTBUS_STOP1))
    nextbus_data.append(
        nextbus.getPredictions(_NEXTBUS_AGENCY, _NEXTBUS_LINE2,
                               _NEXTBUS_STOP2))

    # Open SVG to process
    svg = codecs.open('preprocess.svg', 'r', encoding='utf-8').read()

    # Insert day
    svg = svg.replace('CURRENT_DAY',
                      datetime.strftime(datetime.now(), '%A - %B %d - %Y'))

    # insert weather
    svg = svg.replace('ICON_ONE', weather_data['day_1']['icon'])
    svg = svg.replace('HIGH_ONE', str(weather_data['day_1']['maximum']))
    svg = svg.replace('LOW_ONE', str(weather_data['day_1']['minimum']))

    # insert bus predictions
    for x in range(1, 3):
        svg = svg.replace('LINE_' + str(x) + '_LABEL',
                          nextbus_data[x - 1]['route'])
        for y in range(1, 3):
            #print nextbus_data[x-1]['predictions'][y-1]['datetime']
            #prediction_time = datetime.strptime(nextbus_data[x-1]['predictions'][y-1]['datetime'], '%Y-%m-%d %H:%M:%S')
            if len(nextbus_data[x - 1]['predictions']) >= y:
                prediction_time = datetime.strftime(
                    nextbus_data[x - 1]['predictions'][y - 1]['datetime'],
                    '%-I:%M %p')
                svg = svg.replace('LINE_' + str(x) + '_TIME_' + str(y),
                                  prediction_time)
            else:
                svg = svg.replace('LINE_' + str(x) + '_TIME_' + str(y), 'N/A')

    codecs.open('output.svg', 'w', encoding='utf-8').write(svg)
예제 #30
0
def jarvis(data):
    if "how are you" in data:
        speak("I am fine")
        #LABEL = Label(ROOT, text="I am fine")
        #LABEL.pack()

    # previously it was if "joke" or "jokes" in data
    # thus caused the joke case to run every time! Deleting or "jokes" fixed the issue
    if "joke" in data:
        # get a random number between 0 and 75 to get a random joke
        ranNum = random.randint(0, 75)
        # preload joke before request
        jokeDict = eval(open("dict.txt").read())
        setUpline = jokeDict[ranNum]["setup"]
        punchy = jokeDict[ranNum]["punchline"]
        speak(setUpline)
        speak(punchy)

    if "time" in data:
        tm = datetime.now()
        speak("The time is " + tm.strftime("%I:%M%p"))
        #LABEL = Label(ROOT, text=tm.strftime("%I:%M%p"))
        #LABEL.pack()

    if "date" in data:
        now = datetime.now()
        speak("Today is " + now.strftime("%A,%d %B,%Y"))
        #LABEL = Label(ROOT, text=now.strftime("%A,%d %B,%Y"))
        #LABEL.pack()

    if "news" in data:
        speak("Coming right up")
        #LABEL = Label(ROOT, text="Coming right up")
        #LABEL.pack()
        webbrowser.open('https://news.google.com')

    if "weather" in data:
        speak(str(getWeather()))
예제 #31
0
def main():
    city = request.form["cityname"]
    fname = "static/good.jpg"
    message = "Today"
    x = weather.getWeather(city)
    temps = x[0]
    dates = x[1]
    bestDay = weather.forcast(temps, dates)
    if bestDay == 0:
        message += "'s temperature is just right!"
    elif weather.checkTemp(temps[0]) == 1:
        fname = "static/cold.jpg"
        if bestDay == 7:
            message += " is too cold, and it will never get better."
        else:
            message += " is a too cold. But " + dates[bestDay] + " will be better!"
    else:
        fname = "static/hot.jpg"
        if bestDay == 7:
            message += " is too hot, and it will never get better."
        else:
            message += " is too hot! But " + dates[bestDay] + " will be better!"
    return render_template("base.html", fileName = fname, text = message)
예제 #32
0
파일: main.py 프로젝트: nvblueboy/Work-TV
	def update(self, *args):

		for child in self.ids.Carousel.slides:
			updateFN = getattr(child, "update", None)
			if callable(updateFN):
				child.update(self.runTime)

		slide = self.ids.Carousel.current_slide
		
		if not hasattr(slide,"length") or slide.length == -1:
			slide.length = self.transitionTime

		if (self.captionBox != None):
			self.captionBox.headline = slide.headline
			self.captionBox.caption = slide.caption
			day = time.strftime("%d").lstrip("0")
			month = time.strftime("%m").lstrip("0")
			year = time.strftime("%Y")
			date = month + "/" + day + "/" + year
			self.captionBox.weather = self.weatherString + " | " +date + ", " + str(time.strftime("%I:%M:%S %p")).lstrip("0")

		if (int(time.time()) != self.oldTime):
			self.oldTime = int(time.time())
			self.runTime += 1

			if self.runTime - self.frameStartTime >= slide.length:
				self.ids.Carousel.load_next()
				self.frameStartTime = self.runTime

			if self.runTime % self.weatherUpdate == 0:
				Logger.info("AppContainer: Loading weather")
				self.weatherUpdated = True
				self.weatherString = weather.getWeather(self.weatherLocation)
				Logger.info("AppContainer: Weather String: "+self.weatherString)
					
			else:
				self.weatherUpdated = False
예제 #33
0
def data():
    zip = int(request.args.get('zip'))
    crop_list = request.args.get('crops').split(',')
    barleyPriceData = "/data/barley_price.csv"
    cottonPriceData = "/data/cotton_price.csv"
    cornPriceData = "/data/corn_price.csv"
    soybeanPriceData = "/data/soybean_price.csv"
    wheatPriceData = "/data/wheat_price.csv"
    cropDict = {
        "Corn": '',
        "Cotton": '',
        "Barley": '',
        "Soybean": '',
        "Wheat": ''
    }
    #the dropdown in the UI should use these keys exactly
    data = {
        "Corn": cornPriceData,
        "Cotton": cottonPriceData,
        "Barley": barleyPriceData,
        "Soybean": soybeanPriceData,
        "Wheat": wheatPriceData
    }
    for crop in crop_list:
        #get the correct evaluator for each type of crop
        builder = DataEvalBuilder(zip, data[crop])
        evaluator = builder.get("prices")
        # the evaluator prettifys the data
        dirr = "." + data[crop]
        cropDict[crop] = evaluator.evaluate(dirr)
        # do something with the json file
##        with open("./jsons/" + str(zip) + str(data[crop]) + "price.json") as f:
##            cropDict[data[crop]] = f.read()
    weatherDict = weather.getWeather(zip)
    output = {'cropPrice': cropDict, 'weather': weatherDict}
    return jsonify(output)
예제 #34
0
def weather(bot, update):
    chat_id = update.message.chat_id
    message = str(update.message.text)
    lst = message.split(" ", 1)
    location = lst[1]
    bot.send_message(chat_id=chat_id, text=getWeather(location=str(location)))
예제 #35
0
파일: app.py 프로젝트: imsudip/api-python
def weather():
    if request.method == 'GET':
        return jsonify(getWeather(request.args.get('city')))
예제 #36
0
파일: index.py 프로젝트: ytmzds/DataAPI
def _weather(cityy):
    return weather.getWeather(cityy)
예제 #37
0
파일: views.py 프로젝트: dormbase/dashboard
def weather(request):
    result = w.getWeather('02139', 'static/img/weather/')
    jsonout = json.dumps(result, sort_keys=True, indent=4)
    return HttpResponse(jsonout, mimetype="application/json")
예제 #38
0
def index():
    return render_template("index.html", title = 'Home', weather = getWeather(),  tripData = checkTrains(), myEvents = myCal.getEvents())
예제 #39
0
파일: api.py 프로젝트: hjorthjort/Presens
                'genre':u'classic,thriller'
            },
            {
                'title':u'World in White',
                'synopsis':u'Surrounded by dark forces who suppress and ridicule him, the Hero slowly blossoms into a mature figure who ultimately gets riches, a kingdom, and the perfect mate.',
                'imgurl':u'http://uploads.neatorama.com/images/posts/95/58/58095/1360112719-0.jpg',
                'trailerurl':u'https://www.youtube.com/watch?v=a2MnKebNlRo',
                'genre':u'classic,thriller'
            }
        ]
    },
]

meta = {
    'location': u'London, UK',
    'weather': weather.getWeather(2882, 'London'),
    'trends': twitter().get_trends()
}

def get_lists(recommendation):
    ts = int(time.time())
    datapoint = np.array([weekday(ts), hour_of_day(ts), 1])
    #print datapoint
    #datapoint = np.array([6,10,1])
    list_of_rec = recommendation.get_kmeans_recommendations(datapoint)
    return jsonify({'lists': mapping.programs_to_data(list_of_rec, recommendation.get_meta_data())})

def get_trending_concepts(recommendation):
    list_of_rec = recommendation.get_trend_recommendations()
    return jsonify({'lists': mapping.programs_to_data(list_of_rec, recommendation.get_meta_data())})
예제 #40
0
def search(shelve_name, pickle_name):

	print("Reading shelved data...")
	sh = shelve.open(shelve_name)
	dic = sh["dic"]
	sh.close()

	query=input("\nSearch Query: ")
	query = query.strip().lower() #normalize, remove spacing, go to lower case
	tokens = query.split(" "); #parse into tokens by spaces
	results = []

	#find operator
	if "or" in tokens:
		if "and" in tokens:
			operator = "AND" #if user enters both 'and' and 'or', then 'and'
		else:
			operator = "OR"
	else:
		operator = "AND"

	#remove operator from tokens
	while("and" in tokens):
		tokens.remove("and")
	while("or" in tokens): 
		tokens.remove("or")

	#remove duplicates using a set
	unique_tokens = set()
	for x in tokens:
		unique_tokens.add(x)

	#=======================================
	print("Performing: " + operator + " search for: " + str(unique_tokens) + "\n")

	dt1 = datetime.now()
	if(operator == "OR"):
		bigset = set()
		biglist = []
		for x in unique_tokens:
			if dic.get(x) != None:
				bigset = set(bigset).union(set(dic[x])) #adding all the sets up to get a unique list of line numbers
		biglist = list(bigset)
		biglist.sort()
		results = biglist
	else:
		andlist = []
		for x in unique_tokens:
			if dic.get(x) != None:
				newlist = []
				smlist = []
				if(len(andlist) == 0):
					andlist = list(dic[x]) #initialize the set from the first find.
				else:
					smlist = list(dic[x])
					#keep removing from the first found set.
					for j in smlist:
						if j in andlist:
							newlist.append(j)
					andlist = newlist
		andlist.sort()
		results = andlist				

		
	#read pickled data
	p = open(os.path.join(os.getcwd(), pickle_name), "br")
	file_list = pickle.load(p)
	p.close()
	
	getWeather(query)
	
	for i, x in enumerate(results):
		print("================================================================================")
		print("Result " + str(i + 1) + ": " + x)
		
		#print the first 100 characters from the original text
		for i in range(len(file_list)):
			if(file_list[i][0] == x):
				print("\t  Text Found: " + str(file_list[i][1])[:50] + "...") #only show first 100 characters
				break
		
	dt2 = datetime.now()
	print("\nExecution Time: " + str(dt2.microsecond - dt1.microsecond))
예제 #41
0
파일: textMe.py 프로젝트: RParkerE/textMe
def getInfo(host, usr, pas):
	getWeather()
	sunRise()
	sunSet()
	read(host, usr, pas)