<commit_before>import json
import datetime

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.listview import ListItemButton
from kivy.properties import (ObjectProperty, ListProperty,
                             StringProperty, NumericProperty)
from kivy.network.urlrequest import UrlRequest
from kivy.storage.jsonstore import JsonStore
from kivy.factory import Factory
from kivy.uix.popup import Popup
from kivy.graphics import Rectangle
from kivy.uix.image import Image


__version__ = "0.2"


def locations_args_converter(index, data_item):
    city, country = data_item
    return {'location': (city, country)}


class LocationButton(ListItemButton):
    location = ListProperty()


class WeatherRoot(BoxLayout):

    carousel = ObjectProperty()
#    add_location_form = ObjectProperty()

    def __init__(self, **kargs):
        super(WeatherRoot, self).__init__(**kargs)
        self.locations = {}
        self.store = JsonStore("weather_store.json")
        if self.store.exists('locations'):
            locations = self.store.get('locations')
            for location in locations['locations']:
                location = tuple(location)
                self.locations[location] = WeatherPage(location)
                self.carousel.add_widget(self.locations[location])
            current_location = tuple(locations['current_location'])
            self.carousel.load_slide(self.locations[current_location])
        else:
            Clock.schedule_once(lambda dt: self.show_add_location_form())

    def update_weather(self):
        for location in self.locations:
            self.locations[location].update_weather()

    def remove_location(self, location=None):
        if location is None:
            location = self.carousel.current_slide.location
        location = tuple(location)
        if location in self.locations:
#            if self.carousel.previous_slide is None:
#                self.carousel.load_next()
#            else:
#                self.carousel.load_previous()
            self.carousel.remove_widget(self.locations.pop(location))

    def add_location(self, location=None):
        location = tuple(location)
        if location is not None:
            if location not in self.locations:
                self.locations[location] = WeatherPage(location)
                self.carousel.add_widget(self.locations[location])
                self.store.put("locations",
                               locations=list(self.locations.keys()),
                               current_location=location)
        self.carousel.load_slide(self.locations[location])
        if self.add_location_form is not None:
            self.add_location_form.dismiss()

    def show_add_location_form(self):
        self.add_location_form = Popup(title="Add Location...",
                                       size_hint=(.8, .6),
                                       content=AddLocationForm())
        self.add_location_form.open()


class AddLocationForm(BoxLayout):

    search_input = ObjectProperty()
    search_results = ObjectProperty()

    def search_location(self):
        search_template = ("http://api.openweathermap.org/data/2.5/" +
                           "find?q={}&type=like")
        search_url = search_template.format(self.search_input.text)
        request = UrlRequest(search_url, self.found_location)

    def search_coordinates(self):
        search_template = ("http://api.openweathermap.org/data/2.5/" +
                           "find?lat={}&lon={}&cnt=10")
        coordinates = self.search_input.text.split(',')
        if len(coordinates) == 2:
            try:
                lat, lon = float(coordinates[0]), float(coordinates[1])
                search_url = search_template.format(lat, lon)
                request = UrlRequest(search_url, self.found_location)
            except ValueError:
                pass

    def found_location(self, request, data):
        data = json.loads(data.decode()) if not isinstance(data, dict) else data
        if 'list' in data:
            cities = [(d['name'], d['sys']['country'])
                      for d in data['list']]
        else:
            cities = []
        self.search_results.item_strings = cities
        try:
            self.search_results.adapter.data.clear()
        except AttributeError:
            self.search_results.adapter.data = []
        self.search_results.adapter.data.extend(cities)
        self.search_results._trigger_reset_populate()


class WeatherPage(BoxLayout):
    location = ListProperty(['New York', 'US'])
    temp = NumericProperty()
    forecast_panel = ObjectProperty()
    condition_image = StringProperty()
    conditions = StringProperty()
    temp_min = NumericProperty()
    temp_max = NumericProperty()
    humidity = NumericProperty()
    pressure = NumericProperty()
    bg_img = StringProperty('./imgs/rain_r.jpg')

    def __init__(self, location=None, **kargs):
        super(WeatherPage, self).__init__(**kargs)
        if location is not None:
            self.location = location
        self.update_weather()
        with self.canvas.before:
            self.rect = Rectangle(pos=self.pos, size=self.size)
        self.bind(pos=self._update_rect)
        self.bind(size=self._update_rect)
        self.bind(bg_img=self._update_rect)
        self._update_rect()

    def _update_rect(self, *args):
        if self.bg_img:
            texture = Image(source=self.bg_img).texture
            r_w, r_h = self.size
            self.rect.pos = self.pos
            self.rect.size = self.size
            t_w, t_h = texture.size
            coord = t_w//2 - r_w//2, t_h//2 - r_h//2, r_w, r_h
            self.rect.texture = texture.get_region(*coord)

    def update_weather(self):
        self.update_weather_today()
        self.update_weather_forecast()

    def update_weather_today(self):
        weather_template = ("http://api.openweathermap.org/data/2.5/" +
                            "weather?q={},{}&units={}")
        weather_url = weather_template.format(self.location[0],
                                              self.location[1], 'metric')
        request = UrlRequest(weather_url, self.weather_retrived_today)

    def weather_retrived_today(self, request, data):
        data = json.loads(data.decode()) if not isinstance(data, dict) else data
        conditions = data['weather'][0]['description']
        self.conditions = conditions[0].upper() + conditions[1:].lower()
        self.temp = data['main']['temp']
#        self.condition_image = "http://openweathermap.org/img/w/{}.png".format(data['weather'][0]['icon'])
        self.condition_image = "./imgs/{}.png".format(data['weather'][0]['icon'])
        self.temp_min = data['main']['temp_min']
        self.temp_max = data['main']['temp_max']<commit_msg>Improve image background<commit_after>import json
import datetime

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.listview import ListItemButton
from kivy.properties import (ObjectProperty, ListProperty,
                             StringProperty, NumericProperty)
from kivy.network.urlrequest import UrlRequest
from kivy.storage.jsonstore import JsonStore
from kivy.factory import Factory
from kivy.uix.popup import Popup
from kivy.graphics import Rectangle, Color
from kivy.uix.image import Image


__version__ = "0.2"

BG_MAP = {
    '01d': 'sunshine.jpg',
    '01n': 'moon.jpg',
    '02d': 'sun_cloud.jpg',
    '02n': 'moon_cloud.jpg',
    '03d': 'cloud.jpg',
    '03n': 'moon_cloud.jpg',
    '04d': 'cloud.jpg',
    '04n': 'moon_cloud.jpg',
    '09d': 'rain.jpg',
    '09n': 'rain_night.jpg',
    '10d': 'rain.jpg',
    '10n': 'rain_night.jpg',
    '11d': 'rain.jpg',
    '11n': 'rain_night.jpg',
    '13d': 'snow.jpg',
    '13n': 'snow_night.jpg',
    '50d': 'mist.jpg',
    '50n': 'mist.jpg',
}


def locations_args_converter(index, data_item):
    city, country = data_item
    return {'location': (city, country)}


class LocationButton(ListItemButton):
    location = ListProperty()


class WeatherRoot(BoxLayout):

    carousel = ObjectProperty()
#    add_location_form = ObjectProperty()

    def __init__(self, **kargs):
        super(WeatherRoot, self).__init__(**kargs)
        self.locations = {}
        self.store = JsonStore("weather_store.json")
        if self.store.exists('locations'):
            locations = self.store.get('locations')
            for location in locations['locations']:
                location = tuple(location)
                self.locations[location] = WeatherPage(location)
                self.carousel.add_widget(self.locations[location])
            current_location = tuple(locations['current_location'])
            self.carousel.load_slide(self.locations[current_location])
        else:
            Clock.schedule_once(lambda dt: self.show_add_location_form())

    def update_weather(self):
        for location in self.locations:
            self.locations[location].update_weather()

    def remove_location(self, location=None):
        if location is None:
            location = self.carousel.current_slide.location
        location = tuple(location)
        if location in self.locations:
#            if self.carousel.previous_slide is None:
#                self.carousel.load_next()
#            else:
#                self.carousel.load_previous()
            self.carousel.remove_widget(self.locations.pop(location))

    def add_location(self, location=None):
        location = tuple(location)
        if location is not None:
            if location not in self.locations:
                self.locations[location] = WeatherPage(location)
                self.carousel.add_widget(self.locations[location])
                self.store.put("locations",
                               locations=list(self.locations.keys()),
                               current_location=location)
        self.carousel.load_slide(self.locations[location])
        if self.add_location_form is not None:
            self.add_location_form.dismiss()

    def show_add_location_form(self):
        self.add_location_form = Popup(title="Add Location...",
                                       size_hint=(.8, .6),
                                       content=AddLocationForm())
        self.add_location_form.open()


class AddLocationForm(BoxLayout):

    search_input = ObjectProperty()
    search_results = ObjectProperty()

    def search_location(self):
        search_template = ("http://api.openweathermap.org/data/2.5/" +
                           "find?q={}&type=like")
        search_url = search_template.format(self.search_input.text)
        request = UrlRequest(search_url, self.found_location)

    def search_coordinates(self):
        search_template = ("http://api.openweathermap.org/data/2.5/" +
                           "find?lat={}&lon={}&cnt=10")
        coordinates = self.search_input.text.split(',')
        if len(coordinates) == 2:
            try:
                lat, lon = float(coordinates[0]), float(coordinates[1])
                search_url = search_template.format(lat, lon)
                request = UrlRequest(search_url, self.found_location)
            except ValueError:
                pass

    def found_location(self, request, data):
        data = json.loads(data.decode()) if not isinstance(data, dict) else data
        if 'list' in data:
            cities = [(d['name'], d['sys']['country'])
                      for d in data['list']]
        else:
            cities = []
        self.search_results.item_strings = cities
        try:
            self.search_results.adapter.data.clear()
        except AttributeError:
            self.search_results.adapter.data = []
        self.search_results.adapter.data.extend(cities)
        self.search_results._trigger_reset_populate()


class WeatherPage(BoxLayout):
    location = ListProperty(['New York', 'US'])
    temp = NumericProperty()
    forecast_panel = ObjectProperty()
    condition_image = StringProperty()
    conditions = StringProperty()
    temp_min = NumericProperty()
    temp_max = NumericProperty()
    humidity = NumericProperty()
    pressure = NumericProperty()
    bg_img = StringProperty('')

    def __init__(self, location=None, **kargs):
        super(WeatherPage, self).__init__(**kargs)
        if location is not None:
            self.location = location
        self.update_weather()
        with self.canvas.before:
            self.rect = Rectangle(pos=self.pos, size=self.size)
        self.bind(pos=self._update_rect)
        self.bind(size=self._update_rect)
        self.bind(bg_img=self._update_rect)
        self._update_rect()

    def _update_rect(self, *args):
        if self.bg_img:
            texture = Image(source='imgs/' + self.bg_img).texture
            r_w, r_h = self.size
            self.rect.pos = self.pos
            self.rect.size = self.size
            t_w, t_h = texture.size
            coord = t_w//2 - r_w//2, t_h//2 - r_h//2, r_w, r_h
            self.rect.texture = texture.get_region(*coord)

    def update_weather(self):
        self.update_weather_today()
        self.update_weather_forecast()

    def update_weather_today(self):
        weather_template = ("http://api.openweathermap.org/data/2.5/" +
                            "weather?q={},{}&units={}")
        weather_url = weather_template.format(self.location[0],
                                              self.location[1], 'metric')
        request = UrlRequest(weather_url, self.weather_retrived_today)

    def weather_retrived_today(self, request, data):
        data = json.loads(data.decode()) if not isinstance(data, dict) else data
        conditions = data['weather'][0]['description']
        self.conditions = conditions[0].upper() + conditions[1:].lower()
        self.temp = data['main']['temp']
#        self.condition_image = "http://openweathermap.org/img/w/{}.png".format(data['weather'][0]['icon'])
        self.condition_image = "./imgs/{}.png".format(data['weather'][0]['icon'])
        self.bg_img = BG_MAP[data['weather'][0]['icon']]
        self.temp_min = data['main']['temp_min']
        self.temp_max = data['main']['temp_max']
{'fraction_non_alphanumeric': 0.11983442082368624, 'fraction_numerical': 0.006244299445730723, 'mean_word_length': 2.411680229775012, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3880204', 'n_tokens_mistral': 4237, 'n_tokens_neox': 4049, 'n_words': 758}