Example #1
0
 def update_current_weather(self):
     current_weather = weather.get_current_weather()
     time = current_weather.get('time')
     temperature = current_weather.get('temperature')
     wind_speed = current_weather.get('wind').get('speed')
     wind_direction = current_weather.get('wind').get('direction')
     icon = current_weather.get('icon')
     icon = "icons/" + icon + ".png"
     # rain
     if '1h' in current_weather.get('rain'):
         rain = current_weather.get('rain').get('1h')
         rain_time = '1h'
         norain = False
     elif '2h' in current_weather.get('rain'):
         rain = current_weather.get('rain').get('2h')
         rain_time = '2h'
         norain = False
     elif '3h' in current_weather.get('rain'):
         rain = current_weather.get('rain').get('3h')
         rain_time = '3h'
         norain = False
     else:
         rain = "---"
         norain = True
     self.uhrzeit1.setText("{}".format(time))
     self.temperatur1.setText("{}°C".format(temperature))
     self.wind1.setText("{}kn {}".format(wind_speed, wind_direction))
     if norain:
         self.regen1.setText("{}".format(rain))
     else:
         self.regen1.setText("{} in {}".format(rain, rain_time))
     self.image1.setPixmap(QtGui.QPixmap(icon))
Example #2
0
def main():
    city = None
    name = None
    #pass no args to use the ip of the machine running this pass extra args and it will
    # default to Brentwood
    if len(sys.argv) == 3:
        loc = sys.argv[1]
        if loc == 'local':
            name = 'local_test.html'
            city = location.get_location_by_ip()
        elif loc == 'default':
            city = location.get_location()
            name = 'brentwood_test.html'
        else:
            print(
                'usage:\n python htmlgen.py local newsapikey\n python htmlgen.py default newsapikey\n'
            )
            sys.exit(0)
        newsapi = sys.argv[2]
        try:
            news_data = news.build_url_call(None, newsapi)
        except:
            print('bad key try again')
            sys.exit(1)

    else:
        print(
            'usage:\n python htmlgen.py local newsapikey\n python htmlgen.py default newsapikey\n'
        )
        sys.exit(0)

    current_weather = weather.get_current_weather(city=city)
    forecast = weather.get_forecast(city=city)

    x, y = weather.get_coord(current_weather)
    weather_url = weather.get_map_url(y, x)
    # get the top headline news
    url = news.build_url_call(None, newsapi)
    news_data = news.get_data(url)
    html = html_header1 + builder_header(city) + build_news_section(
        news_data) + build_current_weather(current_weather) + build_forecast(
            forecast) + build_weather_map(weather_url)
    save_file(html, name)
Example #3
0
    def process_automation(self):

        # Get season of today
        self.season = sun.get_season(datetime.date.today())

        # Get all info (sensor, actuator, rule) by room
        self.get_room()

        # Get automation rule
        auto_rule_status, self.automation_rule = self.get_automation_rule()
        if auto_rule_status:

            # Get last weather measures and forecast
            self.weather_forecast = weather.get_forecast(
                self.__client, self.automation_log, False)
            self.weather_current = weather.get_current_weather(
                self.__client, self.automation_log, False)
            if self.weather_forecast and self.weather_current:

                # Check if we have room to process automation
                # Useless check
                if len(self.rooms) > 0:

                    # Walk through all room
                    for room in self.rooms:

                        # Process blind rule
                        self.process_blinds(room)

                        # If True => we can process the room
                        multisensor_status, temp, measures = multisensor.check_multisensor(
                            self.__client, self.automation_log,
                            self.automation_rule, room.sensors)
                        if multisensor_status:

                            # Process valve rule
                            self.process_valves(room, temp)
                            #self.process_valves(room, 26)
            else:
                self.automation_log.log_error(
                    f"In function (process_automation), could not get weather or forecast"
                )
Example #4
0
def reply_weather():  # メンション送られたツイートに天気情報をリプする
    id_list = get_mention()  # メンションされたツイートのidを取得
    if len(id_list) == 0:  # 前回からメンションされてないとき用
        return 0
    for status_id in id_list:
        tweet = api.get_status(id=status_id)
        user_id = tweet.user.screen_name
        text = tweet.text
        city_kanji = text.split()[1]
        city_name = kakasi.to_english(city_kanji)
        if weather.confirm_exists_city(city_name) == "404":
            reply_text = "@"+user_id+"ちょっとわからないですね…"
            api.update_status(status=reply_text, in_reply_to_status_id=status_id)
            with open("log/errorlog.txt", 'w') as file:
                file.write(status_id+text)
        else:
            info = weather.get_current_weather(city_name)
            reply_text = "@"+user_id+"今の"+city_kanji+info[0]+"らしいっすよ\n"\
                         + "最高気温: "+str(info[1])+"\n最低気温: "+str(info[2])
            api.update_status(status=reply_text, in_reply_to_status_id=status_id)
Example #5
0
async def forecast(ctx, city, country=""):
    # @Update - Embedded contents, information
    # Gets the current forecast for the specified city and bulids
    # an embed object to display in the caller's text channel
    result = weather.get_current_weather(city, country)
    forecast_embed = discord.Embed(
        title="Forecast",
        description=f"Today's forecast for {city}, {result['sys']['country']}",
        color=0x4d5ef7)
    forecast_embed.set_image(
        url=
        f"https://openweathermap.org/img/w/{result['weather'][0]['icon']}.png")
    forecast_embed.add_field(
        name=f"Average: {result['main']['temp']}°C",
        value=
        f"Min: {result['main']['temp_min']}°C, Max: {result['main']['temp_max']}°C",
        inline=True)
    forecast_embed.add_field(name=f"{result['weather'][0]['main']}",
                             value=f"{result['weather'][0]['description']}",
                             inline=True)
    forecast_embed.set_footer(text="Weather data provided by OpenWeatherMaps")
    await ctx.send(embed=forecast_embed)
Example #6
0
def search():

    # Calls the get city from the ui module and prompts the user to enter the city
    city = ui.get_city()
    """
    The city variable is passed to the restaurant, events, and weather module to get the data from the server via API
    """
    restaurants = rest.get_restaurants(
        city)  #Returns the restaurant in a particular city
    events = city_event.get_events(city)  # Returns the events at the city
    current_weather = weather.get_current_weather(
        city)  # Returns the weather condition and temp

    # The display function from the ui module takes in the restaurant data, events, and weather as arguments and displays the information
    ui.display(restaurants, events, current_weather)

    # figure out if user wants to save
    choice = input('Do you want to bookmark the results? y or n')
    choice = choice.lower()  # Makes the choice case insensitive

    if choice == 'y':
        db.save(restaurants, events, weather)
Example #7
0
async def weather(*location: str):
    """oh the weather outside is weather"""
    output = weathermodule.get_current_weather('%2C'.join(location))
    await bot.say(output)
Example #8
0
def get_search_term(search_term, city):
    weather_response = weather.get_current_weather(search_term)
    restaurant_response = rest.get_restaurants(search_term)
    event_response = city_event.get_events(search_term, city)
    return weather_response, restaurant_response, event_response
def update_weather():

    current_w = weather.get_current_weather('a874452b76f1cc6022316d344c4ac034',
                                            'Poznan')
    weather_info = weather.dict_to_string_tuple(current_w)
    weather_condition_info.after(1800000)
    weather_info = weather.dict_to_string_tuple(current_w)
    weather_condition_info.after(1800000)


root = tk.Tk()
root.wm_attributes(
    '-type',
    'splash')  #to dodalem zeby usunelo gorny pasek z minimlaizacja itp
root.geometry("100x100")
root.resizable(0, 0)  #Don't allow resizing in the x or y direction
root.geometry("+0+800")

frame = tk.Frame(root, width=150, height=150)  #size of the info square
frame.pack()

current_w = weather.get_current_weather('a874452b76f1cc6022316d344c4ac034',
                                        'Poznan')
weather_info = weather.dict_to_string_tuple(current_w)
current_info = 0

weather_condition_label = tk.Label(frame,
                                   text="Cloudiness:",
                                   font=("Calibri", 10))
weather_condition_label.pack()

weather_condition_info = tk.Label(frame, text="55%", font=("Calibri", 10))
weather_condition_info.pack()
display_weather(current_info)

line_break = tk.Label(frame, text="", font=("Calibri", 10))
line_break.pack()
Example #11
0
def healthcheck():
    return jsonify(get_current_weather("Washington"))
Example #12
0
def index():
    latest_weather_data = get_current_weather()
    return render_template("index.html", wdata=latest_weather_data)
Example #13
0
def weather(city: str):
    """Get weather in the city"""
    return jsonify(get_current_weather(city))
Example #14
0


    # Pull in all the documents from the db.instants database collection
    instants = load_instants_from_db()
    # Start pulling all the data from the weather API
    weather_list = []
    
    # Begin a timer for the process and run the request and load process.
    start_start = time.time()
    print(f'task began at {start_start}')
    k, n = 0, 0 # i for counting zipcodes processed and n for counting API
                # calls made; API calls capped at 60/minute/apikey.
    start_time = time.time()
    for code in codes:
        o = weather.get_current_weather(code)  # 'o' for observation
        n += 1
        location = o.weather['Weather'].pop('location')  # This is needed for 
                                                         # the five_day().
        weath = o.weather.pop('Weather')
        o.as_dict['weather'] = weath
        weather_list.append(o)
        f = weather.five_day(location)  # 'f' for forecasts
        n += 1
        for item in f:
            weather_list.append(item)

            # If the api request rate is greater than 60 just keep going.
            # Otherwise check how many requests have been made, and if it's more
            # than 120 start make_instants.
            if n/2 / (time.time()-start_time) <= 1:
Example #15
0
def main():

    # imposta il tempo di attesa fra un conteggio di persone e l'altro
    print("Orario di inizio detection: " + str(datetime.now()))
    t_end = datetime.now().replace(microsecond=0) + timedelta(
        seconds=DETECTIONS_INTERVAL)
    print("Orario di fine detection:   " + str(t_end))

    # leggi il file json contenente i dati delle webcam
    with open(PATH_WEBCAM_JSON) as f:
        json_data = json.load(f)

    # scorri fra tutte le webcams presenti nel file json
    for webcam in json_data["webcams"]:
        print("Raccolta dati per: " + webcam["location"] + ", " +
              webcam["city"])
        # ottieni la temperatura e il meteo al tempo dell'acquisizione;
        try:
            temperature, weather_description = get_current_weather(
                webcam["latitude"], webcam["longitude"])
            print('Condizioni meteo ottenute con successo')
        except:
            print('Exception nel weather')
            logging.info('Eccezione ore: ' + str(datetime.now()))
            logging.error(sys.exc_info())
            continue

        #imposta l'orario e la data di acquisizione
        current_time = current_date = datetime.now()

        try:
            video_link = fetch_read_m3u8(webcam["link"], webcam["url_prefix"])
        except:
            print("Failed to fetch/read m3u8")
            # continue

            # scarica il video dal link appena ricavato

        try:
            frame_is_read, frame = extract_frame_from_video_url(video_link)
            cv2.imwrite('frame' + str(webcam["city"]) + '.jpg', frame)
            print('Frame estratto con successo')
        except:
            print('Exception: video non disponibile: ' + webcam["location"])
            logging.info('Eccezione ore: ' + str(datetime.now()))
            logging.error(sys.exc_info())
            continue

        try:
            frame_part = cut_frame_in_six(frame)

        except:
            print('Exception')
            logging.info('Eccezione ore: ' + str(datetime.now()))
            logging.error(sys.exc_info())
            continue

        persone_contate = 0

        persone_contate = count_objects_in_frame(frame_part)

        print("Persone: " + str(persone_contate))

        #unisco i frame con i riquadri

        img1 = cv2.imread("detection0.jpg")
        img2 = cv2.imread("detection1.jpg")
        img3 = cv2.imread("detection2.jpg")
        img4 = cv2.imread("detection3.jpg")
        img5 = cv2.imread("detection4.jpg")
        img6 = cv2.imread("detection5.jpg")
        col1 = np.concatenate((img1, img2), axis=0)
        col2 = np.concatenate((img3, img4), axis=0)
        col3 = np.concatenate((img5, img6), axis=0)
        col12 = np.concatenate((col1, col2), axis=1)
        col123 = np.concatenate((col12, col3), axis=1)
        cv2.imwrite('complete' + str(webcam["city"]) + '.jpg', col123)
Example #16
0
def handle_current_weather(message):
    bot.send_message(message.chat.id, wth.get_current_weather())
Example #17
0
def index():
    public_ip, region, isp = get_ip_info()
    weather_info = get_current_weather()
    return render_template('index.html', ip=public_ip, region=region, isp=isp, location=weather_info['location'], description=weather_info['description'], temperature=weather_info['temperature']['now'])
Example #18
0
def main():
    while True:

        # imposta il tempo di attesa fra un conteggio di persone e l'altro
        print("Orario di inizio detection: " + str(datetime.now()))
        t_end = datetime.now().replace(microsecond=0) + timedelta(
            seconds=DETECTIONS_INTERVAL)
        print("Orario di fine detection:   " + str(t_end))

        # leggi il file json contenente i dati delle webcam
        with open(PATH_WEBCAM_JSON) as f:
            json_data = json.load(f)

        # scorri fra tutte le webcams presenti nel file json
        for webcam in json_data["webcams"]:
            print("Raccolta dati per: " + webcam["location"] + ", " +
                  webcam["city"])
            # ottieni la temperatura e il meteo al tempo dell'acquisizione;
            try:
                temperature, weather_description = get_current_weather(
                    webcam["latitude"], webcam["longitude"])
            except:
                print('Exception nel weather')
                logging.info('Eccezione ore: ' + str(datetime.now()))
                logging.error(sys.exc_info())
                continue

            #imposta l'orario e la data di acquisizione
            current_time = current_date = datetime.now()

            try:
                video_link = fetch_read_m3u8(webcam["link"],
                                             webcam["url_prefix"])
            except:
                print("Failed to fetch/read m3u8")
                # continue

                # scarica il video dal link appena ricavato

            try:
                #urllib.request.urlretrieve(video_link, PATH_VIDEOS+"Video" + ".ts")
                frame_is_read, frame = extract_frame_from_video_url(video_link)
                print(frame_is_read)
            except:
                print('Exception: video non disponibile: ' +
                      webcam["location"])
                logging.info('Eccezione ore: ' + str(datetime.now()))
                logging.error(sys.exc_info())
                continue

            try:
                frame_part = cut_frame_in_six(frame)

            except:
                print('Exception')
                logging.info('Eccezione ore: ' + str(datetime.now()))
                logging.error(sys.exc_info())
                continue

            persone_contate = 0

            # conta le persone in ogni sottoframe
            for frame in frame_part:
                persone_contate = persone_contate + detect(frame)

            print("Persone: " + str(persone_contate))

            data = {
                'id_webcam': webcam["id_webcam"],
                'city': webcam["city"],
                'location': webcam["location"],
                'latitude': webcam["latitude"],
                'longitude': webcam["longitude"],
                'numPeople': persone_contate,
                'date': current_date.strftime('%Y-%m-%d %H:%M:%S.%f'),
                'time': current_time.strftime('%Y-%m-%d %H:%M:%S.%f'),
                'type': 0,
                'weather_description': weather_description,
                'temperature': temperature,
                'day_of_week': datetime.now().date().weekday()
            }
            producer.send('gdp', value=data)
            print("ho fatto kafka")
            # inserisci i risultati nel db

        print("waiting for: " + str((t_end - datetime.now()).total_seconds()))
        time.sleep((t_end - datetime.now()).total_seconds())
Example #19
0
import json
import config
import weather
import route

c = config.get_value('openweather_key')
print(c)

e = weather.get_current_weather()
print(e)

t = route.get_current_traffic('2 Impala ave Sandton','39 Rivonia Rd Sandton')
print(t)

Example #20
0
 def update(self, *args):
     temp,desc,_icon = weather.get_current_weather()
     t = '{0}{1}C'.format(temp,u'\xb0')
     self.temperature = t
     self.description = desc
     self.imgpath = _icon
Example #21
0
        elif intent == 'joke':
            print(choice(jokes))

        elif intent == 'thanks':
            print(choice(youre_welcome))

        elif intent in ['weather_get', 'temperature_get', 'is_condition']:
            if not location:
                print(choice(error_no_location))
                continue
            request_condition = data['conditions']
            date_diff = (request_date -
                         date.today()).days if request_date else 0
            if date_diff == 0:
                weather_conditions = weather.get_current_weather(location)
            elif 0 < date_diff < 3:
                weather_conditions = weather.get_forecast(location, date_diff)
            elif date_diff > 3:
                print(choice(error_date_too_late))
                continue
            else:
                print(choice(error_past_date))
                continue
            if intent == 'weather_get':
                print(
                    f'In {location[0]} it {"will be" if date_diff else "is"} {weather_conditions["condition"]}'
                    f' and the temperature {"will be" if date_diff else "is"} {weather_conditions["temperature"]} '
                    f'degrees Celsius')
            elif intent == 'temperature_get':
                print(
Example #22
0
 def get_context_data(self, **kwargs):
     weather = get_current_weather(Account.objects.all()[0])
     return super(HomeView, self).get_context_data(weather=weather, **kwargs)