Пример #1
0
 def on_swipe_delete(self, instance):
     Snackbar(text="Task deleted", snackbar_y=dp(50)).open()
     trash_index = self.done_list.index(instance.text)
     self.done_list.pop(trash_index)
     self.root.ids.done_list.remove_widget(instance)
     self.save_list('done')
Пример #2
0
 def snk(*args):
         Snackbar(text = "Posting...").open()
Пример #3
0
 def on_enter(self, *args):
     self.practice.keyboard_on()
     self.get_revision_words()
     self.practice.set_practice_text()
     if not self.practice.text:
         Snackbar(text="there are no words to revise today").show()
Пример #4
0
    def on_enter(self):
        global previous_screen, location, weatherData_main, weatherData_other, lat, lon, loading
        previous_screen = 'input'

        print(loading)

        if loading == "data":

            def stopSpinner(*args):
                self.ids.spinner.active = False
                self.manager.current = 'data'

            
            BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
            CITY = location
            API_KEY = "OpenWeatherMap API KEY"
            URL = BASE_URL + "q=" + CITY + "&appid=" + API_KEY

            response = ''

            try:
                response = requests.get(URL)
                print(response.json())
                
                if response.status_code == 200:
                    data = response.json()
                    weatherData_main = data['main']
                    lat = data['coord']['lat']
                    lon = data['coord']['lon']
                    weatherData_other['wind'] = data['wind']['speed']
                    weatherData_other['weather'] = data['weather'][0]['main']
                    weatherData_other['country'] = data['sys']['country']
                    print(str(lat) + " | " + str(lon))
                    #stop = stopSpinner(self)
                    Clock.schedule_once(stopSpinner, 0.5)
                else:
                    Snackbar(text="Wrong Location or server unavailable!").open()
                    #Clock.schedule_once(stopSpinner, 5)
                    self.manager.current = 'input'

            except(requests.ConnectionError, requests.Timeout):
                Snackbar(text="No internet connection!").open()
                #Clock.schedule_once(stopSpinner, 3)
                self.manager.current = 'input'

        elif loading == "input":
            self.manager.current = 'input'
        elif loading == 'ndv':
            self.ids.msg.text = "This might take a while..."
            def get(*args):
                global img_gal, img_link, imggalData
                if img_gal == 'apod':
                    url = "https://api.nasa.gov/planetary/apod?api_key=APIKEY"
                    response = requests.get(url)
                    print(response)
                    imggalData = response.json()
                    if imggalData['media_type'] == 'image':
                        #self.ids.img.source = self.link
                        #import requests

                        urllib.request.urlretrieve(imggalData['url'], 'img.jpg')
                        

                        img_link = 'img.jpg'
                        print(img_link)

                        #shutil.move('img.jpg', img_link)
                        
                self.manager.current = 'ndv'
            #Snackbar(text = "This may take a while... Be patient!").open()
            #threading.Thread(target=Snackbar(text = "Getting Data...").open()).start()
            get()
Пример #5
0
 def snk(*args):
     Snackbar(text = "Getting Data...").open()
Пример #6
0
class KitchenSink(MDApp, Screens):
    previous_date = ObjectProperty()
    manager = ObjectProperty()
    instance_menu_source_code = ObjectProperty()
    md_theme_picker = ObjectProperty()
    long_dialog = ObjectProperty()
    input_dialog = ObjectProperty()
    alert_dialog = ObjectProperty()
    ok_cancel_dialog = ObjectProperty()
    dialog = ObjectProperty()
    user_card = ObjectProperty()
    my_snackbar = ObjectProperty(None, allownone=True)
    dialog_load_kv_files = ObjectProperty()

    create_stack_floating_buttons = BooleanProperty(False)
    manager_open = BooleanProperty(False)
    cards_created = BooleanProperty(False)
    toolbar_hide = BooleanProperty(False)

    _interval = NumericProperty(0)
    tick = NumericProperty(0)
    x = NumericProperty(0)
    y = NumericProperty(25)
    file_source_code = StringProperty("", allownone=True)
    directory = StringProperty()

    menu_items = ListProperty()
    hex_primary_color = StringProperty()
    previous_text = StringProperty()
    previous_text_end = StringProperty()
    names_contacts = ListProperty(
        (
            "Alexandr Taylor",
            "Yuri Ivanov",
            "Robert Patric",
            "Bob Marley",
            "Magnus Carlsen",
            "Jon Romero",
            "Anna Bell",
            "Maxim Kramerer",
            "Sasha Gray",
            "Vladimir Ivanenko",
        )
    )
    list_name_icons = ListProperty()

    def __init__(self, **kwargs):
        self.title = "Kitchen Sink"
        self.theme_cls.primary_palette = "BlueGray"
        self.theme_cls.accent_palette = "Gray"
        super().__init__(**kwargs)

        self.menu_items = [
            {
                "viewclass": "MDMenuItem",
                "text": "Example item %d" % i,
                "callback": self.callback_for_menu_items,
            }
            for i in range(15)
        ]
        self.hex_primary_color = get_hex_from_color(
            self.theme_cls.primary_color
        )

        self.previous_text = (
            f"Welcome to the application [b][color={self.hex_primary_color}]"
            f"Kitchen Sink[/color][/b].\nTo see [b]"
            f"[color={self.hex_primary_color}]KivyMD[/color][/b] "
            f"examples, open the menu and select from the list the desired "
            f"example or"
        )
        self.previous_text_end = (
            f"for show example apps\n\n"
            f"Author - [b][color={self.hex_primary_color}]"
            f"Andrés Rodríguez[/color][/b]\n"
            f"[u][b][color={self.hex_primary_color}]"
            f"[email protected][/color][/b][/u]\n\n\n"
            f"Authors this Fork:\n\n"
            f"[b][color={self.hex_primary_color}]"
            f"Ivanov Yuri[/color][/b]\n"
            f"[u][b][color={self.hex_primary_color}]"
            f"[email protected][/color][/b][/u]\n\n"
            f"[b][color={self.hex_primary_color}]Artem S. Bulgakov[/color][/b]\n"
            f"[u][b][color={self.hex_primary_color}]"
            f"[email protected][/color][/b][/u]\n\n"
            f"and contributors..."
        )
        self.list_name_icons = list(md_icons.keys())[0:15]
        Window.bind(on_keyboard=self.events, on_resize=self.window_resize)
        crop_image(
            (Window.width, int(dp(Window.height * 35 // 100))),
            f"{os.environ['KITCHEN_SINK_ASSETS']}guitar-1139397_1280.png",
            f"{os.environ['KITCHEN_SINK_ASSETS']}guitar-1139397_1280_crop.png",
        )

    def window_resize(self, instance_window, width_window, height_window):
        if self.toolbar_hide:
            self.root.ids.toolbar.height = 0

    def build(self):
        self.root = Builder.load_string(root_kv)

    def on_start(self):
        async def load_all_kv_files():
            count_kvs = len(list(self.data.keys()))
            for i, name_screen in enumerate(sorted(self.data.keys())):
                await asynckivy.sleep(0)
                self.dialog_load_kv_files.name_kv_file = name_screen
                self.dialog_load_kv_files.percent = str(
                    ((i + 1) * 100) // count_kvs
                )
                self.load_screen(name_screen)
            self.dialog_load_kv_files.dismiss()

        self.dialog_load_kv_files = DialogLoadKvFiles()
        self.dialog_load_kv_files.open()
        asynckivy.start(load_all_kv_files())

    def on_pause(self):
        return True

    def on_stop(self):
        pass

    def open_settings(self, *args):
        return False

    def show_demo_shrine(self, instance):
        """
        :type instance <Screen name='shrine demo'> object

        """

        def add_screen_shrine(MDShrine):
            def remove_box(*args):
                instance.remove_widget(box)

            md_shrine = MDShrine()
            md_shrine.opacity = 0
            instance.add_widget(md_shrine)

            anim = Animation(opacity=0, d=0.5)
            anim.bind(on_complete=remove_box)
            anim.start(box)
            Animation(opacity=2, d=0.5).start(md_shrine)
            self.theme_cls.primary_palette = "Red"

        def show_demo_shrine(interval):
            from demos.kitchen_sink.studies.shrine.shrine import MDShrine

            anim = Animation(
                size_hint=(0.2, 0.2), pos_hint={"center_y": 0.7}, d=0.5
            )
            anim.bind(on_complete=lambda *x: add_screen_shrine(MDShrine))
            anim.start(box)

        from kivy.uix.image import Image

        self.root.ids.toolbar.right_action_items = []
        self.root.ids.toolbar.left_action_items = []
        self.root.ids.toolbar.height = 0
        self.root.ids.toolbar.title = ""
        box = BoxLayout(
            orientation="vertical",
            size_hint=(0.4, 0.6),
            spacing=dp(10),
            pos_hint={"center_x": 0.5, "center_y": 0.6},
        )
        path_to_logo = (
            f"{os.environ['KITCHEN_SINK_ROOT']}/studies/shrine/data/images/shrine-white.png"
            if self.theme_cls.theme_style == "Dark"
            else f"{os.environ['KITCHEN_SINK_ROOT']}/studies/shrine/data/images/shrine-dark.png"
        )
        logo = Image(
            source=path_to_logo, size_hint_x=0.8, pos_hint={"center_x": 0.5}
        )
        box.add_widget(logo)
        box.add_widget(Factory.ShrinePresplashTile(text="SHRINE"))
        instance.add_widget(box)
        Clock.schedule_once(show_demo_shrine, 1)

    def set_list_for_refresh_layout(self):
        async def set_list_for_refresh_layout():
            names_icons_list = list(md_icons.keys())[self.x : self.y]
            for name_icon in names_icons_list:
                await asynckivy.sleep(0)
                self.data["Refresh Layout"]["object"].ids.box.add_widget(
                    ItemForListRefreshLayout(icon=name_icon, text=name_icon)
                )
            self.data["Refresh Layout"][
                "object"
            ].ids.refresh_layout.refresh_done()

        asynckivy.start(set_list_for_refresh_layout())

    def refresh_callback(self, *args):
        """A method that updates the state of your application
        while the spinner remains on the screen."""

        def refresh_callback(interval):
            self.data["Refresh Layout"]["object"].ids.box.clear_widgets()
            if self.x == 0:
                self.x, self.y = 25, 50
            else:
                self.x, self.y = 0, 25
            self.set_list_for_refresh_layout()
            self.tick = 0

        Clock.schedule_once(refresh_callback, 1)

    def build_tabs(self):
        for name_tab in self.list_name_icons:
            tab = Factory.MyTab(text=name_tab)
            self.data["Tabs"]["object"].ids.android_tabs.add_widget(tab)

    def switch_tabs_to_icon(self, istance_android_tabs):
        for i, instance_tab in enumerate(
            istance_android_tabs.ids.scrollview.children[0].children
        ):
            istance_android_tabs.ids.scrollview.children[0].remove_widget(
                instance_tab
            )
            istance_android_tabs.add_widget(
                Factory.MyTab(text=self.list_name_icons[i])
            )

    def switch_tabs_to_text(self, istance_android_tabs):
        for instance_tab in istance_android_tabs.ids.scrollview.children[
            0
        ].children:
            for k, v in md_icons.items():
                if v == instance_tab.text:
                    istance_android_tabs.ids.scrollview.children[
                        0
                    ].remove_widget(instance_tab)
                    istance_android_tabs.add_widget(
                        Factory.MyTab(text=" ".join(k.split("-")).capitalize())
                    )
                    break

    def crop_image_for_tile(self, instance, size, path_to_crop_image):
        """Crop images for Grid screen."""

        if not os.path.exists(os.path.join(self.directory, path_to_crop_image)):
            size = (int(size[0]), int(size[1]))
            path_to_origin_image = path_to_crop_image.replace("_tile_crop", "")
            crop_image(size, path_to_origin_image, path_to_crop_image)
        instance.source = path_to_crop_image

    def theme_picker_open(self):
        if not self.md_theme_picker:
            from kivymd.uix.picker import MDThemePicker

            self.md_theme_picker = MDThemePicker()
        self.md_theme_picker.open()

    def example_add_stack_floating_buttons(self):
        from kivymd.uix.stackfloatingbutton import MDStackFloatingButtons

        def set_my_language(instance_button):
            toast(instance_button.icon)

        if not self.create_stack_floating_buttons:
            screen = self.root.ids.scr_mngr.get_screen("stack buttons")
            screen.add_widget(
                MDStackFloatingButtons(
                    icon="lead-pencil",
                    floating_data={
                        "Python": "language-python",
                        "Php": "language-php",
                        "C++": "language-cpp",
                    },
                    callback=set_my_language,
                )
            )
            self.create_stack_floating_buttons = True

    def set_expansion_panel(self):
        from kivymd.uix.expansionpanel import MDExpansionPanel

        def callback(text):
            toast(f"{text} to {content.name_item}")

        content = ContentForAnimCard(callback=callback)

        for name_contact in self.names_contacts:
            self.data["Expansion Panel"]["object"].ids.anim_list.add_widget(
                MDExpansionPanel(
                    content=content,
                    icon=f"{os.environ['KITCHEN_SINK_ASSETS']}kivy-logo-white-512.png",
                    title=name_contact,
                )
            )

    def set_chevron_back_screen(self):
        """Sets the return chevron to the previous screen in ToolBar."""

        self.root.ids.toolbar.right_action_items = [
            ["dots-vertical", lambda x: self.root.toggle_nav_drawer()]
        ]

    def download_progress_hide(self, instance_progress, value):
        """Hides progress progress."""

        self.root.ids.toolbar.right_action_items = [
            [
                "download",
                lambda x: self.download_progress_show(instance_progress),
            ]
        ]

    def download_progress_show(self, instance_progress):
        self.set_chevron_back_screen()
        instance_progress.open()
        instance_progress.animation_progress_from_fade()

    def show_example_download_file(self, interval):
        from kivymd.uix.progressloader import MDProgressLoader

        def get_connect(host="8.8.8.8", port=53, timeout=3):
            import socket

            try:
                socket.setdefaulttimeout(timeout)
                socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(
                    (host, port)
                )
                return True
            except (TimeoutError, ConnectionError, OSError):
                return False

        if get_connect():
            link = (
                "https://www.python.org/ftp/python/3.8.0/"
                "python-3.8.0-embed-win32.zip"
            )
            progress = MDProgressLoader(
                url_on_image=link,
                path_to_file=os.path.join(self.directory, "python-3.8.0.zip"),
                download_complete=self.download_complete,
                download_hide=self.download_progress_hide,
            )
            progress.start(self.data["Download File"]["object"].ids.box_flt)
        else:
            toast("Connect error!")

    def download_complete(self):
        self.set_chevron_back_screen()
        toast("Done")

    def open_drop_items_examples(self):
        from kivymd.uix.dialog import MDDialog

        def set_list_drop_items():
            for i in range(20):
                self.data["Dropdown Item List"]["object"].ids.box.add_widget(
                    ItemForDropItemList(
                        items=[str(i + 1), str(i + 2), str(i + 3)]
                    )
                )

        def open_drop_items_examples(text_item, dialog):
            dialog.dismiss()
            data = {"Item": "Dropdown Item", "List": "Dropdown Item List"}
            self.root.ids.scr_mngr.current = self.data[data[text_item]][
                "name_screen"
            ]
            self.set_title_toolbar(data[text_item])
            set_list_drop_items()

        MDDialog(
            title="Kitchen Sink",
            size_hint=(0.8, 0.4),
            text_button_ok="Item",
            text="Open MDDropDownItem or ListButtonDropDown?",
            text_button_cancel="List",
            events_callback=open_drop_items_examples,
        ).open()

    def file_manager_open(self):
        from kivymd.uix.filemanager import MDFileManager
        from kivymd.uix.dialog import MDDialog

        def open_file_manager(text_item, dialog):
            previous = False if text_item == "List" else True
            self.manager = ModalView(size_hint=(1, 1), auto_dismiss=False)
            self.file_manager = MDFileManager(
                exit_manager=self.exit_manager,
                select_path=self.select_path,
                previous=previous,
            )
            self.manager.add_widget(self.file_manager)
            self.file_manager.show(self.user_data_dir)
            self.manager_open = True
            self.manager.open()

        MDDialog(
            title="Kitchen Sink",
            size_hint=(0.8, 0.4),
            text_button_ok="List",
            text="Open manager with 'list' or 'previous' mode?",
            text_button_cancel="Previous",
            events_callback=open_file_manager,
        ).open()

    def select_path(self, path):
        """It will be called when you click on the file name
        or the catalog selection button.
        :type path: str;
        :param path: path to the selected directory or file;
        """

        self.exit_manager()
        toast(path)

    def exit_manager(self, *args):
        """Called when the user reaches the root of the directory tree."""

        self.manager.dismiss()
        self.manager_open = False
        self.set_chevron_menu()

    def set_chevron_menu(self):
        self.root.ids.toolbar.left_action_items = [
            ["menu", lambda x: self.root.toggle_nav_drawer()]
        ]

    def events(self, instance, keyboard, keycode, text, modifiers):
        """Called when buttons are pressed on the mobile device."""

        if keyboard in (1001, 27):
            if self.manager_open:
                self.file_manager.back()
        return True

    def callback_for_menu_items(self, *args):
        toast(args[0])

    def add_cards(self, instance_grid_card):
        """Adds MDCardPost objects to the screen Cards
        when the screen is open."""

        from kivymd.uix.card import MDCardPost

        def callback(instance, value):
            if value is None:
                toast("Delete post %s" % str(instance))
            elif isinstance(value, int):
                toast("Set like in %d stars" % value)
            elif isinstance(value, str):
                toast("Repost with %s " % value)
            elif isinstance(value, list):
                toast(value[1])

        if not self.cards_created:
            self.cards_created = True
            menu_items = [
                {
                    "viewclass": "MDMenuItem",
                    "text": "Example item %d" % i,
                    "callback": self.callback_for_menu_items,
                }
                for i in range(2)
            ]
            buttons = ["facebook", "vk", "twitter"]

            instance_grid_card.add_widget(
                MDCardPost(
                    text_post="Card with text", swipe=True, callback=callback
                )
            )
            instance_grid_card.add_widget(
                MDCardPost(
                    right_menu=menu_items,
                    swipe=True,
                    text_post="Card with a button to open the menu MDDropDown",
                    callback=callback,
                )
            )
            instance_grid_card.add_widget(
                MDCardPost(
                    likes_stars=True,
                    callback=callback,
                    swipe=True,
                    text_post="Card with asterisks for voting.",
                )
            )

            image_for_card = f"{os.environ['KITCHEN_SINK_ASSETS']}kitten-for_card-1049129_1280-crop.png"
            if not os.path.exists(image_for_card):
                crop_image(
                    (int(Window.width), int(dp(200))),
                    f"{os.environ['KITCHEN_SINK_ASSETS']}kitten-1049129_1280.png",
                    image_for_card,
                )
            instance_grid_card.add_widget(
                MDCardPost(
                    source=image_for_card,
                    tile_text="Little Baby",
                    tile_font_style="H5",
                    text_post="This is my favorite cat. He's only six months "
                    "old. He loves milk and steals sausages :) "
                    "And he likes to play in the garden.",
                    with_image=True,
                    swipe=True,
                    callback=callback,
                    buttons=buttons,
                )
            )

    def update_screen(self, instance):
        """Set new label on the screen UpdateSpinner."""

        def update_screen(interval):
            self.tick += 1
            if self.tick > 2:
                instance.update = True
                self.tick = 0
                self.data["Update Screen Widget"][
                    "object"
                ].ids.upd_lbl.text = "New string"
                Clock.unschedule(update_screen)

        Clock.schedule_interval(update_screen, 1)

    def show_user_example_animation_card(self):
        """Create and open instance MDUserAnimationCard
        for the screen UserCard."""

        from kivymd.uix.useranimationcard import MDUserAnimationCard

        def main_back_callback():
            toast("Close card")

        if not self.user_card:
            image_for_user_card = f"{os.environ['KITCHEN_SINK_ASSETS']}guitar-for-user-card1139397_1280-crop.png"
            if not os.path.exists(image_for_user_card):
                crop_image(
                    (int(Window.width), int(dp(Window.height * 40 // 100))),
                    f"{os.environ['KITCHEN_SINK_ASSETS']}guitar-1139397_1280.png",
                    image_for_user_card,
                )

            self.user_card = MDUserAnimationCard(
                user_name="Lion Lion",
                path_to_avatar=image_for_user_card,
                callback=main_back_callback,
            )
            self.user_card.box_content.add_widget(ContentForAnimCard())
        self.user_card.open()

    def show_example_snackbar(self, snack_type):
        """Create and show instance Snackbar for the screen MySnackBar."""

        def callback(instance):
            toast(instance.text)

        def wait_interval(interval):
            self._interval += interval
            if self._interval > self.my_snackbar.duration:
                anim = Animation(y=dp(10), d=0.2)
                anim.start(self.data["Snackbars"]["object"].ids.button)
                Clock.unschedule(wait_interval)
                self._interval = 0
                self.my_snackbar = None

        from kivymd.uix.snackbar import Snackbar

        if snack_type == "simple":
            Snackbar(text="This is a snackbar!").show()
        elif snack_type == "button":
            Snackbar(
                text="This is a snackbar",
                button_text="WITH A BUTTON",
                button_callback=callback,
            ).show()
        elif snack_type == "verylong":
            Snackbar(
                text="This is a very very very very very very very "
                "long snackbar!"
            ).show()
        elif snack_type == "float":
            if not self.my_snackbar:
                self.my_snackbar = Snackbar(
                    text="This is a snackbar!",
                    button_text="Button",
                    duration=3,
                    button_callback=callback,
                )
                self.my_snackbar.show()
                anim = Animation(y=dp(72), d=0.2)
                anim.bind(
                    on_complete=lambda *args: Clock.schedule_interval(
                        wait_interval, 0
                    )
                )
                anim.start(self.data["Snackbars"]["object"].ids.button)

    def show_example_input_dialog(self):
        """Creates an instance of the dialog box and displays it
        on the screen for the screen Dialogs."""

        def result(text_button, instance):
            toast(instance.text_field.text)

        if not self.input_dialog:
            from kivymd.uix.dialog import MDInputDialog

            self.input_dialog = MDInputDialog(
                title="Title",
                hint_text="Hint text",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                events_callback=result,
            )
        self.input_dialog.open()

    def show_example_alert_dialog(self):
        if not self.alert_dialog:
            from kivymd.uix.dialog import MDDialog

            self.alert_dialog = MDDialog(
                title="Title",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text="This is Alert dialog",
                events_callback=self.callback_for_menu_items,
            )
        self.alert_dialog.open()

    def show_example_ok_cancel_dialog(self):
        if not self.ok_cancel_dialog:
            from kivymd.uix.dialog import MDDialog

            self.ok_cancel_dialog = MDDialog(
                title="Title",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text="This is Ok Cancel dialog",
                text_button_cancel="Cancel",
                events_callback=self.callback_for_menu_items,
            )
        self.ok_cancel_dialog.open()

    def show_example_long_dialog(self):
        if not self.long_dialog:
            from kivymd.uix.dialog import MDDialog

            self.long_dialog = MDDialog(
                text="Lorem ipsum dolor sit amet, consectetur adipiscing "
                "elit, sed do eiusmod tempor incididunt ut labore et "
                "dolore magna aliqua. Ut enim ad minim veniam, quis "
                "nostrud exercitation ullamco laboris nisi ut aliquip "
                "ex ea commodo consequat. Duis aute irure dolor in "
                "reprehenderit in voluptate velit esse cillum dolore eu "
                "fugiat nulla pariatur. Excepteur sint occaecat "
                "cupidatat non proident, sunt in culpa qui officia "
                "deserunt mollit anim id est laborum.",
                title="Title",
                size_hint=(0.8, 0.4),
                text_button_ok="Yes",
                events_callback=self.callback_for_menu_items,
            )
        self.long_dialog.open()

    def get_time_picker_date(self, instance, time):
        """Get date for MDTimePicker from the screen Pickers."""

        self.data["Pickers"]["object"].ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        """Show MDTimePicker from the screen Pickers."""

        from kivymd.uix.picker import MDTimePicker

        time_dialog = MDTimePicker()
        time_dialog.bind(time=self.get_time_picker_date)

        if self.data["Pickers"][
            "object"
        ].ids.time_picker_use_previous_time.active:
            try:
                time_dialog.set_time(self.previous_time)
            except AttributeError:
                pass
        time_dialog.open()

    def set_previous_date(self, date_obj):
        """Set previous date for MDDatePicker from the screen Pickers."""

        self.previous_date = date_obj
        self.data["Pickers"]["object"].ids.date_picker_label.text = str(
            date_obj
        )

    def show_example_date_picker(self):
        """Show MDDatePicker from the screen Pickers."""

        from kivymd.uix.picker import MDDatePicker

        if self.data["Pickers"][
            "object"
        ].ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(
                    self.set_previous_date, pd.year, pd.month, pd.day
                ).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

    def show_example_custom_bottom_sheet(
        self, type, corner=None, animation=True
    ):
        """Show menu from the screen BottomSheet."""

        from kivymd.uix.bottomsheet import MDCustomBottomSheet

        if type == "custom":
            custom_screen_for_bottom_sheet = self.data["Popup Screen"]["object"]
        elif type == "list":
            custom_screen_for_bottom_sheet = (
                BoxContentForBottomSheetCustomScreenList()
            )

        MDCustomBottomSheet(
            screen=custom_screen_for_bottom_sheet,
            bg_color=[0.2, 0.2, 0.2, 1],
            animation=animation,
            radius_from=corner,
        ).open()

    def show_example_bottom_sheet(self):
        from kivymd.uix.bottomsheet import MDListBottomSheet

        bs_menu_1 = MDListBottomSheet()
        bs_menu_1.add_item(
            "Here's an item with text only",
            lambda x: self.callback_for_menu_items(
                "Here's an item with text only"
            ),
        )
        bs_menu_1.add_item(
            "Here's an item with an icon",
            lambda x: self.callback_for_menu_items(
                "Here's an item with an icon"
            ),
            icon="clipboard-account",
        )
        bs_menu_1.add_item(
            "Here's another!",
            lambda x: self.callback_for_menu_items("Here's another!"),
            icon="nfc",
        )
        bs_menu_1.open()

    def show_example_grid_bottom_sheet(self):
        from kivymd.uix.bottomsheet import MDGridBottomSheet

        bs_menu = MDGridBottomSheet()
        bs_menu.add_item(
            "Facebook",
            lambda x: self.callback_for_menu_items("Facebook"),
            icon_src=f"{os.environ['KITCHEN_SINK_ASSETS']}facebook-box.png",
        )
        bs_menu.add_item(
            "YouTube",
            lambda x: self.callback_for_menu_items("YouTube"),
            icon_src=f"{os.environ['KITCHEN_SINK_ASSETS']}youtube-play.png",
        )
        bs_menu.add_item(
            "Twitter",
            lambda x: self.callback_for_menu_items("Twitter"),
            icon_src=f"{os.environ['KITCHEN_SINK_ASSETS']}twitter.png",
        )
        bs_menu.add_item(
            "Da Cloud",
            lambda x: self.callback_for_menu_items("Da Cloud"),
            icon_src=f"{os.environ['KITCHEN_SINK_ASSETS']}cloud-upload.png",
        )
        bs_menu.add_item(
            "Camera",
            lambda x: self.callback_for_menu_items("Camera"),
            icon_src=f"{os.environ['KITCHEN_SINK_ASSETS']}camera.png",
        )
        bs_menu.open()

    def set_title_toolbar(self, title):
        """Set string title in MDToolbar for the whole application."""

        self.root.ids.toolbar.title = title

    def callback_for_bottom_app_bar(self, text, value):
        if value and self.data["Bottom App Bar"]["object"]:
            toolbar = self.data["Bottom App Bar"]["object"].ids.bottom_toolbar
            if text == "Off":
                toolbar.remove_notch()
            elif text == "On":
                toolbar.set_notch()
            elif text == "Attached - End":
                toolbar.mode = "end"
            elif text == "Attached - Center":
                toolbar.mode = "center"
            elif text == "Free - End":
                toolbar.mode = "free-end"
            elif text == "Free - Center":
                toolbar.mode = "free-center"

    def show_password(self, field, button):
        """
        Called when you press the right button in the password field
        for the screen TextFields.

        instance_field: kivy.uix.textinput.TextInput;
        instance_button: kivymd.button.MDIconButton;

        """

        # Show or hide text of password, set focus field
        # and set icon of right button.
        field.password = not field.password
        field.focus = True
        button.icon = "eye" if button.icon == "eye-off" else "eye-off"

    def set_error_message(self, *args):
        """Checks text of TextField with type "on_error"
        for the screen TextFields."""

        text_field_error = args[0]
        if len(text_field_error.text) == 2:
            text_field_error.error = True
        else:
            text_field_error.error = False

    def set_list_md_icons(self, text="", search=False):
        """Builds a list of icons for the screen MDIcons."""

        def add_icon_item(name_icon):
            self.root.ids.scr_mngr.get_screen("md icons").ids.rv.data.append(
                {
                    "viewclass": "MDIconItemForMdIconsList",
                    "icon": name_icon,
                    "text": name_icon,
                    "callback": self.callback_for_menu_items,
                }
            )

        self.root.ids.scr_mngr.get_screen("md icons").ids.rv.data = []
        for name_icon in md_icons.keys():
            if search:
                if text in name_icon:
                    add_icon_item(name_icon)
            else:
                add_icon_item(name_icon)

    def set_source_code_file(self):
        """Assigns the file_source_code attribute the file name
        with example code for the current screen."""

        if self.root.ids.scr_mngr.current == "code viewer":
            return

        has_screen = False
        for name_item_drawer in self.data.keys():
            if (
                self.data[name_item_drawer]["name_screen"]
                == self.root.ids.scr_mngr.current
            ):
                self.file_source_code = self.data[name_item_drawer].get(
                    "source_code", None
                )
                has_screen = True
                break
        if not has_screen:
            self.file_source_code = None

    def open_context_menu_source_code(self, instance):
        def callback_context_menu(icon):
            context_menu.dismiss()

            if not self.file_source_code:
                from kivymd.uix.snackbar import Snackbar

                Snackbar(text="No source code for this example").show()
                return
            elif icon == "source-repository":
                if platform in ("win", "linux", "macosx"):
                    webbrowser.open(
                        f"https://github.com/HeaTTheatR/KivyMD/wiki/"
                        f"{os.path.splitext(self.file_source_code)[0]}"
                    )
            elif icon == "language-python":
                self.root.ids.scr_mngr.current = "code viewer"
                try:
                    self.data["Source code"][
                        "object"
                    ].ids.code_input.text = open(
                        f"{os.environ['KITCHEN_SINK_ASSETS']}md/{self.file_source_code}",
                        "rt",
                        encoding="utf-8",
                    ).read()
                except FileNotFoundError:
                    from kivymd.uix.snackbar import Snackbar

                    Snackbar(text="Cannot load source code").show()

        menu_for_context_menu_source_code = []
        data = {
            "Source code": "language-python",
            "Open in Wiki": "source-repository",
        }
        if self.root.ids.scr_mngr.current == "code viewer":
            data = {"Open in Wiki": "source-repository"}
        for name_item in data.keys():
            menu_for_context_menu_source_code.append(
                {
                    "viewclass": "MDIconItemForMdIconsList",
                    "text": name_item,
                    "icon": data[name_item],
                    "text_color": [1, 1, 1, 1],
                    "callback": lambda x=name_item: callback_context_menu(x),
                }
            )
        context_menu = MDDropdownMenu(
            items=menu_for_context_menu_source_code,
            max_height=dp(260),
            width_mult=4,
            width_rectangle=0.1,
            background_color=self.theme_cls.primary_dark,
        )
        context_menu.open(instance.ids.right_actions.children[0])
Пример #7
0
    def daftar(self, nama, email, no_hp, password_field_daftar,
               password_field_daftar_ulangpassword, drop_pertanyaan,
               isi_jawaban):
        if nama == '':
            Snackbar(text="Mohon Isi Nama Anda").show()
        elif email == '':
            Snackbar(text="Mohon Isi Email Anda").show()
        elif no_hp == '':
            Snackbar(text="Mohon Isi No Hp Anda").show()
        elif password_field_daftar == '':
            Snackbar(text="Mohon Isi Password Anda").show()
        elif password_field_daftar_ulangpassword == '':
            Snackbar(text="Mohon Ulangi Password Anda").show()
        elif len(password_field_daftar) <= 6:
            Snackbar(text="Password Terlalu pendek").show()
        elif password_field_daftar != password_field_daftar_ulangpassword:
            Snackbar(text="Password Tidak sama mohon cek kembali password anda"
                     ).show()
        elif drop_pertanyaan == 'Pertanyaan Keamanan Anda':
            Snackbar(text="Mohon Pilih Pertanyaan Keamanan Anda").show()
        elif isi_jawaban == '':
            Snackbar(text="Mohon isi jawaban anda").show()
        else:
            data = {
                'nama': "%s" % nama,
                'email': "%s" % email,
                'no_hp': "%s" % no_hp,
                'password_field_daftar': "%s" % password_field_daftar,
                'drop_pertanyaan': "%s" % drop_pertanyaan,
                'isi_jawaban': "%s" % isi_jawaban
            }
            try:
                auth.create_user_with_email_and_password(
                    email, password_field_daftar)
                email = email.replace('.', '_')
                db.child(email).set(data)
                Snackbar(
                    text="Berhasil Mendaftar, Silahkan Masuk kembali").show()
                self.keluar()
            except:
                Snackbar(
                    text=
                    "Form Pendaftaran tidak valid, mohon lengkapi kolom dan coba lagi"
                ).show()

        print(nama, email, no_hp, password_field_daftar,
              password_field_daftar_ulangpassword, drop_pertanyaan,
              isi_jawaban)
Пример #8
0
 def view(self):
     if self.url != '':
         webbrowser.open(self.url)
     if self.url == '':
         Snackbar(text='Url is not available').show()
Пример #9
0
 def watch(self):
     if self.youtube != '':
         webbrowser.open(self.youtube)
     if self.youtube == '':
         Snackbar(text='Url is not available').show()
Пример #10
0
 def error(self, urlrequest):
     print("error")
     Snackbar(text='Url is not available').show()
Пример #11
0
 def failure(self, urlrequest):
     print("failure")
     Snackbar(text='Url is not available').show()
Пример #12
0
 def version(self):
     Snackbar(text='python version == 3.7').show()
Пример #13
0
    def show_example_snackbar(self, snack_type):
        """Create and show instance Snackbar."""

        def callback(instance):

            toast(instance.text)

        def wait_interval(interval):
            self._interval += interval
            if self._interval > self.snackbar.duration + 0.5:
                anim = Animation(y=dp(10), d=0.2)
                anim.start(self.ids.button)
                Clock.unschedule(wait_interval)
                self._interval = 0
                self.snackbar = None

        from kivymd.uix.snackbar import Snackbar

        if snack_type == "simple":
            Snackbar(text="This is a snackbar!").open()
        elif snack_type == "button":
            snack = Snackbar(text="This is a snackbar")
            snack.buttons = [
                MDFlatButton(
                    text="WITH A BUTTON",
                    text_color=(1, 1, 1, 1),
                    on_release=callback,
                )
            ]
            snack.open()
        elif snack_type == "left":
            Snackbar(
                text="Snackbar coming from the left!",
                snackbar_animation_dir="Left",
                size_hint_x=0.9,
            ).open()
        elif snack_type == "xy":
            snack = Snackbar(
                text="This is a snackbar!", snackbar_x="20dp", snackbar_y="20dp"
            )
            snack.size_hint_x = (
                Window.width - (snack.snackbar_x * 2)
            ) / Window.width
            snack.buttons = [
                MDFlatButton(
                    text="ACTION",
                    text_color=(1, 1, 1, 1),
                    on_release=callback,
                )
            ]
            snack.open()
        elif snack_type == "top":
            snack = Snackbar(
                text="This is a snackbar from the top!",
                snackbar_animation_dir="Top",
            )
            snack.buttons = [
                MDFlatButton(
                    text="ACTION",
                    text_color=(1, 1, 1, 1),
                    on_release=callback,
                )
            ]
            snack.open()
        elif snack_type == "float":
            if not self.snackbar:
                self.snackbar = Snackbar(
                    text="This is a snackbar!",
                    duration=3,
                )
                self.snackbar.buttons = [
                    MDFlatButton(
                        text="ACTION",
                        text_color=(1, 1, 1, 1),
                        on_release=callback,
                    )
                ]
                self.snackbar.open()
                anim = Animation(y=dp(72), d=0.2)
                anim.bind(
                    on_complete=lambda *args: Clock.schedule_interval(
                        wait_interval, 0
                    )
                )
                anim.start(self.ids.button)
Пример #14
0
    def reload(self):
        try:
            students = api.students()
        except Exception as e:
            Snackbar(
                text=f"You seem to be offline, trying again in 10 seconds.",
                snackbar_x="10dp",
                snackbar_y="10dp",
                size_hint_x=.5).open()
            print(str(e))
            Clock.schedule_once(lambda *args: self.reload(), 10)
            return
        try:
            attendance = api.attendance()
        except Exception as e:
            Snackbar(
                text=f"You seem to be offline, trying again in 10 seconds.",
                snackbar_x="10dp",
                snackbar_y="10dp",
                size_hint_x=.5).open()
            print(str(e))
            Clock.schedule_once(lambda *args: self.reload(), 10)
            return

        self.attendance.clear_widgets()

        self.today_att = AttendanceContent()
        self.yesterday_att = AttendanceContent()

        std = MDExpansionPanel(content=self.today_att,
                               panel_cls=MDExpansionPanelOneLine(text="Today"))
        self.attendance.add_widget(std)
        std = MDExpansionPanel(
            content=self.yesterday_att,
            panel_cls=MDExpansionPanelOneLine(text="Yesterday"))
        self.attendance.add_widget(std)

        today = datetime.today()
        today_ = today.strftime('%Y-%m-%d')
        yesterday = (today - timedelta(days=1)).strftime('%Y-%m-%d')
        for student in students:
            if student['status'] == 'inactive':
                continue
            try:
                info = next(att for att in attendance
                            if att['student_id'] == student['id']
                            and att['date'] == today_)
            except StopIteration:
                info = {
                    'student_id': student['id'],
                    'date': today_,
                    'status': ''
                }

            att = Attendance(student_name=student['student_name'],
                             group='today' + student['id'],
                             state=info['status'],
                             student_id=info['student_id'],
                             date=today_)
            self.today_att.add_widget(att)

            has_yesterday = any(att['status'] for att in attendance
                                if att['student_id'] == student['id']
                                and att['date'] == yesterday)
            if not has_yesterday:
                att = Attendance(student_name=student['student_name'],
                                 group='yesterday' + student['id'],
                                 student_id=student['id'],
                                 date=yesterday)
                self.yesterday_att.add_widget(att)
Пример #15
0
class KitchenSink(App, Screens):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = "BlueGray"
    theme_cls.accent_palette = "Gray"
    previous_date = ObjectProperty()
    title = "Kitchen Sink"
    theme_cls.theme_style = "Dark"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.menu_items = [{
            "viewclass": "MDMenuItem",
            "text": "Example item %d" % i,
            "callback": self.callback_for_menu_items,
        } for i in range(15)]
        self.Window = Window
        self.manager = None
        self.md_app_bar = None
        self.instance_menu_demo_apps = None
        self.md_theme_picker = None
        self.long_dialog = None
        self.input_dialog = None
        self.alert_dialog = None
        self.ok_cancel_dialog = None
        self.long_dialog = None
        self.dialog = None
        self.manager_open = False
        self.cards_created = False
        self.user_card = None
        self.bs_menu_1 = None
        self.popup_screen = None
        self.my_snackbar = None
        self.dialog_load_kv_files = None
        self._interval = 0
        self.tick = 0
        self.x = 0
        self.y = 25
        self.create_stack_floating_buttons = False
        self.hex_primary_color = get_hex_from_color(
            self.theme_cls.primary_color)
        self.previous_text = (
            f"Welcome to the application [b][color={self.hex_primary_color}]"
            f"Kitchen Sink[/color][/b].\nTo see [b]"
            f"[color={self.hex_primary_color}]KivyMD[/color][/b] "
            f"examples, open the menu and select from the list the desired "
            f"example or")
        self.previous_text_end = (
            f"for show example apps\n\n"
            f"Author - [b][color={self.hex_primary_color}]"
            f"Andrés Rodríguez[/color][/b]\n"
            f"[u][b][color={self.hex_primary_color}]"
            f"[email protected][/color][/b][/u]\n\n"
            f"Author this Fork - [b][color={self.hex_primary_color}]"
            f"Ivanov Yuri[/color][/b]\n"
            f"[u][b][color={self.hex_primary_color}]"
            f"[email protected][/color][/b][u]")
        self.names_contacts = (
            "Alexandr Taylor",
            "Yuri Ivanov",
            "Robert Patric",
            "Bob Marley",
            "Magnus Carlsen",
            "Jon Romero",
            "Anna Bell",
            "Maxim Kramerer",
            "Sasha Gray",
            "Vladimir Ivanenko",
        )
        self.demo_apps_list = [
            "Shop Window",
            "Coffee Menu",
            "Fitness Club",
            "Registration",
            "Account Page",
        ]
        self.menu_for_demo_apps = []
        self.list_name_icons = list(md_icons.keys())[0:15]
        Window.bind(on_keyboard=self.events)
        crop_image(
            (Window.width, int(dp(Window.height * 35 // 100))),
            f"{demos_assets_path}guitar-1139397_1280.png",
            f"{demos_assets_path}guitar-1139397_1280_crop.png",
        )

    def set_list_for_refresh_layout(self):
        async def set_list_for_refresh_layout():
            names_icons_list = list(md_icons.keys())[self.x:self.y]
            for name_icon in names_icons_list:
                await asynckivy.sleep(0)
                self.data["Refresh Layout"]["object"].ids.box.add_widget(
                    ItemForListRefreshLayout(icon=name_icon, text=name_icon))
            self.data["Refresh Layout"][
                "object"].ids.refresh_layout.refresh_done()

        asynckivy.start(set_list_for_refresh_layout())

    def refresh_callback(self, *args):
        """A method that updates the state of your application
        while the spinner remains on the screen."""
        def refresh_callback(interval):
            self.data["Refresh Layout"]["object"].ids.box.clear_widgets()
            if self.x == 0:
                self.x, self.y = 25, 50
            else:
                self.x, self.y = 0, 25
            self.set_list_for_refresh_layout()
            self.tick = 0

        Clock.schedule_once(refresh_callback, 1)

    def build_tabs(self):
        for name_tab in self.list_name_icons:
            tab = Factory.MyTab(text=name_tab)
            self.data["Tabs"]["object"].ids.android_tabs.add_widget(tab)

    def switch_tabs_to_icon(self, istance_android_tabs):
        for i, instance_tab in enumerate(
                istance_android_tabs.ids.scrollview.children[0].children):
            istance_android_tabs.ids.scrollview.children[0].remove_widget(
                instance_tab)
            istance_android_tabs.add_widget(
                Factory.MyTab(text=self.list_name_icons[i]))

    def switch_tabs_to_text(self, istance_android_tabs):
        for instance_tab in istance_android_tabs.ids.scrollview.children[
                0].children:
            for k, v in md_icons.items():
                if v == instance_tab.text:
                    istance_android_tabs.ids.scrollview.children[
                        0].remove_widget(instance_tab)
                    istance_android_tabs.add_widget(
                        Factory.MyTab(
                            text=" ".join(k.split("-")).capitalize()))
                    break

    def crop_image_for_tile(self, instance, size, path_to_crop_image):
        """Crop images for Grid screen."""

        if not os.path.exists(os.path.join(self.directory,
                                           path_to_crop_image)):
            size = (int(size[0]), int(size[1]))
            path_to_origin_image = path_to_crop_image.replace("_tile_crop", "")
            crop_image(size, path_to_origin_image, path_to_crop_image)
        instance.source = path_to_crop_image

    def theme_picker_open(self):
        if not self.md_theme_picker:
            from kivymd.uix.picker import MDThemePicker

            self.md_theme_picker = MDThemePicker()
        self.md_theme_picker.open()

    def example_add_stack_floating_buttons(self):
        from kivymd.uix.stackfloatingbutton import MDStackFloatingButtons

        def set_my_language(instance_button):
            toast(instance_button.icon)

        if not self.create_stack_floating_buttons:
            screen = self.main_widget.ids.scr_mngr.get_screen("stack buttons")
            screen.add_widget(
                MDStackFloatingButtons(
                    icon="lead-pencil",
                    floating_data={
                        "Python": "language-python",
                        "Php": "language-php",
                        "C++": "language-cpp",
                    },
                    callback=set_my_language,
                ))
            self.create_stack_floating_buttons = True

    def set_expansion_panel(self):
        from kivymd.uix.expansionpanel import MDExpansionPanel

        def callback(text):
            toast(f"{text} to {content.name_item}")

        content = ContentForAnimCard(callback=callback)

        for name_contact in self.names_contacts:
            self.data["Expansion Panel"]["object"].ids.anim_list.add_widget(
                MDExpansionPanel(
                    content=content,
                    icon="assets/kivy-logo-white-512.png",
                    title=name_contact,
                ))

    def set_chevron_back_screen(self):
        """Sets the return chevron to the previous screen in ToolBar."""

        self.main_widget.ids.toolbar.right_action_items = [[
            "dots-vertical", lambda x: self.root.toggle_nav_drawer()
        ]]

    def download_progress_hide(self, instance_progress, value):
        """Hides progress progress."""

        self.main_widget.ids.toolbar.right_action_items = [[
            "download",
            lambda x: self.download_progress_show(instance_progress)
        ]]

    def download_progress_show(self, instance_progress):
        self.set_chevron_back_screen()
        instance_progress.open()
        instance_progress.animation_progress_from_fade()

    def show_example_download_file(self, interval):
        from kivymd.uix.progressloader import MDProgressLoader

        def get_connect(host="8.8.8.8", port=53, timeout=3):
            import socket

            try:
                socket.setdefaulttimeout(timeout)
                socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(
                    (host, port))
                return True
            except (TimeoutError, ConnectionError, OSError):
                return False

        if get_connect():
            link = ("https://www.python.org/ftp/python/3.5.1/"
                    "python-3.5.1-embed-win32.zip")
            progress = MDProgressLoader(
                url_on_image=link,
                path_to_file=os.path.join(self.directory, "python-3.5.1.zip"),
                download_complete=self.download_complete,
                download_hide=self.download_progress_hide,
            )
            progress.start(self.data["Download File"]["object"].ids.box_flt)
        else:
            toast("Connect error!")

    def download_complete(self):
        self.set_chevron_back_screen()
        toast("Done")

    def file_manager_open(self):
        from kivymd.uix.filemanager import MDFileManager
        from kivymd.uix.dialog import MDDialog

        def open_file_manager(text_item, dialog):
            previous = False if text_item == "List" else True
            self.manager = ModalView(size_hint=(1, 1), auto_dismiss=False)
            self.file_manager = MDFileManager(
                exit_manager=self.exit_manager,
                select_path=self.select_path,
                previous=previous,
            )
            self.manager.add_widget(self.file_manager)
            self.file_manager.show(self.user_data_dir)
            self.manager_open = True
            self.manager.open()

        MDDialog(
            title="Title",
            size_hint=(0.8, 0.4),
            text_button_ok="List",
            text="Open manager with 'list' or 'previous' mode?",
            text_button_cancel="Previous",
            events_callback=open_file_manager,
        ).open()

    def select_path(self, path):
        """It will be called when you click on the file name
        or the catalog selection button.
        :type path: str;
        :param path: path to the selected directory or file;
        """

        self.exit_manager()
        toast(path)

    def exit_manager(self, *args):
        """Called when the user reaches the root of the directory tree."""

        self.manager.dismiss()
        self.manager_open = False
        self.set_chevron_menu()

    def set_chevron_menu(self):
        self.main_widget.ids.toolbar.left_action_items = [[
            "menu", lambda x: self.root.toggle_nav_drawer()
        ]]

    def events(self, instance, keyboard, keycode, text, modifiers):
        """Called when buttons are pressed on the mobile device."""

        if keyboard in (1001, 27):
            if self.manager_open:
                self.file_manager.back()
        return True

    def callback_for_menu_items(self, *args):
        toast(args[0])

    def add_cards(self, instance_grid_card):
        """Adds MDCardPost objects to the screen Cards
        when the screen is open."""

        from kivymd.uix.card import MDCardPost

        def callback(instance, value):
            if value is None:
                toast("Delete post %s" % str(instance))
            elif isinstance(value, int):
                toast("Set like in %d stars" % value)
            elif isinstance(value, str):
                toast("Repost with %s " % value)
            elif isinstance(value, list):
                toast(value[1])

        if not self.cards_created:
            self.cards_created = True
            menu_items = [{
                "viewclass": "MDMenuItem",
                "text": "Example item %d" % i,
                "callback": self.callback_for_menu_items,
            } for i in range(2)]
            buttons = ["facebook", "vk", "twitter"]

            instance_grid_card.add_widget(
                MDCardPost(text_post="Card with text",
                           swipe=True,
                           callback=callback))
            instance_grid_card.add_widget(
                MDCardPost(
                    right_menu=menu_items,
                    swipe=True,
                    text_post="Card with a button to open the menu MDDropDown",
                    callback=callback,
                ))
            instance_grid_card.add_widget(
                MDCardPost(
                    likes_stars=True,
                    callback=callback,
                    swipe=True,
                    text_post="Card with asterisks for voting.",
                ))

            image_for_card = f"{demos_assets_path}kitten-for_card-1049129_1280-crop.png"
            if not os.path.exists(image_for_card):
                crop_image(
                    (int(Window.width), int(dp(200))),
                    f"{demos_assets_path}kitten-1049129_1280.png",
                    image_for_card,
                )
            instance_grid_card.add_widget(
                MDCardPost(
                    source=image_for_card,
                    tile_text="Little Baby",
                    tile_font_style="H5",
                    text_post="This is my favorite cat. He's only six months "
                    "old. He loves milk and steals sausages :) "
                    "And he likes to play in the garden.",
                    with_image=True,
                    swipe=True,
                    callback=callback,
                    buttons=buttons,
                ))

    def update_screen(self, instance):
        """Set new label on the screen UpdateSpinner."""
        def update_screen(interval):
            self.tick += 1
            if self.tick > 2:
                instance.update = True
                self.tick = 0
                self.data["Update Screen Widget"][
                    "object"].ids.upd_lbl.text = "New string"
                Clock.unschedule(update_screen)

        Clock.schedule_interval(update_screen, 1)

    main_widget = None

    def build(self):
        self.main_widget = Builder.load_string(main_widget_kv)
        return self.main_widget

    def show_popup_screen(self):
        if not self.popup_screen:
            self.popup_screen = self.data["Popup Screen"]["object"].ids.popup
            content_screen = ContentForPopupScreen()
            self.popup_screen.screen = content_screen
            self.popup_screen.padding = dp(10)
            self.popup_screen.background_color = self.theme_cls.primary_color
        self.popup_screen.show()

    def show_user_example_animation_card(self):
        """Create and open instance MDUserAnimationCard
        for the screen UserCard."""

        from kivymd.uix.useranimationcard import MDUserAnimationCard

        def main_back_callback():
            toast("Close card")

        if not self.user_card:
            image_for_user_card = (
                f"{demos_assets_path}guitar-for-user-card1139397_1280-crop.png"
            )
            if not os.path.exists(image_for_user_card):
                crop_image(
                    (int(Window.width), int(dp(Window.height * 40 // 100))),
                    f"{demos_assets_path}guitar-1139397_1280.png",
                    image_for_user_card,
                )

            self.user_card = MDUserAnimationCard(
                user_name="Lion Lion",
                path_to_avatar=image_for_user_card,
                callback=main_back_callback,
            )
            self.user_card.box_content.add_widget(ContentForAnimCard())
        self.user_card.open()

    def show_example_snackbar(self, snack_type):
        """Create and show instance Snackbar for the screen MySnackBar."""
        def callback(instance):
            toast(instance.text)

        def wait_interval(interval):
            self._interval += interval
            if self._interval > self.my_snackbar.duration:
                anim = Animation(y=dp(10), d=0.2)
                anim.start(self.data["Snackbars"]["object"].ids.button)
                Clock.unschedule(wait_interval)
                self._interval = 0
                self.my_snackbar = None

        from kivymd.uix.snackbar import Snackbar

        if snack_type == "simple":
            Snackbar(text="This is a snackbar!").show()
        elif snack_type == "button":
            Snackbar(
                text="This is a snackbar",
                button_text="WITH A BUTTON",
                button_callback=callback,
            ).show()
        elif snack_type == "verylong":
            Snackbar(text="This is a very very very very very very very "
                     "long snackbar!").show()
        elif snack_type == "float":
            if not self.my_snackbar:
                self.my_snackbar = Snackbar(
                    text="This is a snackbar!",
                    button_text="Button",
                    duration=3,
                    button_callback=callback,
                )
                self.my_snackbar.show()
                anim = Animation(y=dp(72), d=0.2)
                anim.bind(on_complete=lambda *args: Clock.schedule_interval(
                    wait_interval, 0))
                anim.start(self.data["Snackbars"]["object"].ids.button)

    def show_example_input_dialog(self):
        """Creates an instance of the dialog box and displays it
        on the screen for the screen Dialogs."""
        def result(text_button, instance):
            toast(instance.text_field.text)

        if not self.input_dialog:
            from kivymd.dialog import MDInputDialog

            self.input_dialog = MDInputDialog(
                title="Title",
                hint_text="Hint text",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                events_callback=result,
            )
        self.input_dialog.open()

    def show_example_alert_dialog(self):
        if not self.alert_dialog:
            from kivymd.uix.dialog import MDDialog

            self.alert_dialog = MDDialog(
                title="Title",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text="This is Alert dialog",
                events_callback=self.callback_for_menu_items,
            )
        self.alert_dialog.open()

    def show_example_ok_cancel_dialog(self):
        if not self.ok_cancel_dialog:
            from kivymd.uix.dialog import MDDialog

            self.ok_cancel_dialog = MDDialog(
                title="Title",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text="This is Ok Cancel dialog",
                text_button_cancel="Cancel",
                events_callback=self.callback_for_menu_items,
            )
        self.ok_cancel_dialog.open()

    def show_example_long_dialog(self):
        if not self.long_dialog:
            from kivymd.uix.dialog import MDDialog

            self.long_dialog = MDDialog(
                text="Lorem ipsum dolor sit amet, consectetur adipiscing "
                "elit, sed do eiusmod tempor incididunt ut labore et "
                "dolore magna aliqua. Ut enim ad minim veniam, quis "
                "nostrud exercitation ullamco laboris nisi ut aliquip "
                "ex ea commodo consequat. Duis aute irure dolor in "
                "reprehenderit in voluptate velit esse cillum dolore eu "
                "fugiat nulla pariatur. Excepteur sint occaecat "
                "cupidatat non proident, sunt in culpa qui officia "
                "deserunt mollit anim id est laborum.",
                title="Title",
                size_hint=(0.8, 0.4),
                text_button_ok="Yes",
                events_callback=self.callback_for_menu_items,
            )
        self.long_dialog.open()

    def get_time_picker_date(self, instance, time):
        """Get date for MDTimePicker from the screen Pickers."""

        self.data["Pickers"]["object"].ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        """Show MDTimePicker from the screen Pickers."""

        from kivymd.uix.picker import MDTimePicker

        time_dialog = MDTimePicker()
        time_dialog.bind(time=self.get_time_picker_date)

        if self.data["Pickers"][
                "object"].ids.time_picker_use_previous_time.active:
            try:
                time_dialog.set_time(self.previous_time)
            except AttributeError:
                pass
        time_dialog.open()

    def set_previous_date(self, date_obj):
        """Set previous date for MDDatePicker from the screen Pickers."""

        self.previous_date = date_obj
        self.data["Pickers"]["object"].ids.date_picker_label.text = str(
            date_obj)

    def show_example_date_picker(self):
        """Show MDDatePicker from the screen Pickers."""

        from kivymd.uix.picker import MDDatePicker

        if self.data["Pickers"][
                "object"].ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

    def show_example_bottom_sheet(self):
        """Show menu from the screen BottomSheet."""

        from kivymd.uix.bottomsheet import MDListBottomSheet

        if not self.bs_menu_1:
            self.bs_menu_1 = MDListBottomSheet()
            self.bs_menu_1.add_item(
                "Here's an item with text only",
                lambda x: self.callback_for_menu_items(
                    "Here's an item with text only"),
            )
            self.bs_menu_1.add_item(
                "Here's an item with an icon",
                lambda x: self.callback_for_menu_items(
                    "Here's an item with an icon"),
                icon="clipboard-account",
            )
            self.bs_menu_1.add_item(
                "Here's another!",
                lambda x: self.callback_for_menu_items("Here's another!"),
                icon="nfc",
            )
        self.bs_menu_1.open()

    def show_example_grid_bottom_sheet(self):
        """Show menu from the screen BottomSheet."""

        if not self.bs_menu_2:
            from kivymd.uix.bottomsheet import MDGridBottomSheet

            self.bs_menu_2 = MDGridBottomSheet()
            self.bs_menu_2.add_item(
                "Facebook",
                lambda x: self.callback_for_menu_items("Facebook"),
                icon_src="./assets/facebook-box.png",
            )
            self.bs_menu_2.add_item(
                "YouTube",
                lambda x: self.callback_for_menu_items("YouTube"),
                icon_src="./assets/youtube-play.png",
            )
            self.bs_menu_2.add_item(
                "Twitter",
                lambda x: self.callback_for_menu_items("Twitter"),
                icon_src="./assets/twitter.png",
            )
            self.bs_menu_2.add_item(
                "Da Cloud",
                lambda x: self.callback_for_menu_items("Da Cloud"),
                icon_src="./assets/cloud-upload.png",
            )
            self.bs_menu_2.add_item(
                "Camera",
                lambda x: self.callback_for_menu_items("Camera"),
                icon_src="./assets/camera.png",
            )
        self.bs_menu_2.open()

    def set_title_toolbar(self, title):
        """Set string title in MDToolbar for the whole application."""

        self.main_widget.ids.toolbar.title = title

    def set_appbar(self):
        """Create MDBottomAppBar for the screen BottomAppBar."""

        from kivymd.uix.toolbar import MDBottomAppBar

        def press_button(inctance):
            toast("Press Button")

        self.md_app_bar = MDBottomAppBar(
            md_bg_color=self.theme_cls.primary_color,
            left_action_items=[
                ["menu", lambda x: x],
                ["clock", lambda x: x],
                ["dots-vertical", lambda x: x],
            ],
            anchor="right",
            callback=press_button,
        )

    def move_item_menu(self, anchor):
        """Sets icons in MDBottomAppBar for the screen BottomAppBar."""

        md_app_bar = self.md_app_bar
        if md_app_bar.anchor != anchor:
            if len(md_app_bar.right_action_items):
                md_app_bar.left_action_items.append(
                    md_app_bar.right_action_items[0])
                md_app_bar.right_action_items = []
            else:
                left_action_items = md_app_bar.left_action_items
                action_items = left_action_items[0:2]
                md_app_bar.right_action_items = [left_action_items[-1]]
                md_app_bar.left_action_items = action_items

    def show_password(self, field, button):
        """
        Called when you press the right button in the password field
        for the screen TextFields.

        instance_field: kivy.uix.textinput.TextInput;
        instance_button: kivymd.button.MDIconButton;

        """

        # Show or hide text of password, set focus field
        # and set icon of right button.
        field.password = not field.password
        field.focus = True
        button.icon = "eye" if button.icon == "eye-off" else "eye-off"

    def set_error_message(self, *args):
        """Checks text of TextField with type "on_error"
        for the screen TextFields."""

        text_field_error = args[0]
        if len(text_field_error.text) == 2:
            text_field_error.error = True
        else:
            text_field_error.error = False

    def set_list_md_icons(self, text="", search=False):
        """Builds a list of icons for the screen MDIcons."""
        def add_icon_item(name_icon):
            self.main_widget.ids.scr_mngr.get_screen(
                "md icons").ids.rv.data.append({
                    "viewclass":
                    "MDIconItemForMdIconsList",
                    "icon":
                    name_icon,
                    "text":
                    name_icon,
                    "callback":
                    self.callback_for_menu_items,
                })

        self.main_widget.ids.scr_mngr.get_screen("md icons").ids.rv.data = []
        for name_icon in md_icons.keys():
            if search:
                if text in name_icon:
                    add_icon_item(name_icon)
            else:
                add_icon_item(name_icon)

    def set_menu_for_demo_apps(self):
        if not len(self.menu_for_demo_apps):
            for name_item in self.demo_apps_list:
                self.menu_for_demo_apps.append({
                    "viewclass":
                    "OneLineListItem",
                    "text":
                    name_item,
                    "on_release":
                    lambda x=name_item: self.show_demo_apps(x),
                })

    def show_demo_apps(self, name_item):
        self.show_screens_demo(name_item)
        self.main_widget.ids.scr_mngr.current = name_item.lower()
        self.instance_menu_demo_apps.dismiss()

    def on_pause(self):
        return True

    def on_start(self):
        def _load_kv_for_demo(name_screen):
            from demo_apps.formone import FormOne
            from demo_apps.shopwindow import ShopWindow
            from demo_apps.coffeemenu import CoffeeMenu
            from demo_apps.fitnessclub import FitnessClub
            from demo_apps.accountpage import AccountPage

            Builder.load_string(self.data_for_demo[name_screen]["kv_string"])
            self.data_for_demo[name_screen]["object"] = eval(
                self.data_for_demo[name_screen]["class"])
            self.main_widget.ids.scr_mngr.add_widget(
                self.data_for_demo[name_screen]["object"])

        async def load_all_kv_files():
            for name_screen in self.data.keys():
                await asynckivy.sleep(0)
                self.dialog_load_kv_files.name_kv_file = name_screen
                Builder.load_string(self.data[name_screen]["kv_string"])
                self.data[name_screen]["object"] = eval(
                    self.data[name_screen]["Factory"])
                if name_screen == "Bottom App Bar":
                    self.set_appbar()
                    self.data[name_screen]["object"].add_widget(
                        self.md_app_bar)
                self.main_widget.ids.scr_mngr.add_widget(
                    self.data[name_screen]["object"])
                if name_screen == "Text fields":
                    self.data[name_screen]["object"].ids.text_field_error.bind(
                        on_text_validate=self.set_error_message,
                        on_focus=self.set_error_message,
                    )
                elif name_screen == "MD Icons":
                    self.set_list_md_icons()
                elif name_screen == "Tabs":
                    self.build_tabs()
                elif name_screen == "Refresh Layout":
                    self.set_list_for_refresh_layout()

            from demo_apps.formone import registration_form_one
            from demo_apps.shopwindow import screen_shop_window
            from demo_apps.coffeemenu import screen_coffee_menu
            from demo_apps.fitnessclub import screen_fitness_club
            from demo_apps.accountpage import screen_account_page

            data = {
                "Registration": registration_form_one,
                "Shop Window": screen_shop_window,
                "Coffee Menu": screen_coffee_menu,
                "Fitness Club": screen_fitness_club,
                "Account Page": screen_account_page,
            }

            for name_screen in data.keys():
                await asynckivy.sleep(0)
                self.dialog_load_kv_files.name_kv_file = name_screen
                self.data_for_demo[name_screen]["kv_string"] = data[
                    name_screen]
                _load_kv_for_demo(name_screen)

            self.dialog_load_kv_files.dismiss()

        self.dialog_load_kv_files = DialogLoadKvFiles()
        self.dialog_load_kv_files.open()
        asynckivy.start(load_all_kv_files())

    def on_stop(self):
        pass

    def open_settings(self, *args):
        return False
Пример #16
0
 def view(self):
     if self.MealSource != '':
         webbrowser.open_new(self.MealSource)
     else:
         Snackbar(text='Source is not available').show()
Пример #17
0
def alert(text, **kwargs):
    Snackbar(text=text, **kwargs).open()
Пример #18
0
 def deleteOrder(self):
     cursor = db.cursor()
     cursor.execute("update orderDetailsTimeTable set orderStatus = 2 where ordernum = %s", (selected_orderNum_to_see,))
     db.commit()
     Snackbar(text="Order cancelled").show()
     MDApp.get_running_app().root.ids.master.current = 'hotel'
Пример #19
0
    def on_enter(self, *args):
        dbs = db.child(self.temp_email).child("data").get()
        grid = self.ids['grid_banner']
        grid.clear_widgets()
        loading = self.ids['loading']
        try:
            for self.i in dbs.each():
                # ~~~~~~~ Banner ~~~~~~~~
                card = MDCard(size_hint=(.9, .5))
                layout = FloatLayout(pos_hint={'center_x': .5, 'center_y': .5})
                card.add_widget(layout)

                # ~~~~~~~ ID Data ~~~~~~~~
                ids = self.i.val()['ids']
                dataid = MDRaisedButton(text=f'{ids}',
                                        pos_hint={
                                            'center_x': .28,
                                            'top': 1
                                        })
                layout.add_widget(dataid)

                # ~~~~~~~ Nama Data ~~~~~~~~
                nama = self.i.val()['nama']
                datanama = MDLabel(text=nama,
                                   font_style='H6',
                                   halign='left',
                                   pos_hint={
                                       'center_x': .55,
                                       'center_y': .8
                                   })
                layout.add_widget(datanama)

                # ~~~~~~~ Keterangan Data ~~~~~~~~
                keterangan = self.i.val()['keterangan']
                dataket = MDLabel(text=keterangan,
                                  font_style='Body1',
                                  halign='left',
                                  size_hint=(.8, .3),
                                  pos_hint={
                                      'center_x': .47,
                                      'center_y': .5
                                  })
                bgket = MDRectangleFlatButton(size_hint=(.9, .45),
                                              pos_hint={
                                                  'center_x': .5,
                                                  'top': .7
                                              },
                                              disabled=True)
                layout.add_widget(bgket)
                layout.add_widget(dataket)

                # ~~~~~~~ Keluar atau Masuk ~~~~~~~~
                io = self.i.val()['io']
                dataio = MDLabel(text=io,
                                 font_style='Button',
                                 halign='right',
                                 pos_hint={
                                     'center_x': .45,
                                     'top': .65
                                 })
                layout.add_widget(dataio)

                # ~~~~~~~ Jenis Data ~~~~~~~~
                jenis = self.i.val()['jenis']
                datajenis = MDLabel(text=jenis,
                                    font_style='Button',
                                    halign='left',
                                    pos_hint={
                                        'center_x': .55,
                                        'top': .65
                                    })
                layout.add_widget(datajenis)

                # ~~~~~~~ tgl Data ~~~~~~~~
                tgl = self.i.val()['tgl']
                datatgl = MDLabel(text=tgl,
                                  font_style='Button',
                                  halign='right',
                                  pos_hint={
                                      'center_x': .45,
                                      'center_y': .8
                                  })
                layout.add_widget(datatgl)

                # ~~~~~~~ Jumlah Uang ~~~~~~~~
                jumlah = self.i.val()['jumlah']
                matauang = self.i.val()['mata_uang']
                datajumlah = MDLabel(text=matauang + ' ' + jumlah + '',
                                     font_style='Button',
                                     halign='right',
                                     pos_hint={
                                         'center_x': .45,
                                         'top': .55
                                     })
                layout.add_widget(datajumlah)

                # ~~~~~~~ Button Delete ~~~~~~~~
                hapus = Hapus(id=f'{ids}',
                              text='Hapus',
                              on_release=self.delete)

                clear = MDRaisedButton(text='Tutup')

                delete_dialog = MDDialog(title='Apakah Anda Yakin ?',
                                         size_hint=(0.95, 1),
                                         buttons=[hapus, clear])

                hapus.bind(on_release=delete_dialog.dismiss)

                delete = MDIconButton(icon='trash-can',
                                      pos_hint={
                                          'center_x': .9,
                                          'top': 1
                                      },
                                      on_release=delete_dialog.open)

                clear.bind(on_release=delete_dialog.dismiss)

                layout.add_widget(delete)

                # ~~~~~~~ Button Delete ~~~~~~~~
                # edit_menu = print('Teredit')
                edit = Edit(id=f'{ids}',
                            icon='pencil',
                            pos_hint={
                                'center_x': .8,
                                'top': 1
                            },
                            on_release=self.edited)

                layout.add_widget(edit)

                grid.add_widget(card)

            loading.active = False
        except:
            Snackbar(text="Data Kosong").show()
            loading.active = False
Пример #20
0
class AddResourcesWindow(Screen):
    def load_page(self):
        ContentNavigationDrawer.populateNavDrawerValues(self)
        self.rsrcmenu = MDDropdownMenu(caller=self.ids['name'],
                                       width_mult=5,
                                       callback=self.set_item,
                                       position="center")
        items = [
            "Medicine", "Biscuit", "Salt", "Tarpaulin", "Rice", "Daal",
            "Baby Food", "Sugar"
        ]
        for i in items:
            self.rsrcmenu.items.append({"text": str(i)})

    def create_resource(self, name, desc, units, amount):
        rname = name.current_item
        rdesc = desc.text
        runits = units.text
        ramount = amount.text
        valid_str = ""
        if rname == "":
            valid_str = "Select an Item"
        elif runits == "":
            valid_str = "Units is blank"
        elif ramount == "":
            valid_str = "Cost is blank"
        elif int(ramount) > globalvariables.var_bal_amt:
            valid_str = "Insufficient funds"
        if valid_str != "":
            ok_button = MDFlatButton(text='OK', on_release=self.dialog_close)
            self.dialog = MDDialog(title='Alert !',
                                   text=valid_str,
                                   size_hint=(0.7, 1),
                                   buttons=[ok_button])
            self.dialog.open()
        else:
            query1 = f'''INSERT INTO RESOURCES(CONTACT_ID, ACTIVITY_ID, NAME, DESC, UNITS, AMOUNT, DATE) 
            VALUES ({globalvariables.var_userid}, {globalvariables.var_act_id}, '{rname}', '{rdesc}', {runits},
            {ramount}, SYSDATE)'''
            # run direct SQL
            stmt = ibm_db.exec_immediate(connection.conn, query1)
            globalvariables.var_bal_amt = globalvariables.var_bal_amt - int(
                ramount)
            if ibm_db.num_rows(stmt) > 0:
                #self.ids['name'].text=""
                self.ids['desc'].text = ""
                self.ids['units'].text = ""
                self.ids['amount'].text = ""
                self.snackbar = Snackbar(text="Item Added!")
                self.snackbar.show()

    def dialog_close(self, obj):
        self.dialog.dismiss()

    def set_item(self, instance):
        self.ids['name'].set_item(instance.text)
        self.rsrcmenu.dismiss()

    def cancel_resource_creation(self):
        self.manager.transition.direction = 'right'
        self.manager.current = 'activity_detail_window'
        self.manager.get_screen('activity_detail_window').load_page()
Пример #21
0
    def login(self, *args):
        
        if self.ids.email.text != '' and self.ids.password.text != '':

            global localID, isLoggedIn, userdata

            import pyrebase
            import requests, json
            from screens import fbconfig
        
            firebaseConfig = fbconfig.users_firebaseConfig
            firebase = pyrebase.initialize_app(firebaseConfig)
            auth = firebase.auth()

            try:
                user = auth.sign_in_with_email_and_password(self.ids.email.text, self.ids.password.text)
                #print(user)
                print(user['localId'])
                localID = user['localId']
                Snackbar(text="Logged in successfully!").open()
                isLoggedIn = 1
                import base64

                message = self.ids.email.text + "+" + str(self.ids.password.text)
                message = message.encode('ascii')
                message = base64.b64encode(message)
                message = message.decode('ascii')
                print(message)

                with open('helper.tn', 'w') as f:
                    f.write(message)
                
                #global userdata, localID

                config = fbconfig.users_firebaseConfig
                firebase = pyrebase.initialize_app(config)
                db = firebase.database()
                userdata = db.child('users/' + localID).get()
                userdata = userdata.val()
                print(userdata)

                self.manager.current = 'input'
            except requests.HTTPError as e:
                #print('args start')
                error_json = e.args[1]
                #print(error_json)
                error = json.loads(error_json)['error']['message']
                #print(error)
                msg = ''
                if error == "INVALID_EMAIL":
                    msg = "Invalid email!"
                elif error == "EMAIL_NOT_FOUND":
                    msg = "Email not found!"
                elif error == 'INVALID_PASSWORD':
                    msg = "Wrong Password!"
                else:
                    msg = "Something's wrong. Check your internet connection."
                
                Snackbar(text=msg).open()
                if os.path.isfile('helper.tn') == True:
                    os.remove('helper.tn')
        else:
            Snackbar(text="Please enter email and password first!").open()
Пример #22
0
 def show_speech_fail_snackbar(self):
     """
     Shows snackbar that indicates the user failed to speak a word.
     """
     snackbar = Snackbar(text="Try Saying The Word Again")
     snackbar.show()
Пример #23
0
        def graphPlot(category, parameter, *args):
            def snk(*args):
                Snackbar(text = "Getting Data...").open()
            Clock.schedule_once(snk, 0.1)
            cat = ''
            para = ''
            if category == 'Interannual':
                cat = "INTERANNUAL"
                url = "https://power.larc.nasa.gov/cgi-bin/v1/DataAccess.py?&request=execute&identifier=SinglePoint&parameters=" + parameter + "&startDate=" + self.ids.fromd.text[:4].replace('-','') + "&endDate=" + self.ids.to.text[:4].replace('-','') +"&userCommunity=AG&tempAverage=" + cat + "&outputList=JSON&lat=" + str(lat) + "&" + "lon=" + str(lon)
            else:
                cat = "DAILY"
                url = "https://power.larc.nasa.gov/cgi-bin/v1/DataAccess.py?&request=execute&identifier=SinglePoint&parameters=" + parameter + "&startDate=" + self.ids.fromd.text.replace('-','') + "&endDate=" + self.ids.to.text.replace('-','') +"&userCommunity=AG&tempAverage=" + cat + "&outputList=JSON&lat=" + str(lat) + "&" + "lon=" + str(lon)

            if parameter == 'T2M_RANGE':
                para = 'Temperature (C)'
            elif parameter == 'RH2M':
                para = 'Moisture (%)'
            else:
                para = 'Wind Speed (m/s)'

            
            print(url)
            try:
                response = requests.get(url)
                print(response)
                data = response.json()

                data = data['features'][0]['properties']['parameter'][parameter]

                dates = []
                values = []

                for key, value in data.items():
                    if category == 'Interannual': 
                        if key[-2:] != '13' and value >= 0:
                            dates.append(key)
                            values.append(value)
                            print(key + " " + str(value))
                    else:
                        dates.append(key)
                        values.append(value)
                        print(key + " " + str(value))

                import matplotlib.pyplot as plt

                plt.figure(figsize=(17,10))        
                plt.plot(dates, values)
                plt.title(para + ' Vs Year')
                plt.xlabel('Year')
                plt.ylabel(para)
                plt.xticks(rotation=90)
                #my_path = os.path.dirname(os.path.realpath(__file__))

                global graphName
                graphName = 'graphs/graph_' + str(int(time.time())) + '.png'
                print(graphName)

                plt.savefig(graphName, bbox_inches='tight')

                #self.manager.current = 'graph'
                def changeScreen(*args):
                    self.manager.current = 'ndata'

                Clock.schedule_once(changeScreen, 1)
                
            except Exception as e:
                try:
                    self.remove_widget(spinner)
                    self.remove_widget(label)
                except:
                    pass
                print("Error")
                print(e)
                self.manager.current = "nasa"
                Snackbar(text="Can't get data from Nasa!").open()
    def exportarPDF(self):  # SE DEBE BUSCAR LA FORMA DE HACERLO GENÉRICO
        """
        import json
        import requests
        headers = {
            "Authorization": "Bearer ya29.a0AfH6SMDhLxJscYf1Cm4vYtjbKSPdHHIeNH3kuelzz6BgQtDk-sobO5Dzw7FwYrGf17vaKIR_qoKChEYXzc9In5lJVoTTAY5yfXdZdFxZdQ6jkZ2lcr2B6N36s5kihOV5xKjZUR5Kdsk39beA0vx7yTisCP3ulOf8fquyUugdXt0"}
        para = {
            "name": "ReporteGastos.pdf",
        }
        files = {
            'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
            'file': open("./ReporteGastos.pdf", "rb")
        }
        r = requests.post(
            "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
            headers=headers,
            files=files
        )
        print(r.text)
        """
        gauth = GoogleAuth()
        # Try to load saved client credentials
        gauth.LoadCredentialsFile("mycreds.txt")
        if gauth.credentials is None:
            # Authenticate if they're not there
            gauth.LocalWebserverAuth()
        elif gauth.access_token_expired:
            # Refresh them if expired
            gauth.Refresh()
        else:
            # Initialize the saved creds
            gauth.Authorize()
        # Save the current credentials to a file
        gauth.SaveCredentialsFile("mycreds.txt")

        drive = GoogleDrive(gauth)

        folderName = "App Inventario"
        # folder = drive.CreateFile({'title' : folderName, 'mimeType' : 'application/vnd.google-apps.folder'})
        # folder.Upload()

        fileList = drive.ListFile({
            'q': "'root' in parents and trashed=false"
        }).GetList()
        contador = 0

        if len(fileList) == 0:  # No hay archivos
            print("No hay ningun archivo, creando el folder")
            folder = drive.CreateFile({
                'title':
                folderName,
                'mimeType':
                'application/vnd.google-apps.folder'
            })
            folder.Upload()
            contador = -1

        for file in fileList:  # haciendo un for para comprobar los archivos
            # print('Title: %s, ID: %s' % (file['title'], file['id']))
            # Get the folder ID that you want
            if file['title'] == folderName:
                print("Existe el folder necesario")
                contador = -1
                break
            elif file['title'] != folderName:
                print("Archivo sin coincidencia")
                print('Title: %s, ID: %s' % (file['title'], file['id']))
                contador = contador + 1

        if contador == len(
                fileList
        ):  # si son iguales significa que no existe carpeta de la App
            print("Se debe crear el archivo")
            folder = drive.CreateFile({
                'title':
                folderName,
                'mimeType':
                'application/vnd.google-apps.folder'
            })
            folder.Upload()

        #-------Parte de actualizar arc

        folderName = "App Inventario"
        folder_id = ''
        # creacion archivo en un folder específico
        # folders = drive.ListFile(
        # {'q': "title='" + folderName + "' and mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList()

        file_list = drive.ListFile({
            'q': "'root' in parents and trashed=false"
        }).GetList()

        for file in file_list:
            if (file['title'] == folderName):
                folder_id = file['id']

                break

        # 3) Build string dynamically (need to use escape characters to support single quote syntax)
        str = "\'" + folder_id + "\'" + " in parents and trashed=false"

        # 4) Starting iterating over files
        file_list = drive.ListFile({'q': str}).GetList()
        for file in file_list:
            print('title: %s, id: %s' % (file['title'], file['id']))
            if file['title'] == "ReporteGastos.pdf":
                file.Delete()
        file2 = drive.CreateFile({'parents': [{'id': folder_id}]})
        file2.SetContentFile('ReporteGastos.pdf')
        file2.Upload()

        # Informar que se ha subido el archivo
        snackbar = Snackbar(
            text="Se ha realizado el respaldo del Reporte en Google Drive")
        snackbar.show()
Пример #25
0
    def post(self, *args):
        global localID, userdata

        def snk(*args):
                Snackbar(text = "Posting...").open()

        #Clock.schedule_once(snk, 2.5)
        #threading.Thread(target = Snackbar(text="Posting...").open())
        #def go(self, *args):
        global localID, userdata, ts
        if len(self.ids.post_txt.text) < 2048 or len(self.ids.post_txt.text) == 0:
            from screens import fbconfig
            import pyrebase
            ts = str(time.time()).replace('.', '-')
            firebaseConfig = fbconfig.posts_firebaseConfig
            firebase = pyrebase.initialize_app(firebaseConfig)
            storage = firebase.storage()
            db = firebase.database()
            
            
            data = {
                'fullname': userdata['fullname'],
                'pic': userdata['pic']
            }
            db.child(localID).update(data)
            
            
            data = {
                'text': self.ids.post_txt.text
            }
            db.child(localID).child(ts).update(data)
                    
            
            files_url_dict = {}
            
            for i, file in enumerate(self.files):
                fname = file.split('.')
                db_file_location = "posts/" + localID + "/" + ts + "/" + str(i) + '.' + fname[len(fname) - 1]
                storage.child(db_file_location).put(file)
                furl = storage.child(db_file_location).get_url(None)
                # files[i] = url
                files_url_dict[i] = furl
            
            #print(files_url_dict)
            db.child(localID).child(ts).update({'approval' : 'waiting'})
            db.child(localID).child(ts).update({'socialLink' : 'not available'})
            db.child(localID).child(ts).child('files').update(files_url_dict)

            # post = {
            #     'text' : self.ids.post_txt.text,
            #     'files' : files_url_dict
            #     }

            posts = db.child("posts").get()
            length = len(posts.val())
            print(posts, length)

            data = {str(length): localID + ", " + ts}
            db.child('posts').update(data)
            
            firebaseConfig = fbconfig.users_firebaseConfig
            firebase = pyrebase.initialize_app(firebaseConfig)
            db = firebase.database()
            

            self.files = []
            #toast("Post will be judged by moderators.")
            if userdata['points'] == 0:
                userdata['points'] += 30
                toast("You've got 30 points for first post!")
            else:
                userdata['points'] += 0
                toast("Points will be given after moderation!")
            
            db.child('users').child(localID).update({'points' : userdata['points']})
            
            userdata = db.child('users/' + localID).get()
            userdata = userdata.val()
            print(userdata)
            
            self.manager.current = 'social'

        else:
            Snackbar(text="No more than 2048 character!").open()
Пример #26
0
 def show_snackbar(self, text):
     Snackbar(text=text).show()
Пример #27
0
 def on_touch_down(self, touch):
     if self.collide_point(*touch.opos):
         Snackbar(text=self.icon_name, duration=1.5).show()
Пример #28
0
 def copy_phone_number(self, _):
     Clipboard.copy(self.info[3])
     Snackbar(text="Copied to Clipboard!").show()
Пример #29
0
 def copy_mode(self):
     self.memorize_text = False
     Snackbar(text="you are in copy mode").show()
Пример #30
0
 def snackbar_show(self, text, duration=8):
     if self.snackbar:
         self.snackbar = None
     self.snackbar = Snackbar(text=text, duration=duration)
     self.snackbar.show()