コード例 #1
0
ファイル: manager.py プロジェクト: 3ll34ndr0/10cur4
    def getData(self):
        """ Returns a dictionary with all weather variables for each initHour
        that is the database for the current week"""
        print("a ver che...")
        from forecastiopy import ForecastIO
        # TODO: A method that will get the weather variables for the activity
        # initHour when the time comes. DONE
        Cordoba = [-31.4173, -64.1833]  # TODO: Avoid this hardcoded data
        language = 'es'
        with open("forecast.txt", "r") as file:
            forecastAPI = file.readlines().pop().rstrip('\n')
        _, timeRange = ActivityRegister(self.database, self.activity,
                                        self.initHour).periodReport('semanal')
        weatherData = dict()
        timeRange.sort()
        for time in timeRange:
            weatherData[time] = dict()
            weatherData[time]['participants'] = ActivityRegister(
                self.database, self.activity, unicode(time)).howMuch()
            fio = ForecastIO.ForecastIO(forecastAPI,
                                        latitude=Cordoba[0],
                                        longitude=Cordoba[1],
                                        lang=language)
            fio.time_url = time.rstrip('0').rstrip(
                '.')  #needs to be done couse
            #the api doesn't support floating point time
            forecast = json.loads(fio.http_get(fio.get_url()))
            for key in forecast['currently'].keys():
                weatherData[time][key] = forecast['currently'][key]
#                print(time,key,datos,weatherData[time][key])
#'summary','apparentTemperature','precipIntensity',
#'humidity','pressure','precipProbability','windSpeed',
#'Among others variables'
        setattr(self, 'data', weatherData)
コード例 #2
0
    def __init__(self):
        self._apikey = 'f119a2dd4a7d21069aebce2924af6f9a'
        # CCG location coordinates: 42.8057347, -85.5263732
        self._my_location = [42.8057347, -85.5263732]

        self._fio = ForecastIO.ForecastIO(self._apikey,
                                          latitude=self._my_location[0],
                                          longitude=self._my_location[1])
コード例 #3
0
    def get_forecast():
        if Weather.last_updated is not None and datetime.now() - UPDATE_INTERVAL < Weather.last_updated:
            return Weather.data

        Weather.position_api = ForecastIO.ForecastIO(Weather.api_key, latitude=Weather.location[0], longitude=Weather.location[1])

        Weather.data = FIOHourly.FIOHourly(Weather.position_api)
        Weather.last_updated = datetime.now()
        return Weather.data
コード例 #4
0
def call_darksky(api_key: str, location: Tuple[float, float]) -> dict:
    """Make a single call to the Dark Sky API and return the result parsed as dict"""
    return ForecastIO.ForecastIO(
        api_key,
        units=ForecastIO.ForecastIO.UNITS_SI,
        lang=ForecastIO.ForecastIO.LANG_ENGLISH,
        latitude=location[0],
        longitude=location[1],
        extend="hourly",
    ).forecast
コード例 #5
0
def CallFIO(apikey, nowLatitude, nowLongitude, startTime):
    try:
        fio = ForecastIO.ForecastIO(apikey,
                                    units=ForecastIO.ForecastIO.UNITS_SI,
                                    lang=ForecastIO.ForecastIO.LANG_ENGLISH,
                                    latitude=nowLatitude,
                                    longitude=nowLongitude,
                                    exclude='minutely, alerts',
                                    time=startTime)
        return fio
    except:
        ctypes.windll.user32.MessageBoxW(0, "The APIKEY is incorrect",
                                         "Error!", 0)
        sys.exit()
コード例 #6
0
    def downloadData(self,nlat_start,nlat_end):
        '''downloadData(self,nlat_start,nlat_end)
        routine to download data by latitude grid point.
        nlat_start, nlat_end are the indexes of the desired
        latitude points (starting from 0 and ending in self.nlat)
        Done this way because takes a long time to download data, so
        in case some part of the data are missing, can add...
        saves downloaded data into DarkSky.csv'''
        import pandas as pd
        from forecastiopy import ForecastIO,FIODaily

        times = self.dates["time"].to_list()
        key = "43b5a6b6b264933c0cac096ee0900db4"
        df = pd.DataFrame()
        for lat in range(nlat_start,nlat_end):
            for lon in self.lons:
                for t in range(0, len(times)):
                    OKflag = True
                    try:
                        forecast = ForecastIO.ForecastIO(
                        key,
                        latitude=lat,
                        longitude=lon,
                        time=times[t],
                        exclude=["currently", "hourly"],
                        )
                        daily = FIODaily.FIODaily(forecast)
                        new_line_dict = daily.get()
                    except:
                       OKflag=False
                    if OKflag:
                        if df.empty:
                            df = pd.DataFrame.from_dict(new_line_dict["data"])
                            df["time"] = times[t][0:10]
                            df["lat"] = lat
                            df["lon"] = lon
                        else:
                            df1 = pd.DataFrame.from_dict(new_line_dict["data"])
                            df1["time"] = times[t][0:10]
                            df1["lat"] = lat
                            df1["lon"] = lon
                            df = pd.concat([df, df1], sort=True)
                print(lon, "out of ", self.nlons)
            print(lat,'out of ',nlat_start,'-',nlat_end)
            # if wants to save from scratch each iteration (recommended..):
            df.to_csv('DarkSky.csv')
コード例 #7
0
def assistant(command):
    if 'shutdown' in command:
        mavis_response('Bye bye Sir. Have a nice day')
        sys.exit()
    elif 'close' in command:
        Exe = command.split('close')
        Exe = Exe[1] + '.exe'
        os.system("taskkill /f /im " + Exe)
    elif 'launch' in command:
        name = command.split('launch ')
        mavis_response('launching' + name[1])
        name = name[1] + '.exe'
        file_path = fd.file_equal_search(name)
        os.startfile(file_path)
    elif 'Wikipedia' in command:
        query = command.split("for ")
        query = query[1]
        try:

            mavis_response('Searching Wikipedia for ' + query)
            results = wikipedia.summary(query, sentences=2)
            print(results, sep='.')
            mavis_response("According to Wikipedia")
            mavis_response(results)
        except exceptions.DisambiguationError as error:
            mavis_response("Disambiguition while searching for " + query)
            mavis_response(query + ' may refer to one of the following ')
            for i in range(len(error.options)):
                print(error.options[i])
                mavis_response(error.options[i])
            pass
    elif 'list programs' in command:
        mavis_response('Wait. Scanning your device')
        app_list.list()
        mavis_response('These are all the installed programs')

    elif 'search for' in command:
        search = command.split('for ')
        search = search[1]
        url = 'https://www.google.com/search?q=' + search
        results = wikipedia.summary(search, sentences=2)
        webbrowser.open(url)
        mavis_response("results are opened in the browser")
        mavis_response("According to Wikipedia " + results)
    elif 'play music' in command:
        music_dir = 'C:/Users/Sachin Namdeo/Desktop/music'
        songs = os.listdir(music_dir)
        num = random.randint(0, len(songs))
        os.startfile(os.path.join(music_dir, songs[num]))
    elif 'play' in command:
        search = command.split('play ')
        search = search[1]
        query_string = urllib.parse.urlencode({"search_query": search})
        html_content = urllib.request.urlopen(
            "http://www.youtube.com/results?" + query_string)
        search_results = re.findall(r'href=\"\/watch\?v=(.{11})',
                                    html_content.read().decode())
        webbrowser.open("http://www.youtube.com/watch?v=" + search_results[0])
    elif 'open' in command and 'file' in command:
        if 'Word' in command:
            name = command.split('open Word file ')
            name = name[1] + '.docx'
            path = fd.file_search(name)
            os.startfile(path)
        elif 'PPT' in command:
            name = command.split('open PPT file ')
            name = name[1] + '.pptx'
            path = fd.file_search(name)
            os.startfile(path)
        elif 'PDF' in command:
            name = command.split('open PDF file ')
            name = name[1] + '.pdf'
            path = fd.file_search(name)
            os.startfile(path)
        elif 'Rar' in command:
            name = command.split('open Rar file ')
            name = name[1] + '.rar'
            path = fd.file_search(name)
            os.startfile(path)

    elif 'open website' in command:
        site = command.split('open website ')
        site = site[1]
        url = 'https://www.' + site
        webbrowser.open(url)
        mavis_response('opening ' + site)

    elif 'current weather' in command:
        location = loc.locate()
        apikey = 'YOUR-API-KEY'
        lat = location[0]
        lng = location[1]
        response = ForecastIO.ForecastIO(
            apikey,
            units=ForecastIO.ForecastIO.UNITS_SI,
            lang=ForecastIO.ForecastIO.LANG_ENGLISH,
            latitude=lat,
            longitude=lng)
        currently = FIOHourly.FIOHourly(response)
        print(loc.place() + ' has ' + currently.get()['summary'])
        mavis_response(loc.place() + ' has ' + currently.get()['summary'])

    elif 'time' in command:
        now = datetime.datetime.now()
        mavis_response('Current time is %d hours %d minutes' %
                       (now.hour, now.minute))
コード例 #8
0
from forecastiopy import ForecastIO, FIOHourly
import datetime

apikey = "d057f5b3b90154e47107070d1aecf47c"
Stanford = [37.4248, -122.1677]

fio = ForecastIO.ForecastIO(apikey,
                            lang=ForecastIO.ForecastIO.LANG_ENGLISH,
                            latitude=Stanford[0],
                            longitude=Stanford[1])


def get_temps(TOTAL_COUNT):
    '''
  Calculate projected temperatures for Stanford.
  '''

    hourly = FIOHourly.FIOHourly(fio)
    min = datetime.datetime.now().minute
    if min < 20:
        l = hourly.get_hour(0)['temperature']
        r = hourly.get_hour(1)['temperature']
    elif min > 40:
        l = hourly.get_hour(1)['temperature']
        r = hourly.get_hour(2)['temperature']
    else:
        l = (hourly.get_hour(0)['temperature'] +
             hourly.get_hour(1)['temperature']) / 2
        r = (hourly.get_hour(1)['temperature'] +
             hourly.get_hour(2)['temperature']) / 2
    s = (r - l) / 60
コード例 #9
0
col_names.append("Max_3")
col_names.append("Min_4")
col_names.append("Max_4")
col_names.append("Min_5")
col_names.append("Max_5")
col_names.append("Min_avg")
col_names.append("Max_max")




#Obtain and read in weather data through Python3 wrapper for Dark Sky API

for i in range(len(cities)):

    fio = ForecastIO.ForecastIO(key, latitude = cities[i].get_lat(), 
                                longitude = cities[i].get_lon(), units= 'si' )
    

    daily = FIODaily.FIODaily( fio )
    
    for day in range(2, 7):
        
        val = daily.get( day )
        cities[i].add_minmax( str(val[ "temperatureMin" ]), 
                              str(val[ "temperatureMax" ]))





#Write to CSV
コード例 #10
0
# Demonstrates a very basic logging setup and how to
# disable logging messages from the forecastiopy module

# See here for logging details https://docs.python.org/3/library/logging.html

import logging

from forecastiopy import ForecastIO

# Basic logger setup
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)

# Basic logging example
log.debug("A debug message")
log.info("An info message")
log.warning("A warning")

# Will print a warning message
log.info("ForecastIO default")
ForecastIO.ForecastIO("0" * 32)

# Disables the forecastiopy logger
logging.getLogger("forecastiopy").disabled = True

# Will no longer print a warning message
log.info("ForecastIO logger disabled")
ForecastIO.ForecastIO("0" * 32)

logging.info("Finished")