def dummyMethod_killACharacter(self): degenerate = Weather() health = Attribute("Health") health.setValue(-1) degenerate.addAttribute(health) ev = Events.CharacterUpdateEvent(self.characters[self.killerID].getName(), degenerate) self.mediator.post(ev)
def preview_zenith_tau(log, row_list, cl_params, feeds, windows, pols): # if using the weather database if not cl_params.zenithtau: foo = row_list.get(cl_params.mapscans[0], feeds[0], windows[0], pols[0]) ff = fitsio.FITS(cl_params.infilename) extension = foo['EXTENSION'] row = foo['ROW'][0] bar = ff[extension]['OBSFREQ', 'DATE-OBS'][row] dateobs = bar['DATE-OBS'][0] obsfreq = bar['OBSFREQ'][0] ff.close() weather = Weather() pu = Pipeutils() mjd = pu.dateToMjd(dateobs) zenithtau = weather.retrieve_zenith_opacity(mjd, obsfreq) log.doMessage('INFO', 'Zenith opacity for map: {0:.3f}'.format(zenithtau)) # else if set at the command line else: log.doMessage('INFO', 'Zenith opacity for ' 'map: {0:.3f}'.format(cl_params.zenithtau))
class test_Weather: def setup(self): self.weather = Weather() pass def test_retrieve_zenith_opacity(self): zenith_tau = self.weather.retrieve_zenith_opacity(54210, 23.6e9) assert_almost_equal(zenith_tau, 0.1550, places=4) zenith_tau = self.weather.retrieve_zenith_opacity(54215.32, 23.6e9) assert_almost_equal(zenith_tau, 0.1246, places=4)
def Main(): gameIntro = GameIntro() gameIntro.getIntro() player = Player() player.namePlayer() weather = Weather() weather.getWeather() print ("Today's weather forecast is %s." % (weather.weather)) temperature = Temperature() temperature.getTemperature() print("Today's temperature will %s degrees." % (temperature.temperature)) print("Let's get our supplies and make some lemonade.") price = Pricing() price.setprice() playerChoice.setPrice()
def preview_zenith_tau(log, row_list, cl_params, feeds, windows, pols): foo = None # if using the weather database if cl_params.zenithtau is None: for feed in feeds: for window in windows: for pol in pols: try: foo = row_list.get(cl_params.mapscans[0], feed, window, pol) break # if we found a row move on, otherwise try another feed/win/pol except KeyError: continue if not foo: log.doMessage('ERR', 'Could not find scan for zenith opacity preview') return ff = fitsio.FITS(cl_params.infilename) extension = foo['EXTENSION'] row = foo['ROW'][0] bar = ff[extension]['OBSFREQ', 'DATE-OBS'][row] dateobs = bar['DATE-OBS'][0] obsfreq = bar['OBSFREQ'][0] ff.close() weather = Weather() pu = Pipeutils() mjd = pu.dateToMjd(dateobs) zenithtau = weather.retrieve_zenith_opacity(mjd, obsfreq, log) if zenithtau: log.doMessage('INFO', 'Approximate zenith opacity for map: {0:.3f}'.format(zenithtau)) else: log.doMessage('ERR', 'Not able to retrieve integration ' 'zenith opacity for calibration to:', cl_params.units, '\n Please supply a zenith opacity or calibrate to Ta.') sys.exit(9) # else if set at the command line else: log.doMessage('INFO', 'Zenith opacity for ' 'map: {0:.3f}'.format(cl_params.zenithtau))
def WeekendTweet(self): tempTweet = "" for x in range(1, 3): self.weatherObj = Weather(GPSLOCATION, AIRPORT, x) self.rec = Recommendation.Recommendation(self.weatherObj) tempTweet += self.weatherObj.dayofWeek["long"] + "- " + str( self.rec.rating) + "/" tempTweet += self.weatherObj.weatherStatus + "/Morn " + str( math.ceil(self.weatherObj.mornTemp)) + "°F/Eve " + str( math.ceil(self.weatherObj.eveTemp)) + "°F" if ((self.weatherObj.rainText) and (self.weatherObj.weatherStatus != "trace rain")): tempTweet += "/" + self.weatherObj.rainText if (self.rec.weatherEmoji): tempTweet += self.rec.weatherEmoji + "\n" #Get the emoji here self.tweetContents = "THIS WEEKEND: \n" + tempTweet self.addHashTag() TweetPublisher(self.tweetContents)
def getTodayWeather(self, location): json = self.__apicall(location) weatherlist = {} tomorrow = datetime.date.today() + datetime.timedelta(days=1) unixtime = time.mktime(tomorrow.timetuple()) i = 0 while float(json['list'][i]['dt']) <= unixtime: objName = str(json['list'][i]['dt']) temperature = json['list'][i]['main']['temp'] temp_min = json['list'][i]['main']['temp_min'] temp_max = json['list'][i]['main']['temp_max'] temp_feels_like = json['list'][i]['main']['feels_like'] temp_dt = json['list'][i]['dt_txt'] weatherstate = json['list'][i]['weather'][0]['description'] weatherlist[objName] = Weather(temperature, temp_feels_like, temp_min, temp_max, temp_dt, weatherstate) i += 1 return weatherlist
def EventMethods_Weather(self): weatherInfo = Weather() self.message('Beijing ' + weatherInfo.getUpdateTime() + '\n ' + str(weatherInfo.getTemperature()) + chr(4) + 'C RH:' + weatherInfo.getRH()) self.AutoRefreshMethod = 'EventMethods_5_1'
def main(): logger.info('Logging works!') weather = Weather() acceptable_weather_codes = config.get_weather_codes() logger.info('Started Sunmine application') current_state = MiningState.get_state() logger.info("Current state of the miner: " + current_state) # weather # sunset/rise logger.info("Getting sunrise/sunset data from the internet...") sun_api_url = SunTimes.build_sun_api_url(config) sun_data = SunTimes.get_sun_data_from_api(sun_api_url) sun_rise = sun_data.get("results").get("sunrise") sun_set = sun_data.get("results").get("sunset") go_time = False go_time = is_the_sun_up(sun_set, sun_rise) logger.info("Sun is up: " + str(go_time)) logger.info("Getting weather data from the internet...") weather_data = weather.get_weather_data(weather.built_url) weather_id = weather_data.get("weather")[0].get("id") go_weather = False if go_time: for w in acceptable_weather_codes: if w == str(weather_id): go_weather = True break else: go_weather = False logger.info("Weather conditions: " + weather_data.get("weather")[0].get("main") + " - " + str(weather_id)) logger.info("Weather is acceptable for mining: " + str(go_weather)) output = "" if go_time is True and go_weather is True: logger.info("Mining on") output = "Mining On" if is_miner_already_running(config.get_program_name()): logger.warning('Yes %s process was running, not starting.' % (config.get_program_name())) else: logger.warning('No process was running') os.startfile(config.get_program_location()) if "off" in current_state: logger.warning("Changing state, sending email.") send_mail.send(output) MiningState.set_state("on") else: logger.info("Mining Off") output = "Mining Off" if is_miner_already_running(config.get_program_name()): logger.warning('Yes %s process was running, killing.' % (config.get_program_name())) kill_process(config.get_program_name()) else: logger.warning( 'Mining process not running, do not need to kill process.') if "on" in current_state: logger.warning("Changing state, sending email.") send_mail.send(output) MiningState.set_state("off")
from Location import Location from Weather import Weather from News import News import requests def telegram_bot_sendtext(bot_message): bot_token = '1130915184:AAF_R4BGTzM7WHmwEgDVGjo7mRmOOuo6EFE' #bot_chatID = '1062466771' #Testing Personal bot_chatID = '-473488749' #Group send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message response = requests.get(send_text) return response.json() message = telegram_bot_sendtext("Daily Push:\n\n" + "Location: " + Location.get_location() +"\n\nWeather:\n" + Weather.get_Weather() + '\n\nNews:\n' + News.getNews()) #print(message)
class transmittedSolarTest(unittest.TestCase): # For now, this test is giving solar transmittance to be 0, which makes sense for 3-4am in the USA. # Therefore, I am assuming these are calculating correctly at this time. def setUp(self): #self.gbxml = gbXML(os.path.join(os.path.dirname(__file__), 'input/Single_model.xml')) self.gbxml = gbXML( os.path.join(os.path.dirname(__file__), 'input/Two_Room_One_Floor_Model.xml')) self.temp = Temperature() self.shgc_dictionary = self.gbxml.shgc_dictionary self.temp_record = self.gbxml.temp_record self.spaces_dict = self.gbxml.spaces_dict self.shadow_record = self.gbxml.shadow_record self.shade_surf_list = self.gbxml.get_shades() self.surfaces_dict = self.gbxml.surfaces_dict # Get the first surface to check: spaces = self.gbxml.get_spaces() # Space 1 info, surface "su-8" is [7] and is the interior shared wall here space1 = spaces[0] surfaces_inspace1 = spaces[0].surfaces self.surface1_in_space1 = surfaces_inspace1[0] self.surface5_in_space1 = surfaces_inspace1[4] self.surface6_in_space1 = surfaces_inspace1[5] self.surface8_in_space1 = surfaces_inspace1[7] # Space 2 info, surface "su-8" is [7] and is the interior shared wall here #space2 = spaces[1] #surfaces_inspace2 = spaces[1].surfaces #self.surface8_in_space2 = surfaces_inspace1[7] # Create a fake weather self.weather = Weather('Washington', datetime(year=1997, month=1, day=1, hour=3), datetime(year=1997, month=1, day=1, hour=4)) area = Area() #print "test" self.areaWinDict = area.getWinDictionary # And a timestep self.tstep2 = datetime(year=1997, month=1, day=1, hour=4) # get the weather at the tstep self.wtstep2 = self.weather.get_weather_step(self.tstep2) # And another timestep self.tstep = datetime(year=1997, month=1, day=1, hour=3) # get the weather at the tstep self.wtstep = self.weather.get_weather_step(self.tstep) def test_interior_wall(self): T_space = 293 surface = self.surface8_in_space1 T1 = self.wtstep["t_outside"] A = 12.77375 A_noOp = 12.77375 C = 317068.2 #set when next model is tested R3 = 0 #Q_flux = 1 Q_flux = self.temp.interior_wall(surface, A, C, R3, self.spaces_dict, T_space, self.temp_record) self.assertEqual(Q_flux, 1, 'Q_flux is currently: %s ' % Q_flux) def test_exterior_wall(self): T_space = 293 surface = self.surface6_in_space1 T1 = self.wtstep["t_outside"] A = 20.554798 A_noOp = 19.439962 A_noWin = 19.439962 hc = 17.65859 C = 270863.311519 R3 = 1 / 0.729191 ShadowsFlag = 0 ns = (len(self.shade_surf_list) + len(self.shadow_record)) Q_flux = self.temp.exterior_wall(surface, hc, T1, A, A_noWin, self.wtstep, R3, C, T_space, self.temp_record, ShadowsFlag, ns, self.shadow_record, self.shade_surf_list, self.surfaces_dict, self.areaWinDict) self.assertEqual(Q_flux, -7.230236, 'Q_flux is currently: %s ' % Q_flux) def test_roof(self): T_space = 293 surface = self.surface5_in_space1 T1 = self.wtstep["t_outside"] A = 18.580608 A_noOp = 18.580608 A_noWin = 18.580608 hc = 15.24232 C = 36873.89882 R3 = 1 / 0.084111 ShadowsFlag = 0 ns = (len(self.shade_surf_list) + len(self.shadow_record)) Q_flux = self.temp.roof(surface, hc, T1, A, A_noWin, self.wtstep, R3, C, A_noOp, T_space, self.temp_record, ShadowsFlag, ns, self.shadow_record, self.shade_surf_list, self.surfaces_dict, self.areaWinDict) self.assertEqual(Q_flux, -10.487022, 'Q_flux is currently: %s ' % Q_flux) def test_underground_wall(self): Q_flux = 1 # Q_flux = self.temp.underground_wall(surface, hc_external, T1, A, A_noWin, weather, R3, C, A_noOp, shgc_dictionary) self.assertEqual(Q_flux, 1, 'Q_flux is currently: %s ' % Q_flux)
class SurfaceTest(unittest.TestCase): def setUp(self): gbxml = gbXML( os.path.join(os.path.dirname(__file__), 'input/Single_model.xml')) area = Area() area.createAreaDictionary() area.createWinAreaDictionary() self.areaWinDict = area.getWinDictionary() self.areaDict = area.getDictionary() spaces = gbxml.get_spaces() surfaces = spaces[0].surfaces self.surface = Surface() self.surface1 = surfaces[0] self.surface2 = surfaces[1] self.surface3 = surfaces[2] self.surface4 = surfaces[3] self.surface5 = surfaces[4] self.surface6 = surfaces[5] # Create a fake weather self.weather = Weather('Washington', datetime(year=1997, month=1, day=1, hour=3), datetime(year=1997, month=1, day=1, hour=4)) # And a timestep self.tstep2 = datetime(year=1997, month=1, day=1, hour=4) # get the weather at the tstep self.wtstep2 = self.weather.get_weather_step(self.tstep2) # And another timestep self.tstep = datetime(year=1997, month=1, day=1, hour=3) # get the weather at the tstep self.wtstep = self.weather.get_weather_step(self.tstep) def test_get_hc_external(self): # These numbers are giving values that are different than Ben's tests, not sure why/where they came from... h_surface = 1.685925 terrain = "Flat or Open Countryside" hc1 = self.surface.get_hc_external(self.wtstep, self.surface1, h_surface, terrain) self.assertEqual(hc1, 25.82063, 'get_hc is on surface 1: %s ' % hc1) #Ben's test: self.assertEqual(self.surface1.get_hc_external(self.wtstep),17.5617,"Surface 1") hc2 = self.surface.get_hc_external(self.wtstep, self.surface2, h_surface, terrain) self.assertEqual(hc2, 25.82063, 'get_hc is on surface 2: %s ' % hc2) #Ben's test: self.assertEqual(self.surface2.get_hc_external(self.wtstep),8.7809,"Surface 2") hc5 = self.surface.get_hc_external(self.wtstep, self.surface5, h_surface, terrain) self.assertEqual(hc5, 25.82063, 'get_hc is on surface 5: %s ' % hc5) #Ben's test: self.assertEqual(self.surface5.get_hc_external(self.wtstep),18.4740,"Surface 5") hc6 = self.surface.get_hc_external(self.wtstep, self.surface6, h_surface, terrain) self.assertEqual(hc6, 25.82063, 'get_hc is on surface 6: %s ' % hc6) def test_get_A(self): A = self.surface.get_A(self.surface1, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 20.555, 'Total area of surface 1: %s ' % A) A = self.surface.get_A(self.surface2, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 10.277, 'Total area of surface 2: %s ' % A) A = self.surface.get_A(self.surface3, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 20.555, 'Total area of surface 3: %s ' % A) A = self.surface.get_A(self.surface4, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 10.277, 'Total area of surface 4: %s ' % A) A = self.surface.get_A(self.surface5, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 18.581, 'Total area of surface 5: %s ' % A) A = self.surface.get_A(self.surface6, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 18.581, 'Total area of surface 6: %s ' % A) def test_get_A_noWin(self): A = self.surface.get_A_noWin(self.surface1, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 19.440, 'A_no_windows for surface 1: %s ' % A) A = self.surface.get_A_noWin(self.surface2, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 10.277, 'A_no_windows for surface 2: %s ' % A) A = self.surface.get_A_noWin(self.surface3, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 19.440, 'A_no_windows for surface 3: %s ' % A) A = self.surface.get_A_noWin( self.surface4, self.areaDict, self.areaWinDict ) # same as total area because doors are not counted here A = round(A, 3) self.assertEqual(A, 10.277, 'A_no_windows for surface 4: %s ' % A) A = self.surface.get_A_noWin(self.surface5, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 18.581, 'A_no_windows for surface 5: %s ' % A) A = self.surface.get_A_noWin(self.surface6, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 18.581, 'A_no_windows for surface 6: %s ' % A) def test_get_A_noOp(self): A = self.surface.get_A_noOp(self.surface1, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 19.440, 'A_no_openings for surface 1: %s ' % A) A = self.surface.get_A_noOp(self.surface2, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 10.277, 'A_no_openings for surface 2: %s ' % A) A = self.surface.get_A_noOp(self.surface3, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 19.440, 'A_no_openings for surface 3: %s ' % A) A = self.surface.get_A_noOp( self.surface4, self.areaDict, self.areaWinDict ) # same as total area because doors are not counted here A = round(A, 3) self.assertEqual(A, 8.419, 'A_no_openings for surface 4: %s ' % A) A = self.surface.get_A_noOp(self.surface5, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 18.581, 'A_no_openings for surface 5: %s ' % A) A = self.surface.get_A_noOp(self.surface6, self.areaDict, self.areaWinDict) A = round(A, 3) self.assertEqual(A, 18.581, 'A_no_openings for surface 6: %s ' % A) def test_get_C_surface(self): A_total = 20.554798 A_noOp = 19.439962 Coeff = 1 C = self.surface.get_C_surface(A_total, A_noOp, self.surface1, Coeff, self.areaWinDict) # Currently calculating the effective C to be 270863.311519, check against Matlab output self.assertEqual(C, 270863.311519, 'C of surface 1: %s ' % C) A_total = 10.277399 A_noOp = 8.419338 Coeff = 1 # Test surface door which does have a door C = self.surface.get_C_surface(A_total, A_noOp, self.surface4, Coeff, self.areaWinDict) # Currently calculating the effective C to be 270863.311519, check against Matlab output self.assertEqual(C, 242487.186765, 'C of surface 4: %s ' % C) A_total = 18.580608 A_noOp = 18.580608 Coeff = 1 # Test surface door which does have a door C = self.surface.get_C_surface(A_total, A_noOp, self.surface5, Coeff, self.areaWinDict) # Currently calculating the effective C to be 270863.311519, check against Matlab output self.assertEqual(C, 36873.89882, 'C of surface 5: %s ' % C) def test_get_U_surface(self): A_noOp = 19.439962 U = self.surface.get_U_surface(A_noOp, self.surface1) self.assertEqual(U, 0.386384, 'U of surface 1: %s ' % U) A_noOp = 18.580608 U = self.surface.get_U_surface(A_noOp, self.surface5) self.assertEqual(U, 0.084111, 'U of surface 5: %s ' % U) def test_get_U_win(self): U = self.surface.get_U_win(self.surface1) self.assertEqual(U, 0.0, 'U of surface 1: %s ' % U) U = self.surface.get_U_win(self.surface2) self.assertEqual(U, 0, 'U of surface 2: %s ' % U) U = self.surface.get_U_win(self.surface3) self.assertEqual(U, 0.0, 'U of surface 3: %s ' % U) U = self.surface.get_U_win(self.surface4) self.assertEqual(U, 0, 'U of surface 4: %s ' % U) U = self.surface.get_U_win(self.surface5) self.assertEqual(U, 0, 'U of surface 5: %s ' % U) U = self.surface.get_U_win(self.surface6) self.assertEqual(U, 0, 'U of surface 6: %s ' % U) def test_get_U_opening(self): U = self.surface.get_U_opening(self.surface1) self.assertEqual(U, 0, 'U of surface 1: %s ' % U) U = self.surface.get_U_opening(self.surface2) self.assertEqual(U, 0, 'U of surface 2: %s ' % U) U = self.surface.get_U_opening(self.surface3) self.assertEqual(U, 0, 'U of surface 3: %s ' % U) U = self.surface.get_U_opening(self.surface4) self.assertEqual(U, 0.0, 'U of surface 4: %s ' % U) U = self.surface.get_U_opening(self.surface5) self.assertEqual(U, 0, 'U of surface 5: %s ' % U) U = self.surface.get_U_opening(self.surface6) self.assertEqual(U, 0, 'U of surface 6: %s ' % U) def test_get_U_surface_e(self): # Check all these against Matlab output A_total = 20.554798 A_noOp = 19.439962 # Test surface which does have a window U = self.surface.get_U_surface_e(A_total, A_noOp, self.surface1, self.areaWinDict) self.assertEqual(U, 0.729192, 'C of surface 1: %s ' % U) A_total = 10.277399 A_noOp = 8.419338 # Test surface which does have a door U = self.surface.get_U_surface_e(A_total, A_noOp, self.surface4, self.areaWinDict) self.assertEqual(U, 0.985835, 'C of surface 4: %s ' % U) A_total = 18.580608 A_noOp = 18.580608 U = self.surface.get_U_surface_e(A_total, A_noOp, self.surface5, self.areaWinDict) self.assertEqual(U, 0.084111, 'C of surface 5: %s ' % U) A_total = 18.580608 A_noOp = 18.580608 U = self.surface.get_U_surface_e(A_total, A_noOp, self.surface6, self.areaWinDict) self.assertEqual(U, 5.147638, 'C of surface 6: %s ' % U)
from Weather import Weather from Forecast import Forecast import schedule import time try: print('PROGRAM STARTED') f = Forecast() w = Weather() # tweets the daily forecast at 7am cst as well as the weather every 4 hours throughout the day schedule.every().day.at('05:00').do(f.get) schedule.every().day.at('07:00').do(f.tweet) schedule.every().day.at('08:00').do(w.tweet) schedule.every().day.at('14:00').do(w.tweet) schedule.every().day.at('18:00').do(w.tweet) schedule.every().day.at('22:00').do(w.tweet) while 1: schedule.run_pending() time.sleep(1) except: print('PROGRAM STOPPED')
# -*- coding: utf-8 -*- from Weather import Weather weather = Weather('368148', 'c') print "Descripción condición: " + str(weather.canal.condicion.descripcion) print "Temperatura: " + str(weather.canal.condicion.temperatura) print "Pronóstico temperatura Minima: " + str( weather.canal.pronosticos[0].min_temp) print "Pronóstico temperatura Maxima: " + str( weather.canal.pronosticos[0].max_temp) print "Humedad: " + str(weather.canal.atmosfera.humedad)
# Message from Greeting greeting = Greeting(name) greeting_message = greeting.message + "\n" brief_pause = "<break time=\"300ms\"/>" pause = "<break time=\"1000ms\"/>" # print(greeting_message) # Message from todoClass todo = Todo() todo_message = todo.message+ "\n" # print(todo_message) # Message from weather class weather = Weather() weather_message = weather.message + "\n" # print(weather_message) # Message from News class news = News() news_message = news.message+ "\n" # Message from Quote Class quote = Quote() quote_message = quote.message close_message = user.name + brief_pause + "is there anything I can help you with?" message = "<speak>" + greeting_message + brief_pause + todo_message + pause + weather_message + pause + news_message + brief_pause + quote_message + brief_pause + close_message + "</speak>"
import unittest import json import requests from Functions import weather_choices, check_exists, custom_weather_choices from Weather import json_convert, Weather url: str = f"http://api.openweathermap.org/data/2.5/weather?q=melbourne,au&units=metric&appid=b2cf60917edb97ded95da68172607141" response = requests.request("GET", url) response_loaded = json.loads(response.text) cur_temp = f"Current Temperature: {int(response_loaded['main']['temp'])} Degrees Celsius" max_temp = f"Maximum Temperature: {int(response_loaded['main']['temp_max'])} Degrees Celsius" min_temp = f"Minimum Temperature: {int(response_loaded['main']['temp_min'])} Degrees Celsius" feels_like = f"Feels Like: {int(response_loaded['main']['feels_like'])} Degrees Celsius" humidity = f"Humidity: {response_loaded['main']['humidity']}%" test_weather = Weather('melbourne') class testFunctions(unittest.TestCase): def test_weather_choices(self): result = weather_choices('1', 'melbourne') self.assertEqual(result, cur_temp, msg=f"Results: {result}, Expected: {cur_temp}") result = weather_choices('2', 'melbourne') self.assertEqual(result, max_temp, msg=f"Results: {result}, Expected: {max_temp}") result = weather_choices('3', 'melbourne') self.assertEqual(result, min_temp, msg=f"Results: {result}, Expected: {min_temp}") result = weather_choices('4', 'melbourne') self.assertEqual(result, feels_like, msg=f"Results: {result}, Expected: {feels_like}")
def run(inputobs_file, config): # Set up a skypos object to hold site information and provide ra/dec -> alt/az/airmass translations. skypos = SkyPos() skypos.setSite(lat=config['latitude'], lon=config['longitude'], height=config['height'], pressure=config['pressure'], temperature=config['temperature'], relativeHumidity=config['relativeHumidity'], lapseRate=config['lapseRate']) # Set up a Weather object to read the site weather data. t = time.time() weather = Weather() weather.readWeather(config) dt, t = dtime(t) print '# Reading weather required %.2f seconds' %(dt) # Set up a Downtime object to read the downtime data. downtime = Downtime() downtime.readDowntime(config) dt, t = dtime(t) print '# Reading downtime required %.2f seconds' %(dt) # Read observations. obs = ObsFields() obs.readInputObs(inputobs_file, config) nobs = len(obs.ra) dt, t = dtime(t) print '# Reading %d input observations required %.2f seconds' %(nobs, dt) # Check timing of input observations. if config['check_observations']: obs.checkInputObs(config) dt, t = dtime(t) print '# Checking %d input observations required %.2f seconds' %(nobs, dt) else: print '# Did not check input observations for minimum required timing separation!' # Calculate alt/az/airmass for all fields. obs.getAltAzAirmass(skypos) dt, t = dtime(t) print '# Calculating alt/az/airmass for %d input observations required %.2f seconds' %(nobs, dt) # Calculate weather (cloud/seeing) for all fields. dt, t = dtime(t) obs.getObsWeather(weather, config) dt, t = dtime(t) print '# Getting weather information for %d observations required %.2f seconds' %(nobs, dt) # Check downtime status for these observations obs.getDowntime(downtime, config) # Calculate position of sun at the times of these observations. sun = Sun() dt, t = dtime(t) sun.calcPos(obs.mjd) sun.getAltAz(skypos) dt, t = dtime(t) print '# Calculating sun position at %d times required %.2f seconds' %(nobs, dt) # Calculate the position, phase and altitude of the Moon. moon = Moon() moon.calcPos(obs.mjd, config) moon.getAltAz(skypos) dt, t = dtime(t) print '# Calculating moon position at %d times required %.2f seconds' %(nobs, dt) # Will clean this up and put into classes as time is available. # Calculate the sky brightness. skybright = SkyBright(model='Perry', solar_phase='ave') sky = numpy.zeros(len(obs.mjd), 'float') filterlist = numpy.unique(obs.filter) for f in filterlist: condition = (obs.filter == f) skybright.setSkyBright(obs.alt[condition], obs.az[condition], moon.alt[condition], moon.az[condition], moon.phase[condition], bandpass = f) sky[condition] = skybright.getSkyBright() # Add modification to match 'skybrightness_modified' (which is brighter in twilight) sky = numpy.where(sun.alt > -18, 17, sky) dt, t = dtime(t) print '# Calculating the sky brightness for %d observations required %.2f seconds' %(nobs, dt) # Calculate the 5-sigma limiting magnitudes. maglimit = numpy.zeros(len(obs.mjd), 'float') m5 = m5calculations() # Read the throughput curves for LSST (needed to determine zeropoints). m5.setup_Throughputs(verbose=False) # Swap 'y4' for 'y' (or other default y value). tmp_filters = m5.check_filter(obs.filter) # Determine the unique exposure times, as have to set up dark current, etc. based on this for telescope ZP's. exptimes = numpy.unique(obs.exptime) for expT in exptimes: condition = [obs.exptime == expT] # Calculate telescope zeropoints. # Calculate actual open-sky time, after accounting for readout time, number of exposures per visit, shutter time, etc. opentime = ((expT - config['readout_time']*config['nexp_visit'] - config['nexp_visit']* config['add_shutter']*config['shutter_time']) / float(config['nexp_visit'])) print "# Calculating depth for %d exposures of %.2f open shutter time" %(config['nexp_visit'], opentime) m5.setup_values(expTime=opentime, nexp=config['nexp_visit']) # Calculate 5sigma limiting magnitudes. maglimit[condition] = m5.calc_maglimit(obs.seeing[condition], sky[condition], tmp_filters[condition], obs.airmass[condition], snr=5.0) dt, t = dtime(t) print '# Calculating the m5 limit for %d observations required %.2f seconds' %(nobs, dt) # Print out interesting values. obs.printObs(sun, moon, sky, maglimit, config)
def PMTweet(self): self.weatherObj = Weather(GPSLOCATION, AIRPORT, 1) self.rec = Recommendation.Recommendation(self.weatherObj) self.formTweet() TweetPublisher(self.tweetContents)
from Weather import Weather import datetime import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.OUT) current_Date_Time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") location = "60 Cranbury Neck Road" while (True): print(Weather(location, current_Date_Time).makeRequest()) if (Weather(location, current_Date_Time).makeRequest()) < 32: print("its cold") #turn on LED GPIO.output(4, True) time.sleep(4) GPIO.output(4, False) time.sleep(2) time.sleep(3) GPIO.cleanup()
from Weather import Weather from CSVReader import Reader import sys, re climita = Weather() lector = Reader() """Aquí se concretarán las peticiones y formato de respuestas a nuestros clientes""" def run(): validate_file(sys.argv) """Aquí tenemos una lista de diccionarios con las peticiones de climas a resolver""" entradas = lector.read_csv_file(sys.argv[1]) solicitudes_no_repetidas = lector.read_no_repeated_coordinates(sys.argv[1]) """Busca y selecciona las peticiones no repetidas para posteriormente enviarlas al servidor""" peticiones = {} for solicitud in solicitudes_no_repetidas: peticion = climita.make_api_request_by_coordinates( solicitud[0], solicitud[1]) peticiones.setdefault(solicitud, peticion) """Selecciona y asigna a cada linea del archivo original su solicitud completada""" for entrada in entradas: print("CLIMA DE ORIGEN ({}):\n".format(entrada['origin']) + peticiones[(entrada['origin_latitude'], entrada['origin_longitude'])] + "\nCLIMA DE DESTINO ({}):\n".format(entrada['destination']) + peticiones[(entrada['destination_latitude'], entrada['destination_longitude'])] + "\n\n\n")
def getopsimouts(inputobs_file , override_config_file=None, outfile=None, verbose=False): """ Obtains the output of opsimObs for interesting quantities based on the input file. This function is used in creating the ouputs converted into the simlib file. TODO: Actually this function should go into makelsstsims rather than here. """ config = setDefaultConfigs(override_config_file) # Set up a skypos object to hold site information and provide ra/dec -> alt/az/airmass translations. skypos = SkyPos() skypos.setSite(lat=config['latitude'], lon=config['longitude'], height=config['height'], pressure=config['pressure'], temperature=config['temperature'], relativeHumidity=config['relativeHumidity'], lapseRate=config['lapseRate']) # Set up a Weather object to read the site weather data. t = time.time() weather = Weather() weather.readWeather(config) dt, t = dtime(t) if verbose: print '# Reading weather required %.2f seconds' %(dt) # Set up a Downtime object to read the downtime data. downtime = Downtime() downtime.readDowntime(config) dt, t = dtime(t) if verbose: print '# Reading downtime required %.2f seconds' %(dt) # Read observations. obs = ObsFields() obs.readInputObs(inputobs_file, config) nobs = len(obs.ra) dt, t = dtime(t) if verbose: print '# Reading %d input observations required %.2f seconds' %(nobs, dt) # Check timing of input observations. if config['check_observations']: obs.checkInputObs(config) dt, t = dtime(t) if verbose: print '# Checking %d input observations required %.2f seconds' %(nobs, dt) print '# Did not check input observations for minimum required timing separation!' # Calculate alt/az/airmass for all fields. obs.getAltAzAirmass(skypos) dt, t = dtime(t) if verbose: print '# Calculating alt/az/airmass for %d input observations required %.2f seconds' %(nobs, dt) # Calculate weather (cloud/seeing) for all fields. dt, t = dtime(t) obs.getObsWeather(weather, config) dt, t = dtime(t) if verbose: print '# Getting weather information for %d observations required %.2f seconds' %(nobs, dt) # Check downtime status for these observations obs.getDowntime(downtime, config) # Calculate position of sun at the times of these observations. sun = Sun() dt, t = dtime(t) sun.calcPos(obs.mjd) sun.getAltAz(skypos) dt, t = dtime(t) if verbose: print '# Calculating sun position at %d times required %.2f seconds' %(nobs, dt) # Calculate the position, phase and altitude of the Moon. moon = Moon() moon.calcPos(obs.mjd, config) moon.getAltAz(skypos) dt, t = dtime(t) if verbose: print '# Calculating moon position at %d times required %.2f seconds' %(nobs, dt) # Will clean this up and put into classes as time is available. # Calculate the sky brightness. skybright = SkyBright(model='Perry', solar_phase='ave') sky = numpy.zeros(len(obs.mjd), 'float') filterlist = numpy.unique(obs.filter) for f in filterlist: condition = (obs.filter == f) skybright.setSkyBright(obs.alt[condition], obs.az[condition], moon.alt[condition], moon.az[condition], moon.phase[condition], bandpass = f) sky[condition] = skybright.getSkyBright() """ for i in range(len(obs.mjd)): # Calculate sky brightness for each observation. skybright.setSkyBright(obs.alt[i], obs.az[i], moon.alt[i], moon.az[i], moon.phase[i], bandpass=obs.filter[i]) sky[i] = skybright.getSkyBright() """ # Add modification to match 'skybrightness_modified' (which is brighter in twilight) sky = numpy.where(sun.alt > -18, 17, sky) dt, t = dtime(t) if verbose: print '# Calculating the sky brightness for %d observations required %.2f seconds' %(nobs, dt) # Calculate the 5-sigma limiting magnitudes. maglimit = numpy.zeros(len(obs.mjd), 'float') m5 = m5calculations() # Read the throughput curves for LSST (needed to determine zeropoints). m5.setup_Throughputs(verbose=False) # Swap 'y4' for 'y' (or other default y value). tmp_filters = m5.check_filter(obs.filter) # Determine the unique exposure times, as have to set up dark current, etc. based on this for telescope ZP's. exptimes = numpy.unique(obs.exptime) for expT in exptimes: condition = [obs.exptime == expT] # Calculate telescope zeropoints. # Calculate actual open-sky time, after accounting for readout time, number of exposures per visit, shutter time, etc. opentime = ((expT - config['readout_time']*config['nexp_visit'] - config['nexp_visit']* config['add_shutter']*config['shutter_time']) / float(config['nexp_visit'])) print "# Calculating depth for %d exposures of %.2f open shutter time" %(config['nexp_visit'], opentime) m5.setup_values(expTime=opentime, nexp=config['nexp_visit']) # Calculate 5sigma limiting magnitudes. maglimit[condition] = m5.calc_maglimit(obs.seeing[condition], sky[condition], tmp_filters[condition], obs.airmass[condition], snr=5.0) dt, t = dtime(t) if verbose: print '# Calculating the m5 limit for %d observations required %.2f seconds' %(nobs, dt) # Print out interesting values. obs.printObs(sun, moon, sky, maglimit, config, outfile)
class FullscreenWindow: def __init__(self): self.tk = Tk() self.tk.configure(background='black') self.topFrame = Frame(self.tk, background = 'black') self.bottomFrame = Frame(self.tk, background = 'black') self.topFrame.pack(side = TOP, fill=BOTH, expand = YES) self.bottomFrame.pack(side = BOTTOM, fill=BOTH, expand = YES) self.state = False self.tk.bind("<Return>", self.toggle_fullscreen) self.tk.bind("<Escape>", self.end_fullscreen) # weather self.weather = Weather(self.topFrame) self.weather.place(x=0, y=5, anchor=NW, width=700, height=400) # Date self.date = Date(self.topFrame) self.date.place(x=1015, y=10, anchor=NE, width=350, height=90) # Day self.day = Day(self.topFrame) self.day.place(x=860, y=10, anchor=NE, width=300, height=90) # clock self.clock = Clock(self.topFrame) self.clock.place(x=940, y=60, anchor=NE, width=250, height=90) #Seconds self.sec = Sec(self.topFrame) self.sec.place(x=1015, y=60, anchor=NE, width=80, height=85) # news self.news = News(self.bottomFrame) self.news.pack(side=LEFT, anchor=S, padx=0, pady=10) # Facial rec #self.FacialRecognition = News(self.bottomFrame) #self.FacialRecognition.pack(side=LEFT, anchor=N, padx=100, pady=60) # calender self.calender = Calendar(self.topFrame) self.calender.place(x=1015, y=150, width=250, anchor=NE) # calender Time self.calenderTime = CalendarTime(self.topFrame) self.calenderTime.place(x=850, y=172, width=250, anchor=NE) #Traffic self.traffic = Traffic(self.topFrame) #Launch self.launch = Launch(self.topFrame) #crypto name self.crypto = Crypto(self.topFrame) self.crypto.pack(side=TOP, anchor=NE) #Crypto Time self.cryptoPrice = CryptoPrice(self.topFrame) self.cryptoPrice.pack(side=TOP, anchor=NE) #camera s = FacialRec() def toggle_fullscreen(self, event=None): self.state = not self.state # Just toggling the boolean self.tk.attributes("-fullscreen", self.state) return "break" def end_fullscreen(self, event=None): self.state = False self.tk.attributes("-fullscreen", False) return "break"
class ResponseGenerator: weather = Weather() whQuestions = [ 'what', 'who', 'why', 'where', 'when', 'which', 'whom', 'whose', 'how' ] timeDateKeywords = ['time', 'date', 'day'] dayResponses = ['sir, today is ', 'today is '] timeResponses = ['sir, it is ', "it's ", 'it is '] def getWords(self, sentence): return sentence.split(' ') def isSelf(self, words): _list = ['you', 'your'] for word in words: if word in _list: return True def isGreeting(self, sentence): for word in self.greetings: if sentence.__contains__(word): return True def isWhQuestion(self, sentence): isWhQuestion = False for whQuestion in self.whQuestions: if sentence.__contains__(whQuestion): isWhQuestion = True break return isWhQuestion, whQuestion def getCurrentSystemTime(self): return datetime.now().strftime( Utility.getValueFromConfigurationFile("time-format")) def getCurrentSystemDate(self): return datetime.now().strftime( Utility.getValueFromConfigurationFile("date-format")) def hasNumbers(self, sentence): return any(char.isdigit() for char in sentence) def calculate(self, words): # needs to be fixed... i = 0 result = 0.0 operator = '' _list = [ "sir, if I'm not mistaken, the result should be ", "the result is " ] for word in words: if word == '+' or word == '-' or word == 'x' or word == 'into' or word == '/' or word == 'divided' or word == 'by' or word == 'over': operator = word else: try: if i == 0: result = float(word) elif operator == '+': result += float(word) elif operator == '-': result -= float(word) elif operator == 'x' or operator == 'into': result *= float(word) elif operator == '/' or operator == 'divided' or operator == 'by' or 'over': result /= float(word) i += 1 except: continue return str(result) def getResponse(self, sentence): # major modification needs to be done... response = None sentence = sentence.lower() words = self.getWords(sentence) if self.hasNumbers(sentence) and ( sentence.__contains__('+') or sentence.__contains__('-') or sentence.__contains__('into') or sentence.__contains__('x') or sentence.__contains__('/') or sentence.__contains__('divided') or sentence.__contains__('by') or sentence.__contains__('over')): response = self.calculate(words) elif sentence.__contains__('time') and (sentence.__contains__('date') or words.__contains__('day')): response = random.choice( self.dayResponses) + self.getCurrentSystemDate( ) + ' and ' + random.choice( self.timeResponses) + self.getCurrentSystemTime() elif sentence.__contains__('time'): response = random.choice( self.timeResponses) + self.getCurrentSystemTime() elif sentence.__contains__('date') or words.__contains__('day'): response = random.choice( self.dayResponses) + self.getCurrentSystemDate() elif sentence.__contains__('weather'): response = self.weather.getWeatherStatus("Dhaka, BD") elif sentence.__contains__('temperature'): response = self.weather.getTemperature("Dhaka, BD") elif sentence.__contains__('humidity'): response = self.weather.getHumidity("Dhaka, BD") elif sentence.__contains__('wind'): # needs to be fixed... response = self.weather.getWindInformation("Dhaka, BD") elif sentence.__contains__('sun'): _lists = [['rise', 'shine'], ['set']] if sentence.__contains__(_lists[0][0]) or sentence.__contains__( _lists[0][1]): response = 'Sun will ' + random.choice( _lists[0]) + ' at ' + self.weather.getSunriseTime( "Dhaka, BD") elif sentence.__contains__(_lists[1][0]): response = 'Sun will ' + random.choice( _lists[1]) + ' at ' + self.weather.getSunsetTime( "Dhaka, BD") else: response = Utility.getData( sentence, Utility.getDataFrame("response.xlsx")) # needs to be fixed... return str(response)
def test_convert_array_to_string(self): array = ["I ", "like ", "making ", "unit ", "tests!"] self.assertEqual(Weather.convert_array_to_string(self, array), "I like making unit tests!")
}, { 'music': '瞬き', 'artist': 'Back Number' }, { 'music': '津軽海峡冬景色', 'artist': '石川さゆり' }] return musiclist[random.randrange(0, len(musiclist) - 1)] if __name__ == '__main__': try: locate = ('130010', '140010', '120010') #東京、神奈川、千葉 selectday = ('今日', '明日', '明後日') weather = Weather() getmusic = Music() getedweather = weather.returnweather(selectday[0], locate[0]) musicinfo = getrandommusic(getedweather[2]) #ここに天気を渡して、DBからランダムで曲名を取り出す処理を書く resultmusic = getmusic.setkeywords(musicinfo['music'], musicinfo['artist']) text_header = getedweather[0] + 'の' + getedweather[ 1] + 'の天気は' + getedweather[2] + 'です。' if resultmusic[0] == '検索結果0': text_subject = musicinfo['artist'] + 'の' + musicinfo[ 'music'] + 'ですが、youtubeの検索で該当しませんでした。' lambda_handler(text_header, text_subject)
#Connectors iotfClient = IBMConnector(commandCallback) time.sleep(2) csvPersistor = CSVPersistor("Plant1") time.sleep(1) #Sensors waterTemperature = Dallas() time.sleep(1) airInside = DHT(23) time.sleep(1) airOutside = DHT(24) time.sleep(1) systemData = SystemData() time.sleep(1) weather = Weather() time.sleep(1) #Actuators outsideFan = TimedDigitalActuator(20) time.sleep(1) insideFan = TimedDigitalActuator(21) time.sleep(1) humidifier = TimedDigitalActuator(16) time.sleep(1) hatch = Hatch() time.sleep(1) stepper = Stepper() time.sleep(1) #picture
def weather(self): # Create Weather Class as a container to what will happen during time # THIS NEEDS TO BE SET TO PRACTICAL DEGENERATIVE PARAMETERS time = Weather() # Add Attributes this Weather will help morale = Attribute("Morale") morale.setValue(-1) time.addAttribute(morale) hygiene = Attribute("Hygiene") hygiene.setValue(-1) time.addAttribute(hygiene) hunger = Attribute("Hunger") hunger.setValue(-1) time.addAttribute(hunger) fatigue = Attribute("Fatigue") fatigue.setValue(-1) time.addAttribute(fatigue) health = Attribute("Health") health.setValue(-100) time.addAttribute(health) # Post as a Cluster Weather Event ev = Events.ClusterWeatherEvent(0, time) self.mediator.post(ev)
with open(feed_path, "w") as file: file.write(f""" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="container mb-5"> <h1>Your feed for {today.strftime('%d %b %Y')}</h1> """) w = Weather() w.write_weather() e = Events() e.write_events() r = Reddit() with open(feed_path, "a") as file: file.write("<h2>Reddit</h2>") r.fetch_subs_and_write("reactjs") r.fetch_subs_and_write("webdev") r.fetch_subs_and_write("frontend") r.fetch_subs_and_write("python") r.fetch_subs_and_write("rollerblading")
def weatherForcast(): frame = Frame(win, width=480, height=720) frame.pack(fill=BOTH, expand=TRUE) weatherFrame = Weather() weatherFrame.getWeather(frame, registerwin, name, city)
def main(): address_old = 'localhost' port_old = 27017 address_new = '192.168.6.254' port_new = 37017 print("convert label type data") LabelType.insert_label_type(address_new, port_new) print("convert area data") Area.insert_area(address_old, port_old, address_new, port_new) print("convert label data") Label.convert_label(address_old, port_old, address_new, port_new) # 城市表 依赖新导入的Label表,需保证City前导入Label print("convert city data") City.convert_city(address_old, port_old, address_new, port_new) print("convert weather data") Weather.convert_weather(address_old, port_old, address_new, port_new, Weather.collection_old, Weather.collection_new, Weather.params_map) # 特别注意 weather_history 表依赖于当前的 weather 表 print("create weather_history data") WeatherHistory.create_weather_history(address_new, port_new, address_new, port_new, WeatherHistory.collection_old, WeatherHistory.collection_new, WeatherHistory.params_map) print("convert pgc data") Pgc.convert_pgc(address_old, port_old, address_new, port_new) print("convert label data") Label.convert_label(address_old, port_old, address_new, port_new) print("convert attraction data") Attraction.convert_attraction(address_old, port_old, address_new, port_new, Attraction.collection_old, Attraction.collection_new, Attraction.params_map) print("convert restaurant data") Restaurant.convert_restaurant(address_old, port_old, address_new, port_new, Restaurant.collection_old, Restaurant.collection_new, Restaurant.params_map) print("convert shopping data") Shopping.convert_shopping(address_old, port_old, address_new, port_new, Shopping.collection_old, Shopping.collection_new, Shopping.params_map) print("convert activity data") Activity.convert_activity(address_old, port_old, address_new, port_new, Activity.collection_old, Activity.collection_new, Activity.params_map) print("convert recommendBynamic data") # RecommendDynamic.convert_recommendDynamic(address_old, port_old, address_new, port_new,RecommendDynamic.collection_old, # RecommendDynamic.collection_new, RecommendDynamic.params_map) print("convert plan data") Plan.convert_plan(address_old, port_old, address_new, port_new, Plan.collection_old, Plan.collection_new, Plan.params_map) print("convert brand data") Brand.convert_brand(address_old, port_old, address_new, port_new, Brand.collection_old, Brand.collection_new, Brand.params_map) print("OK")
class HeatCalculationTest(unittest.TestCase): def setUp(self): self.gbxml = gbXML( os.path.join(os.path.dirname(__file__), 'input/Single_model.xml')) #self.gbxml = gbXML(os.path.join(os.path.dirname(__file__), 'input/Four_Room_Two_Floors_Model.xml')) # To test middle interior floor area = Area() area.createAreaDictionary() area.createWinAreaDictionary() self.areaWinDict = area.getWinDictionary() self.areaDict = area.getDictionary() spaces = self.gbxml.get_spaces() surfaces = spaces[0].surfaces self.heat = HeatCalculation() self.temp_record = self.gbxml.temp_record self.spaces_dict = self.gbxml.spaces_dict self.shgc_dictionary = self.gbxml.shgc_dictionary self.shadow_record = self.gbxml.shadow_record self.shade_surf_list = self.gbxml.get_shades() self.surfaces_dict = self.gbxml.surfaces_dict self.space1 = spaces[0] #surfaces1 = spaces[0].surfaces #self.space2 = spaces[1] #surfaces2 = spaces[1].surfaces #self.surface6 = surfaces1[5] # su-6 #self.surface11 = surfaces2[5] # su-11 self.surface1 = surfaces[0] self.surface2 = surfaces[1] self.surface3 = surfaces[2] self.surface4 = surfaces[3] self.surface5 = surfaces[4] self.surface6 = surfaces[5] self.G_space_record = dict() self.G_space_record["sp-1-Room"] = 0 # Create a fake weather self.weather = Weather('Washington', datetime(year=1997, month=1, day=1, hour=3), datetime(year=1997, month=1, day=1, hour=4)) # And a timestep self.tstep2 = datetime(year=1997, month=1, day=1, hour=4) # get the weather at the tstep self.wtstep2 = self.weather.get_weather_step(self.tstep2) # And another timestep self.tstep = datetime(year=1997, month=1, day=1, hour=3) # get the weather at the tstep self.wtstep = self.weather.get_weather_step(self.tstep) def test_get_floor_heat( self): # done with the four room model as gbxml input above A_noOp_floor = 9.290304 G_space = 0 #floor_heat = self.heat.get_floor_heat(self.surface6, self.wtstep, G_space, self.spaces_dict, A_noOp_floor, self.temp_record) #self.assertEqual(floor_heat, -16.112311, 'top heat for surface 6: %s ' % floor_heat) #Getting -16.112311 but need to check these with Na, also the G_space Coeff = 1 A_noOp_floor = 9.290304 G_space = 0 floor_heat = self.heat.get_floor_heat(self.space1, self.surface6, self.wtstep, G_space, self.spaces_dict, A_noOp_floor, self.temp_record, Coeff, self.areaDict, self.areaWinDict) floor_heat = round(floor_heat, 3) self.assertEqual( floor_heat, -1.984, 'top heat for surface 11: %s ' % floor_heat ) #Getting -16.112311 but need to check these with Na, also the G_space def test_get_top_heat(self): Coeff = 1 floor_heat = self.heat.get_top_heat(self.space1, self.surface4, self.wtstep, self.spaces_dict, self.temp_record, Coeff, self.G_space_record, self.areaDict, self.areaWinDict) floor_heat = round(floor_heat, 15) self.assertEqual(floor_heat, -0.00000000000236, 'top heat for surface 5 (roof): %s ' % floor_heat) def test_get_raised_floor_heat(self): A_noOp_floor = 18.580608 G_space = 0 h_surface = 0 terrain = "Flat or Open Countryside" Coeff = 1 self.wtstep["t_outside"] = 280 # Fake Temp Value #self.wtstep["ground_temperature_K"] = 280 # Fake Temp Value floor_heat = self.heat.get_raised_floor_heat( self.surface6, self.wtstep, G_space, A_noOp_floor, self.temp_record, self.space1, self.spaces_dict, h_surface, terrain, Coeff, self.areaDict, self.areaWinDict) self.assertEqual( floor_heat, -5.492465, 'floor heat for surface 6: %s ' % floor_heat ) #Getting -40.221503 with G_space = 0, will need updating for model 1 def test_get_ground_heat(self): A_noOp_floor = 18.580608 G_space = 0 Coeff = 1 ground_heat = self.heat.get_ground_heat(self.surface6, self.wtstep, G_space, A_noOp_floor, self.temp_record, self.space1, self.spaces_dict, Coeff, self.areaDict, self.areaWinDict) self.assertEqual( ground_heat, -3.720495, 'ground heat for surface 6: %s ' % ground_heat ) #Getting -38.264154 with G_space = 0, will need updating for model 1
def getDailyWeather(): return jsonify(DailyForecast=Weather().getDaily())
#! -*- coding: utf-8 -*- from Weather import Weather if __name__ == '__main__': w = Weather() w.getData()
def setup(self): self.weather = Weather() pass
def testWeatherConstructorEmptyState(self): w = Weather(1, 2, 3, 4) self.assertEqual(w.getWeatherState(), '')
class SpaceTest(unittest.TestCase): def setUp(self): self.gbxml = gbXML( os.path.join(os.path.dirname(__file__), 'input/Single_model.xml')) #self.gbxml = gbXML(os.path.join(os.path.dirname(__file__), 'input/Four_Room_Two_Floors_Model.xml')) # To test middle interior floor area = Area() area.createAreaDictionary() area.createWinAreaDictionary() self.areaWinDict = area.getWinDictionary() self.areaDict = area.getDictionary() spaces = self.gbxml.get_spaces() self.volume = Space() self.temp_record = self.gbxml.temp_record self.spaces_dict = self.gbxml.spaces_dict self.shgc_dictionary = self.gbxml.shgc_dictionary self.shadow_record = self.gbxml.shadow_record self.shade_surf_list = self.gbxml.get_shades() self.surfaces_dict = self.gbxml.surfaces_dict self.space1 = spaces[0] surfaces = spaces[0].surfaces self.surface6 = surfaces[5] self.surface5 = surfaces[4] self.surface4 = surfaces[3] self.surface3 = surfaces[2] self.surface2 = surfaces[1] self.surface1 = surfaces[0] # Create a fake weather self.weather = Weather('Washington', datetime(year=1997, month=1, day=1, hour=3), datetime(year=1997, month=1, day=1, hour=4)) # And a timestep self.tstep2 = datetime(year=1997, month=1, day=1, hour=4) # get the weather at the tstep self.wtstep2 = self.weather.get_weather_step(self.tstep2) # And another timestep self.tstep = datetime(year=1997, month=1, day=1, hour=3) # get the weather at the tstep self.wtstep = self.weather.get_weather_step(self.tstep) def test_calculate_space_heatflux(self): Coeff = 1 ShadowsFlag = 0 terrain = "Flat or Open Countryside" A = 0 missing_surfaces = dict() # Should not matter for this test case G_space_record = dict() G_space_record["su-1"] = 0 G_space_record["su-2"] = 0 G_space_record["su-3"] = 0 G_space_record["su-4"] = 0 G_space_record["su-5"] = 0 G_space_record["su-6"] = 0 ns = (len(self.shade_surf_list) + len(self.shadow_record)) heatflux = self.volume.calculate_space_heatflux( self.space1, self.wtstep, self.spaces_dict, self.temp_record, Coeff, ShadowsFlag, ns, self.shadow_record, self.shade_surf_list, self.surfaces_dict, A, missing_surfaces, terrain, G_space_record, self.areaDict, self.areaWinDict) self.assertEqual( heatflux, 45.659443, 'heatflux for this space is: %s ' % heatflux ) # Getting 45.256363 for single model until compare with Na def test_get_height(self): x = self.temp_record height = self.volume.get_height(self.surface5) self.assertEqual(height, 3.37185, 'height for surface 5: %s ' % height) height = self.volume.get_height(self.surface6) self.assertEqual(height, 0, 'height for surface 6: %s ' % height) #This is the floor level = 0 height = self.volume.get_height(self.surface1) self.assertEqual(height, 1.685925, 'height for surface 1: %s ' % height) height = self.volume.get_height(self.surface2) self.assertEqual(height, 1.685925, 'height for surface 2: %s ' % height) height = self.volume.get_height(self.surface3) self.assertEqual(height, 1.685925, 'height for surface 3: %s ' % height) height = self.volume.get_height(self.surface4) self.assertEqual(height, 1.685925, 'height for surface 4: %s ' % height) def test_get_height_floorspace(self): height = self.volume.get_height_floorspace(self.space1) #print "height is: ", height self.assertEqual(height[0], 0, 'height for surface 6: %s ' % height[0]) # 6 is the only floor to test here
from Location import Location from Weather import Weather from datetime import datetime import time weatherKey = 'XXXXXXXXXXXXX' IPKey = 'XXXXXXXXXXX' units = 'imperial' syncTime = False; while True: location = Location(IPKey).getLocation() weatherTime = Weather(weatherKey, location).getTime() actualWeather = Weather(weatherKey, location).getWeather() actualTime = datetime.now() forcastTime = datetime.fromtimestamp(Weather(weatherKey, location).getForecast(units, 1)[0]) forcastWeather = Weather(weatherKey, location).getForecast(units, 1)[1][0]['main'] print('Real time: '+str(actualTime)) print('App time: '+str(weatherTime)) print('Current weather:'+actualWeather) print('Forecast time: '+str(forcastTime)) print('Forecast Weather: '+forcastWeather) if forcastWeather == 'Rain': print('Bring Umbrella\n') elif forcastWeather == 'Clouds': print('Enjoy the cloudy weather!\n') elif forcastWeather == 'Clear': print('Nice weather!\n') else: print(forcastWeather)
def main(): #---------------------------------------------------------------------------# # Logging - Rotate log file at midnight and keep for 7 days #---------------------------------------------------------------------------# handler = logging.handlers.TimedRotatingFileHandler(Config.Log_Filename, when="midnight", interval=1, backupCount=7) handler.setFormatter( logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logger = logging.getLogger('cr-smart-home') logger.addHandler(handler) logger.setLevel(Config.Log_Level) log = Log() log.info('Server', 'Starting CR Smart Home %s...' % Config.Version) #---------------------------------------------------------------------------# # Upgrade #---------------------------------------------------------------------------# upgrade = Upgrade() upgrade.Upgrade() #---------------------------------------------------------------------------# # Startup #---------------------------------------------------------------------------# weather = Weather() sun = Sun() lamp = Lamp() sensor = Sensor() log.info( 'Server', 'System is running in %s (Lat=%f, Long=%f)' % (weather.city, sun.latitude, sun.longitude)) bStartUp = True #---------------------------------------------------------------------------# # Run program #---------------------------------------------------------------------------# while True: # Update current weather on startup or every 30 minutes if (datetime.now().minute == 0 or datetime.now().minute == 30 or bStartUp == True): weather.UpdateCurrentWeather() # Update sun to database every hour if (datetime.now().minute == 0 or bStartUp == True): sun.UpdateDb() # Lamp schedule lamp.Schedule() # Sensors if (datetime.now().minute % 10 == 0 or bStartUp): sensor.readAll() #Reset startup bool bStartUp = False #Sleep one minute time.sleep(60 - datetime.now().second)