Beispiel #1
0
    def test_weather_api(self):

        fake_json = {"cod":"200","message":0.0106,"cnt":40,"list":[{"dt":1567198800,"main":{"temp":73.94,"temp_min":70.54,"temp_max":73.94,"pressure":1018.87,"sea_level":1018.87,"grnd_level":985.61,"humidity":54,"temp_kf":1.89},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"clouds":{"all":31},"wind":{"speed":7.29,"deg":290.115},"sys":{"pod":"d"},"dt_txt":"2019-08-30 21:00:00"},{"dt":1567209600,"main":{"temp":65.3,"temp_min":62.74,"temp_max":65.3,"pressure":1020.29,"sea_level":1020.29,"grnd_level":986.92,"humidity":71,"temp_kf":1.42},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"clouds":{"all":65},"wind":{"speed":5.28,"deg":298.278},"sys":{"pod":"n"},"dt_txt":"2019-08-31 00:00:00"}]}

        with patch('weather_api.requests.get') as mock_get:
            mock_get.return_value.status_code = 200
            mock_get.return_value.json.return_value = fake_json

            obj = WeatherApi()
            response = obj.get_current_temp()

        self.assertEqual("The temperature is currently 73.94", response)
Beispiel #2
0
def index():
  today = datetime.datetime.now()
  map_input = {
    "day": today.strftime("%A"),
    "conditions": WeatherApi.current_weather_condition()
  }
  return render_template("map.html", map_input = map_input, title = "Map")
Beispiel #3
0
 def getWeather(self):
     successfulResponse = False
     weatherResponse = WeatherApi('Fetch')
     if weatherResponse.response.status_code == 200:
         weatherConditions = WeatherConditions(
             weatherResponse.response.text)
         successfulResponse = True
     else:
         if self.CachedWeather.response is not None:
             if self.CachedWeather.response.status_code == 200:
                 weatherConditions = WeatherConditions(
                     self.CachedWeather.response.text)
                 successfulResponse = True
     if successfulResponse == True:
         self.currentWeatherIcon.setPixmap(weatherConditions.pixMap)
         self.temperatureLabel.setText(weatherConditions.temperature +
                                       u'\u00b0' + 'F')
         self.currentWeatherDescription.setText(
             weatherConditions.description)
         self.CachedWeather = weatherResponse
Beispiel #4
0
class Comparator:
    def __init__(self, logger):
        self.logger = logger
        self.weather_ui = WeatherUi(logger)
        self.weather_api = WeatherApi(logger)
        self.result = dict()

    def get_temp_comparision(self, cities, variance):
        self.logger.info(
            'Starting weather details comparision from UI and API')
        temp_from_ui = self.weather_ui.get_weather_details(cities)
        temp_from_api = self.weather_api.get_weather_details(cities)
        for ct in cities:
            res = abs(
                float(temp_from_ui.get(ct, 0)) -
                float(temp_from_api.get(ct, 0)))
            if res < variance:
                self.result[ct] = True
            else:
                self.result[ct] = False
        return self.result
Beispiel #5
0
 def do_weather(self, location):
     data = WeatherApi.get_weather(self.api_key, location)
     print "\n\n\nWeather result:\n{}\n\n\n".format(data)
Beispiel #6
0
 def __init__(self, filename='db.sqlite') -> None:
     self.filename = filename
     global_init(filename)
     self.weather = WeatherApi()
Beispiel #7
0
class Data:
    def __init__(self, filename='db.sqlite') -> None:
        self.filename = filename
        global_init(filename)
        self.weather = WeatherApi()

    def search_city(self, name):
        session = create_session()
        cities = self.weather.get_city(name)
        data = map(lambda x: x.title, session.query(City).all())
        filtered = filter(lambda x: x['name'] not in data, cities)
        return list(filtered)

    def add_city(self, data: dict):
        session = create_session()
        city = City()
        city.title = data['name']
        city.link = self.weather.link + data['url'].replace(
            'weather', 'weather-history')
        session.add(city)
        session.commit()

    def load_cities(self) -> List[City]:
        session = create_session()
        cities = session.query(City).all()
        return cities

    def load_weather(self, date_from: datetime, date_to: datetime,
                     city: City) -> List[str]:
        session = create_session()
        data = []
        url = city.link
        winds = session.query(Winds).filter(
            and_(Winds.date >= date_from.strftime('%Y-%m-%d'),
                 Winds.date <= date_to.strftime('%Y-%m-%d'),
                 Winds.city_id == city.id)).all()
        if len(winds) == 0:
            days = date_to.__sub__(date_from).days
            for i in range(1, days):
                date = date_to - timedelta(days=i)
                direction = self.weather.get_wind_direction(url, date)
                if not direction:
                    continue
                data.append(direction)
                wind = Winds()
                wind.date = date
                wind.city_id = city.id
                wind.wind = direction
                session.add(wind)
                session.commit()
        else:
            data = list(map(lambda x: x.wind, winds))
            db_date_from = min(list(map(lambda x: x.date, winds)))
            days = db_date_from.__sub__(date_from).days
            for i in range(1, days):
                date = db_date_from - timedelta(days=i)
                direction = self.weather.get_wind_direction(url, date)
                if not direction:
                    continue
                data.append(direction)
                wind = Winds()
                wind.date = date
                wind.city_id = city.id
                wind.wind = direction
                session.add(wind)
                session.commit()
        return data
Beispiel #8
0
def weather_forecast():
  return jsonify(WeatherApi.forecast_weather())
Beispiel #9
0
 def __init__(self, logger):
     self.logger = logger
     self.weather_ui = WeatherUi(logger)
     self.weather_api = WeatherApi(logger)
     self.result = dict()
Beispiel #10
0
import time
import machine
from dht import DHT22

from pms7003 import PassivePms7003, UartError
from thingspeak import Thingspeak
from weather_api import WeatherApi

if machine.reset_cause() == machine.DEEPSLEEP_RESET:
    print("Woke up ESP32 from deep sleep")

dht22 = DHT22(machine.Pin(4))
pms7003 = PassivePms7003(uart=2)
thingspeak = Thingspeak()
weather_api = WeatherApi()

# create data dict for data
data = {}

try:
    # wake up pms7003
    print("Waking up pms7003 from sleep mode")
    pms7003.wakeup()

    # wait 60 seconds to stabilize airflow
    print("Sleep 60 seconds to stabilize airflow")
    time.sleep(60)

    # get openweathermap data
    print("Getting OWM data")
    data.update(weather_api.get_weather_data())
Beispiel #11
0
 def do_weather(self, location):
     data = WeatherApi.get_weather(self.api_key, location)
     print "\n\n\nWeather result:\n{}\n\n\n".format(data)
Beispiel #12
0
class MainWindow(QMainWindow, mainwindow_auto.Ui_MainWindow):
    # access variables inside of the UI's file

    CachedWeather = WeatherApi('Initial')
    #AlarmAnimation = QtCore.QPropertyAnimation()
    AlarmInfo = Alarm()
    Pandora = Pandora()
    AlarmCurrentState = 'Closed'
    PandoraCurrentState = 'Closed'
    CalendarCurrentState = 'Closed'
    ANIMATIONDURATION = 650

    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi(self)  # gets defined in the UI file
        self.initUI()

    def initUI(self):
        self.alarmWidget.setGeometry(QtCore.QRect(800, 310, 300, 100))
        self.pandoraWidget.setGeometry(QtCore.QRect(800, 240, 300, 100))
        self.calendarWidget.setGeometry(QtCore.QRect(800, 170, 300, 100))

        self.setupTimers()

        self.getTime()
        self.getWeather()
        self.setupScrollers()
        #self.alarmSlider.setStyleSheet(self.styleAlarmSlider())
        self.pauseToolButton.hide()
        self.alarmOnToolButton.hide()

        self.setupHooks()

        self.hourListWidget.setCurrentRow(2)
        self.minuteListWidget.setCurrentRow(2)
        self.amPmListWidget.setCurrentRow(2)

    def setupTimers(self):
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.getTime)
        self.timer.start(10)
        self.alarmTimer = QtCore.QTimer(self)
        self.alarmTimer.timeout.connect(self.checkAlarm)
        self.alarmTimer.start(10)
        self.weatherTimer = QtCore.QTimer(self)
        self.weatherTimer.timeout.connect(self.getWeather)
        self.weatherTimer.start(600000)

    def setupHooks(self):
        self.alarmToolButton.clicked.connect(lambda: self.pressedAlarmButton())
        self.hourListWidget.itemSelectionChanged.connect(
            lambda: self.hourListWidgetSelectionChange())
        self.minuteListWidget.itemSelectionChanged.connect(
            lambda: self.minuteListWidgetSelectionChange())
        self.amPmListWidget.itemSelectionChanged.connect(
            lambda: self.amPmListWidgetSelectionChange())
        self.alarmOnToolButton.clicked.connect(
            lambda: self.pressedAlarmOnButton())
        self.alarmOffToolButton.clicked.connect(
            lambda: self.pressedAlarmOffButton())
        self.pandoraToolButton.clicked.connect(
            lambda: self.pressedPandoraButton())
        self.playToolButton.clicked.connect(lambda: self.pressedPlayButton())
        self.pauseToolButton.clicked.connect(lambda: self.pressedPauseButton())
        self.stopToolButton.clicked.connect(lambda: self.pressedStopButton())
        self.skipToolButton.clicked.connect(lambda: self.pressedSkipButton())
        self.calendarToolButton.clicked.connect(
            lambda: self.pressedCalendarButton())

    def setupStatusbar(self):
        self.alarmStatusWidget = QToolButton()
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("images/alarm-clock.png"),
                       QtGui.QIcon.Normal, QtGui.QIcon.On)
        self.alarmStatusWidget.setIcon(icon)
        self.alarmStatusWidget.setFixedSize(QSize(24, 24))
        self.alarmStatusWidget.setIconSize(QSize(24, 24))

        self.statusBar.setStyleSheet("""QStatusBar::item {
                                        border: none;
                                        }""")

    def setupScrollers(self):
        sp = QScrollerProperties()
        sp.setScrollMetric(QScrollerProperties.DragVelocitySmoothingFactor,
                           0.6)
        sp.setScrollMetric(QScrollerProperties.MinimumVelocity, 0.0)
        sp.setScrollMetric(QScrollerProperties.MaximumVelocity, 0.5)
        sp.setScrollMetric(QScrollerProperties.AcceleratingFlickMaximumTime,
                           0.4)
        sp.setScrollMetric(QScrollerProperties.AcceleratingFlickSpeedupFactor,
                           1.2)
        sp.setScrollMetric(QScrollerProperties.SnapPositionRatio, 0.2)
        sp.setScrollMetric(QScrollerProperties.MaximumClickThroughVelocity, 0)
        sp.setScrollMetric(QScrollerProperties.DragStartDistance, 0.001)
        sp.setScrollMetric(QScrollerProperties.MousePressEventDelay, 0.5)

        hourListScroller = QScroller.scroller(self.hourListWidget)
        hourListScroller.grabGesture(self.hourListWidget,
                                     QScroller.LeftMouseButtonGesture)
        hourListScroller.setScrollerProperties(sp)

        minuteListScroller = QScroller.scroller(self.minuteListWidget)
        minuteListScroller.grabGesture(self.minuteListWidget,
                                       QScroller.LeftMouseButtonGesture)
        minuteListScroller.setScrollerProperties(sp)

        amPmListScroller = QScroller.scroller(self.amPmListWidget)
        amPmListScroller.grabGesture(self.amPmListWidget,
                                     QScroller.LeftMouseButtonGesture)
        amPmListScroller.setScrollerProperties(sp)

    def getTime(self):
        self.timeDisplay.display(strftime("%I" + ":" + "%M").lstrip('0'))
        self.dateLabel.setText(
            strftime("%A" + " " + "%B" + " " + "%d" + ", " + "%Y"))

    def getWeather(self):
        successfulResponse = False
        weatherResponse = WeatherApi('Fetch')
        if weatherResponse.response.status_code == 200:
            weatherConditions = WeatherConditions(
                weatherResponse.response.text)
            successfulResponse = True
        else:
            if self.CachedWeather.response is not None:
                if self.CachedWeather.response.status_code == 200:
                    weatherConditions = WeatherConditions(
                        self.CachedWeather.response.text)
                    successfulResponse = True
        if successfulResponse == True:
            self.currentWeatherIcon.setPixmap(weatherConditions.pixMap)
            self.temperatureLabel.setText(weatherConditions.temperature +
                                          u'\u00b0' + 'F')
            self.currentWeatherDescription.setText(
                weatherConditions.description)
            self.CachedWeather = weatherResponse

    def pressedAlarmButton(self):
        try:
            alarmButtonCurrentGeometry = QtCore.QRect(
                self.alarmToolButton.geometry())
            alarmButtonAnimation = QPropertyAnimation(
                self.alarmToolButton, 'geometry'.encode(encoding='utf_8'))
            alarmButtonAnimation.setDuration(self.ANIMATIONDURATION)
            alarmButtonAnimation.setStartValue(alarmButtonCurrentGeometry)

            alarmWidgetCurrentGeometry = QtCore.QRect(
                self.alarmWidget.geometry())
            alarmWidgetAnimation = QPropertyAnimation(
                self.alarmWidget, 'geometry'.encode(encoding='utf_8'))
            alarmWidgetAnimation.setDuration(self.ANIMATIONDURATION)
            alarmWidgetAnimation.setStartValue(alarmWidgetCurrentGeometry)

            if self.AlarmCurrentState == 'Closed':
                alarmButtonEndTopLeftCorner = QtCore.QPoint(
                    self.alarmToolButton.pos() - QtCore.QPoint(275, 0))
                alarmWidgetEndTopLeftCorner = QtCore.QPoint(
                    self.alarmWidget.pos() - QtCore.QPoint(275, 0))
                self.AlarmCurrentState = 'Open'
            else:
                alarmButtonEndTopLeftCorner = QtCore.QPoint(
                    self.alarmToolButton.pos() + QtCore.QPoint(275, 0))
                alarmWidgetEndTopLeftCorner = QtCore.QPoint(
                    self.alarmWidget.pos() + QtCore.QPoint(275, 0))
                self.AlarmCurrentState = 'Closed'

            alarmButtonFinalGeometry = QtCore.QRect(
                alarmButtonEndTopLeftCorner,
                QtCore.QSize(self.alarmToolButton.width(),
                             self.alarmToolButton.height()))
            alarmButtonAnimation.setEndValue(alarmButtonFinalGeometry)

            alarmWidgetFinalGeometry = QtCore.QRect(
                alarmWidgetEndTopLeftCorner,
                QtCore.QSize(self.alarmWidget.width(),
                             self.alarmWidget.height()))
            alarmWidgetAnimation.setEndValue(alarmWidgetFinalGeometry)

            alarmButtonAnimation.start()
            alarmWidgetAnimation.start()
            #self.setAlarmWidgetStyleSheet()
            self.AlarmIconAnimation = alarmButtonAnimation
            self.AlarmWidgetAnimation = alarmWidgetAnimation
        except Exception as e:
            print(e.strerror)

    def setAlarmWidgetStyleSheet(self):
        style1 = "background-color: white"
        style2 = "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(0, 0, 0, 255), stop:1 rgba(255, 255, 255, 255))"

        # animation doesn't work for strings but provides an appropriate delay
        animation = QtCore.QPropertyAnimation(
            self.alarmWidget, 'styleSheet'.encode(encoding='utf_8'))
        animation.setDuration(500)

        state1 = QtCore.QState()
        state2 = QtCore.QState()
        state3 = QtCore.QState()
        state1.assignProperty(self.alarmWidget, 'styleSheet', style1)
        state2.assignProperty(self.alarmWidget, 'styleSheet', style2)
        state3.assignProperty(self.alarmWidget, 'styleSheet', style2)
        #              change a state after an animation has played
        #                               v
        state1.addTransition(state1.propertiesAssigned, state2)
        state2.addTransition(state2.propertiesAssigned, state3)

        self.alarmWidget.machine = QtCore.QStateMachine()
        self.alarmWidget.machine.addDefaultAnimation(animation)
        self.alarmWidget.machine.addState(state1)
        self.alarmWidget.machine.addState(state2)
        self.alarmWidget.machine.setInitialState(state1)
        self.alarmWidget.machine.start()

    def hourListWidgetSelectionChange(self):
        value = self.hourListWidget.currentRow()
        if value < 2:
            value = 2
        if value > 13:
            value = 13
        item = self.hourListWidget.item(value)
        self.hourListWidget.scrollToItem(item,
                                         QAbstractItemView.PositionAtCenter)
        self.hourListWidget.setCurrentRow(value)

    def minuteListWidgetSelectionChange(self):
        value = self.minuteListWidget.currentRow()
        if value < 2:
            value = 2
        if value > 61:
            value = 61
        item = self.minuteListWidget.item(value)
        self.minuteListWidget.scrollToItem(item,
                                           QAbstractItemView.PositionAtCenter)
        self.minuteListWidget.setCurrentRow(value)

    def amPmListWidgetSelectionChange(self):
        value = self.amPmListWidget.currentRow()
        if value < 2:
            value = 2
        if value > 3:
            value = 3
        item = self.amPmListWidget.item(value)
        self.amPmListWidget.scrollToItem(item,
                                         QAbstractItemView.PositionAtCenter)
        self.amPmListWidget.setCurrentRow(value)

    def styleAlarmSlider(self):
        return """
            QSlider::groove:horizontal {
                height: 20px; /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #B1B1B1, stop:1 #c4c4c4);
                margin: 2px 0;
            }
            
            QSlider::sub-page:horizontal {
                background: qlineargradient(x1: 0, y1: 0,    x2: 0, y2: 1,
                    stop: 0 #66e, stop: 1 #bbf);
                background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1,
                    stop: 0 #bbf, stop: 1 #55f);
                height: 40px;
            }

            QSlider::handle:horizontal {
                background: #bbf;
                border: 0px;
                width: 5px;
                margin-top: 0px;
                margin-bottom: 0px;
                border-radius: 0px;
            }
        """

#    def alarmSliderValueChange(self):
#        if self.alarmSlider.value() == 0:
#            self.AlarmInfo.disableAlarm()
#        else:
#            hourItem = self.hourListWidget.currentItem()
#            minuteItem = self.minuteListWidget.currentItem()
#            amPmItem = self.amPmListWidget.currentItem()
#            timeToSet = hourItem.text() + ':' + minuteItem.text() + ' ' + amPmItem.text()
#            self.AlarmInfo.setAlarm(timeToSet)

    def pressedAlarmOffButton(self):
        self.alarmOffToolButton.hide()
        self.alarmOnToolButton.show()
        hourItem = self.hourListWidget.currentItem()
        minuteItem = self.minuteListWidget.currentItem()
        amPmItem = self.amPmListWidget.currentItem()
        timeToSet = hourItem.text() + ':' + minuteItem.text(
        ) + ' ' + amPmItem.text()
        self.AlarmInfo.setAlarm(timeToSet)

        self.statusBar.addWidget(self.alarmStatusWidget)
        self.alarmStatusWidget.show()

    def pressedAlarmOnButton(self):
        self.alarmOnToolButton.hide()
        self.alarmOffToolButton.show()
        self.AlarmInfo.disableAlarm()
        self.statusBar.removeWidget(self.alarmStatusWidget)

    def pressedPandoraButton(self):
        pandoraButtonCurrentGeometry = QtCore.QRect(
            self.pandoraToolButton.geometry())
        pandoraButtonAnimation = QPropertyAnimation(
            self.pandoraToolButton, 'geometry'.encode(encoding='utf_8'))
        pandoraButtonAnimation.setDuration(self.ANIMATIONDURATION)
        pandoraButtonAnimation.setStartValue(pandoraButtonCurrentGeometry)

        pandoraWidgetCurrentGeometry = QtCore.QRect(
            self.pandoraWidget.geometry())
        pandoraWidgetAnimation = QPropertyAnimation(
            self.pandoraWidget, 'geometry'.encode(encoding='utf_8'))
        pandoraWidgetAnimation.setDuration(self.ANIMATIONDURATION)
        pandoraWidgetAnimation.setStartValue(pandoraWidgetCurrentGeometry)

        if self.PandoraCurrentState == 'Closed':
            pandoraButtonEndTopLeftCorner = QtCore.QPoint(
                self.pandoraToolButton.pos() - QtCore.QPoint(275, 0))
            pandoraWidgetEndTopLeftCorner = QtCore.QPoint(
                self.pandoraWidget.pos() - QtCore.QPoint(275, 0))
            self.PandoraCurrentState = 'Open'
            if self.Pandora.started == True:
                self.playToolButton.hide()
                self.pauseToolButton.show()
        else:
            pandoraButtonEndTopLeftCorner = QtCore.QPoint(
                self.pandoraToolButton.pos() + QtCore.QPoint(275, 0))
            pandoraWidgetEndTopLeftCorner = QtCore.QPoint(
                self.pandoraWidget.pos() + QtCore.QPoint(275, 0))
            self.PandoraCurrentState = 'Closed'

        pandoraButtonFinalGeometry = QtCore.QRect(
            pandoraButtonEndTopLeftCorner,
            QtCore.QSize(self.pandoraToolButton.width(),
                         self.pandoraToolButton.height()))
        pandoraButtonAnimation.setEndValue(pandoraButtonFinalGeometry)

        pandoraWidgetFinalGeometry = QtCore.QRect(
            pandoraWidgetEndTopLeftCorner,
            QtCore.QSize(self.pandoraWidget.width(),
                         self.pandoraWidget.height()))
        pandoraWidgetAnimation.setEndValue(pandoraWidgetFinalGeometry)

        pandoraButtonAnimation.start()
        pandoraWidgetAnimation.start()
        #self.setpandoraWidgetStyleSheet()
        self.PandoraIconAnimation = pandoraButtonAnimation
        self.PandoraWidgetAnimation = pandoraWidgetAnimation

    def pressedPlayButton(self):
        if self.Pandora.started == False:
            self.songLabel.setText('Loading...')
            self.Pandora.start('*****@*****.**', 'bgc7y9l')
            self.playToolButton.hide()
            self.pauseToolButton.show()
            self.Pandora.read()
            self.songLabel.setText(self.Pandora.output)
        else:
            if self.playToolButton.isvisible():
                self.Pandora.play()
                self.playToolButton.hide()
                self.pauseToolButton.show()
                self.Pandora.read()
                self.songLabel.setText(self.Pandora.output)

    def pressedPauseButton(self):
        self.Pandora.pause()
        self.pauseToolButton.hide()
        self.playToolButton.show()

    def pressedStopButton(self):
        self.Pandora.stop()
        self.pauseToolButton.hide()
        self.playToolButton.show()

    def pressedSkipButton(self):
        self.Pandora.skip()

    def checkAlarm(self):
        if self.AlarmInfo.alarmSet == True:
            self.AlarmInfo.checkAlarm()
            if self.AlarmInfo.alarmSet == False:
                self.alarmOnToolButton.hide()
                self.alarmOffToolButton.show()
                #self.pressedPlayButton()
                self.statusBar.removeWidget(self.alarmStatusWidget)

    def pressedCalendarButton(self):
        try:
            calendarButtonCurrentGeometry = QtCore.QRect(
                self.calendarToolButton.geometry())
            calendarButtonAnimation = QPropertyAnimation(
                self.calendarToolButton, 'geometry'.encode(encoding='utf_8'))
            calendarButtonAnimation.setDuration(self.ANIMATIONDURATION)
            calendarButtonAnimation.setStartValue(
                calendarButtonCurrentGeometry)

            calendarWidgetCurrentGeometry = QtCore.QRect(
                self.calendarWidget.geometry())
            calendarWidgetAnimation = QPropertyAnimation(
                self.calendarWidget, 'geometry'.encode(encoding='utf_8'))
            calendarWidgetAnimation.setDuration(self.ANIMATIONDURATION)
            calendarWidgetAnimation.setStartValue(
                calendarWidgetCurrentGeometry)

            if self.CalendarCurrentState == 'Closed':
                calendarButtonEndTopLeftCorner = QtCore.QPoint(
                    self.calendarToolButton.pos() - QtCore.QPoint(275, 0))
                calendarWidgetEndTopLeftCorner = QtCore.QPoint(
                    self.calendarWidget.pos() - QtCore.QPoint(275, 0))
                self.CalendarCurrentState = 'Open'
                self.Calendar = Calendar()
                self.calendarLabel.setText(self.Calendar.EventList)
            else:
                calendarButtonEndTopLeftCorner = QtCore.QPoint(
                    self.calendarToolButton.pos() + QtCore.QPoint(275, 0))
                calendarWidgetEndTopLeftCorner = QtCore.QPoint(
                    self.calendarWidget.pos() + QtCore.QPoint(275, 0))
                self.CalendarCurrentState = 'Closed'

            calendarButtonFinalGeometry = QtCore.QRect(
                calendarButtonEndTopLeftCorner,
                QtCore.QSize(self.calendarToolButton.width(),
                             self.calendarToolButton.height()))
            calendarButtonAnimation.setEndValue(calendarButtonFinalGeometry)

            calendarWidgetFinalGeometry = QtCore.QRect(
                calendarWidgetEndTopLeftCorner,
                QtCore.QSize(self.calendarWidget.width(),
                             self.calendarWidget.height()))
            calendarWidgetAnimation.setEndValue(calendarWidgetFinalGeometry)

            calendarButtonAnimation.start()
            calendarWidgetAnimation.start()
            #self.setcalendarWidgetStyleSheet()
            self.CalendarIconAnimation = calendarButtonAnimation
            self.CalendarWidgetAnimation = calendarWidgetAnimation
        except Exception as e:
            print(e.strerror)
Beispiel #13
0
 def say_weather(self, location):
     WeatherApi.get_weather(location)
Beispiel #14
0
 def __init__(self) -> None:
     self.weather = WeatherApi()
Beispiel #15
0
class Ui_MainWindow(object):
    def __init__(self) -> None:
        self.weather = WeatherApi()

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(600, 400)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.panel = QtWidgets.QTabWidget(self.centralwidget)
        self.panel.setObjectName("panel")
        self.roze = QtWidgets.QWidget()
        self.roze.setObjectName("roze")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.roze)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.label = QtWidgets.QLabel(self.roze)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 1, 1, 1)
        self.city_choosing = QtWidgets.QComboBox(self.roze)
        self.city_choosing.setObjectName("city_choosing")
        self.city_choosing.addItem("")
        self.gridLayout.addWidget(self.city_choosing, 1, 1, 1, 1)
        self.label_2 = QtWidgets.QLabel(self.roze)
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 2, 1, 1, 1)
        day_now, mouth_now, year_now = datetime.now().day, datetime.now(
        ).month, datetime.now().year

        self.date_from = QtWidgets.QDateEdit(self.roze)
        self.date_from.setDate(QtCore.QDate(year_now, mouth_now, day_now))
        self.date_from.setMaximumDate(
            QtCore.QDate(year_now, mouth_now, day_now))
        self.date_from.setObjectName("date_from")
        self.gridLayout.addWidget(self.date_from, 3, 1, 1, 1)
        self.label_3 = QtWidgets.QLabel(self.roze)
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")
        self.gridLayout.addWidget(self.label_3, 4, 1, 1, 1)
        self.date_to = QtWidgets.QDateEdit(self.roze)
        self.date_to.setDate(QtCore.QDate(year_now, mouth_now, day_now))
        self.date_to.setMaximumDate(QtCore.QDate(year_now, mouth_now, day_now))
        self.date_to.setObjectName("date_to")
        self.gridLayout.addWidget(self.date_to, 5, 1, 1, 1)
        self.create_rose = QtWidgets.QPushButton(self.roze)
        self.create_rose.setObjectName("create_rose")
        self.gridLayout.addWidget(self.create_rose, 6, 1, 1, 1)
        self.label_4 = QtWidgets.QLabel(self.roze)
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setObjectName("label_4")
        self.gridLayout.addWidget(self.label_4, 7, 1, 1, 1)
        self.file_name = QtWidgets.QLineEdit(self.roze)
        self.file_name.setObjectName("file_name")
        self.gridLayout.addWidget(self.file_name, 8, 1, 1, 1)
        self.save_file = QtWidgets.QPushButton(self.roze)
        self.save_file.setObjectName("save_file")
        self.gridLayout.addWidget(self.save_file, 9, 1, 1, 1)
        self.roze_image = RoseWidget()
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(
            self.roze_image.sizePolicy().hasHeightForWidth())
        self.roze_image.setSizePolicy(sizePolicy)
        self.roze_image.setMinimumSize(QtCore.QSize(400, 300))
        self.roze_image.setObjectName("roze_image")
        self.gridLayout.addWidget(self.roze_image, 0, 0, 10, 1)
        self.horizontalLayout_2.addLayout(self.gridLayout)
        self.panel.addTab(self.roze, "")
        self.add_city = QtWidgets.QWidget()
        self.add_city.setObjectName("add_city")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.add_city)
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.gridLayout_2 = QtWidgets.QGridLayout()
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.city_search_name = QtWidgets.QLineEdit(self.add_city)
        self.city_search_name.setText("")
        self.city_search_name.setObjectName("city_search_name")
        self.gridLayout_2.addWidget(self.city_search_name, 0, 0, 1, 1)
        self.city_search = QtWidgets.QPushButton(self.add_city)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.city_search.sizePolicy().hasHeightForWidth())
        self.city_search.setSizePolicy(sizePolicy)
        self.city_search.setMinimumSize(QtCore.QSize(150, 0))
        self.city_search.setObjectName("city_search")
        self.gridLayout_2.addWidget(self.city_search, 0, 1, 1, 1)
        self.listWidget = QtWidgets.QListWidget(self.add_city)
        self.listWidget.setGridSize(QtCore.QSize(0, 0))
        self.listWidget.setWordWrap(False)
        self.listWidget.setObjectName("listWidget")
        self.gridLayout_2.addWidget(self.listWidget, 1, 0, 1, 2)
        self.city_add = QtWidgets.QPushButton(self.add_city)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.city_add.sizePolicy().hasHeightForWidth())
        self.city_add.setSizePolicy(sizePolicy)
        self.city_add.setMinimumSize(QtCore.QSize(200, 0))
        self.city_add.setObjectName("city_add")
        self.gridLayout_2.addWidget(self.city_add, 2, 0, 1, 2,
                                    QtCore.Qt.AlignHCenter)
        self.horizontalLayout_3.addLayout(self.gridLayout_2)
        self.panel.addTab(self.add_city, "")
        self.horizontalLayout.addWidget(self.panel)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.panel.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Роза ветров"))
        self.label.setText(_translate("MainWindow", "Город"))
        self.city_choosing.setItemText(0, _translate("MainWindow", "тест"))
        self.label_2.setText(_translate("MainWindow", "Дата начала измерений"))
        self.label_3.setText(_translate("MainWindow", "Дата конца измерений"))
        self.create_rose.setText(_translate("MainWindow", "Создать"))
        self.label_4.setText(_translate("MainWindow", "Имя файла"))
        self.save_file.setText(_translate("MainWindow", "Сохранить"))
        self.panel.setTabText(self.panel.indexOf(self.roze),
                              _translate("MainWindow", "роза ветров"))
        self.city_search.setText(_translate("MainWindow", "Поиск"))
        self.city_add.setText(_translate("MainWindow", "Добавить в базу"))
        self.panel.setTabText(self.panel.indexOf(self.add_city),
                              _translate("MainWindow", "добавить город"))

    def bind_cuttons(self):
        self.create_rose.clicked.connect(self.set_weather)

    def set_weather(self):
        date_to = self.date_from.date().toString('dd.MM.yyyy')
        date_from = self.date_to.date().toString('dd.MM.yyyy')
        date_from = datetime.strptime(date_from, '%d.%m.%Y')
        date_to = datetime.strptime(date_to, '%d.%m.%Y')

        if date_from > date_to:
            return

        data = self.weather.get_wind_during_date(
            'https://www.worldweatheronline.com/kazan-weather-history/tatarstan/ru.aspx',
            date_from, date_to)
        print(data)
        self.roze_image.set_winds(data)
Beispiel #16
0
import json
import sys

import dateutil.parser

from weather_api import WeatherApi

loc = 'newcastle+nsw'
w = WeatherApi(search=loc, debug=0)

location = w.location()

# check if the search produced a result (other methods will also return None if the search fails).
if location is None:
    sys.exit('Search failed for location ' + loc)

print("{\"acknowedgment\":", end="")
print("\"", w.acknowedgment, "\"", sep="", end="")
print(", ", end="")

print("\"location\": ", end="")
print(json.dumps(location), end="")
print(", ", end="")

# for warn in w.warnings():
#    print(f"Warning short title:  {warn['short_title']}")
#    warning = w.warning(id=warn['id'])
#    print(f"Warning title:        {warning['title']}")

print("\"now\": ", end="")
print(json.dumps(w.observations()), end="")