def setUpClass(cls): try: data = WeatherData() data.load('weather_data.csv') cls.data = data except Exception: pass
def __print_labels(data: WeatherData): for i in range(len(data.get_times())): current_time = data.get_times()[i] current_t = data.get_temperature()[i] plt.annotate(current_t if current_t < 0 else '+' + str(current_t), xy=(current_time, current_t), color='green')
def test_user_provided_location(): w = WeatherData("london") assert w.userProvidedLocation == True w.get_weather() assert w.location == "London" w2 = WeatherData() assert w2.userProvidedLocation == False
def updateView(self): self._secs_since_last_update += 1 time_now = time.strftime("%H:%M:%S") date_now = time.strftime("%d.%m.%Y") if self._secs_since_last_update > 10: print('WeatherUI :: updateView -> getting data') self._secs_since_last_update = 0 self._is_time_to_repaint = True self._my_data = WeatherData(time_now) self._my_data.start() if not self._my_data.is_alive() and self._is_time_to_repaint: print('WeatherUI :: updateView -> repainting') self._is_time_to_repaint = False self.txt_label_inside.configure(text=self._get_inside_text()) self.txt_label_current.configure( text=self._get_current_weather_text( self._my_data.get_current_weather())) self.txt_label_forecast_today.configure( text=self._get_next_hours_text()) self.txt_label_plus_1d.configure(text=self._get_next_days_text( self._my_data.get_forecast_plus_1d())) self.txt_label_plus_2d.configure(text=self._get_next_days_text( self._my_data.get_forecast_plus_2d())) self.txt_label_plus_3d.configure(text=self._get_next_days_text( self._my_data.get_forecast_plus_3d())) self.txt_label_plus_4d.configure(text=self._get_next_days_text( self._my_data.get_forecast_plus_4d())) img = PhotoImage(file=self._icon_helper.get_icon_path( self._my_data.get_current_weather().weather_id)) self.img_label_current.configure(image=img) self.img_label_current.image = img img = PhotoImage(file=self._icon_helper.get_icon_path( self._my_data.get_forecast_plus_1d().weather_id)) self.img_label_plus_1d.configure(image=img) self.img_label_plus_1d.image = img img = PhotoImage(file=self._icon_helper.get_icon_path( self._my_data.get_forecast_plus_2d().weather_id)) self.img_label_plus_2d.configure(image=img) self.img_label_plus_2d.image = img img = PhotoImage(file=self._icon_helper.get_icon_path( self._my_data.get_forecast_plus_3d().weather_id)) self.img_label_plus_3d.configure(image=img) self.img_label_plus_3d.image = img img = PhotoImage(file=self._icon_helper.get_icon_path( self._my_data.get_forecast_plus_4d().weather_id)) self.img_label_plus_4d.configure(image=img) self.img_label_plus_4d.image = img self.txt_label_time.configure(text=time_now) self.txt_label_date.configure(text=date_now) self.after(1000, self.updateView)
def main(): weather_data = WeatherData() current_condition_display = CurrentConditionDisplay() weather_data.add_observer(current_condition_display) weather_data.set_measurements(10, 12, 30) weather_data.set_measurements(50, 60, 70) weather_data.delete_observer(current_condition_display) weather_data.set_measurements(100, 200, 300)
def print_graphic(data: WeatherData, path, count): if data.is_valid(): x = data.get_times() new_x = np.linspace(0, count - 2, num=100, endpoint=True) fig, axs = plt.subplots(2, 1, sharex=True, sharey=False, gridspec_kw={'height_ratios': [1, 3]}, figsize=(10, 5)) labels_x = [] for lx in x: if lx > 24: labels_x.append(lx - 24) else: labels_x.append(lx) plt.xticks(np.arange(min(x), max(x) + 1, 3.0), labels_x) __print_labels(data) t = data.get_temperature() interpolation_t = interp1d(x, t, kind='cubic') points_t = np.array([new_x, interpolation_t(new_x)]).T.reshape(-1, 1, 2) segments_t = np.concatenate([points_t[:-1], points_t[1:]], axis=1) norm_t = plt.Normalize(-15, 18) line_collect_t = LineCollection(segments_t, cmap='cividis', norm=norm_t) line_collect_t.set_array(interpolation_t(new_x)) line_collect_t.set_linewidth(3) axs[1].add_collection(line_collect_t) axs[1].set_xlabel('Температура') axs[0].set_xlabel('Количество осадков') p = data.get_precipitation() interpolation_p = interp1d(x, p, kind='cubic') points_p = np.array([new_x, interpolation_p(new_x)]).T.reshape(-1, 1, 2) segments_p = np.concatenate([points_p[:-1], points_p[1:]], axis=1) norm_p = plt.Normalize(0, 0.3) line_collect_p = LineCollection(segments_p, cmap='Greens', norm=norm_p) line_collect_p.set_array(interpolation_p(new_x)) line_collect_p.set_linewidth(3) axs[0].add_collection(line_collect_p) axs[0].set_xlim(0, count) axs[1].set_ylim(0 if min(t) > 1 else min(t) - 1, 0 if max(t) < -1 else max(t) + 1) axs[0].set_ylim(0, 1 if max(p) < 0.8 else max(p) + 0.5) plt.savefig(path, dpi=150)
def save_graphics_two_day(file_path): today = parser_weather_gis.get_today_weather() next_day = parser_weather_gis.get_tomorrow_weather() union_data = WeatherData() union_data.set_times(today.get_times() + __add_next_day_times(next_day.get_times())) union_data.set_precipitation(today.get_precipitation() + next_day.get_precipitation()) union_data.set_temperature(today.get_temperature() + next_day.get_temperature()) render_graphics.print_graphic(union_data, file_path, 47)
def test_model_import(): # 测试导出的模型再导入是否正确 with open('knn.pickle', 'rb') as fr: clf = pickle.load(fr) wd = WeatherData() res = clf.score(wd.X, wd.y) print('import model, score: ', res)
def test_event_decision4(self): """Test ED._temp_factor rule 2a & 3a and _rain_factor rule 1c""" weather_data = WeatherData() weather_data._weather_data.append( WeatherDataItem(5, 44, 20, 10, 61, 15, 30, "ESE", 1, 1016.3)) sp = self.prediction.SimplePrediction(weather_data, 1) event = self.event_decision.Event('My Event', True, True, 13) ed = self.event_decision.EventDecision(event, sp) self.aggregate(self.assertAlmostEqual, ed._temperature_factor(), -1.8, places=3, tag='_temperature_factor') self.aggregate(self.assertAlmostEqual, ed._rain_factor(), 0, places=3, tag='_rain_factor') self.aggregate(self.assertAlmostEqual, ed.advisability(), -1.8, places=3, tag='advisability') self.aggregate_tests()
def __init__(self, uno, nano, db, data): self.uno = uno self.nano = nano self.current_weather_data = WeatherData() self.current_sensor_data = SensorData() self.current_device_data = data self.db = db
def __init__(self, width, height, master=None): tk.Frame.__init__(self, master) self._width = width self._height = height self._config = configparser.ConfigParser() self._config.read(CONFIG_FILE) self._realtime_api = self._config.get('weather', 'realtime_api') self._airquality_api = self._config.get('weather', 'airquality_api') self._refresh_milliseconds = int( self._config.get('weather', 'refresh_seconds')) * 1000 self._city_code = self._config.get('city', 'code') self._spider = WeatherSpider(realtime_api=self._realtime_api, airquality_api=self._airquality_api) self._weather_data = WeatherData(self._city_code) self._canvas = tk.Canvas(root, width=self._width, height=self._height, bg='white') self._canvas.config(highlightthickness=0) # 去掉边框 self._canvas.pack() self._image = Image.new('1', (self._width, self._height), 'white') image_draw = ImageDraw.Draw(self._image) self._weather_painter = WeatherPainterSmall(image_draw, self._width, self._height) self._tkimg = None self.update_weather_info()
def hello_world(): data = WeatherData() return render_template("index.html", city=data.location, weather=data.weather_dict, clothing=data.clothing, searchCity=data.userProvidedLocation)
def main(): """Main application's starting point.""" check_again = True weather_data = WeatherData() weather_data.load("weather_data.csv") user_interface = UserInteraction() print("Let's determine how suitable your event is for the predicted " "weather.") event = user_interface.get_event_details() while check_again: prediction_model = user_interface.get_prediction_model(weather_data) decision = EventDecision(event, prediction_model) impact = decision.advisability() user_interface.output_advisability(impact) check_again = user_interface.another_check()
def do_export_model(): # 最优模型是knn分类器,模型参数如下 clf = KNeighborsClassifier(n_neighbors=15, weights='uniform', metric='euclidean') # 训练模型 wd = WeatherData() clf.fit(wd.X, wd.y) # 导出模型,用于在RPi Zero中导入 export_model(clf, 'knn.pickle')
def searchcity(): city = request.form['city'] data = WeatherData(city) return render_template("index.html", city=data.location, weather=data.weather_dict, clothing=data.clothing, searchCity=data.userProvidedLocation)
def get_tomorrow_weather(): data = WeatherData() session = requests.session() r = session.get(BASE_URL + NEXT_URL, headers=HEADERS, timeout=5) soup = bs4.BeautifulSoup(r.content, "lxml") widget = __get_widget_container(soup) data.set_temperature(__get_list_of_temperature(widget)) data.set_times(__get_list_of_time(widget)) data.set_precipitation(__get_widget_precipitation(widget)) return data
def test_weather_station(self): weather_data = WeatherData() current_display = CurrentConditionsDisplay(weather_data) statistics_display = StatisticsDisplay(weather_data) forecast_display = ForecastDisplay(weather_data) heat_index_display = HeatIndexDisplay(weather_data) weather_data.set_measurements(80, 65, 30.4) weather_data.set_measurements(82, 70, 29.2) weather_data.set_measurements(78, 90, 29.2)
def show_info(): global img city = city_text.get() if not city: output["text"] = "Please enter the city name!" else: data = WeatherData(city) if data.status >= 400: output["text"] = f"Please check the city name!" else: img = PhotoImage(file=f"icons/{data.icon}.png") status["image"] = img output["text"] = f"Country: {data.country}\n" \ f"City: {data.city}\n" \ f"Temperature: {data.temp} °C"
def main(): # subject weather_data = WeatherData() # observers current_display = CurrentConditionsDisplay(weather_data) heat_index_display = HeatIndexDisplay(weather_data) forecast_display = ForecastDisplay(weather_data) stats_display = StatisticsDisplay(weather_data) weather_data.set_measurements(80, 65, 30.4) weather_data.set_measurements(82, 70, 29.2) weather_data.set_measurements(78, 90, 29.2)
def main(): weatherStation = WeatherData() currentConditonsDisplay = CurrentConditionsDisplay(weatherStation) forecastDisplay = ForecastDisplay(weatherStation) statisticsDisplay = StatisticsDisplay(weatherStation) currentConditonsDisplay.display() forecastDisplay.display() statisticsDisplay.display() weatherStation.setMeasurements(12.0, 25.0, 10.0) weatherStation.setMeasurements(25.0, 15.0, 12.0) weatherStation.setMeasurements(5.0, 10.0, 8.0)
def convert_xml_to_weather_record(data_element): import datetime from weather_data import WeatherData cloudiness = data_element.findtext("nn_shortText", default="") wind_direction = data_element.findtext("dd_longText", default="") wind_speed = data_element.findtext("ff_value", default=data_element.findtext("ff_val")) findtext = data_element.findtext("msl") if findtext: pressure = float(findtext) else: pressure = None return WeatherData( datetime.datetime.strptime( data_element.find("tsValid_issued_UTC").text, "%d.%m.%Y %H:%M %Z"), cloudiness, wind_direction, float(wind_speed), float(data_element.findtext("t")), float(data_element.findtext("rh")), pressure)
def __init__(self, width, height): self._width = width self._height = height self._config = configparser.ConfigParser() self._config.read(CONFIG_FILE) self._realtime_api = self._config.get('weather', 'realtime_api') self._airquality_api = self._config.get('weather', 'airquality_api') self._refresh_seconds = int( self._config.get('weather', 'refresh_seconds')) self._city_code = self._config.get('city', 'code') self._spider = WeatherSpider(realtime_api=self._realtime_api, airquality_api=self._airquality_api) self._weather_data = WeatherData(self._city_code) self._epd = epd2in13_V2.EPD() self._image = Image.new('1', (self._width, self._height), 'white') image_draw = ImageDraw.Draw(self._image) self._weather_painter = WeatherPainterSmall(image_draw, self._width, self._height)
class WeatherUI(Frame): def __init__(self): super().__init__() self.initUI() def initUI(self): print('WeatherUI :: initUI') self._deg_sign = chr(176) self._secs_since_last_update = 11 self._is_time_to_repaint = False self._icon_helper = IconHelper() # main view self.master.title('Windows') self.pack(fill=BOTH, expand=True) self.configure(background='black') # args self._text_style_args = dict(fg='white', bg='black', font='14') self._text_padding_args = dict(pady=5, padx=5) self._photo_style_args = dict(borderwidth=0, highlightthickness=0) # columns self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) self.columnconfigure(2, weight=1) # view frames self._add_time_and_date_frame() self._add_current_weather_frame() self._add_forecast_today_frame() self._add_inside_status_frame() self._add_forecast_for_coming_days_frame() self.updateView() def _add_time_and_date_frame(self): frame_date_time = Frame(self, highlightcolor="grey", highlightthickness=1, background='black') frame_date_time.columnconfigure(0, weight=1) self.txt_label_time = Label(frame_date_time, text='', **self._text_style_args) self.txt_label_time.grid(row=0, column=0, **self._text_padding_args) self.txt_label_date = Label(frame_date_time, text='', **self._text_style_args) self.txt_label_date.grid(row=0, column=1, sticky=E, **self._text_padding_args) frame_date_time.grid(row=0, column=0, columnspan=4, sticky=W + E + N + S) def _add_current_weather_frame(self): frame_current_weather = Frame(self, highlightcolor="grey", highlightthickness=1, background='black') img = PhotoImage(file='../resource/92.png') self.img_label_current = Label(frame_current_weather, image=img, **self._photo_style_args) self.img_label_current.image = img self.img_label_current.grid(row=0, column=0, sticky=W + N) self.txt_label_current = Label(frame_current_weather, text='', justify=LEFT, **self._text_style_args) self.txt_label_current.grid(row=0, column=1, sticky=W + N, **self._text_padding_args) frame_current_weather.grid(row=1, column=0, sticky=W + E + N + S) def _add_forecast_today_frame(self): # forecast today, +3h +6 +9h frame_forecast_today = Frame(self, highlightcolor="grey", highlightthickness=1, background='black') frame_forecast_today.rowconfigure(0, weight=1) self.txt_label_forecast_today = Label(frame_forecast_today, text='', justify=LEFT, **self._text_style_args) self.txt_label_forecast_today.grid(row=0, column=0, **self._text_padding_args) frame_forecast_today.grid(row=1, column=1, sticky=W + E + N + S) def _add_inside_status_frame(self): frame_inside = Frame(self, highlightcolor="grey", highlightthickness=1, background='black') frame_inside.rowconfigure(0, weight=1) self.txt_label_inside = Label(frame_inside, justify=LEFT, text='', **self._text_style_args) self.txt_label_inside.grid(row=0, column=0, **self._text_padding_args) frame_inside.grid(row=1, column=2, sticky=W + E + N + S) def _add_forecast_for_coming_days_frame(self): frame_forecast = Frame(self, highlightcolor="grey", highlightthickness=1, background='black') # forecast + 1 day img = PhotoImage(file='../resource/92.png') self.img_label_plus_1d = Label(frame_forecast, image=img, **self._photo_style_args) self.img_label_plus_1d.image = img self.img_label_plus_1d.grid(row=0, column=0, sticky=W + N) self.txt_label_plus_1d = Label(frame_forecast, text='', justify=LEFT, **self._text_style_args) self.txt_label_plus_1d.grid(row=0, column=1, sticky=W + N, **self._text_padding_args) # forecast + 2 days img = PhotoImage(file='../resource/92.png') self.img_label_plus_2d = Label(frame_forecast, image=img, **self._photo_style_args) self.img_label_plus_2d.image = img self.img_label_plus_2d.grid(row=0, column=2, sticky=W + N) self.txt_label_plus_2d = Label(frame_forecast, text='', justify=LEFT, **self._text_style_args) self.txt_label_plus_2d.grid(row=0, column=3, sticky=W + N, **self._text_padding_args) # forecast + 3 days img = PhotoImage(file='../resource/92.png') self.img_label_plus_3d = Label(frame_forecast, image=img, **self._photo_style_args) self.img_label_plus_3d.image = img self.img_label_plus_3d.grid(row=0, column=4, sticky=W + N) self.txt_label_plus_3d = Label(frame_forecast, text='', justify=LEFT, **self._text_style_args) self.txt_label_plus_3d.grid(row=0, column=5, sticky=W + N, **self._text_padding_args) # forecast + 4 days img = PhotoImage(file='../resource/92.png') self.img_label_plus_4d = Label(frame_forecast, image=img, **self._photo_style_args) self.img_label_plus_4d.image = img self.img_label_plus_4d.grid(row=0, column=6, sticky=W + N) self.txt_label_plus_4d = Label(frame_forecast, text='', justify=LEFT, **self._text_style_args) self.txt_label_plus_4d.grid(row=0, column=7, sticky=W + N, **self._text_padding_args) frame_forecast.grid(row=2, column=0, columnspan=4, sticky=W + E + N + S) def updateView(self): self._secs_since_last_update += 1 time_now = time.strftime("%H:%M:%S") date_now = time.strftime("%d.%m.%Y") if self._secs_since_last_update > 10: print('WeatherUI :: updateView -> getting data') self._secs_since_last_update = 0 self._is_time_to_repaint = True self._my_data = WeatherData(time_now) self._my_data.start() if not self._my_data.is_alive() and self._is_time_to_repaint: print('WeatherUI :: updateView -> repainting') self._is_time_to_repaint = False self.txt_label_inside.configure(text=self._get_inside_text()) self.txt_label_current.configure( text=self._get_current_weather_text( self._my_data.get_current_weather())) self.txt_label_forecast_today.configure( text=self._get_next_hours_text()) self.txt_label_plus_1d.configure(text=self._get_next_days_text( self._my_data.get_forecast_plus_1d())) self.txt_label_plus_2d.configure(text=self._get_next_days_text( self._my_data.get_forecast_plus_2d())) self.txt_label_plus_3d.configure(text=self._get_next_days_text( self._my_data.get_forecast_plus_3d())) self.txt_label_plus_4d.configure(text=self._get_next_days_text( self._my_data.get_forecast_plus_4d())) img = PhotoImage(file=self._icon_helper.get_icon_path( self._my_data.get_current_weather().weather_id)) self.img_label_current.configure(image=img) self.img_label_current.image = img img = PhotoImage(file=self._icon_helper.get_icon_path( self._my_data.get_forecast_plus_1d().weather_id)) self.img_label_plus_1d.configure(image=img) self.img_label_plus_1d.image = img img = PhotoImage(file=self._icon_helper.get_icon_path( self._my_data.get_forecast_plus_2d().weather_id)) self.img_label_plus_2d.configure(image=img) self.img_label_plus_2d.image = img img = PhotoImage(file=self._icon_helper.get_icon_path( self._my_data.get_forecast_plus_3d().weather_id)) self.img_label_plus_3d.configure(image=img) self.img_label_plus_3d.image = img img = PhotoImage(file=self._icon_helper.get_icon_path( self._my_data.get_forecast_plus_4d().weather_id)) self.img_label_plus_4d.configure(image=img) self.img_label_plus_4d.image = img self.txt_label_time.configure(text=time_now) self.txt_label_date.configure(text=date_now) self.after(1000, self.updateView) def _get_inside_text(self): text ='# Inside # \n' +\ 'Temp: ' + str(self._my_data.get_inside().temperature) + ' ' + self._deg_sign + 'C\n' + \ 'Humidity: ' + str(self._my_data.get_inside().humidity) + ' %' return text def _get_current_weather_text(self, data): text = '# Today @ ' + str(data.time) + ' #\n' + \ str(data.temp) + ' ' + self._deg_sign + 'C\n' + \ str(data.wind) + ' m/s, ' + str(data.deg) + self._deg_sign + '\n' + \ str(data.description) return text def _get_next_hours_text(self): data = [ self._my_data.get_forecast_next_3_hours(), self._my_data.get_forecast_next_6_hours(), self._my_data.get_forecast_next_9_hours(), self._my_data.get_forecast_next_12_hours() ] ret_val = "# Coming hours #\n" for i in range(len(data)): text = \ '@ ' + str(data[i].time) + ': ' + \ str(data[i].temp) + ' ' + self._deg_sign + 'C, ' + \ str(data[i].wind) + ' m/s, ' + \ str(data[i].description) ret_val += text if len(data) - 1 != i: ret_val += '\n' return ret_val def _get_next_days_text(self, data): text = '# ' + str(data.time) + ' #\n' + \ 'Day: ' + str(data.temp_day) + ' ' + self._deg_sign + 'C\n' + \ 'Night: ' + str(data.temp_night) + ' ' + self._deg_sign + 'C\n' + \ str(data.wind) + ' m/s, ' + str(data.deg) + self._deg_sign + '\n' + \ str(data.description) return text
from weather_data import WeatherData from billboard import CurrentConditionDisplay if __name__ == '__main__': weather_data = WeatherData() current_display = CurrentConditionDisplay(weather_data) weather_data.set_measurements(80, 65, 30.4) weather_data.set_measurements(82, 70, 29.2) weather_data.set_measurements(78, 90, 29.2)
class TestHighTempEdgeCases(TestA2): """ Test edge cases around high temperature (45). Test air pressure impact on predictions. Test max wind speed impact on wind speed. """ weather_data = WeatherData() day_low = WeatherDataItem(1, 44, 29, 10, 49, 14, 40, "N", 1, 1015) day_mid = WeatherDataItem(2, 45, 30, 10, 50, 15, 60, "SE", 2, 1016) day_high = WeatherDataItem(3, 46, 31, 10, 51, 16, 100, "W", 3, 1017) @skipIfFailed(TestDesign, TestDesign.test_simple_prediction_defined.__name__, tag='defined') def test_simple_prediction(self): """Test SimplePrediction with high temp, little rain, low humidity""" TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_low) TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_high) TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_mid) sp = self.prediction.SimplePrediction( TestHighTempEdgeCases.weather_data, len(TestHighTempEdgeCases.weather_data._weather_data)) self.aggregate(self.assertEqual, sp.get_number_days(), len(TestHighTempEdgeCases.weather_data._weather_data), tag='get_number_days') self.aggregate(self.assertEqual, sp.chance_of_rain(), 18, tag='chance_of_rain') self.aggregate(self.assertAlmostEqual, sp.high_temperature(), 46, places=2, tag='high_temperature') self.aggregate(self.assertAlmostEqual, sp.low_temperature(), 29, places=2, tag='low_temperature') self.aggregate(self.assertEqual, sp.humidity(), 50, tag='humidity') self.aggregate(self.assertEqual, sp.cloud_cover(), 2, tag='cloud_cover') self.aggregate(self.assertEqual, sp.wind_speed(), 15, tag='wind_speed') self.aggregate_tests() @skipIfFailed(TestDesign, TestDesign.test_sophisticated_prediction_defined.__name__, tag='defined') def test_sophisticated_prediction_high_pressure(self): """Test SophisticatedPrediction with high temp and high pressure""" TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_low) TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_mid) TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_high) sp = self.prediction.SophisticatedPrediction( TestHighTempEdgeCases.weather_data, len(TestHighTempEdgeCases.weather_data._weather_data)) self.aggregate(self.assertEqual, sp.get_number_days(), len(TestHighTempEdgeCases.weather_data._weather_data), tag='get_number_days') self.aggregate(self.assertEqual, sp.chance_of_rain(), 14, tag='chance_of_rain') self.aggregate(self.assertAlmostEqual, sp.high_temperature(), 47, places=2, tag='high_temperature') self.aggregate(self.assertAlmostEqual, sp.low_temperature(), 30, places=2, tag='low_temperature') self.aggregate(self.assertEqual, sp.humidity(), 35, tag='humidity') self.aggregate(self.assertEqual, sp.cloud_cover(), 2, tag='cloud_cover') self.aggregate(self.assertEqual, sp.wind_speed(), 18, tag='wind_speed') self.aggregate_tests() @skipIfFailed(TestDesign, TestDesign.test_sophisticated_prediction_defined.__name__, tag='defined') def test_sophisticated_prediction_equal_pressure(self): """Test SophisticatedPrediction with high temp and equal pressure""" TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_low) TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_high) TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_mid) sp = self.prediction.SophisticatedPrediction( TestHighTempEdgeCases.weather_data, len(TestHighTempEdgeCases.weather_data._weather_data)) self.aggregate(self.assertEqual, sp.get_number_days(), len(TestHighTempEdgeCases.weather_data._weather_data), tag='get_number_days') self.aggregate(self.assertEqual, sp.chance_of_rain(), 17, tag='chance_of_rain') self.aggregate(self.assertAlmostEqual, sp.high_temperature(), 45, places=2, tag='high_temperature') self.aggregate(self.assertAlmostEqual, sp.low_temperature(), 30, places=2, tag='low_temperature') self.aggregate(self.assertEqual, sp.humidity(), 50, tag='humidity') self.aggregate(self.assertEqual, sp.cloud_cover(), 2, tag='cloud_cover') self.aggregate(self.assertEqual, sp.wind_speed(), 15, tag='wind_speed') self.aggregate_tests() @skipIfFailed(TestDesign, TestDesign.test_sophisticated_prediction_defined.__name__, tag='defined') def test_sophisticated_prediction_low_pressure(self): """Test SophisticatedPrediction with high temp and low pressure""" TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_mid) TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_high) TestHighTempEdgeCases.weather_data._weather_data.append( TestHighTempEdgeCases.day_low) sp = self.prediction.SophisticatedPrediction( TestHighTempEdgeCases.weather_data, len(TestHighTempEdgeCases.weather_data._weather_data)) self.aggregate(self.assertEqual, sp.get_number_days(), len(TestHighTempEdgeCases.weather_data._weather_data), tag='get_number_days') self.aggregate(self.assertEqual, sp.chance_of_rain(), 20, tag='chance_of_rain') self.aggregate(self.assertAlmostEqual, sp.high_temperature(), 45, places=2, tag='high_temperature') self.aggregate(self.assertAlmostEqual, sp.low_temperature(), 28, places=2, tag='low_temperature') self.aggregate(self.assertEqual, sp.humidity(), 65, tag='humidity') self.aggregate(self.assertEqual, sp.cloud_cover(), 4, tag='cloud_cover') self.aggregate(self.assertEqual, sp.wind_speed(), 15, tag='wind_speed') self.aggregate_tests()
from display import ( CurrentConditionsDisplay, ForecastDisplay, HeatIndexDisplay, StatisticsDisplay, ) from weather_data import WeatherData """ Notes: - All instantied displays are registred in a subject(topic). - When the states changes(set_measurements), all display are notified. - We can register and unregister a observer as we can see in the last two lines. """ weather_data = WeatherData() current_Display = CurrentConditionsDisplay(weather_data) statistics_display = StatisticsDisplay(weather_data) forecast_display = ForecastDisplay(weather_data) heat_index_display = HeatIndexDisplay(weather_data) weather_data.set_measurements(80, 65, 30.4) weather_data.set_measurements(82, 70, 29.2) weather_data.set_measurements(78, 90, 29.2) weather_data.remove_observer(forecast_display) weather_data.set_measurements(62.0, 90.0, 28.1)
def query(self, text): from voice_recognition import VoiceRecognition text = text.lower() vr = VoiceRecognition() if "search " in text: print(text[8:]) if "wikipedia" in text: text = text.replace("wikipedia", "") result = wiki.summery(text, sentences=2) vr.speak(f"According to wikipedia, {result}") if "play music" in text: songs = subprocess.Popen("ls ~/Music/*.mp3", shell=True, stdout=subprocess.PIPE) all_songs = [] for song in songs.stdout: song = str(song) all_songs.append(f"{song[1:-3]}'") os.system(f"open {choice(all_songs)}") if "system" in text: os.system("alacritty -e htop") if "the time" in text: cur_time = datetime.datetime.now().strftime("%H:%M:%S") vr.speak(f"sir, current time is {cur_time}") print(f"sir, current time is {cur_time}") if "weather" in text: weather = WeatherData() cur_weather = weather.get_current_data() vr.speak(f"current weather is {cur_weather['status']}, \ having {cur_weather['temp']} temperature") print( f"current weather is {cur_weather['status']}, having {cur_weather['temp']} temperature" ) if "current price" in text: tracker = PriceTracker() try: data = tracker.get_data() except Exception as e: vr.speak( "Sir, you have not given url of the product you are trying to track. Please go to gui section and click on price tracker button and set urls first" ) print( "Sir, you have not given url of the product you are trying to track. Please go to gui section and click on price tracker button and set urls first" ) if "amazon" in text: amazon_price = data['amazon'] vr.speak( f"currently, price of your selected product {amazon_price[0]} on amazon is {amazon_price[1]}" ) print( f"currently, price of your selected product {amazon_price[0]} on amazon is {amazon_price[1]}" ) elif "flipkart" in text: flipkart_price = data['flipkart'] vr.speak( f"currently, price of your selected product {flipkart_price[0]} on flipkart is {flipkart_price[1]}" ) print( f"currently, price of your selected product {flipkart_price[0]} on flipkart is {flipkart_price[1]}" ) else: vr.speak(f"Ok sir") vr.speak( f"Your product : {data['amazon'][0]} on amazon has price of rupees {data['amazon'][1]}" ) vr.speak( f"and {data['flipkart'][0]} on flipkart has price of rupees {data['flipkart'][1]}" ) vr.speak( f"currently price is low on {data['low price website']} which is {data[data['low price website']][1]}" ) vr.speak(f"and your desired price is {data['desired price']}") print( f"Your product : {data['amazon'][0]} on amazon has price of rupees {data['amazon'][1]}" ) print( f"and {data['flipkart'][0]} on flipkart has price of rupees {data['flipkart'][1]}" ) print( f"currently price is low on {data['low price website']} which is {data[data['low price website']][1]}" ) print(f"and your desired price is {data['desired price']}")
class TestDisplayElement(TestCase): def setUp(self): self.weather_data = WeatherData() def test_CurrentConditionsDisplay(self): display = CurrentConditionsDisplay(self.weather_data) self.weather_data.set_measurements(1, 2, 3) def test_ForecastDisplay(self): display = ForecastDisplay(self.weather_data) self.weather_data.set_measurements(1, 2, 3) self.weather_data.set_measurements(1, 2, 4) self.weather_data.set_measurements(1, 2, 4) def test_StatisticsDisplay(self): display = StatisticsDisplay(self.weather_data) self.weather_data.set_measurements(2, 2, 3) self.weather_data.set_measurements(4, 2, 3) self.weather_data.set_measurements(1, 2, 3) def test_ThirdPartyDisplay(self): display = ThirdPartyDisplay(self.weather_data) self.weather_data.set_measurements(1, 2, 3) def test_weather_station(self): weather_data = WeatherData() current_display = CurrentConditionsDisplay(weather_data) statistics_display = StatisticsDisplay(weather_data) forecast_display = ForecastDisplay(weather_data) heat_index_display = HeatIndexDisplay(weather_data) weather_data.set_measurements(80, 65, 30.4) weather_data.set_measurements(82, 70, 29.2) weather_data.set_measurements(78, 90, 29.2) def test_remove_observer(self): display = StatisticsDisplay(self.weather_data) self.weather_data.set_measurements(1, 2, 3) self.weather_data.remove_observer(display) self.weather_data.set_measurements(3, 2, 1)
def test_weather_object(): w = WeatherData() w.get_weather() assert type(w.weather_dict["humidity"]) == int assert type(w.weather_dict["status"]) == str
def test_clothing(): w = WeatherData() w.weather_dict = test_dict w.determine_clothing() assert w.clothing["boots"] == True assert w.clothing["sun hat"] == False
def setUp(self): self.weather_data = WeatherData()