Пример #1
0
 def launch_alarm_popup(self, instance):
     widget = self.build_alarm_popup()
     title = 'Set ' + self.name
     popup = Popup(title=title, content=widget, size_hint=(0.7, 0.3), 
         pos_hint={'y' : 35.0 / Window.height})
     popup.bind(on_dismiss=self.update_alarm)
     popup.open()
class Root(FloatLayout):
    loadfile = ObjectProperty(None)
    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9))
        self._popup.open()

    def show_save(self):
        content = SaveDialog(save=self.save, cancel=self.dismiss_popup)
        self._popup = Popup(title="Save file", content=content, size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path, filename):
        with open(os.path.join(path, filename[0])) as stream:
            self.text_input.text = stream.read()

        self.dismiss_popup()

    def save(self, path, filename):
        with open(os.path.join(path, filename), 'w') as stream:
            stream.write(self.text_input.text)

        self.dismiss_popup()
Пример #3
0
    def do_branches(self, *args):
        '''Shows a list of git branches and allow to change the current one
        '''
        d = get_designer()
        if d.popup:
            return False
        branches = []
        for b in self.repo.heads:
            branches.append(b.name)

        # create the popup
        fake_setting = FakeSettingList()
        fake_setting.allow_custom = True
        fake_setting.items = branches
        fake_setting.desc = 'Checkout to the selected branch. \n' \
                'You can type a name to create a new branch'
        fake_setting.group = 'git_branch'

        content = SettingListContent(setting=fake_setting)
        popup_width = min(0.95 * Window.width, 500)
        popup_height = min(0.95 * Window.height, 500)
        popup = Popup(
            content=content, title='Git - Branches', size_hint=(None, None),
            size=(popup_width, popup_height), auto_dismiss=False)

        content.bind(on_apply=self._perform_do_branches,
                     on_cancel=d.close_popup)

        content.selected_items = [self.repo.active_branch.name]
        content.show_items()
        d.popup = popup
        popup.open()
 def on_customize(self, *args):
     if self.point:
         content = GeoPointEditor(point=self.point, databus=self.databus)
         popup = Popup(title="Edit Track Target", content=content, size_hint=(None, None), size=(dp(500), dp(220)))
         content.bind(on_close=lambda *args: popup.dismiss())
         content.bind(on_point_edited=self._on_edited)
         popup.open()
Пример #5
0
    def _perform_do_pull(self, instance, remotes, *args):
        '''Try to perform a pull
        '''
        remote = remotes[0]
        remote_repo = self.repo.remotes[remote]
        progress = GitRemoteProgress()

        status = Popup(title='Git pull progress',
                       content=progress.label,
                       size_hint=(None, None),
                       size=(500, 200))
        status.open()

        @ignore_proj_watcher
        def pull(*args):
            '''Do a pull in a separated thread
            '''
            try:
                remote_repo.pull(progress=progress)

                def set_progress_done(*args):
                    progress.label.text = 'Completed!'

                Clock.schedule_once(set_progress_done, 1)
                progress.stop()
                show_message('Git remote pull completed!', 5)
            except GitCommandError as e:
                progress.label.text = 'Failed to pull!\n' + str(e)
            get_designer().close_popup()

        progress.start()
        threading.Thread(target=pull).start()
Пример #6
0
 def on_touch_down(self, touch):
   if not self.collide_point(touch.x, touch.y):
     return
   popup = Popup(title='Edit variable',
     content=VariableSelector(self),
     size_hint=(None, None), size=(400, 400))
   popup.open()
Пример #7
0
    def do_add(self, *args):
        '''Git select files from a list to add
        '''
        d = get_designer()
        if d.popup:
            return False
        files = self.repo.untracked_files
        if not files:
            show_alert('Git Add', 'All files are already indexed by Git')
            return

        # create the popup
        fake_setting = FakeSettingList()
        fake_setting.allow_custom = False
        fake_setting.items = files
        fake_setting.desc = 'Select files to add to Git index'

        content = SettingListContent(setting=fake_setting)
        popup_width = min(0.95 * Window.width, 500)
        popup_height = min(0.95 * Window.height, 500)
        popup = Popup(
            content=content, title='Git - Add files', size_hint=(None, None),
            size=(popup_width, popup_height), auto_dismiss=False)

        content.bind(on_apply=self._perform_do_add,
                     on_cancel=d.close_popup)

        content.show_items()
        d.popup = popup
        popup.open()
Пример #8
0
    def do_email(self, popup, address, filename, widget):
        thread = SenderThread(address, filename)
        thread.daemon = True
        thread.start()
        popup.dismiss()

        layout = BoxLayout(orientation='vertical')
        label = Label(
            text='Just sent this image to:\n\n{}'.format(address),
            font_size=30)
        button = Button(
            text='Awesome!',
            font_size=30,
            background_color=(0, 1, 0, 1))
        layout.add_widget(label)
        layout.add_widget(button)

        popup = Popup(
            title='Just thought you should know...',
            content=layout,
            size_hint=(.5, .5))

        button.bind(on_release=popup.dismiss)
        from kivy.core.window import Window

        Window.release_all_keyboards()
        self.reset_email_textinput()
        popup.open()
Пример #9
0
    def confirm_print(self):
        layout0 = BoxLayout(orientation='vertical')
        layout1 = BoxLayout(orientation='horizontal')
        label = Label(
            text='You want to print {} copies?'.format(self.prints),
            font_size=30)
        button0 = Button(
            text='Just do it!',
            font_size=30,
            background_color=(0, 1, 0, 1))
        button1 = Button(
            text='No',
            font_size=30,
            background_color=(1, 0, 0, 1))
        layout1.add_widget(button1)
        layout1.add_widget(button0)
        layout0.add_widget(label)
        layout0.add_widget(layout1)

        popup = Popup(
            title='Are you sure?',
            content=layout0,
            size_hint=(.5, .5),
            auto_dismiss=False)

        button0.bind(on_release=partial(
            self.handle_print_touch, popup))

        button1.bind(on_release=popup.dismiss)
        popup.open()
Пример #10
0
 def posterror(self, message, dt):
     print(message)
     self.switchscreen(self.startmenu)
     errorpopup = Popup(title='Error',
                   content=Label(text=message),
                        size_hint=(None, None), size=(600,200))
     errorpopup.open()
Пример #11
0
    def changeScreen(self, screen):
        # back button
        print screen
        print self.currentScreen
        if(screen != '' and screen != 'back' and screen != 'setting'):
            self.currentScreen = screen
        elif(screen == 'back'):
            screen = self.currentScreen

        if(screen == 'receptor'):
            #Check data input
            Receptors = Variable.parsepdb.Receptors
            Ligands = Variable.parsepdb.Ligands
            if(len(Receptors) == 0 or len(Ligands) == 0):
                popup = Popup(title='Warning!',
                content=Label(text='Please insert your data to two \ncolumn Receptors and Ligands before \nrunning this simulation'),
                size_hint=(None, None), size=(300, 200))
                popup.open()
                return

        if(screen == 'load'):
            self.get_screen(screen).setupView()
        elif(screen == 'receptor'):
            self.get_screen(screen).setupView()
        elif (screen == 'running'):
            self.get_screen(screen).setupView()
        elif (screen == 'configuration'):
            self.get_screen(screen).setupView()

        self.current = screen
Пример #12
0
    def yes_callback(self):
        print('The button Yes is being pressed' + self.notary_file)

        json = getMetaData(self.notary_file_no_path,self.file_owner,self.file_created_dt,self.file_created_by)

        print('Meta Json Test: ' + str(json))
        import notary_client
        try :
            result = notary_app.notary_obj.notarize_file(str(self.notary_file), json)
        except notary_client.NotaryException as e:
           print("Code %s " % e.error_code)
           print(e.message)

        try :
            notary_app.notary_obj.upload_file_encrypted(str(self.notary_file))
        except notary_client.NotaryException as e:
           print("Code %s " % e.error_code)
           print(e.message)

        popup = Popup(title='Confirmation of Upload',
                      content=Label(text='Congrats. Your document notariztion and upload are successfully.'),
                      size_hint=(None, None),
                      size=(400, 200))
        popup.open()

        notary_app.sm.current = 'viewclaims'
Пример #13
0
class Add_debris_select(BoxLayout):
    debris_id = ObjectProperty(None)
    get_debris_id = ObjectProperty(None)
    debris_type = ObjectProperty(None)
    get_debris_type = ObjectProperty(None)
    debris_weight = ObjectProperty(None)
    get_debris_weight = ObjectProperty(None)
    debris_lat = ObjectProperty(None)
    get_debris_lat = ObjectProperty(None)
    debris_long = ObjectProperty(None)
    get_debris_long = ObjectProperty(None)
    add_debris_to_db = ObjectProperty(None) 

    def __init__(self,**kwargs):
        super(Add_debris_select,self).__init__(**kwargs)
        
    def on_back(self):
        self.parent.parent.transition.direction = 'left'
        self.parent.parent.current = 'display_database'
        
    def on_dismiss(self, arg):
        pass

    def not_full_info(self,event):
        self.popup = Popup(title= "Information",
        content = Info_Pop(),
        size_hint=(None, None), size=(self.width/2, self.height/2))
        self.popup.bind(on_dismiss = self.on_dismiss)
        self.popup.open() 
Пример #14
0
class VariableDescriptions(Widget):

    def tab_info(self):
        self.pbuilder = self.parent.parent
        self.description_tab = TabbedPanel()
        particle_info = TabbedPanelHeader(text = 'Particle')
        behavior_info = TabbedPanelHeader(text = 'Behavior')
        color_info = TabbedPanelHeader(text = 'Color')
        particle_info.font_size = self.size[0]*.28
        behavior_info.font_size = self.size[0]*.28
        color_info.font_size = self.size[0]*.28
        particle_info.content = RstDocument(source="param_descriptions/ParticleTab.rst")
        behavior_info.content = RstDocument(source="param_descriptions/BehaviorTab.rst")
        color_info.content = RstDocument(source="param_descriptions/ColorTab.rst")
        particle_info.scroll_distance = 2
        particle_info.scroll_timeout = 500
        behavior_info.scroll_distance = 2
        behavior_info.scroll_timeout = 500
        color_info.scroll_distance = 2
        color_info.scroll_timeout = 500
        self.description_tab.default_tab = particle_info
        self.description_tab.tab_width = self.size[0]*4.36
        self.description_tab.tab_height = self.size[1]*.7
        self.description_tab.add_widget(particle_info)
        self.description_tab.add_widget(behavior_info)
        self.description_tab.add_widget(color_info)
        self.description_popup = Popup(title="Variable Descriptions", content = self.description_tab, size_hint = (.8,.8), on_open=self._popup_opened, on_dismiss=self._popup_dismissed)
        self.description_popup.open()

    def _popup_opened(self, instance):
        self.pbuilder.demo_particle.pause()

    def _popup_dismissed(self, instance):
        self.pbuilder.demo_particle.resume()
Пример #15
0
 def weather(self, obj):
     weather = getWeather()
     popup = Popup(title='Test popup',
                   content=Label(text=weather),
                   size_hint=(None, None),
                   size=(400, 400))
     popup.open()
Пример #16
0
class Root(FloatLayout):
    loadfile = ObjectProperty(None)
    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)
    
    #def erro_popup():
		# we have to create Error_POP up with "Ok" button, when Ok button 
		# will b pressend Error_popup will be dismissed 
		   
    def dismiss_popup(self):
		
        # dismissing the popup created for Load Dialog
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        
        # created the POPUP for load Dialog
        self._popup = Popup(title="Load file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path,filename):
    	
        self.text_input.text = read_pdf(filename[0])
        self.dismiss_popup()
Пример #17
0
    def load_particle(self,name='templates/thelight.pex'):
        progress_dialog = Popup(title="Loading...", content=Label(text="Please wait while the particle file is being loaded."), size_hint=(.5,.5))
        progress_dialog.open()

        pbuilder = self.parent.parent
        pl = pbuilder.params_layout
        pw = pbuilder.particle_window

        if not pl.tabs_loaded:
            # if the default panel is loaded, we need to create tabs
            pl.create_tabs()
        else:
            # if not, then the tabs are already there, but we do need to stop and remove the particle
            pbuilder.demo_particle.stop(clear = True)
            pw.remove_widget(pbuilder.demo_particle)

        new_particle = kivyparticle.ParticleSystem(name)
        new_particle.pos = pw.center_x, pw.center_y
        pbuilder.demo_particle = new_particle
        pw.add_widget(pbuilder.demo_particle)
        pbuilder.demo_particle.start()
        pbuilder.active_filename = os.path.basename(name)

        pl.particle_tabs.tab_list[0].content.get_values_from_particle()
        pl.particle_tabs.tab_list[1].content.get_values_from_particle()
        pl.particle_tabs.tab_list[2].content.get_values_from_particle()
        pl.open_first_tab()

        progress_dialog.dismiss()
Пример #18
0
	def mail_pop(self):
		"""Popup with features to mail timesheet """

		f=FloatLayout()
		global popup2
		popup2 = Popup(title='Mail Timesheet',content=f,
		size_hint=(1.0, 0.6), size=(400, 400))
		g=GridLayout(cols=1,row_force_default=True,
					 row_default_height=40,pos_hint={'center_x':.5})
		global msg
		msg=Label(text="ENTER AN EMAIL ID")
		global mail_id
		mail_id=TextInput(write_tab=False)
		g.add_widget(msg)
		g.add_widget(mail_id)
		btn1=Button(text='MAIL',size_hint=(0.2,0.1),
					pos=(popup2.width-350,popup2.height-250) )
		btn1.bind(on_press=(MyApp.mail_timesheet))
		btn2=Button(text='CLOSE',size_hint=(0.2,0.1),
					pos=(popup2.width-50,popup2.height-250))
		f.add_widget(btn1)
		f.add_widget(btn2)
		f.add_widget(g)
		popup2.open()
		btn2.bind(on_press=popup2.dismiss)
Пример #19
0
	def readme_pop(self):
		""" Readme """

		popup = Popup(title='README')
		b=BoxLayout(orientation='vertical')
		s = ScrollView()
		global tslabel
		tslabel=Label(size_hint_y=None,line_height=1.5,valign="top",
					  text= "Copyright (C) 2015 Revathy Narayanan\n" +
					  "The TimeTracker is a Python application \n that will keep"+
					  " track of time spent\n in day-to-day activities.\n\n"+
"The Application will have features \n"+
"* Start/Stop watch \n * Log Task\n * Add Comments\n"+
"* Generate & View Timesheet\n * Mail Timesheet\n\n "+
"The code is licensed under MIT License(MIT).\n "+
"Please see the file license in this distribution\n for license terms in the link below :\n"+
"https://github.com/rev20/Time-Tracker/blob/master/LICENSE \n\n"+
"Following is the link for the repository: \n"+
"https://github.com/rev20/Time-Tracker/")

		tslabel.bind(texture_size=tslabel.setter('size'))
		btn1=Button(text='CLOSE',size_hint=(1,.06))
		s.add_widget(tslabel)
		b.add_widget(s)
		b.add_widget(btn1)
		popup.content=b
		popup.open()
		btn1.bind(on_press=popup.dismiss)
Пример #20
0
class ChooseOptionPopup:
    m_dictOptionCallback = None
    
    def __init__(self, title, listOptionCallback):
        self.m_dictOptionCallback = {}
        
        layout = BoxLayout(orientation="vertical")
        
        for option,callback in listOptionCallback:
            if callback != None:
                self.m_dictOptionCallback[option] = callback
                btn = Button(text=option, size_hint=(1, 0.1))
                btn.bind(on_release = self.choice)
                layout.add_widget(btn)
            else:
                layout.add_widget(Label(text=option, size_hint=(1, 0.1)))
        
        self.popup = Popup(title=title,content=layout,size_hint=(0.5, min(0.1 + len(listOptionCallback) * 0.1, 1.0)))
        self.popup.open()
        
    def choice(self, instance):
        self.dismiss_popup()
        (self.m_dictOptionCallback[instance.text])()
        
    def dismiss_popup(self):
        self.popup.dismiss()
Пример #21
0
	def timesheet_pop(self):
		"""Popup to display the Timesheet"""

		popup = Popup(title='Timesheet')
		b=BoxLayout(orientation='vertical')
		s = ScrollView()
		global tslabel
		tslabel=Label(size_hint_y=None,line_height=1.5,valign="top",
					  text="|_ID_|______DATE______|___TIME_SPENT____|_____TASK_________|")
		tslabel.bind(texture_size=tslabel.setter('size'))
		btn1=Button(text='CLOSE',size_hint=(1,.06))
		s.add_widget(tslabel)
		b.add_widget(s)
		b.add_widget(btn1)
		popup.content=b
		popup.open()
		btn1.bind(on_press=popup.dismiss)

		con=lite.connect('TimeTracker.db')
		with con:
				cur=con.cursor()
				cur.execute("SELECT ID, TASK_DATE, TIME, TASK FROM Timesheet")
				rows = cur.fetchall()
				for row in rows:
				  tslabel.text=tslabel.text+"\n   "
				  tslabel.text+=str(row[0]).center(4)+"      "+str(row[1])
				  tslabel.text+="  "+str(row[2]).center(34)+"  "+str(row[3])
		if con:
				con.close()
Пример #22
0
    def open_statistics(self):
        """Utworzenie i wyświetlenie okienka zawierającego najlepszy i kilka ostatnich wyników z danego ćwiczenia"""
        from stats import ScoresPopupContent

        st = Popup(title=u"{t} - Wyniki".format(t=self.name), content=ScoresPopupContent(table_name=self.table_name), size_hint_x=0.8)
        st.open()
        st.content.close_bt.bind(on_release=st.dismiss)
Пример #23
0
 def oblicz(self, *args):
     tab=[]
     ident=['X1','Y1','X2','Y2','D','K']
     Light=True
     for i in ident:
         lab=self.ids[i]
         value=lab.text
         try:
             value=float(value)
             tab.append(value)
         except:
             Light = False
             #lis=BiegunApp().ustawienia(config,'ustawienia','miarakatowa')
             msg=  u"Popraw daną "+ i + ' miara katowa to: '+ katy
     if Light==True:
         x1=tab[0]
         y1=tab[1]
         x2=tab[2]
         y2=tab[3]
         Az=Obliczenia().Azymut(x1,y1,x2,y2)
         AzC=Az+tab[5]
         X=x1+math.cos(AzC*math.pi/200)*tab[4]
         X=round(X,3)
         Y=y1+math.sin(AzC*math.pi/200)*tab[4]
         Y=round(Y,3)
         lab=self.ids['WspX']
         lab.text='X: '+str(X)
         lab=self.ids['WspY']
         lab.text='Y: '+str(Y)
     else:
         popup=Popup(title="ERROR", title_color=(1,0,0,1), content=Label(text= msg, font_size=40,bold=True),
                     size_hint=(None, None),size=(self.width,self.height/2))
         popup.open()
Пример #24
0
    def on_close_tab(self, instance, *args):
        '''Event handler to close icon
        :param instance: tab instance
        '''
        d = get_designer()
        if d.popup:
            return False

        self.switch_to(instance)
        if instance.has_modification:
            # show a dialog to ask if can close
            confirm_dlg = ConfirmationDialog(
                    'All unsaved changes will be lost.\n'
                    'Do you want to continue?')
            popup = Popup(
                    title='New',
                    content=confirm_dlg,
                    size_hint=(None, None),
                    size=('200pt', '150pt'),
                    auto_dismiss=False)

            def close_tab(*args):
                d.close_popup()
                self._perform_close_tab(instance)

            confirm_dlg.bind(
                    on_ok=close_tab,
                    on_cancel=d.close_popup)
            popup.open()
            d.popup = popup
        else:
            Clock.schedule_once(partial(self._perform_close_tab, instance))
Пример #25
0
 def AzDlOblicz(self, *args):
     tabAzDl=[]
     tabIdent=['AzX1','AzY1','AzX2','AzY2']
     Light = True
     for i in tabIdent:
         lab=self.ids[i]
         value=lab.text
         try:
             value=float(value)
             tabAzDl.append(value)
         except:
             Light = False
             msg= "wpisz wartosc "+i
     if Light == True:
         x1=tabAzDl[0]
         y1=tabAzDl[1]
         x2=tabAzDl[2]
         y2=tabAzDl[3]
         Az=Obliczenia().Azymut(x1,y1,x2,y2)
         Dl=Obliczenia().Dlugosc(x1,y1,x2,y2)
         lab=self.ids['Az']
         lab.text='Azymut: '+str(round(Az,4))
         lab=self.ids['Dl']
         lab.text='Dlugosc: '+str(round(Dl,3))
     else:
         popup=Popup(title="ERROR", title_color=(1,0,0,1), content=Label(text=msg, font_size=40,bold=True),size_hint=(None, None),size=(self.width,self.height/2))
         popup.open()
Пример #26
0
class SettingsApp(App):

	settings_cls = SettingsWithSidebar
	display_type = 'popup'
	popup = None
	
	def build(self):
		bt = Button(text='Open settings')
		bt.bind(on_press=self.open_settings)

		return bt
	
	def on_settings_cls(self, *args):
		self.destroy_settings()
	
	
	def display_settings(self, settings):
		if self.display_type == 'popup':
			if self.popup is None:
				self.popup = Popup(content=settings, title='Settings', size_hint=(0.8, 0.8))
			self.popup.open()
		else:
			super(SettingsApp, self).display_settings(settings)
	
	def close_settings(self, *args):
		if self.display_type == 'popup':
			if self.popup is not None:
				self.popup.dismiss()
		else:
			super(SettingsApp, self).close_settings()
Пример #27
0
 def show_color_picker(self, current_color):
     popup = Popup(title='Color Picker',
                   size_hint=(0.5, 0.5))
     color_picker = ColorPicker(color=current_color)
     color_picker.bind(color=self.on_paint_color)
     popup.content = color_picker
     popup.open()
Пример #28
0
    def show_confirm_dialog(self, title, msg, on_confirm, on_cancel=None,
                            cancel_btn_text='Cancel',
                            confirm_btn_text='Confirm',
                            on_open=None):
        confirm_popup = None

        def dismiss_confirm_dialog():
            if confirm_popup and hasattr(confirm_popup, 'dismiss'):
                confirm_popup.dismiss()

        def on_confirm_wrapper():
            dismiss_confirm_dialog()
            on_confirm()

        def on_cancel_wrapper():
            dismiss_confirm_dialog()
            if callable(on_cancel):
                on_cancel()

        content = ConfirmDialog(confirm_callback=on_confirm_wrapper,
                                cancel_callback=on_cancel_wrapper,
                                cancel_btn_text=cancel_btn_text,
                                confirm_btn_text=confirm_btn_text)
        content.message_label.text = msg
        confirm_popup = Popup(
            title=title, content=content,
            auto_dismiss=False, size_hint=(0.9, None), height=200)
        if on_open:
            confirm_popup.on_open = on_open
        confirm_popup.open()
        return confirm_popup
Пример #29
0
 def showProgressPopup(self, title, content):
     self.dismissPopups()
     if type(content) is str:
         content = Label(text=content)
     popup = Popup(title=title, content=content, auto_dismiss=False, size_hint=(None, None), size=(dp(400), dp(200)))
     popup.open()
     self.tracksUpdatePopup = popup
Пример #30
0
    def openinfo(self, *args):
        """
        Display element info into pop-up
        """

        boxpop = BoxLayout(orientation='vertical')

        description = Description()
        description.text = self.main.tip_info

        boxpop.add_widget(TitreDescription())
        boxpop.add_widget(description)

        usage = Usage()
        usage.text = self.main.apl_info

        boxpop.add_widget(TitreUsage())
        boxpop.add_widget(usage)
       
        popup = Popup(
            title=self.main.nametext,
            content=boxpop,
            separator_color=get_color_from_hex('42bd3bff'),
            title_size = 20,
            size_hint=(None, None),
            size=(640, 280))
        popup.open()
Пример #31
0
class Root(FloatLayout):
    loadfile = ObjectProperty(None)
    savefile = ObjectProperty(None)

    input_path = os.path.dirname(os.path.realpath(__file__))
    files = []
    filename = 'output'
    extention = 'csv'

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title='Выбрать директорию с музыкой',
                            content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def show_save(self):
        content = SaveDialog(save=self.save, cancel=self.dismiss_popup)
        self._popup = Popup(title='Выбрать директорию для сохранения выгрузки',
                            content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path, filename):
        self.input_path = path if path != os.sep else os.path.dirname(
            os.path.realpath(__file__))
        self.dismiss_popup()

    def save(self, path, filename):
        self.files = [(f, os.path.join(self.input_path, f))
                      for f in os.listdir(self.input_path)
                      if os.path.isfile(os.path.join(self.input_path, f))]
        self.output_path = path if path != os.sep else os.path.dirname(
            os.path.realpath(__file__))
        self.filename = filename or self.filename

        write_filename = os.path.join(
            self.output_path, '{}.{}'.format(self.filename, self.extention))
        metadata = []

        for f in self.files:
            try:
                metadata.append({
                    'filename': f[0],
                    'metadata': mutagen.File(f[1])
                })
            except mutagen.mp3.HeaderNotFoundError as err:
                print('ERROR: Bad file, ', err)

        metadata = [m for m in metadata if m.get('metadata')]

        with open(write_filename, 'w', encoding='utf-8') as write_file:
            csv_writer = csv.writer(write_file,
                                    delimiter=';',
                                    quotechar='|',
                                    quoting=csv.QUOTE_MINIMAL,
                                    lineterminator='\n')
            col_names = [
                'Имя файла', 'Название', 'Исполнитель', 'Жанр', 'Альбом',
                'Композитор', 'Комментарий'
            ]
            csv_writer.writerow(
                [i.encode('utf8').decode('utf8') for i in col_names])

            for row in metadata:
                filename = row.get('filename', '')
                meta = row.get('metadata')
                name = meta.get('TIT2', '')
                singer = meta.get('TPE1', '')
                genre = meta.get('TXXX:WM/GenreID ', '')
                album = meta.get('TALB', '')
                composer = meta.get('TCOM', '')
                comment = meta.get('COMM::rus', '')

                csv_writer.writerow(
                    [filename, name, singer, genre, album, composer, comment])

        self.dismiss_popup()
Пример #32
0
class Screen(FloatLayout):
    image = ObjectProperty(None)
    text_output = ObjectProperty(None)
    corner_images = ObjectProperty(None)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)  
        
    def dismiss_popup(self):
        self._popup.dismiss(animation=False)

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content,
                            size_hint=(0.9, 0.8), pos_hint={'y': 0.2},
                            auto_dismiss=False)
        self._popup.open()

    def load(self, path, filename):
        self.dismiss_popup()

        if not filename:
            return
        try:
            extracted_features = card_detection.for_classification(os.path.join(path, filename[0]))
            image = extracted_features['image']
            self.loaded_corners = extracted_features['corners']

            prepared = []
            for group in self.loaded_corners:
                prepared_group = []
                for im in group:
                    im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
                    im = cv2.resize(im, (ISIZE, ISIZE))
                    im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
                    prepared_group.append(im)
                prepared.append(prepared_group)

            self.image.texture = to_texture(image)            
            self.corner_images.clear()
            for i, card_corners in enumerate(prepared):
                color = None
                if i % 2 == 0:
                    color = 0.2
                else:
                    color = 0.3
                new_widget = CardPredictions(card_corners, color=color)
                self.corner_images.add(new_widget)

            self.text_output.text = "Image loaded"

        except ValueError as e:
            self.text_output.text = str(e)

    def detect_hand(self):
        if self.loaded_corners is None:
            self.text_output.text = "Image couldn't be processed"
            return        

        predictions = nn_network.predict(self.loaded_corners)
        labels = [p['classes'] for p in predictions]
                
        for widget, results in zip(self.corner_images.get_widgets(), predictions):            
            widget.set_results(results)
        
        if len(self.loaded_corners) == 5:
            self.text_output.text = interpret_labels.get_combination(labels)
        else:
            self.text_output.text = "Couldn't find 5 cards in the image"
Пример #33
0
 def finish_popup(self, operation_type):
     content = PopUps(cancel=self.dismiss_popup)
     self._popup = Popup(title=operation_type,
                         content=content,
                         size_hint=(0.3, 0.3))
     self._popup.open()
Пример #34
0
class MyWidget(BoxLayout):
    def dismiss_popup(self):
        self._popup.dismiss()

    def finish_popup(self, operation_type):
        content = PopUps(cancel=self.dismiss_popup)
        self._popup = Popup(title=operation_type,
                            content=content,
                            size_hint=(0.3, 0.3))
        self._popup.open()

    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)
        self.drives_list.adapter.bind(
            on_selection_change=self.drive_selection_changed
        )  #Display contents of selected  Drive

    def get_sys_drives(
            self):  #Get a list of Drives Locations that are currently mounted
        drives = []
        getDrives = psutil.disk_partitions()
        for i in range(len(getDrives)):
            drives.append(getDrives[i][1])
        return drives

    def drive_selection_changed(
        self, *args
    ):  #Setting fileSytem path based on Drive selected to view contents
        selected_item = args[0].selection[0].text
        self.file_chooser.path = selected_item

    def get_selected_file(self, path, filename):
        stream = os.path.join(path, filename[0])  # get file selected
        print(stream)
        return stream

    def get_selected_directory(self, path):
        selected_directory = path
        return selected_directory

    def copy_file(self, path, filename):
        selected_file = self.get_selected_file(path, filename)
        return selected_file

    def paste_file(self, path, filename, symlinks=False, ignore=None):
        source = self.copy_file(path, filename)
        destination = self.get_selected_directory(path)
        print(destination)

        if os.path.isdir(source):

            print("Yes a Directory was passed!!!")

            def copytreex(srce, dst, symlinks=False, ignore=None):

                if not os.path.exists(dst):
                    os.makedirs(dst)
                    shutil.copystat(srce, dst)
                lst = os.listdir(srce)
                if ignore:
                    excl = ignore(srce, lst)
                    lst = [x for x in lst if x not in excl]
                for item in lst:

                    s = os.path.join(srce, item)
                    d = os.path.join(dst, item)
                    if symlinks and os.path.islink(s):
                        if os.path.lexists(d):
                            os.remove(d)
                        os.symlink(os.readlink(s), d)
                        try:
                            st = os.lstat(s)
                            mode = stat.S_IMODE(st.st_mode)
                            os.lchmod(d, mode)
                        except:
                            pass  # lchmod not available
                    elif os.path.isdir(s):
                        copytreex(s, d, symlinks, ignore)
                    else:
                        shutil.copy2(s, d)

                        print("Operation complete")

                copytreex(source, destination)
                self.finish_popup("Copy Operation")

            '''shutil.copytree(source, destination, symlinks, ignore)
            self.finish_popup("Copy Operation")
            print("Folder Copied!!")'''

        else:
            StartTime = time.time()
            shutil.copy2(source, destination)

            self.finish_popup("Copy Operation")
            StopTime = time.time()
            TimeElapsed = StopTime - StartTime
            print("File Copied!!")
            print(TimeElapsed)

    def delete_file(self, path, filename):  #deleting file
        sfile = self.get_selected_file(path, filename)
        print(sfile)
        if os.path.isdir(sfile):
            shutil.rmtree(sfile)  #it finally works #delete the matching  item
            self.finish_popup("Deletion Operation")

            print('Folder Deleted!!')
        else:
            os.remove(sfile)
            self.finish_popup("Deletion Operation")

            print("File Deleted!!")

    def compress_file(
            self, path,
            filename):  #Fuction for file compression using zlib module
        folder_name = filename
        folder_path = path
        cfile = self.get_selected_file(
            path, filename)  #call the get_selected_file methode

        if os.path.isdir(cfile):
            f_Name = cfile.split('/')
            new_file = folder_path + '/' + f_Name[-1] + ".zip"
            new_zip = zipfile.ZipFile(new_file, 'a')
            lst = os.listdir(cfile)

            for item in lst:

                s = os.path.join(cfile, item)
                new_zip.write(s, compress_type=zipfile.ZIP_DEFLATED)

            new_zip.close()
            self.finish_popup("Compression Operation")
            print("Done")

        else:
            scrap = cfile.split('/')[-1]
            f_Name = scrap.split(".")[0]
            new_file = folder_path + '/' + f_Name + ".zip"
            new_zip = zipfile.ZipFile(new_file, 'w')
            new_zip.write(cfile, compress_type=zipfile.ZIP_DEFLATED)
            new_zip.close()
            self.finish_popup("Compression Operation")

    def decompress_file(
            self, path,
            filename):  #Fuction for file Decompression using zlib module
        folder_path = path
        cfile = self.get_selected_file(
            path, filename)  #call the get_selected_file methode

        scrap = cfile.split(".")[0]
        new_file_name = scrap.split("/")[-1]
        current_directory = folder_path + "/" + new_file_name

        print(cfile)
        print(folder_path)
        print(new_file_name)
        print(current_directory)

        decompZip = zipfile.ZipFile(cfile)

        decompZip.extractall(current_directory)
        decompZip.close()
        self.finish_popup("Decompression Operation")
Пример #35
0
class MusicPlayer(Widget):

    directory = ''  #location of songs folder
    nowPlaying = ''  #Song that is currently playing

    def getpath(self):
        try:
            f = open("sav.dat", "r")
            self.ids.direct.text = str(f.readline())
            f.close()
            self.ids.searchBtn.text = "Scan"
            self.getSongs()
        except:
            self.ids.direct.text = ''

    def savepath(self, path):
        f = open("sav.dat", "w")
        f.write(path)
        f.close()

    def dismiss_popup(self):
        self._popup.dismiss()

    def fileSelect(self):
        content = ChooseFile(select=self.select, cancel=self.dismiss_popup)

        self._popup = Popup(title="Select Folder",
                            content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def select(self, path):
        self.directory = path
        self.ids.direct.text = self.directory
        self.ids.searchBtn.text = "Scan"
        self.savepath(self.directory)
        self.getSongs()
        self.dismiss_popup()

    def getSongs(self):

        songs = []  #List to hold songs from music directory
        self.directory = self.ids.direct.text  #Directory entered by the user

        if self.directory == '':
            self.fileSelect()

        #To make sure that the directory ends with a '/'
        if not self.directory.endswith('/'):
            self.directory += '/'

        #Check if directory exists
        if not path.exists(self.directory):
            self.ids.status.text = 'Folder Not Found'
            self.ids.status.color = (1, 0, 0, 1)

        else:

            self.ids.status.text = ''

            self.ids.scroll.bind(
                minimum_height=self.ids.scroll.setter('height'))

            #get mp3 files from directory
            for fil in listdir(self.directory):
                if fil.endswith('.mp3'):
                    songs.append(fil)

            #If there are no mp3 files in the chosen directory
            if songs == [] and self.directory != '':
                self.ids.status.text = 'No Music Found'
                self.ids.status.color = (1, 0, 0, 1)

            songs.sort()

            for song in songs:

                def playSong(bt):
                    try:
                        self.nowPlaying.stop()
                    except:
                        pass
                    finally:
                        self.nowPlaying = SoundLoader.load(self.directory +
                                                           bt.text + '.mp3')
                        self.nowPlaying.play()
                        self.ids.nowplay.text = bt.text

                btn = Button(text=song[:-4], on_press=playSong)
                icon = Button(size_hint_x=None,
                              width=50,
                              background_down="ico.png",
                              background_normal="ico.png")

                #Color Buttons Alternatively
                if songs.index(song) % 2 == 0:
                    btn.background_color = (0, 0, 1, 1)
                else:
                    btn.background_color = (0, 0, 2, 1)

                self.ids.scroll.add_widget(icon)  #Add icon to layout
                self.ids.scroll.add_widget(btn)  #Add btn to layout
Пример #36
0
 def show_save(self):
     content = SaveDialog(save=self.save, cancel=self.dismiss_popup)
     self._popup = Popup(title='Выбрать директорию для сохранения выгрузки',
                         content=content,
                         size_hint=(0.9, 0.9))
     self._popup.open()
Пример #37
0
 def show_load(self):
     content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
     self._popup = Popup(title='Выбрать директорию с музыкой',
                         content=content,
                         size_hint=(0.9, 0.9))
     self._popup.open()
Пример #38
0
class MainApp(App):
    def build(self):
        Window.size = (800, 725)
        self.chosenKeyInd = 0
        self.valArray = []
        self.smellName = "ERR"
        Window.clearcolor = (0.5, 0.5, 0.5, 0.5)
        boxlayout = BoxLayout(orientation='vertical')

        label = Label(text='DATA SENDER APP',
                      size_hint=(.5, .5),
                      pos_hint={
                          'center_x': .5,
                          'center_y': .85
                      },
                      color=[1, 1, 1, 1],
                      font_size=70)
        """fetchKey = TextInput(
            halign="left", font_size=55, hint_text='Key input to fetch', size_hint=(0.8, 1), pos_hint={"center_x": 0.5, "center_y": 0.65}
        )"""

        #layout = FloatLayout(size=(300, 300))
        layout = BoxLayout(orientation="vertical")
        button = Button(text='START FETCHING DATA',
                        size_hint=(0.8, 1),
                        pos_hint={
                            "center_x": 0.5,
                            "center_y": 0.65
                        },
                        background_color=[0, 0, 1, 1])

        layout.add_widget(label)

        #layout.add_widget(fetchKey)
        layout.add_widget(button)
        button.bind(on_press=self.on_press_button)

        self.progresslabel = Label(text='On standby',
                                   size_hint=(.5, .5),
                                   pos_hint={
                                       'center_x': .5,
                                       'center_y': .53
                                   },
                                   color=[1, 1, 1, 1],
                                   font_size=30)

        label2 = Label(text='CURRENT DATA:',
                       size_hint=(.5, .5),
                       color=[1, 1, 1, 1],
                       pos_hint={
                           'center_x': .5,
                           'center_y': .375
                       },
                       font_size=60)
        layout.add_widget(self.progresslabel)
        layout.add_widget(label2)

        #dropdown = DropDown(size_hint=(.5, .5))
        #btn1 = Button(text='AVERAGED DATA', size_hint_y=None, height=44)
        #btn2 = Button(text='RAW DATA', size_hint_y=None,  height=44)
        #btn1.bind(on_release=lambda btn: dropdown.select(btn1.text))
        #btn2.bind(on_release=lambda btn: dropdown.select(btn2.text))
        #dropdown.add_widget(btn1)
        #dropdown.add_widget(btn2)
        #mainbutton = Button(text='Data View', size_hint_x = 0.4, size_hint_y = 0.1, pos_hint={'center_x': 0.5, 'center_y': 0.25})
        #mainbutton.bind(on_release=dropdown.open)
        #dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
        #layout.add_widget(mainbutton);

        gridlayout = GridLayout(cols=2,
                                row_force_default=True,
                                row_default_height=100,
                                size_hint_x=0.8,
                                pos_hint={
                                    'center_x': 0.5,
                                    'center_y': 0.25
                                })
        gridlayout.add_widget(
            Button(text='COMPOUND',
                   size_hint_x=None,
                   width=350,
                   background_color=[0, 0, 1, 1]))
        gridlayout.add_widget(
            Button(text='VALUE', background_color=[0, 0, 1, 1]))

        self.MQ136 = TextInput(halign="left",
                               font_size=55,
                               hint_text='MQ136 value')

        #gridlayout.add_widget(Button(text='200'))

        self.MQ137 = TextInput(halign="left",
                               font_size=55,
                               hint_text='MQ137 value')

        self.MQ3 = TextInput(halign="left",
                             font_size=55,
                             hint_text='MQ3 value')

        self.MQ5 = TextInput(halign="left",
                             font_size=55,
                             hint_text='MQ5 value')

        self.MQblank = TextInput(halign="left",
                                 font_size=55,
                                 hint_text='MQblank value')
        self.MQblank2 = TextInput(halign="left",
                                  font_size=55,
                                  hint_text='MQblank2 value')

        gridlayout.add_widget(
            Button(text='MQ136',
                   size_hint_x=None,
                   width=350,
                   background_color=[0, 0, 1, 1]))
        gridlayout.add_widget(self.MQ136)

        gridlayout.add_widget(
            Button(text='MQ137',
                   size_hint_x=None,
                   width=350,
                   background_color=[0, 0, 1, 1]))
        gridlayout.add_widget(self.MQ137)

        gridlayout.add_widget(
            Button(text='MQ3',
                   size_hint_x=None,
                   width=350,
                   background_color=[0, 0, 1, 1]))
        gridlayout.add_widget(self.MQ3)

        gridlayout.add_widget(
            Button(text='MQ5',
                   size_hint_x=None,
                   width=350,
                   background_color=[0, 0, 1, 1]))
        gridlayout.add_widget(self.MQ5)

        gridlayout.add_widget(
            Button(text='MQblank',
                   size_hint_x=None,
                   width=350,
                   background_color=[0, 0, 1, 1]))
        gridlayout.add_widget(self.MQblank)

        gridlayout.add_widget(
            Button(text='MQblank2',
                   size_hint_x=None,
                   width=350,
                   background_color=[0, 0, 1, 1]))
        gridlayout.add_widget(self.MQblank2)

        #gridlayout.add_widget(Button(text='200'))

        boxlayout.add_widget(layout)
        boxlayout.add_widget(gridlayout)

        #db = firebase.database()
        #db.child("Signal").push("")

        return boxlayout

    def on_press_button(self, instance):
        print('You pressed the button!')
        button_text = instance.text
        if button_text == 'START FETCHING DATA':
            self.valArray = []
            self.progresslabel.text = 'Fetching data...'
            #create a csv file with all of the values from the firebase database

            ref = firebase.database()
            data = ref.child("smells").get()
            key = data.val()
            print("hello")
            if (key == None):
                self.progresslabel.text = 'No data currently in database'

            else:
                db = firebase.database()
                a = db.child("smells")
                smelldict = a.get().val()
                print(smelldict)
                with open('finalsmelllist.csv', 'w', newline='') as file:
                    writer = csv.writer(file)
                    writer.writerow([
                        "MQ136", "MQ137", "MQ3", "MQ5", "MQblank", "MQblank2"
                    ])
                    for key in smelldict:
                        MQ136 = db.child("smells").child(key).child(
                            "MQ136").get().val()
                        MQ137 = db.child("smells").child(key).child(
                            "MQ137").get().val()
                        MQ3 = db.child("smells").child(key).child(
                            "MQ3").get().val()
                        MQ5 = db.child("smells").child(key).child(
                            "MQ5").get().val()
                        MQblank = db.child("smells").child(key).child(
                            "MQblank").get().val()
                        MQblank2 = db.child("smells").child(key).child(
                            "MQblank2").get().val()
                        writer.writerow(
                            [MQ136, MQ137, MQ3, MQ5, MQblank, MQblank2])
                print("Finished writing csv file.")

                self.progresslabel.text = 'Data fetched! CSV generated in folder.'

                with open('finalsmelllist.csv', 'r') as file:
                    reader = csv.reader(file)
                    counter = 0.0
                    MQ136count = 0.0
                    MQ137count = 0.0
                    MQ3count = 0.0
                    MQ5count = 0.0
                    MQblankcount = 0.0
                    MQblank2count = 0.0
                    next(reader)
                    for row in reader:
                        if counter != 0.0:
                            MQ136count = MQ136count + float(row[0])
                            MQ137count = MQ137count + float(row[1])
                            MQ3count = MQ3count + float(row[2])
                            MQ5count = MQ5count + float(row[3])
                            MQblankcount = MQblankcount + float(row[4])
                            MQblank2count = MQblank2count + float(row[5])
                        counter = counter + 1.0
                self.MQ136.text = str(MQ136count / counter)
                self.MQ137.text = str(MQ137count / counter)
                self.MQ3.text = str(MQ3count / counter)
                self.MQ5.text = str(MQ5count / counter)
                self.MQblank.text = str(MQblankcount / counter)
                self.MQblank2.text = str(MQblank2count / counter)

                self.valArray.append(MQ3count / counter)
                self.valArray.append(MQ137count / counter)
                self.valArray.append(MQ5count / counter)
                self.valArray.append(MQblankcount / counter)
                self.valArray.append(MQblank2count / counter)

                print("ValArray v")
                print(self.valArray)

                self.progresslabel.text = 'Data fetched! CSV generated in folder. Values updated.'
                self.swap_label(
                    'Data fetched! CSV generated in folder. On standby for a signal.'
                )
                '''print('3 seconds start')
                time.sleep(2)
                print('3 seconds are over')
                self.swap_label('On Standby. Looking for signal from synthesizer (every 2 seconds).')'''
                instance.text = "Check for Signal"

                #instance.text = "Push to Database"

        if button_text == "Check for Signal":
            x = 1
            self.progresslabel.text = 'Checking for Signal......'
            while True:
                ref = firebase.database()
                users = ref.child("Signal").get()
                key = users.val()
                #print(key)
                if (key == None):
                    self.progresslabel.text = 'On Standby. No Signal yet.'
                else:
                    db = firebase.database()
                    keyDict = firebase.database().child("Signal").get().val()
                    keyList = list(keyDict)
                    self.chosenKeyInd = 0
                    finalKey = firebase.database().child("Signal").child(
                        keyList[0]).get().val()

                    keyCount = int(len(keyDict))
                    print(keyCount)
                    if (keyCount == 1):
                        self.progresslabel.text = 'Ready to Go! Key = ' + str(
                            finalKey)
                        instance.text = "Push to Database"
                    else:
                        content = BoxLayout(orientation="vertical")

                        for x in range(0, keyCount):
                            db = firebase.database()
                            keyDict = firebase.database().child(
                                "Signal").get().val()
                            keyList = list(keyDict)
                            thisKey = firebase.database().child(
                                "Signal").child(keyList[x]).get().val()

                            button = Button(text=str(thisKey),
                                            background_color=[0, 0, 1, 1])
                            content.add_widget(button)
                            button.thisKeyInd = x
                            button.bind(on_press=self.chooseSignal)
                            button.subInst = instance

                        self.popup = Popup(
                            content=content,
                            auto_dismiss=False,
                            title="Pick a synthesis key!",
                            title_align="center",
                        )

                        # bind the on_press event of the button to the dismiss function

                        # open the popup
                        self.popup.open()
                    break
                if (x == 10):
                    print('program terminated')
                    self.progresslabel.text = "No Signal Found."
                    instance.text = "Click button to check again for Signal."
                    break
                x = x + 1
                print(x)
                time.sleep(2)

        if button_text == "Click button to check again for Signal.":
            x = 1
            self.progresslabel.text = 'Checking for Signal......'
            while True:
                ref = firebase.database()
                users = ref.child("Signal").get()
                key = users.val()
                #print(key)
                if (key == None):
                    self.progresslabel.text = 'On Standby. No Signal yet.'
                else:
                    db = firebase.database()
                    keyDict = firebase.database().child("Signal").get().val()
                    keyList = list(keyDict)
                    chosenKeyInd = 0
                    finalKey = firebase.database().child("Signal").child(
                        keyList[0]).get().val()

                    keyCount = int(len(keyDict))
                    print(keyCount)
                    if (keyCount == 1):
                        self.progresslabel.text = 'Ready to Go! Key = ' + str(
                            finalKey)
                        instance.text = "Push to Database"
                        chosenKeyInd = 0
                    else:
                        content = BoxLayout(orientation="vertical")

                        for x in range(0, keyCount):
                            db = firebase.database()
                            keyDict = firebase.database().child(
                                "Signal").get().val()
                            keyList = list(keyDict)
                            thisKey = firebase.database().child(
                                "Signal").child(keyList[x]).get().val()

                            button = Button(text=str(thisKey),
                                            background_color=[0, 0, 1, 1])
                            content.add_widget(button)
                            button.thisKeyInd = x
                            button.bind(on_press=self.chooseSignal)
                            button.subInst = instance

                        self.popup = Popup(
                            content=content,
                            auto_dismiss=False,
                            title="Pick a synthesis key!",
                            title_align="center",
                        )

                        # bind the on_press event of the button to the dismiss function

                        # open the popup
                        self.popup.open()
                    break
                if (x == 10):
                    print('program terminated')
                    self.progresslabel.text = "No Signal Found."
                    instance.text = "Click button to check again for Signal."
                    break
                x = x + 1
                print(x)
                time.sleep(2)

        if button_text == "Push to Database":
            db = firebase.database()
            keyDict = firebase.database().child("Signal").get().val()
            keyList = list(keyDict)
            finalKey = firebase.database().child("Signal").child(
                keyList[self.chosenKeyInd]).get().val()
            b = db.child(finalKey)

            #Algorithm goes here##---------------------------------##

            valArray = self.valArray
            '''valArray = []
            valArray.append(111)
            valArray.append(13.0)
            valArray.append(88.3)
            valArray.append(7.6)
            valArray.append(71.26)'''

            x = valArray[0]
            print(x)
            testAvg = x
            #testAvg = 190
            print(testAvg)

            meanList = [
                101.77966101694915, 187.50169491525423, 143.08474576271186,
                111.5186440677966, 207.4237288135593, 246.92542372881357
            ]

            dists = []
            currentLowest = 0
            for x in range(6):
                dists.append(abs(testAvg - meanList[x]))
                if (x != 0):
                    if (dists[x] < dists[currentLowest]):
                        currentLowest = x

            print(dists)
            print(currentLowest)
            if currentLowest == 0:
                print("LemonGrass")
                self.smellName = "LemonGrass"
                finalNum = 4
            if currentLowest == 1:
                print("Eucalyptus")
                self.smellName = "Eucalyptus"
                finalNum = 2
            if currentLowest == 2:
                print("Peppermint")
                self.smellName = "Peppermint"
                finalNum = 1
            if currentLowest == 3:
                print("Lavendar")
                self.smellName = "Lavendar"
                finalNum = 6
            if currentLowest == 4:
                print("TeaTree")
                self.smellName = "TeaTree"
                finalNum = 5
            if currentLowest == 5:
                print("Orange")
                self.smellName = "Orange"
                finalNum = 3

    #Algorithm ends here##---------------------------------##
            data = finalNum
            b.child("finalint").set(data)
            self.progresslabel.text = 'Smell classified as ' + self.smellName + '. Data sent!'
            instance.text = "START FETCHING DATA"

    def swap_label(self, progText):
        self.progresslabel.text = progText
        print(progText)

    def chooseSignal(self, instance):

        #self.chosenKeyInd = instance.thisKeyInd

        db = firebase.database()
        keyDict = firebase.database().child("Signal").get().val()
        keyList = list(keyDict)
        finalKey = firebase.database().child("Signal").child(
            keyList[self.chosenKeyInd]).get().val()

        self.progresslabel.text = 'Ready to Go! Key = ' + str(finalKey)
        instance.subInst.text = "Push to Database"

        self.popup.dismiss()
    def change_number(self,event):
        try:
            number=int(self.textnumber.text)
        except ValueError:
            number =self.counter
            popup = Popup(title=' ', content=Label(text='Not an int'), size_hint=(None, None),
                          size=(400, 100))
            popup.open()

        if number < 0:
            popup = Popup(title=' ', content=Label(text='Wrong number'), size_hint=(None, None),
                          size=(400, 100))
            popup.open()
        elif number * 100 > len(self.listimage):
            print(number * 100 + 100,len(self.listimage),'****')
            popup = Popup(title=' ', content=Label(text='Wrong number'), size_hint=(None, None),
                          size=(400, 100))
            popup.open()

        else:
            self.forward_backward_state=number
            self.update(event)
Пример #40
0
    def alarmPopup(self, *args):
        box = FloatLayout()
        hourbutton = Button(text='Select Hour',
                            size_hint=(.2, .2),
                            pos_hint={
                                'x': .2,
                                'y': .5
                            })
        hourdropdown = DropDown()
        for i in range(24):
            if (i < 10):
                btn = Button(text='0%r' % i, size_hint_y=None, height=70)
            else:
                btn = Button(text='%r' % i, size_hint_y=None, height=70)
            btn.bind(on_release=lambda btn: hourdropdown.select(btn.text))
            hourdropdown.add_widget(btn)

        hourbutton.bind(on_release=hourdropdown.open)
        hourdropdown.bind(
            on_select=lambda instance, x: setattr(hourbutton, 'text', x))
        box.add_widget(hourbutton)
        box.add_widget(hourdropdown)
        minutebutton = Button(text='Select Minute',
                              size_hint=(.2, .2),
                              pos_hint={
                                  'x': .6,
                                  'y': .5
                              })
        minutedropdown = DropDown()

        for i in range(60):
            if (i < 10):
                btn = Button(text='0%r' % i, size_hint_y=None, height=70)
            else:
                btn = Button(text='%r' % i, size_hint_y=None, height=70)
            btn.bind(on_release=lambda btn: minutedropdown.select(btn.text))
            minutedropdown.add_widget(btn)

        minutebutton.bind(on_release=minutedropdown.open)
        minutedropdown.bind(
            on_select=lambda instance, x: setattr(minutebutton, 'text', x))
        box.add_widget(minutebutton)
        box.add_widget(minutedropdown)

        #button to dismiss alarm selector and set alarm once user has chosen alarm
        dismissButton1 = SetAlarmPopup()
        dismissButton2 = SetSleepPopup()
        box.add_widget(dismissButton1)
        box.add_widget(dismissButton2)

        currentDay = time.strftime("%A")
        alarmPopup = Popup(title='Set Your Alarm for {}:'.format(currentDay),
                           content=box,
                           size_hint=(.8, .8))
        dismissButton1.bind(
            on_press=partial(dismissButton1.dismissAlarmPopup, alarmPopup,
                             hourbutton, minutebutton))
        dismissButton2.bind(
            on_press=partial(dismissButton2.dismissSleepPopup, alarmPopup,
                             hourbutton, minutebutton))
        alarmPopup.open()
Пример #41
0
 def popup_folder_exist(self, ):
     error_popup = Popup(title='Folder Exist',
                         content=Label(text='That folder already exists'),
                         size_hint=(.5, .5))
     error_popup.open()
Пример #42
0
    def on_press_button(self, instance):
        print('You pressed the button!')
        button_text = instance.text
        if button_text == 'START FETCHING DATA':
            self.valArray = []
            self.progresslabel.text = 'Fetching data...'
            #create a csv file with all of the values from the firebase database

            ref = firebase.database()
            data = ref.child("smells").get()
            key = data.val()
            print("hello")
            if (key == None):
                self.progresslabel.text = 'No data currently in database'

            else:
                db = firebase.database()
                a = db.child("smells")
                smelldict = a.get().val()
                print(smelldict)
                with open('finalsmelllist.csv', 'w', newline='') as file:
                    writer = csv.writer(file)
                    writer.writerow([
                        "MQ136", "MQ137", "MQ3", "MQ5", "MQblank", "MQblank2"
                    ])
                    for key in smelldict:
                        MQ136 = db.child("smells").child(key).child(
                            "MQ136").get().val()
                        MQ137 = db.child("smells").child(key).child(
                            "MQ137").get().val()
                        MQ3 = db.child("smells").child(key).child(
                            "MQ3").get().val()
                        MQ5 = db.child("smells").child(key).child(
                            "MQ5").get().val()
                        MQblank = db.child("smells").child(key).child(
                            "MQblank").get().val()
                        MQblank2 = db.child("smells").child(key).child(
                            "MQblank2").get().val()
                        writer.writerow(
                            [MQ136, MQ137, MQ3, MQ5, MQblank, MQblank2])
                print("Finished writing csv file.")

                self.progresslabel.text = 'Data fetched! CSV generated in folder.'

                with open('finalsmelllist.csv', 'r') as file:
                    reader = csv.reader(file)
                    counter = 0.0
                    MQ136count = 0.0
                    MQ137count = 0.0
                    MQ3count = 0.0
                    MQ5count = 0.0
                    MQblankcount = 0.0
                    MQblank2count = 0.0
                    next(reader)
                    for row in reader:
                        if counter != 0.0:
                            MQ136count = MQ136count + float(row[0])
                            MQ137count = MQ137count + float(row[1])
                            MQ3count = MQ3count + float(row[2])
                            MQ5count = MQ5count + float(row[3])
                            MQblankcount = MQblankcount + float(row[4])
                            MQblank2count = MQblank2count + float(row[5])
                        counter = counter + 1.0
                self.MQ136.text = str(MQ136count / counter)
                self.MQ137.text = str(MQ137count / counter)
                self.MQ3.text = str(MQ3count / counter)
                self.MQ5.text = str(MQ5count / counter)
                self.MQblank.text = str(MQblankcount / counter)
                self.MQblank2.text = str(MQblank2count / counter)

                self.valArray.append(MQ3count / counter)
                self.valArray.append(MQ137count / counter)
                self.valArray.append(MQ5count / counter)
                self.valArray.append(MQblankcount / counter)
                self.valArray.append(MQblank2count / counter)

                print("ValArray v")
                print(self.valArray)

                self.progresslabel.text = 'Data fetched! CSV generated in folder. Values updated.'
                self.swap_label(
                    'Data fetched! CSV generated in folder. On standby for a signal.'
                )
                '''print('3 seconds start')
                time.sleep(2)
                print('3 seconds are over')
                self.swap_label('On Standby. Looking for signal from synthesizer (every 2 seconds).')'''
                instance.text = "Check for Signal"

                #instance.text = "Push to Database"

        if button_text == "Check for Signal":
            x = 1
            self.progresslabel.text = 'Checking for Signal......'
            while True:
                ref = firebase.database()
                users = ref.child("Signal").get()
                key = users.val()
                #print(key)
                if (key == None):
                    self.progresslabel.text = 'On Standby. No Signal yet.'
                else:
                    db = firebase.database()
                    keyDict = firebase.database().child("Signal").get().val()
                    keyList = list(keyDict)
                    self.chosenKeyInd = 0
                    finalKey = firebase.database().child("Signal").child(
                        keyList[0]).get().val()

                    keyCount = int(len(keyDict))
                    print(keyCount)
                    if (keyCount == 1):
                        self.progresslabel.text = 'Ready to Go! Key = ' + str(
                            finalKey)
                        instance.text = "Push to Database"
                    else:
                        content = BoxLayout(orientation="vertical")

                        for x in range(0, keyCount):
                            db = firebase.database()
                            keyDict = firebase.database().child(
                                "Signal").get().val()
                            keyList = list(keyDict)
                            thisKey = firebase.database().child(
                                "Signal").child(keyList[x]).get().val()

                            button = Button(text=str(thisKey),
                                            background_color=[0, 0, 1, 1])
                            content.add_widget(button)
                            button.thisKeyInd = x
                            button.bind(on_press=self.chooseSignal)
                            button.subInst = instance

                        self.popup = Popup(
                            content=content,
                            auto_dismiss=False,
                            title="Pick a synthesis key!",
                            title_align="center",
                        )

                        # bind the on_press event of the button to the dismiss function

                        # open the popup
                        self.popup.open()
                    break
                if (x == 10):
                    print('program terminated')
                    self.progresslabel.text = "No Signal Found."
                    instance.text = "Click button to check again for Signal."
                    break
                x = x + 1
                print(x)
                time.sleep(2)

        if button_text == "Click button to check again for Signal.":
            x = 1
            self.progresslabel.text = 'Checking for Signal......'
            while True:
                ref = firebase.database()
                users = ref.child("Signal").get()
                key = users.val()
                #print(key)
                if (key == None):
                    self.progresslabel.text = 'On Standby. No Signal yet.'
                else:
                    db = firebase.database()
                    keyDict = firebase.database().child("Signal").get().val()
                    keyList = list(keyDict)
                    chosenKeyInd = 0
                    finalKey = firebase.database().child("Signal").child(
                        keyList[0]).get().val()

                    keyCount = int(len(keyDict))
                    print(keyCount)
                    if (keyCount == 1):
                        self.progresslabel.text = 'Ready to Go! Key = ' + str(
                            finalKey)
                        instance.text = "Push to Database"
                        chosenKeyInd = 0
                    else:
                        content = BoxLayout(orientation="vertical")

                        for x in range(0, keyCount):
                            db = firebase.database()
                            keyDict = firebase.database().child(
                                "Signal").get().val()
                            keyList = list(keyDict)
                            thisKey = firebase.database().child(
                                "Signal").child(keyList[x]).get().val()

                            button = Button(text=str(thisKey),
                                            background_color=[0, 0, 1, 1])
                            content.add_widget(button)
                            button.thisKeyInd = x
                            button.bind(on_press=self.chooseSignal)
                            button.subInst = instance

                        self.popup = Popup(
                            content=content,
                            auto_dismiss=False,
                            title="Pick a synthesis key!",
                            title_align="center",
                        )

                        # bind the on_press event of the button to the dismiss function

                        # open the popup
                        self.popup.open()
                    break
                if (x == 10):
                    print('program terminated')
                    self.progresslabel.text = "No Signal Found."
                    instance.text = "Click button to check again for Signal."
                    break
                x = x + 1
                print(x)
                time.sleep(2)

        if button_text == "Push to Database":
            db = firebase.database()
            keyDict = firebase.database().child("Signal").get().val()
            keyList = list(keyDict)
            finalKey = firebase.database().child("Signal").child(
                keyList[self.chosenKeyInd]).get().val()
            b = db.child(finalKey)

            #Algorithm goes here##---------------------------------##

            valArray = self.valArray
            '''valArray = []
            valArray.append(111)
            valArray.append(13.0)
            valArray.append(88.3)
            valArray.append(7.6)
            valArray.append(71.26)'''

            x = valArray[0]
            print(x)
            testAvg = x
            #testAvg = 190
            print(testAvg)

            meanList = [
                101.77966101694915, 187.50169491525423, 143.08474576271186,
                111.5186440677966, 207.4237288135593, 246.92542372881357
            ]

            dists = []
            currentLowest = 0
            for x in range(6):
                dists.append(abs(testAvg - meanList[x]))
                if (x != 0):
                    if (dists[x] < dists[currentLowest]):
                        currentLowest = x

            print(dists)
            print(currentLowest)
            if currentLowest == 0:
                print("LemonGrass")
                self.smellName = "LemonGrass"
                finalNum = 4
            if currentLowest == 1:
                print("Eucalyptus")
                self.smellName = "Eucalyptus"
                finalNum = 2
            if currentLowest == 2:
                print("Peppermint")
                self.smellName = "Peppermint"
                finalNum = 1
            if currentLowest == 3:
                print("Lavendar")
                self.smellName = "Lavendar"
                finalNum = 6
            if currentLowest == 4:
                print("TeaTree")
                self.smellName = "TeaTree"
                finalNum = 5
            if currentLowest == 5:
                print("Orange")
                self.smellName = "Orange"
                finalNum = 3

    #Algorithm ends here##---------------------------------##
            data = finalNum
            b.child("finalint").set(data)
            self.progresslabel.text = 'Smell classified as ' + self.smellName + '. Data sent!'
            instance.text = "START FETCHING DATA"
Пример #43
0
class ResultScreen(Screen):
    def __init__(self, *args, **kwargs):
        super(ResultScreen, self).__init__(*args, **kwargs)
        self.app = App.get_running_app()
        self.process_info = {
            'calculating': False,
            'out_progress': 0,
            'in_stop': False,
            'out_ended': False,
            'in_use_temp_images': True,
            'out_temp_images': []
        }
        self.capture = None
        self.images = [None] * 3
        self.waiter = None

        self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        self._keyboard.bind(on_key_down=self._on_keyboard_down)

    def _keyboard_closed(self):
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard = None

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        if keycode[1] == 'escape':
            self._stop_stack_movie_calculate()
        if keycode[1] == "o" and 'ctrl' in modifiers:
            self.app.stack_movie_screen.open_file_dialog()
        return True

    def _init_stack_movie_calculate(self, capture):
        # need to stop running thread first
        if self.waiter: self.waiter.cancel()
        if self.process_info['out_ended']:
            self.process_info['calculating'] = False
        if self.process_info['calculating']:
            self.ids.label_status.text = 'stopping previous...'
            self.process_info['in_stop'] = True
            Clock.schedule_once(
                lambda dt: self._init_stack_movie_calculate(capture), 0.2)
            return
        self.process_info['in_stop'] = False
        self.process_info['out_ended'] = False
        self.process_info['out_temp_images'] = []
        self.process_info['calculating'] = True
        self.app.result_screen.ids.result_save.disabled = True
        self.ids.image_result.opacity = 0
        self.capture = capture
        self.ids.progressbar.height = '50sp'
        self.ids.progressbar.opacity = 1
        self.ids.label_spacer.height = '250sp'
        self.ids.label_status.text = 'calculating...'

        self.thread_stack_movie_calculate = threading.Thread(
            target=self._stack_movie_calculate)  # ,args=(q,)
        self.app.stack_movie_screen.ids.image_video_player.stop_updating()
        self.thread_stack_movie_calculate.start()
        # we need to do this, to get out of the thread
        self.waiter = Clock.schedule_interval(self._wait_to_finish, 0.2)

    def _wait_to_finish(self, *args):
        if not self.process_info['calculating']:
            self.waiter.cancel()
            self.show_image()
        else:
            if len(self.process_info['out_temp_images']) > 0:
                self.images = self.process_info['out_temp_images']
                self.show_image(temporary=True)

        self.ids.progressbar.value = self.process_info['out_progress']

    def _stop_stack_movie_calculate(self):
        self.ids.label_status.text = 'stopping...'
        self.process_info['in_stop'] = True

    def _stack_movie_calculate(self):
        first = self.app.stack_movie_screen.ids.first.value / 100
        last = self.app.stack_movie_screen.ids.last.value / 100
        frame_step = self.app.stack_movie_screen.ids.frame_step.value
        align = self.app.stack_movie_screen.ids.align.active
        align_method = self.app.stack_movie_screen.ids.dropbut_align_method.text
        align_warp_mode = self.app.stack_movie_screen.ids.dropbut_align_warp_mode.text.lower(
        )
        # get stacked image, first image, last image
        self.images = affex.stackMovie(self.capture,
                                       first=first,
                                       last=last,
                                       frame_step=frame_step,
                                       align=align,
                                       align_method=align_method,
                                       align_warp_mode=align_warp_mode,
                                       output_float=True,
                                       process_info=self.process_info)
        self.process_info['calculating'] = False

    def show_image(self, temporary=False):
        if not temporary:
            self.ids.progressbar.height = '0sp'
            self.ids.progressbar.opacity = 0
            if (self.process_info['in_stop'] == True):
                self.ids.label_status.text = 'Finished (prematurely).'
            else:
                self.ids.label_status.text = 'Finished.'
        self.ids.label_spacer.height = '0sp'
        self.ids.image_result.texture = frame_to_image(
            np.array(np.round(self.images[0]), dtype=np.uint8))
        self.ids.image_result.opacity = 1
        self.ids.result_save.disabled = False
        self.app.stack_movie_screen.ids.button_previous_result.disabled = False

    def dismiss_popup_save(self):
        self.popup_save.dismiss()

    def save_image_overwrite(self, overwrite=False):
        self.popup_save_exists.dismiss()
        self.save_overwrite = overwrite
        if overwrite:
            self.save_image_write()

    def save_image_write(self):
        extension = os.path.splitext(self.save_filename)[1][1:]
        if not extension in ['png', 'jpg', 'tiff']:
            self.popup_save_error = PopupError()
            self.popup_save_error.ids.label_error.text = 'Unsupported extension: %s.' % extension
            self.popup_save_error.open()
        elif os.path.isfile(self.save_filename) and not self.save_overwrite:
            self.popup_save_exists = PopupFileExists()
            self.popup_save_exists.ids.label_text.text = 'File %s exists.\n\nOverwrite?' % self.save_filename
            self.popup_save_exists.open()
        else:
            print('Saving: %s' % self.save_filename)
            if extension == "png" or extension == "tiff":  # save 16 bit image
                cv2.imwrite(
                    self.save_filename,
                    np.array(np.round(256 * self.images[0]), dtype=np.uint16),
                    [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
            else:
                cv2.imwrite(self.save_filename,
                            np.array(np.round(self.images[0]), dtype=np.uint8),
                            [int(cv2.IMWRITE_JPEG_QUALITY), 90])
            if self.process_info['calculating']:
                self.ids.label_status.text = 'calculating... (saved temporary result).'
            else:
                self.ids.label_status.text = 'Saved.'
            self.dismiss_popup_save()

    def save_image_init(self, path, filename):
        self.save_filename = os.path.join(path, filename)
        self.save_overwrite = False
        self.save_image_write()

    def save_image(self):
        if self.ids.result_save.disabled:
            return False
        dir = os.path.dirname(
            os.path.realpath(self.app.stack_movie_screen.capture_filename))
        content = SaveDialog(save=self.save_image_init,
                             cancel=self.dismiss_popup_save)
        content.ids.filechooser.path = dir
        content.ids.text_input.text = os.path.splitext(
            self.app.stack_movie_screen.capture_filename)[0] + '.png'
        self.popup_save = Popup(title="Save image...",
                                content=content,
                                size_hint=(0.9, 0.9))
        self.popup_save.open()
Пример #44
0
 def success(self):
     popup = Popup(title='Closing',
                   content=Label(text=str('Success')),
                   size_hint=(.5, .5),
                   on_dismiss=self.close)
     popup.open()
Пример #45
0
 def show_popup(self, content, title="Load file"):
     self._popup = Popup(title=title, content=content, size_hint=(.8, .8))
     self._popup.open()
Пример #46
0
class StackMovieScreen(Screen):
    helper = HelperManager()
    app = None
    capture = None
    slider_markers = [None, None]
    popup_error = None
    load_path = None

    def __init__(self, *args, **kwargs):
        super(StackMovieScreen, self).__init__(*args, **kwargs)
        Window.bind(on_dropfile=self._on_file_drop)
        self.app = App.get_running_app()
        self.popup_error = PopupError()

        self.ids.first.bind(value=self._mark_first)
        self.ids.last.bind(value=self._mark_last)
        self.ids.video_slider.bind(size=self._mark_firstlast)

    def _mark_firstlast(self, first=True, last=True):
        if (not first) and (not last): return
        if first:
            marker = 0
            val = self.ids.first.value / 100
        elif last:
            marker = 1
            val = self.ids.last.value / 100
        s = self.ids.video_slider
        p = (s.x + s.padding + val * (s.width - 2 * s.padding), s.y)
        points = [p[0], p[1] + s.height / 3, p[0], p[1] + s.height / 3 * 2]
        if not self.slider_markers[marker]:
            with self.ids.video_slider.canvas:
                self.slider_markers[marker] = Line(points=points, width=2)
        else:
            self.slider_markers[marker].points = points
        if first and last:
            self._mark_firstlast(first=False, last=True)

    def _mark_first(self, *args):
        self._mark_firstlast(1)

    def _mark_last(self, *args):
        self._mark_firstlast(0)

    def _on_file_drop(self, window, file_path):
        self.load_file(file_path.decode("utf-8"))

    def dismiss_popup_load(self):
        self.popup_load.dismiss()

    def open_file_dialog(self):
        self._video_player_pause()
        self.app.root.transition.direction = 'right'
        self.app.root.current = 'stack_movie_screen'
        content = LoadDialog(load=self.load_file_init,
                             cancel=self.dismiss_popup_load)
        if self.load_path:
            dir = self.load_path
        else:
            dir = os.getcwd()
        content.ids.filechooser.path = dir
        self.popup_load = Popup(title="Load video file...",
                                content=content,
                                size_hint=(0.9, 0.9))
        self.popup_load.open()

    def load_file_init(self, path, filename):
        self.load_file(os.path.join(path, filename))
        self.load_path = path
        self.dismiss_popup_load()

    def load_file(self, filename):
        print('Loading: %s' % filename)
        self.capture = cv2.VideoCapture(filename, cv2.CAP_FFMPEG)
        fps = self.capture.get(cv2.CAP_PROP_FPS)
        totalFrames = self.capture.get(cv2.CAP_PROP_FRAME_COUNT)
        if fps > 0 and totalFrames == -1.0:  # there seems to be a bug sometimes with getting the total number of frames
            totalFrames = affex.getTotalFrames(self.capture)
        if fps > 0 and totalFrames > 1:
            self.ids.button_process.disabled = False
            self.ids.image_video_player.init_update(capture=self.capture,
                                                    totalFrames=totalFrames)
            self.capture_filename = filename
        else:
            self.unload_file()
            if not fps > 0:
                txt_error = 'Cannot open file %s.\nUnsupported file format.' % os.path.basename(
                    filename)
            else:
                txt_error = 'Frames in file %s: %d.\nWe need more to stack and align.' % (
                    filename, totalFrames)
            self.popup_error.ids.label_error.text = txt_error
            self.popup_error.open()
            return False

    def unload_file(self):
        self.capture = None
        self.capture_filename = None
        self.ids.image_video_player.capture = None
        self.ids.image_video_player.texture = None
        self.ids.button_process.disabled = True
        self._video_player_pause()

    def _video_player_play(self):
        self.ids.image_video_player.start_updating()

    def _video_player_pause(self):
        self.ids.image_video_player.stop_updating()

    def on_stop(self):
        self.capture.release()

    def stack_movie(self):
        if self.capture:
            self.app.root.transition.direction = 'left'
            self.app.root.transition.duration = 0.5
            self.app.root.current = 'result_screen'

            self.app.result_screen._init_stack_movie_calculate(self.capture)
Пример #47
0
class Connect_4(App):
    def build(self):

        self.player1 = Player()
        self.player2 = AI()
        self.board = Board()
        self.list_bords = [self.board.copy()]
        self.turn = 0
        self.game_over = False

        self.root = BoxLayout(orientation='vertical')

        ################################################################################

        self.intro_main_Box = BoxLayout(orientation='vertical')
        self.intro_Box0 = BoxLayout(orientation='vertical', size_hint=(1, .6))
        self.intro_Box1 = BoxLayout(orientation='vertical', size_hint=(1, .2))
        self.intro_Box2 = BoxLayout(orientation='horizontal',
                                    size_hint=(1, .1))
        self.intro_Box3 = BoxLayout(orientation='horizontal',
                                    size_hint=(1, .1))

        self.intro_Box0.add_widget(Image(source='images/start.png'))
        self.intro_main_Box.add_widget(self.intro_Box0)

        self.intro_main_Box.add_widget(self.intro_Box1)

        self.intro_Box2.add_widget(
            Label(text='Choose the number of player(s) : ', size_hint=(.3, 1)))
        self.intro_Box2.add_widget(
            Label(text='Choose the color of the 1st player : ',
                  size_hint=(.32, 1)))
        self.intro_Box2.add_widget(
            Label(text='Choose the level of the ai :', size_hint=(.25, 1)))
        self.intro_Box2.add_widget(Label(text='', size_hint=(.15, 1)))

        self.intro_main_Box.add_widget(self.intro_Box2)
        #####
        self.choice1 = BoxLayout(orientation='horizontal', size_hint=(.3, 1))

        self.btn_ai_vs_player = Button(text='AI vs\nPlayer')
        self.btn_ai_vs_player.bind(on_release=self.ai_vs_player)

        self.btn_player_vs_ai = Button(text='Player\nvs AI')
        self.btn_player_vs_ai.bind(on_release=self.player_vs_ai)

        self.btn_2_players = Button(text='2 Players')
        self.btn_2_players.bind(on_release=self.two_players)

        self.choice1.add_widget(self.btn_ai_vs_player)
        self.choice1.add_widget(self.btn_player_vs_ai)
        self.choice1.add_widget(self.btn_2_players)

        self.intro_Box3.add_widget(self.choice1)
        self.intro_Box3.add_widget(Label(text='', size_hint=(.03, 1)))

        #####
        self.choice2 = BoxLayout(orientation='horizontal', size_hint=(.3, 1))

        self.btn_red = Button(text='Red')
        self.btn_red.bind(on_release=self.red)

        self.btn_yellow = Button(text='Yellow')
        self.btn_yellow.bind(on_release=self.yellow)

        self.choice2.add_widget(self.btn_red)
        self.choice2.add_widget(self.btn_yellow)

        self.intro_Box3.add_widget(self.choice2)
        self.intro_Box3.add_widget(Label(text='', size_hint=(.03, 1)))
        ######
        self.choice3 = BoxLayout(size_hint=(.25, 1))

        self.btn_level_1 = Button(text='1')
        self.btn_level_1.bind(on_release=self.set_level_1)

        self.btn_level_2 = Button(text='2')
        self.btn_level_2.bind(on_release=self.set_level_2)

        self.btn_level_3 = Button(text='3')
        self.btn_level_3.bind(on_release=self.set_level_3)

        self.btn_level_4 = Button(text='4')
        self.btn_level_4.bind(on_release=self.set_level_4)

        self.btn_level_5 = Button(text='5')
        self.btn_level_5.bind(on_release=self.set_level_5)

        self.choice3.add_widget(self.btn_level_1)
        self.choice3.add_widget(self.btn_level_2)
        self.choice3.add_widget(self.btn_level_3)
        self.choice3.add_widget(self.btn_level_4)
        self.choice3.add_widget(self.btn_level_5)

        self.intro_Box3.add_widget(self.choice3)

        self.intro_Box3.add_widget(Label(text='', size_hint=(.05, 1)))

        self.btn_intro = Button(text='Enter', size_hint=(.1, 1))
        self.btn_intro.bind(on_release=self.clear)
        self.intro_Box3.add_widget(self.btn_intro)

        self.intro_main_Box.add_widget(self.intro_Box3)
        self.root.add_widget(self.intro_main_Box)

        ################################################################################

        self.main_Box = BoxLayout(orientation='vertical')
        self.Box1 = BoxLayout(orientation='vertical', size_hint=(1, .9))
        self.Box2 = BoxLayout(orientation='horizontal', size_hint=(1, .1))

        image = Image(source='images/beginning.png')
        self.Box1.add_widget(image)
        self.label = Label(text="Enter a valid column : ", size_hint=(.32, 1))
        self.label2 = Label(text="", size_hint=(.13, 1))
        self.col_input = BoxLayout(orientation='horizontal',
                                   size_hint=(.45, 1))

        ################################################################################

        self.btn_0 = Button(text='1')
        self.btn_0.bind(on_release=self.zero)

        self.btn_1 = Button(text='2')
        self.btn_1.bind(on_release=self.one)

        self.btn_2 = Button(text='3')
        self.btn_2.bind(on_release=self.two)

        self.btn_3 = Button(text='4')
        self.btn_3.bind(on_release=self.three)

        self.btn_4 = Button(text='5')
        self.btn_4.bind(on_release=self.four)

        self.btn_5 = Button(text='6')
        self.btn_5.bind(on_release=self.five)

        self.btn_6 = Button(text='7')
        self.btn_6.bind(on_release=self.six)

        self.col_input.add_widget(self.btn_0)
        self.col_input.add_widget(self.btn_1)
        self.col_input.add_widget(self.btn_2)
        self.col_input.add_widget(self.btn_3)
        self.col_input.add_widget(self.btn_4)
        self.col_input.add_widget(self.btn_5)
        self.col_input.add_widget(self.btn_6)

        self.Box2.add_widget(self.label)
        self.Box2.add_widget(self.col_input)
        self.Box2.add_widget(self.label2)

        ################################################################################

        self.btn_ai = Button(text='AI')
        self.btn_ai.bind(on_release=self.ai_play)

        self.btn_undo = Button(text='undo', size_hint=(.1, 1))
        self.btn_undo.bind(on_release=self.undo)
        self.Box2.add_widget(self.btn_undo)

        self.btn_menu = Button(text='Menu', size_hint=(.1, 1))
        self.btn_menu.bind(on_release=self.menu)
        self.Box2.add_widget(self.btn_menu)

        self.main_Box.add_widget(self.Box1)
        self.main_Box.add_widget(self.Box2)

        ################################################################################

        self.popup_Box = BoxLayout(orientation='vertical')
        self.popup_btn_menu = Button(text='Play again',
                                     font_size='20sp',
                                     background_normal='',
                                     background_color=[.6, .6, .6, 1])
        self.popup_btn_menu.bind(on_release=self.menu)
        self.popup_Box.add_widget(self.popup_btn_menu)

        self.popup = Popup(title='End of party',
                           content=self.popup_Box,
                           auto_dismiss=True,
                           size_hint=(.4, .25),
                           pos_hint={
                               'right': .7,
                               'top': .25
                           },
                           title_size='30sp',
                           separator_color=[.0, .0, .0, 1])

        return self.root

################################################################################

    def draw(self):

        filename = self.board.draw(self.game_over)
        image = Image(source=filename)
        remove_file(filename)
        self.Box1.clear_widgets()
        self.Box1.add_widget(image)

################################################################################

    def clear(self, obj):
        self.root.clear_widgets()
        self.root.add_widget(self.main_Box)

        if isinstance(self.player1, AI) and not isinstance(self.player2, AI):
            self.player1.play(self.board)
            self.draw()

################################################################################

    def menu(self, obj):
        try:
            self.root.clear_widgets()
            self.root.add_widget(self.intro_main_Box)
        except:
            pass
        for i in range(self.board.i + 2):
            path = '.\\images\\to_disp' + str(i) + '.png'
            if exists(path): remove_file(path)

        self.Box1.clear_widgets()

        self.Box1.add_widget(Image(source='images/beginning.png'))

        i = self.board.i
        del self.board.board
        del self.board
        del self.list_bords

        self.board = Board()
        self.list_bords = [self.board.copy()]

        self.board.i = i
        self.game_over = False
        self.turn = 0

################################################################################

    def ai_play(self, obj):

        if self.turn == 0 and not self.game_over and isinstance(
                self.player1, AI):

            self.player1.play(self.board)
            self.list_bords.append(self.board.copy())
            self.draw()

            if self.board.winning_move(self.player1.color):
                print("Player 1 wins!")
                self.game_over = True
                self.draw()
                self.popup.title = "Player 1 wins!"

                if self.player1.color == RED:
                    self.popup.title_color = [1, .02, .02, .4]
                else:
                    self.popup.title_color = [1, 1, .05, .4]

                self.popup.open()
            self.turn = 1 - self.turn

        if self.turn == 1 and not self.game_over and isinstance(
                self.player2, AI):

            self.player2.play(self.board)
            self.list_bords.append(self.board.copy())
            self.draw()

            if self.board.winning_move(self.player2.color):
                print("Player 2 wins!")
                self.game_over = True
                self.draw()
                self.popup.title = "Player 2 wins!"

                if self.player2.color == RED:
                    self.popup.title_color = [1, .02, .02, .4]
                else:
                    self.popup.title_color = [1, 1, .05, .4]

                self.popup.open()

            self.turn = 1 - self.turn

    ################################################################################

    def PLAY(self, col):

        if self.game_over:
            self.popup.open()

        if not self.game_over:

            if (self.turn == 0 and isinstance(self.player1, Player)):

                row = self.board.get_next_open_row(col)
                self.board.drop_piece(row, col, self.player1.color)
                self.list_bords.append(self.board.copy())

                if self.board.winning_move(self.player1.color):
                    print("Player 1 wins!")
                    self.game_over = True

                    self.draw()

                    self.popup.title = "Player 1 wins!"
                    if self.player1.color == RED:
                        self.popup.title_color = [1, .02, .02, 1]
                    else:
                        self.popup.title_color = [1, 1, .05, 1]

                    self.popup.open()

                else:
                    self.draw()

                if isinstance(self.player2, AI): self.turn = 1 - self.turn
                else:
                    self.turn = 1 - self.turn
                    return

                if not self.game_over:
                    self.btn_ai.trigger_action()

            if (self.turn == 1 and isinstance(self.player2, Player)
                    and not self.game_over):

                row = self.board.get_next_open_row(col)
                self.board.drop_piece(row, col, self.player2.color)
                self.list_bords.append(self.board.copy())

                if self.board.winning_move(self.player2.color):
                    print("Player 2 wins!")
                    self.game_over = True

                    self.draw()

                    self.popup.title = "Player 2 wins!"
                    if self.player2.color == RED:
                        self.popup.title_color = [1, .02, .02, 1]
                    else:
                        self.popup.title_color = [1, 1, .05, 1]

                    self.popup.open()

                else:
                    self.draw()
                if isinstance(self.player1, AI): self.turn = 1 - self.turn
                if not self.game_over:
                    self.btn_ai.trigger_action()

        if isinstance(self.player1, Player) and isinstance(
                self.player2, Player):
            self.turn = 1 - self.turn

        return

################################################################################

    def undo(self, obj):

        try:
            del self.list_bords[-1]
            self.board = self.list_bords[-1]
            self.game_over = False
            self.turn = 1 - self.turn
            if  self.turn == 1 and not self.game_over and isinstance(self.player2, AI) or \
                self.turn == 0 and not self.game_over and isinstance(self.player1, AI):

                del self.list_bords[-1]
                self.board = self.list_bords[-1]
                self.game_over = False
                self.turn = 1 - self.turn

        except:
            print('Error undo')
            self.board = Board()
            self.list_bords = [self.board.copy()]
            self.turn = 0
            if isinstance(self.player1, AI):
                self.btn_ai.trigger_action()

        self.draw()

################################################################################

    def zero(self, obj):
        self.PLAY(0)

    def one(self, obj):
        self.PLAY(1)

    def two(self, obj):
        self.PLAY(2)

    def three(self, obj):
        self.PLAY(3)

    def four(self, obj):
        self.PLAY(4)

    def five(self, obj):
        self.PLAY(5)

    def six(self, obj):
        self.PLAY(6)

    ################################################################################

    def ai_vs_player(self, obj):
        self.player1 = AI()
        self.player2 = Player()

    def player_vs_ai(self, obj):
        self.player1 = Player()
        self.player2 = AI()

    def two_players(self, obj):
        self.player1 = Player(color=YELLOW)
        self.player2 = Player(color=RED)

################################################################################

    def yellow(self, obj):
        self.player1.set_color(YELLOW)
        self.player2.set_color(RED)

    def red(self, obj):
        self.player1.set_color(RED)
        self.player2.set_color(YELLOW)

################################################################################

    def set_level_1(self, obj):
        if isinstance(self.player1, AI):
            self.player1.set_level(1)
        if isinstance(self.player2, AI):
            self.player2.set_level(1)

    def set_level_2(self, obj):
        if isinstance(self.player1, AI):
            self.player1.set_level(2)
        if isinstance(self.player2, AI):
            self.player2.set_level(2)

    def set_level_3(self, obj):
        if isinstance(self.player1, AI):
            self.player1.set_level(3)
        if isinstance(self.player2, AI):
            self.player2.set_level(3)

    def set_level_4(self, obj):
        if isinstance(self.player1, AI):
            self.player1.set_level(4)
        if isinstance(self.player2, AI):
            self.player2.set_level(4)

    def set_level_5(self, obj):
        if isinstance(self.player1, AI):
            self.player1.set_level(5)
        if isinstance(self.player2, AI):
            self.player2.set_level(5)
Пример #48
0
 def pop_up(self, header, message):
     popup = Popup(title=header,
                   content=Label(text=message),
                   size_hint=(None, None),
                   size=(400, 400))
     popup.open()
Пример #49
0
class Viewer(Widget):
    '''A button that results in a popup window when pressed. Changing the test within
    the popup menu changes the text on the button'''
    def __init__(self, title, but, Set_Label):

        super(Viewer, self).__init__()

        self.Set_Label = Set_Label
        self.but = but
        self.title = title
        self.Pops = Popup(title=self.title,
                          size_hint=(None, None),
                          size=(300, 150),
                          auto_dismiss=False,
                          pos_hint={
                              'x': .425,
                              'y': .6
                          },
                          separator_color=[0.3, 0.2, 0, 1],
                          title_color=[0.3, 0.2, 0, 1],
                          title_size='20sp')
        #self.Pops.background = 'images/Pop_Background.png'

        self.Pops.bind(on_open=lambda widget: self.FocTxt())
        self.Tex = TextInput(font_size=35, multiline=False)

        self.B = Button(text='Press To Confirm')
        self.B.bind(on_press=lambda widget: self.SubChangeDismiss(
            self.Tex, self.Set_Label, self.Pops))
        self.FL = BoxLayout(orientation='vertical',
                            size_hint_x=1,
                            size_hint_y=1,
                            rows=1)
        self.box1 = BoxLayout(orientation='vertical',
                              size_hint_x=1,
                              size_hint_y=.6,
                              rows=1)
        self.box2 = BoxLayout(orientation='vertical',
                              size_hint_x=1,
                              size_hint_y=.4,
                              rows=1)

        self.Pops.add_widget(self.FL)
        self.FL.add_widget(self.box1)
        self.FL.add_widget(self.box2)
        self.box1.add_widget(self.Tex)
        self.box2.add_widget(self.B)

        self.add_widget(self.Pops)

        self.wasUpdated = 'Hello Peter'

    def SubChangeDismiss(self, Tx, Bt, PP):
        '''When activated, this function changes the text
        of a button to the text of the text input, defocuses
        on the text input box and closes the popup'''
        if Tx.text.strip() == '':
            Bt.text = '0'
        else:
            Bt.text = Tx.text
        Tx.focus = False
        self.wasUpdated = 'hello Chad'
        PP.dismiss()

    def FocTxt(self):
        '''When the popup is opened up, it immediately focuses on the text box.
        This will automatically call keyboards in apple/android devices, plus is
        just convienient'''
        self.Tex.focus = True
        return self.Pops

    '''def build(self):
Пример #50
0
    def build(self):

        self.player1 = Player()
        self.player2 = AI()
        self.board = Board()
        self.list_bords = [self.board.copy()]
        self.turn = 0
        self.game_over = False

        self.root = BoxLayout(orientation='vertical')

        ################################################################################

        self.intro_main_Box = BoxLayout(orientation='vertical')
        self.intro_Box0 = BoxLayout(orientation='vertical', size_hint=(1, .6))
        self.intro_Box1 = BoxLayout(orientation='vertical', size_hint=(1, .2))
        self.intro_Box2 = BoxLayout(orientation='horizontal',
                                    size_hint=(1, .1))
        self.intro_Box3 = BoxLayout(orientation='horizontal',
                                    size_hint=(1, .1))

        self.intro_Box0.add_widget(Image(source='images/start.png'))
        self.intro_main_Box.add_widget(self.intro_Box0)

        self.intro_main_Box.add_widget(self.intro_Box1)

        self.intro_Box2.add_widget(
            Label(text='Choose the number of player(s) : ', size_hint=(.3, 1)))
        self.intro_Box2.add_widget(
            Label(text='Choose the color of the 1st player : ',
                  size_hint=(.32, 1)))
        self.intro_Box2.add_widget(
            Label(text='Choose the level of the ai :', size_hint=(.25, 1)))
        self.intro_Box2.add_widget(Label(text='', size_hint=(.15, 1)))

        self.intro_main_Box.add_widget(self.intro_Box2)
        #####
        self.choice1 = BoxLayout(orientation='horizontal', size_hint=(.3, 1))

        self.btn_ai_vs_player = Button(text='AI vs\nPlayer')
        self.btn_ai_vs_player.bind(on_release=self.ai_vs_player)

        self.btn_player_vs_ai = Button(text='Player\nvs AI')
        self.btn_player_vs_ai.bind(on_release=self.player_vs_ai)

        self.btn_2_players = Button(text='2 Players')
        self.btn_2_players.bind(on_release=self.two_players)

        self.choice1.add_widget(self.btn_ai_vs_player)
        self.choice1.add_widget(self.btn_player_vs_ai)
        self.choice1.add_widget(self.btn_2_players)

        self.intro_Box3.add_widget(self.choice1)
        self.intro_Box3.add_widget(Label(text='', size_hint=(.03, 1)))

        #####
        self.choice2 = BoxLayout(orientation='horizontal', size_hint=(.3, 1))

        self.btn_red = Button(text='Red')
        self.btn_red.bind(on_release=self.red)

        self.btn_yellow = Button(text='Yellow')
        self.btn_yellow.bind(on_release=self.yellow)

        self.choice2.add_widget(self.btn_red)
        self.choice2.add_widget(self.btn_yellow)

        self.intro_Box3.add_widget(self.choice2)
        self.intro_Box3.add_widget(Label(text='', size_hint=(.03, 1)))
        ######
        self.choice3 = BoxLayout(size_hint=(.25, 1))

        self.btn_level_1 = Button(text='1')
        self.btn_level_1.bind(on_release=self.set_level_1)

        self.btn_level_2 = Button(text='2')
        self.btn_level_2.bind(on_release=self.set_level_2)

        self.btn_level_3 = Button(text='3')
        self.btn_level_3.bind(on_release=self.set_level_3)

        self.btn_level_4 = Button(text='4')
        self.btn_level_4.bind(on_release=self.set_level_4)

        self.btn_level_5 = Button(text='5')
        self.btn_level_5.bind(on_release=self.set_level_5)

        self.choice3.add_widget(self.btn_level_1)
        self.choice3.add_widget(self.btn_level_2)
        self.choice3.add_widget(self.btn_level_3)
        self.choice3.add_widget(self.btn_level_4)
        self.choice3.add_widget(self.btn_level_5)

        self.intro_Box3.add_widget(self.choice3)

        self.intro_Box3.add_widget(Label(text='', size_hint=(.05, 1)))

        self.btn_intro = Button(text='Enter', size_hint=(.1, 1))
        self.btn_intro.bind(on_release=self.clear)
        self.intro_Box3.add_widget(self.btn_intro)

        self.intro_main_Box.add_widget(self.intro_Box3)
        self.root.add_widget(self.intro_main_Box)

        ################################################################################

        self.main_Box = BoxLayout(orientation='vertical')
        self.Box1 = BoxLayout(orientation='vertical', size_hint=(1, .9))
        self.Box2 = BoxLayout(orientation='horizontal', size_hint=(1, .1))

        image = Image(source='images/beginning.png')
        self.Box1.add_widget(image)
        self.label = Label(text="Enter a valid column : ", size_hint=(.32, 1))
        self.label2 = Label(text="", size_hint=(.13, 1))
        self.col_input = BoxLayout(orientation='horizontal',
                                   size_hint=(.45, 1))

        ################################################################################

        self.btn_0 = Button(text='1')
        self.btn_0.bind(on_release=self.zero)

        self.btn_1 = Button(text='2')
        self.btn_1.bind(on_release=self.one)

        self.btn_2 = Button(text='3')
        self.btn_2.bind(on_release=self.two)

        self.btn_3 = Button(text='4')
        self.btn_3.bind(on_release=self.three)

        self.btn_4 = Button(text='5')
        self.btn_4.bind(on_release=self.four)

        self.btn_5 = Button(text='6')
        self.btn_5.bind(on_release=self.five)

        self.btn_6 = Button(text='7')
        self.btn_6.bind(on_release=self.six)

        self.col_input.add_widget(self.btn_0)
        self.col_input.add_widget(self.btn_1)
        self.col_input.add_widget(self.btn_2)
        self.col_input.add_widget(self.btn_3)
        self.col_input.add_widget(self.btn_4)
        self.col_input.add_widget(self.btn_5)
        self.col_input.add_widget(self.btn_6)

        self.Box2.add_widget(self.label)
        self.Box2.add_widget(self.col_input)
        self.Box2.add_widget(self.label2)

        ################################################################################

        self.btn_ai = Button(text='AI')
        self.btn_ai.bind(on_release=self.ai_play)

        self.btn_undo = Button(text='undo', size_hint=(.1, 1))
        self.btn_undo.bind(on_release=self.undo)
        self.Box2.add_widget(self.btn_undo)

        self.btn_menu = Button(text='Menu', size_hint=(.1, 1))
        self.btn_menu.bind(on_release=self.menu)
        self.Box2.add_widget(self.btn_menu)

        self.main_Box.add_widget(self.Box1)
        self.main_Box.add_widget(self.Box2)

        ################################################################################

        self.popup_Box = BoxLayout(orientation='vertical')
        self.popup_btn_menu = Button(text='Play again',
                                     font_size='20sp',
                                     background_normal='',
                                     background_color=[.6, .6, .6, 1])
        self.popup_btn_menu.bind(on_release=self.menu)
        self.popup_Box.add_widget(self.popup_btn_menu)

        self.popup = Popup(title='End of party',
                           content=self.popup_Box,
                           auto_dismiss=True,
                           size_hint=(.4, .25),
                           pos_hint={
                               'right': .7,
                               'top': .25
                           },
                           title_size='30sp',
                           separator_color=[.0, .0, .0, 1])

        return self.root
Пример #51
0
from kivy.properties import ObjectProperty
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
import json
import requests

shareEmptyContent = GridLayout(cols=1)
shareEmptyContent.add_widget(
    Label(text='The share input field  cannot be empty.'))
shareEmptyButton = Button(text='OK')
shareEmptyContent.add_widget(shareEmptyButton)
shareEmptyPopup = Popup(title='Empty input Error',
                        content=shareEmptyContent,
                        auto_dismiss=False,
                        size_hint=(.8, .2))
shareEmptyButton.bind(on_press=shareEmptyPopup.dismiss)

maxContent = GridLayout(cols=1)
maxContent.add_widget(
    Label(text='You have gone beyond the max quantity to share this item'))
maxButton = Button(text='OK')
maxContent.add_widget(maxButton)
maxPopup = Popup(title='Exceeded max input Error',
                 content=maxContent,
                 auto_dismiss=False,
                 size_hint=(.8, .2))
maxButton.bind(on_press=maxPopup.dismiss)

typeContent = GridLayout(cols=1)
Пример #52
0
class ZAxisPopupContent(GridLayout):
    done = ObjectProperty(None)

    def initialize(self, zStepSizeVal):
        '''
        
        Initialize the z-axis popup
        
        '''
        self.unitsBtn.text = self.data.units
        self.distBtn.text = str(zStepSizeVal)

    def setDist(self):
        self.popupContent = TouchNumberInput(done=self.dismiss_popup,
                                             data=self.data)
        self._popup = Popup(title="Change increment size of machine movement",
                            content=self.popupContent,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def units(self):
        '''
        
        Toggle the machine units.
        
        '''
        if self.data.units == "INCHES":
            self.data.units = "MM"
            self.distBtn.text = "{0:.2f}".format(25.4 *
                                                 float(self.distBtn.text))
        else:
            self.data.units = "INCHES"

            self.distBtn.text = "{0:.2f}".format(
                float(self.distBtn.text) / 25.4)

        self.unitsBtn.text = self.data.units

    def zIn(self):
        '''
        
        Move the z-axis in
        
        '''
        self.data.gcode_queue.put("G91 G00 Z" +
                                  str(-1 * float(self.distBtn.text)) + " G90 ")

    def zOut(self):
        '''
        
        Move the z-axis out
        
        '''
        self.data.gcode_queue.put("G91 G00 Z" + str(self.distBtn.text) +
                                  " G90 ")

    def zero(self):
        '''
        
        Define the z-axis to be currently at height 0
        
        '''
        self.data.gcode_queue.put("G10 Z0 ")

    def stopZMove(self):
        '''
        
        Send the imediate stop command
        
        '''
        print("z-axis Stopped")
        self.data.quick_queue.put("!")
        with self.data.gcode_queue.mutex:
            self.data.gcode_queue.queue.clear()

    def dismiss_popup(self):
        '''
        
        Close The Pop-up to enter distance information
        
        '''
        try:
            tempfloat = float(self.popupContent.textInput.text)
            self.distBtn.text = str(
                tempfloat
            )  # Update displayed text using standard numeric format
        except:
            pass  #If what was entered cannot be converted to a number, leave the value the same
        self._popup.dismiss()
    def IntConfEthernetIntExecute(self):
        

        #Try statement to ensure that any errors connecting and configuring the device are handled gracefully and the user is informed of what the potential error was using popups
        try:

            #Define the three potential commands as empty variables

            description_command = ''
            duplex_command = ''
            bandwidth_command = ''

            interface = self.ids._Int_Conf_Ethernet_Int_Layout_.ids.InterfaceSelectionLayout.ids.InterfaceTypeSpinnerLayout.ids.InterfaceTypeSpinner.text + ' ' +  self.ids._Int_Conf_Ethernet_Int_Layout_.ids.InterfaceSelectionLayout.ids.InterfaceNumberTextInput.text
            interface_command = "interface " + interface


            #If statement to check if user has selected Transport Method checkbox, if so the command will be created and inserted into the variable. Else the variable will be left blank

            if self.ids._Int_Conf_Ethernet_Int_Function_Select_.ids.DescriptionCheckbox.active == True:

                description_command = 'description ' + self.ids._Int_Conf_Ethernet_Int_Layout_.ids.IntConfEthernetIntDescriptionLayout.ids.EthernetIntDescriptionTextInput.text
            
            else:
                pass



            #If statement to check if user has selected Duplex checkbox, if so the command will be created and inserted into the variable. Else the variable will be left blank

            if self.ids._Int_Conf_Ethernet_Int_Function_Select_.ids.DuplexCheckbox.active == True:
            

                #If statement for handling if a user does not change duplex type or - It will default to Auto

                if self.ids._Int_Conf_Ethernet_Int_Layout_.ids.IntConfEthernetIntDuplexLayout.ids.DuplexTypeSpinner.text == 'Duplex Type':
                    duplex_type = 'Auto'
                else:
                    duplex_type = self.ids._Int_Conf_Ethernet_Int_Layout_.ids.IntConfEthernetIntDuplexLayout.ids.DuplexTypeSpinner.text

                duplex_command = 'duplex ' + duplex_type #Creates the final duplex command

            else:
                pass

            #If statement to check if user has selected Bandwidth checkbox, if so the command will be created and inserted into the variable. Else the variable will be left blank

            if self.ids._Int_Conf_Ethernet_Int_Function_Select_.ids.BandwidthCheckbox.active == True:
            
                bandwidth_command = 'bandwidth ' + self.ids._Int_Conf_Ethernet_Int_Layout_.ids.IntConfEthernetIntBandwidthLayout.ids.BandwidthTextInput.text
            else:
                pass



            #Try statement to ensure the IP address entered is valid. If it is an invalid address the ipaddress module will raise a value error, at which point the user is informed that a valid IP address is required using a popup
            try:

                device_ip_address = self.ids._IPv4_Target_Device_Layout_.ids.IPv4AddressTextInput.text
                ipaddress.ip_address(device_ip_address)

            #ipaddress raises a value error when an invalid IP address is used
            except ValueError:

                Factory.InvalidIPAddressPopup().open() 
                return #Exit from the function


            #If statement to ensure user has entered a username or password
            if App.get_running_app().device_username == '' or App.get_running_app().device_password == '':

                Factory.NoUserOrPassPopup().open() 
                return #Exit from the function

            else:

                device_username = App.get_running_app().device_username
                device_password = App.get_running_app().device_password


            device = { 
              'device_type': 'cisco_ios', 
              'ip': device_ip_address, 
              'username': device_username, 
              'password': device_password, 
              } 

        
            config_commands = [interface_command, description_command, duplex_command, bandwidth_command]
        

            net_connect = ConnectHandler(**device) 

            net_connect.send_config_set(config_commands)

            #Set the password and username back to empty after completion of configuration
            App.get_running_app().device_username = ''
            App.get_running_app().device_password = ''

            #Create and display a popup to inform the user of the successful configuration
            popup = Popup(title='', content=Label(markup = True, text="Successfully configured interface '[b]" +  interface + "[/b]' of device with IP address '[b]" + device_ip_address + "[/b]'"), size_hint =(0.8, 0.3))
            popup.open()

        #Except error to catch when Credentials are incorrect, informs the user of the error using a popup defined in the MainApplication.kv
        except AuthenticationException:

            Factory.NetmikoAuthenticateFailurePopup().open()

        #Except error to catch when Netmiko timeouts and is unable to connect to device, informs the user of the error using a popup defined in the MainApplication.kv
        except NetMikoTimeoutException:

            Factory.NetmikoTimeoutPopup().open()
Пример #54
0
 def show_load(self):
     content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
     self._popup = Popup(title="Load file",
                         content=content,
                         size_hint=(0.9, 0.9))
     self._popup.open()
Пример #55
0
class DatePicker(TextInput):
    """ 
    Date picker is a textinput, if it focused shows popup with calendar
    which allows you to define the popup dimensions using pHint_x, pHint_y, 
    and the pHint lists, for example in kv:
    DatePicker:
        pHint: 0.7,0.4 
    would result in a size_hint of 0.7,0.4 being used to create the popup
    """

    # keep a somewhat-calendar-like aspect ratio: hints will be different
    #  based on screen aspect ratio - calculate at popup time instead of here
    #  in case window has been resized after opening
    pHint_x = NumericProperty(0.7)
    pHint_y = NumericProperty(0.7)
    pHint = ReferenceListProperty(pHint_x, pHint_y)

    def __init__(self, touch_switch=False, *args, **kwargs):
        super(DatePicker, self).__init__(*args, **kwargs)

        self.touch_switch = touch_switch
        self.init_ui()

    def init_ui(self):

        self.text = today_date()
        # Calendar
        self.cal = CalendarWidget(as_popup=True,
                                  touch_switch=self.touch_switch,
                                  dp=self)
        # Popup
        # don't assume that dismiss should update the value; dismiss via escape
        #  should not update the value; explicitly update the value then dismiss
        #  when a date is clicked
        self.popup = Popup(content=self.cal, title="")
        self.cal.parent_popup = self.popup

        self.bind(focus=self.show_popup)

    def show_popup(self, inst, val):
        """ 
        Open popup if textinput focused, 
        and regardless update the popup size_hint 
        """

        self.popup.size_hint = None, None
        self.popup.width = min(Window.width * 0.9, 600)
        self.popup.height = self.popup.width * 0.75  # always use a 4:3 aspect ratio

        if val:
            # Automatically dismiss the keyboard
            # that results from the textInput
            Window.release_all_keyboards()
            self.popup.open()

    def update_value(self, inst):
        """ Update textinput value on popup close """

        #         self.text = "%s-%s-%s" % tuple(self.cal.active_date)
        [d, m, y] = self.cal.active_date
        #         self.text = "%s. %s. %s, %s" % (self.cal.days_abrs[datetime(y,m,d).weekday()],month_abbr[m],d,y)
        self.text = get_date_str(y, m, d)
        self.focus = False
    def IntConfAssignIPv4Execute(self):

        #Try statement to ensure that any errors connecting and configuring the device are handled gracefully and the user is informed of what the potential error was using popups
        try:
        
            interface = self.ids._Int_Conf_Assign_IPv4_Layout_.ids.InterfaceSelectionLayout.ids.InterfaceTypeSpinnerLayout.ids.InterfaceTypeSpinner.text + ' ' +  self.ids._Int_Conf_Assign_IPv4_Layout_.ids.InterfaceSelectionLayout.ids.InterfaceNumberTextInput.text
            ip_address = self.ids._Int_Conf_Assign_IPv4_Layout_.ids.IPv4AndSubnetMaskLayout.ids.IPv4AddressTextInput.text + ' ' +  self.ids._Int_Conf_Assign_IPv4_Layout_.ids.IPv4AndSubnetMaskLayout.ids.SubnetMaskSpinnerLayout.ids.SubnetMaskSpinner.text


            #Try statement to ensure the IP address entered is valid. If it is an invalid address the ipaddress module will raise a value error, at which point the user is informed that a valid IP address is required using a popup
            try:

                device_ip_address = self.ids._IPv4_Target_Device_Layout_.ids.IPv4AddressTextInput.text
                ipaddress.ip_address(device_ip_address)

            #ipaddress raises a value error when an invalid IP address is used
            except ValueError:

                Factory.InvalidIPAddressPopup().open() 
                return #Exit from the function


            #If statement to ensure user has entered a username or password
            if App.get_running_app().device_username == '' or App.get_running_app().device_password == '':

                Factory.NoUserOrPassPopup().open() 
                return #Exit from the function

            else:

                device_username = App.get_running_app().device_username
                device_password = App.get_running_app().device_password


            device = { 
              'device_type': 'cisco_ios', 
              'ip': device_ip_address, 
              'username': device_username, 
              'password': device_password, 
             } 


            config_commands = ["interface " + interface, 'ip address ' + device_ip_address]

            net_connect = ConnectHandler(**device) 

            net_connect.send_config_set(config_commands)

            #Set the password and username back to empty after completion of configuration
            App.get_running_app().device_username = ''
            App.get_running_app().device_password = ''

            #Create and display a popup to inform the user of the successful configuration
            popup = Popup(title='', content=Label(markup = True, text="Successfully set '[b]" +  interface + "[/b]' with an of IP address '[b]" + ip_address + "[/b]'"), size_hint =(0.65, 0.3))
            popup.open()

            
        #Except error to catch when Credentials are incorrect, informs the user of the error using a popup defined in the MainApplication.kv
        except AuthenticationException:

            Factory.NetmikoAuthenticateFailurePopup().open()

        #Except error to catch when Netmiko timeouts and is unable to connect to device, informs the user of the error using a popup defined in the MainApplication.kv
        except NetMikoTimeoutException:

            Factory.NetmikoTimeoutPopup().open()
Пример #57
0
 def _fileInfo(self):
     popup = Popup(title='File Info',content=Label(text=self.fileInfo),size_hint=(None, None), size=(600, 600))
     popup.open()
Пример #58
0
 def _alter(self, msg: str):
     content = Button(text=msg)
     alert = Popup(title="Alert:", content=content, auto_dismiss=False)
     content.bind(on_press=alert.dismiss)
     alert.open()
Пример #59
0
 def _stats(self,suiteName):
     queries = self.controller.getStatsQueries(suiteName,self.databaseLogger.TODAY)
     formatted = self.databaseLogger.computeAndFormatStats(queries)
     popup = Popup(title=suiteName + ' stats for today',content=Label(text=formatted),size_hint=(None, None), size=(600, 600))
     popup.open()
Пример #60
0
class ViViChart(Widget):
    paired_device = StringProperty('No Paired Device')
    n_paired_devices = NumericProperty(0)
    data = ListProperty([])
    recv_stream = ObjectProperty(None)
    #exception = StringProperty(None)
    data_thread = ObjectProperty(None)
    spike_threshold = NumericProperty(None)
    H1 = ListProperty([])
    N1 = ListProperty([])
    
    def __init__(self):
        super(ViViChart, self).__init__()
        graph_theme = {'background_color': 'f8f8f2'}
        self.graph = self.ids.graph
        self.plot = MeshLinePlot(color=[1, 0, 0, 1])
        self.plot.points = []
        self.graph.add_plot(self.plot)
        self.start = time.time()
        
    def discover(self):
        paired_devices = BluetoothAdapter.getDefaultAdapter().getBondedDevices().toArray()
        btns = []
        for device in paired_devices:
            btns.append(Device(text = device.getName()))
        return btns
    
    def search_for_devices(self):
        self.popup=Popup(title='Paired devices', size_hint = [0.8, 0.8],
                         on_open=self.ids.popup2.dismiss)
        btns = self.discover()
        popup_grid = GridLayout(rows = len(btns))
        for btn in btns:        
            popup_grid.add_widget(btn) 
        self.popup.add_widget(popup_grid)
        self.popup.open()
        
    def H1_indices(data, spike_threshold):
        result = []
        for i in xrange(0, len(data)-1):
            if data[i] > spike_threshold and data[i] > data[i - 1] and data[i] >= data[i + 1]:
                result.append(i)
        return numpy.array(result, dtype = int)
    
    # Locate indices for Notch 1 (N1)
    def N1_indices(data, H1):
        result = []
        for i in xrange(0, len(H1) - 1):
            # fist local minimum after H1 as the notch
            pt = next(j for j in xrange(H1[i], H1[i+1]+1) if data[j] <= data[j - 1] and data[j] <= data[j + 1])
            result.append(pt)
        return numpy.array(result, dtype = int)
        
    # Locate indices of P2 peaks
    #def H2_indices(data, H1, N1):
    #    result = []
    #    # in between each spike there is a mini-peak. find it
    #    for i in xrange(0, len(H1)):
    #        # these are subthreshold places where it goes from increasing to decreasing
    #        d = data[H1[i]:N1[i]]
    #        d = signal.savgol_filter(d, 5, 2, 2)
    #        pt = next(j for j in xrange(1,(len(d) - 1)) if d[j-1] >= 0 and d[j+1] <= 0)
    #        result.append(int(range(H1[i],N1[i])[pt]))
    #    return numpy.array(result, dtype = int)
        
    def update(self, outfile, dt):
        
        try:
            BluetoothSocket.isConnected()
        except Exception:
            pass
        else:
            if BluetoothSocket.isConnected() and self.data_thread is None:
                self.data_thread = threading.Thread(target = self.data_logging, args = (outfile,))
                self.data_thread.setDaemon(True)
                self.data_thread.start()
    
                    
        # Plot data in real time
        try:
            self.graph.remove_plot(self.plot)
            #self.data = random.sample(range(0,1024), 300) #mock data
            self.plot.points = zip(range(1, len(self.data)+1), self.data)#[( x, sin(x / 10.)) for x in range(0, int(200*random.random()) )] # This is just some mock data
            self.graph.add_plot(self.plot)
        except Exception:
            pass
        
        try:
            #x = random.sample(xrange(1,100), 10)
            self.spike_threshold = int(numpy.mean(self.data) + numpy.std(self.data))
        except Exception:
            pass
        
        try:
            self.H1 = self.H1_indices(self.data, self.spike_threshold)
        except Exception:
            pass
        
        try:
            self.N1 = self.N1_indices(self.data, self.spike_threshold)
        except Exception:
            pass
        
        
    def data_logging(self, outfile):
        recv_stream = BufferedReader(InputStreamReader(BluetoothSocket.getInputStream()))
        while recv_stream.readLine is not None:
            d = recv_stream.readLine()
            try:
                self.data.append(float(d[:4]))
                self.data = self.data[-300:] #plot the latest 300 data points in real-time
                self.data = numpy.array(self.data)
            except Exception:
                pass
            now = time.time()
            outfile.write(str(now) + "," + str(d)  + "\n")