示例#1
0
 def show_error_dialog(self, errors):
     content = MDLabel(text='\n\n' + '\n'.join(errors),
                       padding=(10, 10),
                       theme_text_color='Error')
     dialog = MDDialog(title='Errors', content=content, size_hint=(.75, .5))
     dialog.add_action_button('close', dialog.dismiss)
     dialog.open()
示例#2
0
def error_pop(matter):
	content = MDLabel(font_style='Body1',theme_text_color='Secondary',text=matter,size_hint_y=None,valign='top')
	content.bind(texture_size=content.setter('size'))
	dialog2 = MDDialog(title="Error",content=content,size_hint=(.8, None),height=dp(200),auto_dismiss=False)
	dialog2.add_action_button("Dismiss",action=lambda *x:dialog2.dismiss())
	dialog2.open()
#This PC\Lenovo K8 Plus\SanDisk SD card\Android\data\org.coursera.android\files\Download
示例#3
0
def dialog(font_style='Body1',
           theme_text_color='Secondary',
           title='Title',
           text='Text',
           valign='top',
           dismiss=True,
           buttons=None,
           ref_callback=None,
           height=dp(200)):
    '''Вывод диалоговых окон.'''

    if buttons is None:
        buttons = []

    content = MDLabel(font_style=font_style,
                      theme_text_color=theme_text_color,
                      text=text,
                      valign=valign,
                      markup=True)
    content.bind(size=content.setter('text_size'))
    if ref_callback:
        content.bind(on_ref_press=ref_callback)

    dialog = MDDialog(title=title,
                      content=content,
                      size_hint=(.8, None),
                      height=height,
                      auto_dismiss=dismiss)

    for list_button in buttons:
        text_button, action_button = list_button
        dialog.add_action_button(text_button, action=action_button)
    dialog.open()

    return dialog
示例#4
0
class RemoveButton(IRightBodyTouch, MDIconButton):
    name = StringProperty()

    def remove_anime_from_list(x, self, anime_to_remove):
        x.parent.parent.parent.remove_widget(x.parent.parent)
        if anime_to_remove in Global.ANIME_CONFIRM_LIST:
            Global.ANIME_CONFIRM_LIST.remove(anime_to_remove)

        self.dismiss()

    def on_release(self):
        anime_to_remove = self.parent.parent.text
        self.dialog3 = MDDialog(title='Are you sure you want to remove ' +
                                anime_to_remove +
                                ' anime from your watchlist?',
                                size_hint=(.8, None),
                                height=dp(150),
                                auto_dismiss=False)

        self.dialog3.add_action_button(
            "Actually....", action=lambda *x: self.dialog3.dismiss())
        self.dialog3.add_action_button(
            "Im Sure!",
            action=lambda *x: self.remove_anime_from_list(
                self.dialog3, anime_to_remove))
        self.dialog3.open()

        pass
示例#5
0
    def set_address_dialog(self):
        def save_apply_address(*args):

            m = re.match(r'([0-9a-zA-Z\.]+):([0-9]+)', addr_field.text)

            if m is not None:
                self.set_scoreboard_address(addr_field.text)
                dialog.dismiss()
            else:
                # don't know what to do
                pass

        addr_field = MDTextField(hint_text='adress:port')
        if self._unformatted_address is not None:
            addr_field.text = self._unformatted_address
        contents = addr_field

        dialog = MDDialog(title='Set Scoreboard Address',
                          content=contents,
                          size_hint=(0.5, 0.5),
                          auto_dismiss=True)

        dialog.add_action_button("Save & Apply", action=save_apply_address)

        dialog.open()
示例#6
0
def dialog(font_style='Body1', theme_text_color='Secondary', title='Title',
           text='Text', valign='top', dismiss=True, buttons=None,
           use_check=False, text_check='', height=300, size_hint=(.85, None),
           ref_callback=None, check_callback=None):
    '''Вывод диалоговых окон.'''

    if buttons is None:
        buttons = []

    text_dialog = MDLabel(
        font_style=font_style, theme_text_color=theme_text_color,
        text=text, valign=valign, markup=True,
        size_hint_y=None
    )
    dialog = MDDialog(
        title=title, content=text_dialog, size_hint=size_hint,
        auto_dismiss=dismiss, height=dp(height)
    )

    text_dialog.bind(texture_size=text_dialog.setter('size'))
    if ref_callback:
        text_dialog.bind(on_ref_press=ref_callback)

    if use_check:
        selection = Selection(text=text_check)
        if check_callback:
            selection.callback = check_callback
        dialog.children[0].children[1].add_widget(selection)

    for list_button in buttons:
        text_button, action_button = list_button
        dialog.add_action_button(text_button, action=action_button)
    dialog.open()

    return dialog
示例#7
0
def conf_pop(dis,but1,action1):
	content = MDLabel(font_style='Body1',theme_text_color='Secondary',text=dis,size_hint_y=None,valign='top')
	content.bind(texture_size=content.setter('size'))
	dialog0 = MDDialog(content=content,size_hint=(.8, None),height=dp(200),auto_dismiss=True)
	dialog0.add_action_button(but1,action= action1)
	dialog0.add_action_button("cancel",action=lambda *x: dialog0.dismiss())
	return dialog0
示例#8
0
class PopList(TwoLineListItem):
    def __init__(self,**kwargs):
        super(PopList,self).__init__(**kwargs)

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            self.pressed = touch.pos
            print(str(self.text))
            content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="{}".format(self.secondary_text),
                          size_hint_y=None,
                          valign='top')
            content.bind(texture_size=content.setter('size'))
            self.dialog = MDDialog(title="{}".format(self.text),
                                   content=content,
                                   size_hint=(.9, None),
                                   height=dp(300),
                                   auto_dismiss=False)

            self.dialog.add_action_button("Dismiss",
                                          action=lambda *x: self.dialog.dismiss())
            self.dialog.open()

        super(PopList, self).on_touch_down(touch)
class CalculatorApp(App):
    theme_cls = ThemeManager()
    theme_cls.theme_style = 'Dark'
    nav_drawer = ObjectProperty()
    
           
    def build(self):
        self.content_widgets = Content()
        return self.content_widgets

    def get_value(self, text):
        self.value = text
        calculator = ComplexCalculator()
       
        result,initial_expression = calculator.calculate(text)
        
        if(result == False):
           self.error_dialog()
        else:
            expression_show = ' '.join([str(elem) for elem in initial_expression ])   
            self.success_dialog(result,expression_show)
    

    def success_dialog(self,result,expression_show):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="Expresion ingresada:  "+str(expression_show),
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="Resultado:  "+str(result),
                               content=content,
                               size_hint=(.8, None),
                               height=100,
                               auto_dismiss=False)

        self.dialog.add_action_button("Cerrar",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        
    def error_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="Error al ingresar la expresión",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="Error",
                               content=content,
                               size_hint=(.8, None),
                               height=100,
                               auto_dismiss=False)

        self.dialog.add_action_button("Cerrar",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
示例#10
0
class DisposalList(MDList):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.refresh_list()

    def refresh_list(self):
        #обновление списка задач
        try:
            res = GetResult('getDisposalList', {'readed': 0}, [
                'Number', 'Theme', 'ShortTask', 'Sender_id', 'Receiver_id',
                'Task', 'isExecute'
            ])

            for i in res:
                # текст задачи
                if i[2] != '':
                    disposal_text = i[2]
                else:
                    disposal_text = 'ПУСТО'
                # иконка выполнения
                if i[6] == '0':
                    icon_text = 'clock'
                else:
                    icon_text = 'calendar-check'

                # номер + тема задачи
                theme_text = (i[0] + ' ' + i[1])
                if len(theme_text) > 30:
                    theme_text = theme_text[:27] + '...'

                item = DisposalItem(text=theme_text,
                                    secondary_text=disposal_text,
                                    icon_text=icon_text,
                                    data=i)
                self.add_widget(item)
        except:
            #сообщение об ошибке
            content = MDLabel(font_style='Body1',
                              text='Не подключения, проверьте настройки!',
                              size_hint_y=None,
                              valign='top')
            content.bind(texture_size=content.setter('size'))
            self.dialog = MDDialog(title="Внимание",
                                   content=content,
                                   size_hint=(.8, None),
                                   height=dp(200))

            self.dialog.add_action_button(
                "ОК", action=lambda *x: self.dialog.dismiss())
            self.dialog.open()
示例#11
0
 def create_list_dialog(title, items, on_selected_item):
     """
     Creates a dialog from given title and list.
     items is a list of BaseListItem objects.
     """
     # select_list = PWSelectList(items=items, on_release=on_release)
     select_list = PWSelectList(items=items)
     select_list.bind(selected_item=on_selected_item)
     content = select_list
     dialog = MDDialog(title=title, content=content, size_hint=(.9, .9))
     # workaround for MDDialog container size (too small by default)
     dialog.ids.container.size_hint_y = 1
     # close the dialog as we select the element
     select_list.bind(
         selected_item=lambda instance, value: dialog.dismiss())
     dialog.add_action_button("Dismiss", action=lambda *x: dialog.dismiss())
     return dialog
示例#12
0
 def prompt_password_dialog(self):
     """
     Prompt the password dialog.
     """
     title = "Enter your password"
     content = PasswordForm()
     dialog = MDDialog(title=title,
                       content=content,
                       size_hint=(.8, None),
                       height=dp(250),
                       auto_dismiss=False)
     # workaround for MDDialog container size (too small by default)
     dialog.ids.container.size_hint_y = 1
     dialog.add_action_button(
         "Unlock",
         action=lambda *x: self.on_unlock_clicked(dialog, content.password))
     return dialog
示例#13
0
def dialog(font_style='Body1',
           theme_text_color='Secondary',
           title='Title',
           text='Text',
           valign='top',
           dismiss=True,
           buttons=None,
           use_check=False,
           text_check='',
           height=300,
           size_hint=(.85, None),
           ref_callback=None,
           check_callback=None):
    '''Вывод диалоговых окон.'''

    if buttons is None:
        buttons = []

    text_dialog = MDLabel(font_style=font_style,
                          theme_text_color=theme_text_color,
                          text=text,
                          valign=valign,
                          markup=True,
                          size_hint_y=None)
    dialog = MDDialog(title=title,
                      content=text_dialog,
                      size_hint=size_hint,
                      auto_dismiss=dismiss,
                      height=dp(height))

    text_dialog.bind(texture_size=text_dialog.setter('size'))
    if ref_callback:
        text_dialog.bind(on_ref_press=ref_callback)

    if use_check:
        selection = Selection(text=text_check)
        if check_callback:
            selection.callback = check_callback
        dialog.children[0].children[1].add_widget(selection)

    for list_button in buttons:
        text_button, action_button = list_button
        dialog.add_action_button(text_button, action=action_button)
    dialog.open()

    return dialog
示例#14
0
class TelaVisualizarContato(Screen):
    cheaderwidget = ObjectProperty()
    contato = ObjectProperty()

    def __init__(self, contato_id, **kwargs):
        self.app = App.get_running_app()
        self.contato = ContatoModel[contato_id]

        super(TelaVisualizarContato, self).__init__(**kwargs)

    def on_pre_enter(self, *args):
        toolbar = self.app.root.ids['toolbar']
        toolbar.title = s.perfil.capitalize()
        toolbar.left_action_items = [[
            'arrow-left',
            lambda x: self.app.root.switch_to(TELAS.LISTA_CONTATO)
        ]]
        toolbar.right_action_items = [[
            'delete', lambda x: self.delete_contact()
        ]]

    def delete_contact(self):
        content = MDLabel(
            text=
            "Tem certeza que quer excluir este contato?\nEsta ação não tem retorno.",
            font_style='Caption',
            size_hint_y=None,
            valign='center')
        self.dialog = MDDialog(title="Excluir Contato.",
                               content=content,
                               size_hint=(0.8, None),
                               height=dp(300),
                               auto_dismiss=True)
        self.dialog.add_action_button("Confirmar",
                                      action=lambda *x: self.confirm_delete())
        self.dialog.add_action_button("Cancelar",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def confirm_delete(self):
        self.dialog.dismiss()
        db(ContatoModel.id == self.contato.id).delete()
        self.app.root.switch_to(TELAS.LISTA_CONTATO)
示例#15
0
 def create_dialog(title, body):
     """
     Creates a dialog from given title and body.
     Adds it to the dialogs track list.
     """
     content = MDLabel(font_style='Body1',
                       theme_text_color='Secondary',
                       text=body,
                       size_hint_y=None,
                       valign='top')
     content.bind(texture_size=content.setter('size'))
     dialog = MDDialog(title=title,
                       content=content,
                       size_hint=(.8, None),
                       height=dp(200),
                       auto_dismiss=False)
     dialog.add_action_button("Dismiss", action=lambda *x: dialog.dismiss())
     dialog.bind(on_dismiss=Controller.on_dialog_dismiss)
     Controller.dialogs.append(dialog)
     return dialog
示例#16
0
class BodyScanApp(App):
	theme_cls = ThemeManager()
	nav_drawer = ObjectProperty()
	username = StringProperty("")
	rights = StringProperty("")

	def showAddUserdialog(self):
		content = AddUserContent()
		self.dialog = MDDialog(title="Add Friend/Coach",
								content=content,
								size_hint=(.8, None),
								height=dp(200),
								auto_dismiss=False)
		self.dialog.add_action_button("Dismiss",
										action=lambda
										*x: self.dialog.dismiss())
		self.dialog.open()

	def build(self):
		self.nav_drawer = BodyScanNavDrawer()
		self.theme_cls.primary_palette = "Blue"
		self.theme_cls.primary_hue = "500"
示例#17
0
class QuoteButton(TwoLineListItem):
    def __init__(self, **kwargs):
        super(QuoteButton, self).__init__(**kwargs)

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            self.pressed = touch.pos
            if touch.is_double_tap:
                print('doouble')
            else:
                content = MDLabel(font_style='Body1',
                                  theme_text_color='Secondary',
                                  text="{}".format(self.secondary_text),
                                  valign='top')

                content.bind(size=content.setter('text_size'))
                self.dialog = MDDialog(title="{}".format(self.text),
                                       content=content,
                                       size_hint=(.9, None),
                                       height=dp(200),
                                       auto_dismiss=False)

                self.dialog.add_action_button(
                    "Dismiss", action=lambda *x: self.dialog.dismiss())
                self.dialog.add_action_button("Share",
                                              action=lambda *x: self.share())
                self.dialog.open()
        super(QuoteButton, self).on_touch_down(touch)

    def share(self):
        print 'sharing'
        intent = Intent()
        intent.setAction(Intent.ACTION_SEND)
        intent.putExtra(Intent.EXTRA_TEXT,
                        String('{}'.format(self.secondary_text)))
        intent.setType('text/plain')
        chooser = Intent.createChooser(intent, String('Share...'))
        PythonActivity.mActivity.startActivity(chooser)
示例#18
0
class AddCommentButton(MDFloatingActionButton):

    def commit(self):
        if self.dialog.content.text.strip() != "":
            GetResult('SendComment', {'disposal_id': int(self.parent.parent.ids.number.text), 'comment': self.dialog.content.text.strip()}, [])
            self.dialog.dismiss()
            self.parent.parent.load_comments()

    def on_press(self):
        content = MDTextField()
        content.multiline = True
        content.hint_text = "Введите комментарий"
        content.focus = True
        self.dialog = MDDialog(title="Новый комментарий",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(400))

        self.dialog.add_action_button("Сохранить",
                                      action=lambda *x: self.commit())
        self.dialog.add_action_button("Отмена",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
示例#19
0
def card_with_buttons(content,
                      title=None,
                      background_color=None,
                      size=(.7, .5),
                      buttons=None):
    '''Вывод диалоговых окон с кастомным контентом.'''

    if not background_color:
        background_color = [1.0, 1.0, 1.0, 1]

    card = MDDialog(size_hint=(1, 1),
                    padding=5,
                    background_color=background_color)

    if title:
        box = BoxLayout(orientation='vertical', padding=dp(8))
        box.add_widget(
            MDLabel(text=title,
                    theme_text_color='Secondary',
                    font_style="Title",
                    size_hint_y=None,
                    height=dp(36)))
        box.add_widget(MDSeparator(height=dp(1)))
        box.add_widget(content)
        card.add_widget(box)
    else:
        card.add_widget(content)

    for list_button in buttons:
        text_button, action_button = list_button
        card.add_action_button(text_button, action=action_button)

    dialog = ModalView(size_hint=size, background_color=[0, 0, 0, .2])
    dialog.add_widget(card)
    dialog.open()

    return dialog
示例#20
0
class MyApp(App):
    theme_cls = ThemeManager()
    nav_drawer = ObjectProperty()

    def build(self):
        print('here we start')
        # self.theme_cls.theme_style = 'Dark'
        # self.show_example_dialog()
        # self.show_menu()
        return RootScreen()

    def test(self):
        print('here we go')

    def show_menu(self):
        self.nav_drawer = MyNavDrawer()
        self.nav_drawer.toggle()

    def show_example_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="This is a dialog with a title and some text. "
                               "That's pretty awesome right!",
                          valign='top')

        content.bind(size=content.setter('text_size'))
        self.dialog = MDDialog(title="This is a pretty dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda
                                          *x: self.dialog.dismiss())
        self.dialog.open()
示例#21
0
    def assign_game_id_dialog(self):
        def apply_game_id(*args):
            # do apply
            gid = id_field.text

            # do some processing
            if len(id_field.text) == 0:
                return

            self.assign_game_user_id(gid)
            dialog.dismiss()

        id_field = MDTextField(hint_text='Identifier')

        if self._user_id is not None:
            id_field.text = self._user_id

        dialog = MDDialog(title='Set Game Identifier',
                          content=id_field,
                          size_hint=(0.5, 0.5),
                          auto_dismiss=True)
        dialog.add_action_button('Apply', action=apply_game_id)

        dialog.open()
示例#22
0
class mainapp(BoxLayout):
    def __init__(self, **kwargs):
        BoxLayout.__init__(self, **kwargs)
        self.orientation = "vertical"
        self.numpad = Builder.load_string(calc)
        self.add_widget(self.numpad)

        #Buttons
        self.out = self.numpad.ids['out']
        self.rout = self.numpad.ids['real_time_update']
        self.rout_2 = self.numpad.ids['real_time_update_2']
        self.delbutton = self.numpad.ids['cancel_but']
        self.equalbutton = self.numpad.ids['equal_but']
        self.differnbutton = self.numpad.ids['differentiate']
        self.integrabutton = self.numpad.ids['integrate']
        self.simplifybutton = self.numpad.ids['simplify']
        self.factorisebutton = self.numpad.ids['factorise']
        self.expandbutton = self.numpad.ids['expand']
        self.fractog = self.numpad.ids['fractog']
        self.solvebutton = self.numpad.ids['solve']

        #Binds
        self.delbutton.bind(on_release=self.delholdclr, on_press=self.delbut)
        self.equalbutton.bind(on_release=self.equal_call)
        self.differnbutton.bind(on_release=self.differentiate)
        self.integrabutton.bind(on_release=self.integral)
        self.simplifybutton.bind(on_release=self.simplify)
        self.factorisebutton.bind(on_release=self.factorise)
        self.expandbutton.bind(on_release=self.expand)
        self.out.bind(text=self.rout_update)
        self.rout_2.bind(text=self.rout_update)
        self.fractog.bind(active=self.rout_update)
        self.solvebutton.bind(on_release=self.solver)

        #Clock
        Clock.schedule_interval(self.outputloop, 0)

        # Coloring
        self.numpad.ids['arrow'].md_bg_color = (0.1, 0, 0, 0.1)

        for x in self.numpad.ids['basic_buts'].children:
            x.md_bg_color = (1, 0, 0, 0.2)

        for x in self.numpad.ids['functions_but'].children:
            x.md_bg_color = (0.1, 0, 0, 0.2)

        self.numpad.ids['inv'].md_bg_color = (0, 0.5, 0.5, 0.2)

        for x in self.numpad.ids['inv_tri'].children:
            x.md_bg_color = (0, 0.5, 0.5, 0.2)

        self.numpad.ids['back'].md_bg_color = (0.1, 0, 0, 0.2)

        # init() of matrix
        self.mat_init()

        # init() of limit
        self.limit_init()

        # extras
        self.pretex = '..'
        self.expr = 0

    def outputloop(self, dt):
        tex = self.out.text
        if tex == '':
            tex = '0'

        elif len(tex) > 1 and tex[:1] == '0':
            tex = tex[1:]
        self.out.text = tex

    def delbut(self, ins):
        tex = self.out.text
        tex = tex[:-1]
        self.out.text = tex
        Clock.schedule_once(self.clearall, 1)

    def clearall(self, ins):
        self.out.text = '0'

    def delholdclr(self, ins):
        Clock.unschedule(self.clearall)

    def equal_call(self, ins, out=None):
        if out == None:
            self.ou = self.out
        else:
            self.ou = out
        special_expr = False
        final_expr_str = self.out.text.replace('^', '**')
        try:
            expr = sympy.N(
                parse_expr(final_expr_str, transformations=transformations))
            try:
                expr = float(expr)
            except:
                pass

            if expr != expr.doit():
                self.out.text = str(expr.doit())
                spx = str(expr) + " = " + str(expr.doit())
                special_expr = 'Eq(' + str(expr) + ', ' + str(
                    expr.doit()) + ')'
                if sympy.sympify(special_expr) == True:
                    special_expr = False
                print("special expr", special_expr)
                self.out.text = str(expr.doit())
            self.expr = expr
        except Exception as e:
            print(e)
            expr = final_expr_str
        try:
            tex = str(eval(str(expr)))
        except:
            tex = expr
        if out == None:
            self.ou.text = str(tex).replace('**', '^')
        else:
            self.ou.text = str(tex)
            if special_expr:
                self.ou.text = special_expr
        self.out.text = self.out.text.replace('**', '^')

    def equalcall_old(self, ins, out=None):
        try:
            expr = N(
                parse_expr(self.out.text,
                           transformations=transformations,
                           evaluate=True))
            tex = str(expr)
            self.out.text = tex
        except:
            pass

    def rout_update(self, *args):
        exprg = self.expgen()
        if exprg != False:
            newtext = sympy.pretty(self.expgen())
            self.rout.text = newtext

    def differentiate(self, ins):
        try:
            expr = self.expgen()
            diff_expr = diff(expr, x)
            self.finaloutstr(diff_expr)

        except Exception as e:
            print(e)

    def integral(self, ins):
        try:
            expr = self.expgen()
            int_expr = integrate(expr, x)
            self.finaloutstr(int_expr)

        except Exception as e:
            print(e)

    def simplify(self, ins):
        try:
            expr = self.expgen()
            simplified_expr = simplify(expr)
            self.finaloutstr(simplified_expr)

        except Exception as e:
            print(e)

    def factorise(self, ins):
        try:
            expr = self.expgen()
            simplified_expr = sympy.factor(expr)
            self.finaloutstr(simplified_expr)

        except Exception as e:
            print(e)

    def expand(self, ins):
        try:
            expr = self.expgen()
            expand_expr = sympy.expand(expr)
            self.finaloutstr(expand_expr)

        except Exception as e:
            print(e)
            print(self.rout.text)

    def expgen(self):
        try:
            final_expr_str = self.out.text.replace('^', '**')
            if not self.fractog.active:
                expr = N(
                    parse_expr(final_expr_str,
                               transformations=transformations))
            else:
                expr = (parse_expr(final_expr_str,
                                   transformations=transformations))

            print("Generated Expr ", expr)
            return expr

        except Exception as e:
            print("Expression generated Error! \n", e)
            return False

    def finaloutstr(self, expr):
        tmps = str(expr)
        tmps.replace('**', '^').replace('(pi/180)', u'\u00b0')
        print(tmps)
        self.out.text = tmps
        self.equalcall(None)

    def solver(self, *args):
        try:
            expr = self.expgen()
            Logger.info(expr)
            eq = sympy.Eq(expr, 0, evaluate=False)
            finalcc = '\n\nExpression : \n' + sympy.pretty(eq)

            for symbol in list(expr.atoms(sympy.Symbol)):
                Logger.info(symbol)
                os.environ['dbg'] = '1'

                solved = sympy.solveset(eq, symbol)
                os.environ['dbg'] = '0'

                Logger.info(solved)
                solved_pretty = sympy.pretty(solved,
                                             use_unicode=True,
                                             num_columns=4000)
                top_content = '\n \n Solution for ' + str(symbol) + ':\n\n'
                finalc = (top_content + solved_pretty)
                try:
                    finalc.encode('utf-8')
                except:
                    pass
                finally:
                    print(finalc)
                print('creating button')
                finalcc += finalc
            self.make_dialog('Solve', finalcc)
            print('button created')

        except Exception as e:
            print(e)

    def make_dialog(self, title, finalc):
        content = Button(text=finalc,
                         padding=(0, 0),
                         font_name='Hack-Regular',
                         halign='left',
                         size_hint=(None, None),
                         color=[0, 0, 0, 1],
                         background_normal='./transparent.png',
                         background_down='./transparent.png')
        content.bind(size=lambda x, y: Logger.info(y))
        content.bind(
            texture_size=lambda obj, t: content.setter('size')(obj, t))
        bx = ScrollView(size_hint=(1, None),
                        size=(Window.width * 0.7, Window.height * 0.6))
        bx.add_widget(content)
        bx.bind(size=lambda obj, x: Logger.info(x))
        self.dialog = MDDialog(title=title, content=bx, size_hint=(0.8, 0.8))
        self.dialog.add_action_button('Dismiss',
                                      lambda *args: self.dialog.dismiss())
        self.dialog.open()

    ## MATRIX

    def mat_init(self):
        self.rows = self.numpad.ids['row']
        self.rows_2 = self.numpad.ids['row2']
        self.columns = self.numpad.ids['col']
        self.columns_2 = self.numpad.ids['col2']
        self.matrixgrid = self.numpad.ids['matrix_grid']
        self.matrixgrid2 = self.numpad.ids['matrix_grid_2']
        self.rrefbut = self.numpad.ids['rref']
        self.matrixmenu = self.numpad.ids['Matrix_menu']

        self.rrefbut.bind(on_release=self.rref_call)
        self.rows.bind(on_release=self.matup1)
        self.columns.bind(on_release=self.matup1)
        self.rows_2.bind(on_release=self.matup2)
        self.columns_2.bind(on_release=self.matup2)
        self.matupdate(1)
        self.matupdate(no=2)

        self.matrixgrid.bind(minimum_height=self.matrixgrid.setter('height'))
        self.matrixgrid2.bind(minimum_height=self.matrixgrid2.setter('height'))

        self.matrix1 = self.matrix2 = None

    def matup1(self, *args):
        self.matupdate(1)

    def matup2(self, *args):
        self.matupdate(no=2)

    def matupdate(self, no, *args):
        try:
            if no == 1:
                self.matrixgrid.cols = int(self.columns.text)
                self.matgridform(rows=int(self.rows.text),
                                 cols=int(self.columns.text),
                                 matgrid=self.matrixgrid)

            elif no == 2:
                self.matrixgrid2.cols = int(self.columns_2.text)
                self.matgridform(rows=int(self.rows_2.text),
                                 cols=int(self.columns_2.text),
                                 matgrid=self.matrixgrid2)

        except:
            pass

    def matgridform(self, rows, cols, matgrid):
        try:
            if len(matgrid.children) > rows * cols:
                for x in range((len(matgrid.children)) - rows * cols):
                    matgrid.remove_widget(matgrid.children[-1])

            else:
                for x in range(rows * cols - (len(matgrid.children))):
                    matgrid.add_widget(self.matblock())

        except Exception as e:
            print(e)

    def matblock(self):
        b = MDTextField(text='0', hint_text='0', padding_x=20)
        b.bind(text=self.checktext)

        return b

    def checktext(self, obj, text):
        if text == '':
            obj.text = '0'

        elif len(text) > 1 and text[:1] == '0':
            obj.text = text[1:]

    def make_matrix(self, cols, matgrid, mat):
        try:
            mat_list = []
            tmpl = []
            for x in matgrid.children:
                print(x.text)
                tmpl.append(
                    parse_expr(str(x.text), transformations=transformations))
            tmpl = tmpl[::-1]
            Logger.info(tmpl)
            try:
                mat_list = [
                    tmpl[i:i + cols] for i in xrange(0, len(tmpl), cols)
                ]
                print(mat_list)

            except:
                mat_list = [
                    tmpl[i:i + cols] for i in range(0, len(tmpl), cols)
                ]
                print(mat_list)

            mat = sympy.Matrix(mat_list)
            Logger.info(mat_list)
            print(mat_list)
            return mat

        except Exception as e:
            Logger.error(e)
            print(e)
            return False

    def rref_call(self, matno=1, *args):
        if matno == 2:
            matrix = self.matrix2
            matgrid = self.matrixgrid2
            cols = int(self.columns_2.text)

        else:
            matrix = self.matrix1
            matgrid = self.matrixgrid
            cols = int(self.columns.text)

        for x in matgrid.children:
            print(x.text)

        matrix = self.make_matrix(cols=cols, matgrid=matgrid, mat=matrix)
        print(matrix)
        if matrix == None or matrix == False:
            return

        rref = matrix.rref()[0]
        count = 0
        for x in matgrid.children:
            count -= 1
            x.text = str(rref[count])

        self.make_dialog(title='RREF',
                         finalc=sympy.pretty(sympy.Eq(matrix,
                                                      rref,
                                                      evaluate=False),
                                             use_unicode=True))

    ## LIMIT

    def limit_init(self):
        self.func = self.numpad.ids['f(x)']
        self.x0 = self.numpad.ids['X0']
        self.Sign = self.numpad.ids['sign']
        self.doit = self.numpad.ids['do_it']
示例#23
0
class ImportSearchTable2(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    data_object = ImportDetail()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 4
    _data = None

    search_result = data_object.get_import_details()

    _filter_import_id = False
    _filter_product_id = False
    _product_id_search = " AND product_id = {} "
    _filter_quantity = False
    _quantity_search = " AND quantity LIKE {} "
    _filter_unitprice = False
    _unitprice_search = " AND unitprice LIKE {} "

    def __init__(self, **kwargs):
        super(ImportSearchTable2, self).__init__(**kwargs)
        self.pagination_next()
        self.call_load()
        try:
            self.k_id = sorted([int(x) for x in self._data])[-1] + 1
            print self.parent
        except:
            print "Error"

    def activate_import_id(self, state):
        if state == 'down':
            self._filter_import_id = True
        else:
            self._filter_import_id = False
            self.search_result = self.data_object.get_import_details()
            self.pagination_next()

    def activate_product_id(self, state):
        if state == 'down':
            self._filter_product_id = True
        else:
            self._filter_product_id = False

    def activate_quantity(self, state):
        if state == 'down':
            self._filter_quantity = True
        else:
            self._filter_quantity = False

    def activate_unitprice(self, state):
        if state == 'down':
            self._filter_unitprice = True
        else:
            self._filter_unitprice = False

    def filter(self, import_import_search_id_text, import_product_search_id,
               import_search_quantity, import_search_unit_price):
        if self._filter_import_id:
            if import_import_search_id_text != '':
                self.sql = "SELECT * FROM import_details WHERE import_id = {} ".format(
                    import_import_search_id_text)
            else:
                self.sql = "SELECT * FROM import_details WHERE import_id LIKE '%%' "
            if self._filter_product_id and import_product_search_id != '':
                self.sql += self._product_id_search.format(
                    import_product_search_id)
            if self._filter_quantity and import_search_quantity != '':
                self.sql += self._quantity_search.format(
                    import_search_quantity)
            if self._filter_unitprice and import_search_unit_price != '':
                self.sql += self._unitprice_search.format(
                    import_search_unit_price)
            s = self.data_object.execute(self.sql)
            name = dict()
            for val in s:
                name[val['import_id']] = val
            self.search_result = name
        else:
            self.search_result = self.data_object.get_import_details()

        self.pagination_next()

    def delete_data(self, id):
        try:
            self.data_object.import_id = id
            self.data_object.delete_import_detail()
            self.pagination_next(self.current)
        except KeyError:
            Snackbar(text=" Key Not Found ").show()
        except _mysql_exceptions.IntegrityError:
            Snackbar(
                text=
                "Cannot delete or update a parent row: a foreign key constraint fails"
            ).show()

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def calc_pages(self, pages, num_pages, num_page):
        pages_dict = dict()
        pages_lens = list()
        num = 0
        while num <= len(self.pages):
            pages_lens.append(num)
            num = num + self.offset
        pages_lens.append(len(self.pages))
        for num in range(0, num_pages):
            pages_dict[num + 1] = pages[pages_lens[num]:pages_lens[num + 1]]
        page_count = len(pages_dict.keys())
        return num_page, page_count, pages_dict[num_page]

    def pagination_next(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == page_count:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == 1:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        import_data_object = Import()
        import_data_dict = import_data_object.get_imports()
        product_data_object = Product()
        product_data_dict = product_data_object.get_products()
        # print product_data_dict
        # print self._data
        for key in self._data:

            id = str(self.search_result.get(key)['id'])
            import_id = import_data_dict.get(
                str(self.search_result.get(key)
                    ['import_id']))['receipt_number']
            product_id = product_data_dict.get(
                str(self.search_result.get(key)['product_id']))['brandname']
            # print str(self.data_object.get_import_details().get(key)['product_id']) , "=>" , product_id
            quantity = str(self.search_result.get(key)['quantity'])
            unitprice = str(self.search_result.get(key)['unitprice'])

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=import_id))
            self.d.add_widget(DataLabel(text=product_id))
            self.d.add_widget(DataLabel(text=quantity))
            self.d.add_widget(DataLabel(text=unitprice))
            self.d.add_widget(option)

            super(ImportSearchTable2, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, import_id, product_id, quantity, unitprice):
        self.data_object.id = id
        self.data_object.import_id = import_id
        self.data_object.product_id = product_id
        self.data_object.quantity = quantity
        self.data_object.status = unitprice
        self.data_object.update_import_detail()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        import_id = str(
            self.data_object.get_import_details().get(id)['import_id'])
        product_id = str(
            self.data_object.get_import_details().get(id)['product_id'])
        quantity = str(
            self.data_object.get_import_details().get(id)['quantity'])
        unitprice = str(
            self.data_object.get_import_details().get(id)['unitprice'])
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        imp_id = DialogTextInput(import_id)
        prod_id = DialogTextInput(product_id)
        qty = DialogTextInput(quantity)
        uprice = DialogTextInput(unitprice)

        b.add_widget(
            MDLabel(id='destination',
                    text="Import ID",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(imp_id)
        b.add_widget(MDLabel(text="Product ID", size_hint_x=None,
                             width="90px"))
        b.add_widget(prod_id)
        b.add_widget(
            MDLabel(id='date', text="Quantity", size_hint_x=None,
                    width="90px"))
        b.add_widget(qty)
        b.add_widget(
            MDLabel(id='date',
                    text="Unit Price",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(uprice)

        self.dialog = MDDialog(title="Update Import",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save",
            action=lambda *x: self.save_edited_data(
                id, imp_id.text, prod_id.text, qty.text, uprice.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
示例#24
0
class KitchenSink(App):
    theme_cls = ThemeManager()
    previous_date = ObjectProperty()
    title = "KivyMD Kitchen Sink"

    menu_items = [
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
    ]

    def build(self):
        main_widget = Builder.load_string(main_widget_kv)
        # self.theme_cls.theme_style = 'Dark'

        main_widget.ids.text_field_error.bind(
            on_text_validate=self.set_error_message,
            on_focus=self.set_error_message)
        self.bottom_navigation_remove_mobile(main_widget)
        return main_widget

    def bottom_navigation_remove_mobile(self, widget):
        # Removes some items from bottom-navigation demo when on mobile
        if DEVICE_TYPE == 'mobile':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_2)
        if DEVICE_TYPE == 'mobile' or DEVICE_TYPE == 'tablet':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_1)

    def show_example_snackbar(self, snack_type):
        if snack_type == 'simple':
            Snackbar(text="This is a snackbar!").show()
        elif snack_type == 'button':
            Snackbar(text="This is a snackbar",
                     button_text="with a button!",
                     button_callback=lambda *args: 2).show()
        elif snack_type == 'verylong':
            Snackbar(
                text=
                "This is a very very very very very very very long snackbar!"
            ).show()

    def show_example_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="This is a dialog with a title and some text. "
                          "That's pretty awesome right!",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="This is a test dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def show_example_long_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="Lorem ipsum dolor sit amet, consectetur "
                          "adipiscing elit, sed do eiusmod tempor "
                          "incididunt ut labore et dolore magna aliqua. "
                          "Ut enim ad minim veniam, quis nostrud "
                          "exercitation ullamco laboris nisi ut aliquip "
                          "ex ea commodo consequat. Duis aute irure "
                          "dolor in reprehenderit in voluptate velit "
                          "esse cillum dolore eu fugiat nulla pariatur. "
                          "Excepteur sint occaecat cupidatat non "
                          "proident, sunt in culpa qui officia deserunt "
                          "mollit anim id est laborum.",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="This is a long test dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def get_time_picker_data(self, instance, time):
        self.root.ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        self.time_dialog = MDTimePicker()
        self.time_dialog.bind(time=self.get_time_picker_data)
        if self.root.ids.time_picker_use_previous_time.active:
            try:
                self.time_dialog.set_time(self.previous_time)
            except AttributeError:
                pass
        self.time_dialog.open()

    def set_previous_date(self, date_obj):
        self.previous_date = date_obj
        self.root.ids.date_picker_label.text = str(date_obj)

    def show_example_date_picker(self):
        if self.root.ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

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

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

    def set_error_message(self, *args):
        if len(self.root.ids.text_field_error.text) == 2:
            self.root.ids.text_field_error.error = True
        else:
            self.root.ids.text_field_error.error = False

    def on_pause(self):
        return True

    def on_stop(self):
        pass
示例#25
0
class ImportSearchTable1(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    data_object = Import()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 4
    _data = None

    _filter_date = False
    _date_search = " AND date LIKE '%{}%' "
    _filter_status = False
    _status_search = " AND status LIKE '%{}%' "
    _filter_supplier_id = False
    _supplier_id_search = " AND supplier_id = {} "

    search_result = dict()

    def __init__(self, **kwargs):
        super(ImportSearchTable1, self).__init__(**kwargs)
        self.pagination_next()
        self.call_load()

    def activate_date(self, state):
        if state == 'down':
            self._filter_date = True
        else:
            self._filter_date = False

    def activate_status(self, state):
        if state == 'down':
            self._filter_status = True
        else:
            self._filter_status = False

    def activate_supplier_id(self, state):
        if state == 'down':
            self._filter_supplier_id = True
        else:
            self._filter_supplier_id = False

    def filter(self, import_receipt_search_number, imports_search_date_label,
               import_supplier_search_id, import_search_status):
        self.sql = "SELECT * FROM imports WHERE receipt_number LIKE '%{}%' ".format(
            import_receipt_search_number)

        if self._filter_date:
            self.sql += self._date_search.format(imports_search_date_label)

        if self._filter_supplier_id:
            self.sql += self._supplier_id_search.format(
                import_supplier_search_id)

        if self._filter_status:
            self.sql += self._status_search.format(import_search_status)

        s = self.data_object.execute(self.sql)
        name = dict()
        for val in s:
            name[val['receipt_number']] = val
        self.search_result = name
        self.pagination_next()

    def delete_data(self, id):
        try:
            self.data_object.id = id
            self.data_object.delete_import()
            self.pagination_next(self.current)
        except KeyError:
            Snackbar(text=" Key Not Found ").show()
        except _mysql_exceptions.IntegrityError:
            Snackbar(
                text=
                "Cannot delete or update a parent row: a foreign key constraint fails"
            ).show()

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def calc_pages(self, pages, num_pages, num_page):
        pages_dict = dict()
        pages_lens = list()
        num = 0
        while num <= len(self.pages):
            pages_lens.append(num)
            num = num + self.offset
        pages_lens.append(len(self.pages))
        for num in range(0, num_pages):
            pages_dict[num + 1] = pages[pages_lens[num]:pages_lens[num + 1]]
        page_count = len(pages_dict.keys())
        return num_page, page_count, pages_dict[num_page]

    def pagination_next(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == page_count:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == 1:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        data_object = Supplier()
        data_dict = data_object.get_suppliers()
        for key in self._data:
            id = str(self.search_result.get(key)['id'])
            receipt_number = self.search_result.get(key)['receipt_number']
            date = str(self.search_result.get(key)['date'])
            supplier_id = str(
                data_dict.get(str(
                    self.search_result.get(key)['supplier_id']))['name'])
            status = str(self.search_result.get(key)['status'])

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=receipt_number))
            self.d.add_widget(DataLabel(text=date))
            self.d.add_widget(DataLabel(text=supplier_id))
            self.d.add_widget(DataLabel(text=status))
            self.d.add_widget(option)

            super(ImportSearchTable1, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, receipt_number, date, supplier_id, status):
        self.data_object.id = id
        self.data_object.receipt_number = receipt_number
        self.data_object.date = date
        self.data_object.supplier_id = supplier_id
        self.data_object.status = status
        self.data_object.update_import()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        receipt_ = self.data_object.get_imports().get(id)['receipt_number']
        dat = str(self.data_object.get_imports().get(id)['date'])
        supplier_ = str(self.data_object.get_imports().get(id)['supplier_id'])
        stat = str(self.data_object.get_imports().get(id)['status'])
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        receipt_number = DialogTextInput(receipt_)
        date = DialogTextInput(dat)
        supplier_id = DialogTextInput(supplier_)
        status = DialogTextInput(stat)

        b.add_widget(
            MDLabel(text="Receipt Number", size_hint_x=None, width="90px"))
        b.add_widget(receipt_number)
        b.add_widget(MDLabel(text="Date", size_hint_x=None, width="90px"))
        b.add_widget(date)
        b.add_widget(MDLabel(text="Suppler ID", size_hint_x=None,
                             width="90px"))
        b.add_widget(supplier_id)
        b.add_widget(
            MDLabel(id='date', text="Status", size_hint_x=None, width="90px"))
        b.add_widget(status)

        self.dialog = MDDialog(title="This is a test dialog",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button("Save",
                                      action=lambda *x: self.save_edited_data(
                                          id, receipt_number.text, date.text,
                                          supplier_id.text, status.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
示例#26
0
class AudioEntry(OneLineAvatarIconListItem):
    #label = ObjectProperty(MDLabel(size_hint_x=None, width=35, font_style="Body1"))
    display_mode = StringProperty()

    def __init__(self, audio_file, **kwargs):
        super().__init__(**kwargs)
        self.audio_file = audio_file
        self.text = audio_file.name
        self.secondary_text = str(dict(self.audio_file.params)).replace(
            "{", "").replace("}", "")

        if audio_file.kivy_image:
            self.ids.avatar.texture = audio_file.kivy_image.texture

        self.menu_items = [
            dict(viewclass="MDMenuItem", text="Edit", on_release=self.edit),
            dict(viewclass="MDMenuItem",
                 text="Info",
                 on_release=self.info_dialog),
        ]

    def on_display_mode(self, *args):
        text = text_color = ""
        theme_text_color = "Hint"

        if self.display_mode == "bitrate":
            bitrate = self.audio_file.bitrate
            if bitrate < 150:
                text = self.audio_file.bitrate_str
                text_color = (1, 0.2, 0.2, 0.7)
                theme_text_color = "Custom"
            else:
                text = self.audio_file.bitrate_str

        elif self.display_mode == "date":
            text = str(self.audio_file.date)

        elif self.display_mode == "moods":
            text = str(self.audio_file.moods)

        elif self.display_mode == "images":
            text = f"{len(self.audio_file.images)} images"
            theme_text_color = "Hint"

        label = self.ids.label
        label.text = text
        label.theme_text_color = theme_text_color
        label.text_color = text_color if text_color else label.text_color

    def on_touch_up(self, touch):
        super().on_touch_up(touch)
        if self.collide_point(*touch.pos) and touch.grab_current is not None:
            if touch.device == "mouse" and touch.button == "right":
                MDDropdownMenu(items=self.menu_items,
                               width_mult=2).open(touch, touch=True)

    def edit(self):
        print("Editing")

    def info_dialog(self):
        content = MDList()
        label = MDLabel(font_style='Subhead',
                        theme_text_color='Secondary',
                        text="\n" + str(self.audio_file),
                        valign='center',
                        halign="center")
        label.bind(texture_size=label.setter('size'))

        image = SmartTile(allow_stretch=True,
                          keep_ratio=True,
                          box_color=[0, 0, 0, 0],
                          size_hint_y=None,
                          height=300)
        image._img_widget.texture = self.ids.avatar.texture

        content.add_widget(image)
        content.add_widget(label)

        self.dialog = MDDialog(title=self.audio_file.name,
                               content=content,
                               size_hint=(.8, 0.75),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
示例#27
0
class SupplierTable(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    data_object = Supplier()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 11
    _data = None
    data_in_page = None

    def __init__(self, **kwargs):
        super(SupplierTable, self).__init__(**kwargs)
        self.pagination_next()
        self.call_load()

    def delete_data(self, id):
        try:
            self.data_object.id = id
            self.data_object.delete_supplier()
            self.pagination_next(self.current)
        except KeyError:
            print "Key Not Found"
        except e:
            Snackbar(text=str(e)).show()

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def pagination_next(self, page=1):
        self.current = int(page)
        no_pages = int(
            math.ceil(
                float(self.data_object.count_supplier()) / float(self.offset)))
        if self.current <= no_pages:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.data_object.get_suppliers_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = False
        if self.current >= no_pages:
            deactivate = True
            self.current = no_pages
        else:
            deactivate = False
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        if self.current > 0:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.data_object.get_suppliers_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = True
            self.current = 1
        if self.current == 1:
            deactivate = True
        else:
            deactivate = False
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        for key in self._data:
            id = str(self.data_in_page.get(key)['id'])
            name = str(self.data_in_page.get(key)['name'])
            address = str(self.data_in_page.get(key)['address'])
            contact = str(self.data_in_page.get(key)['contact'])

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=name))
            self.d.add_widget(DataLabel(text=address))
            self.d.add_widget(DataLabel(text=contact))
            self.d.add_widget(option)

            super(SupplierTable, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, name, address, contact):
        self.data_object.id = id
        self.data_object.name = name
        self.data_object.address = address
        self.data_object.contact = contact
        self.data_object.update_supplier()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        name = self.data_in_page.get(id)['name']
        address = str(self.data_in_page.get(id)['address'])
        contact = self.data_in_page.get(id)['contact']
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        name_wid = DialogTextInput(name)
        address_wid = DialogTextInput(address)
        contact_wid = DialogTextInput(contact)

        b.add_widget(
            MDLabel(id='Name',
                    text="Destination",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(name_wid)
        b.add_widget(MDLabel(text="Address", size_hint_x=None, width="90px"))
        b.add_widget(address_wid)
        b.add_widget(
            MDLabel(id='Contact',
                    text="Status",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(contact_wid)

        self.dialog = MDDialog(title="This is a test dialog",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save",
            action=lambda *x: self.save_edited_data(
                id, name_wid.text, address_wid.text, contact_wid.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        self.pagination_next()
        self.call_load()

    def add_data(self, name, address, contact):
        self.data_object.name = name
        self.data_object.address = address
        self.data_object.contact = contact
        if name != '' and address != '' and contact != '':
            self.data_object.insert_supplier()
        else:
            Snackbar(text=" You Need To Fill All Fields ").show()
        self.pagination_next()
        self.call_load()
示例#28
0
class MainApp(App):
    theme_cls = ThemeManager()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.minimum_height = None
        self.ids = None
        self.conn = sqlite3.connect('SCHOOL.db')
        self.c = self.conn.cursor()
        self.all_students = self.c.execute('SELECT * FROM STUDENTS')
        self.all_subjects = self.c.execute('SELECT * FROM SUBJECTS')
        self.get_courses = self.c.execute('SELECT * FROM COURSES')

    def database_creations(self):
        self.conn = sqlite3.connect('SCHOOL.db')
        self.c = self.conn.cursor()
        # creating student

        self.c.execute('''CREATE TABLE STUDENTS(
                        STUDENT_ID INT NOT NULL, 
                        STUDENT_NAME VARCHAR (250),
                        STUDENT_COURSE VARCHAR (250), 
                        STUDENT_CLASS_NAME VARCHAR (250),
                        PRIMARY KEY (STUDENT_ID));''')
        self.conn.commit()
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="T"
                          "PERFECT TABLE CREATED!",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="SUCCESSFUL",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)
        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        print("committed")

    def get_student(self, value):

        sv = ScrollView()
        ml = MDList()
        sv.add_widget(ml)
        get_student = self.c.execute(
            'SELECT * FROM STUDENTS WHERE STUDENT_CLASS_NAME = ?', (value, ))
        for row in get_student:
            ml.add_widget(OneLineListItem(text=str(row[1])))
        sv.do_scroll_y = True
        sv.do_scroll_x = False
        r = GridLayout(cols=1, rows=1)
        r.add_widget(sv)
        p = Popup(title='STUDENTS',
                  size_hint=(.7, 0.7),
                  background_color=(0, 0, .9, .5),
                  auto_dismiss=True)
        p.add_widget(r)
        p.open()

    def list_course(self):
        box = BoxLayout()
        sv = ScrollView()
        ml = MDList()
        self.get_courses = self.c.execute('SELECT * FROM COURSES')

        for row in sorted(self.get_courses):
            ml.add_widget(OneLineListItem(text=str(row[1])))
        sv.do_scroll_y = True
        sv.do_scroll_x = False
        sv.add_widget(ml)
        self.root.ids.courses.add_widget(sv)
        self.root.ids.screen_manager.current = str(self.root.ids.courses.name)

    def subjects(self):
        self.conn = sqlite3.connect('SCHOOL.db')
        self.c = self.conn.cursor()
        self.all_subjects = self.c.execute('SELECT * FROM STUDENTS')
        sv = ScrollView()
        ml = MDList()
        for row in sorted(self.all_subjects):
            ml.add_widget(
                ThreeLineListItem(text=str(row[1]),
                                  secondary_text="id: " + str(row[0]) + '\n'
                                  'under : ' + row[2]))
        sv.do_scroll_y = True
        sv.do_scroll_x = False
        sv.add_widget(ml)
        self.root.ids.subjects.add_widget(sv)
        self.root.ids.screen_manager.current = str(self.root.ids.subjects.name)

    def teachers(self):
        sv = ScrollView()
        ml = MDList()
        rows = self.c.execute('SELECT * FROM TEACHERS')
        for row in sorted(rows):
            ml.add_widget(
                ThreeLineListItem(text=str(row[1]),
                                  secondary_text="id: " + str(row[0]) + '\n'
                                  'under : ' + row[2]))
        sv.do_scroll_y = True
        sv.do_scroll_x = False
        sv.add_widget(ml)
        self.root.ids.teachers.add_widget(sv)
        self.root.ids.screen_manager.current = str(self.root.ids.teachers.name)

    def all_student(self):
        self.conn = sqlite3.connect('SCHOOL.db')
        self.c = self.conn.cursor()
        self.all_students = self.c.execute('SELECT * FROM STUDENTS')

        gris = GridLayout(
            rows=2,
            # row_default_height=(self.width - self.cols * self.spacing[0]) / self.cols,
            # row_force_default=True,
            # size_hint_y=None,
            # height=self.minimum_height,
            padding=(dp(1), dp(1)),
            spacing=dp(1))
        sv = ScrollView()
        ml = MDList()
        for row in self.all_students:
            ml.add_widget(
                ThreeLineListItem(text=str(row[1]),
                                  secondary_text=row[2] + '\n' + row[3]))
        sv.do_scroll_y = True
        sv.do_scroll_x = False
        sv.add_widget(ml)
        gris.add_widget(
            MDTextField(hint_text="Helper text on focus",
                        helper_text="This will disappear when you click off",
                        helper_text_mode="on_focus"))
        gris.add_widget(sv)
        self.root.ids.students.add_widget(gris)
        self.root.ids.screen_manager.current = str(self.root.ids.students.name)
示例#29
0
class StatusTab(MDTab):
    app = ObjectProperty(None)
    irc_action = ObjectProperty(None)
    irc_action_send_btn = ObjectProperty(None)

    def __init__(self, **kw):
        super(StatusTab, self).__init__(**kw)
        self.app = App.get_running_app()
        Clock.schedule_once(self.__post_init__)

    def __post_init__(self, args):
        pass

    def update_irc_action_text(self, dt):
        self.irc_action.text = ''
        self.irc_action.on_focus()

    def send_action(self):
        Clock.schedule_once(self.update_irc_action_text)
        self.app.connection.sendLine(self.irc_action.text.strip('/'))
        self.msg_list.add_widget(
            MultiLineListItem(
                text="[b][color=1A237E]" +
                self.app.config.get('irc', 'nickname') + "[/color][/b] " +
                self.irc_action.text,
                font_style='Subhead',
            ))
        self.msg_list.parent.scroll_to(self.msg_list.children[0])
        Logger.info(
            "IRC: <%s> %s" %
            (self.app.config.get('irc', 'nickname'), self.irc_action.text))

    def on_irc_unknown(self, prefix, command, params):
        Logger.info("IRC UNKNOWN: <%s> %s %s" % (prefix, command, params))

    def on_noticed(self, user, channel, action):
        user = user.split('!')[0]
        if user == 'ChanServ':
            content = MDLabel(font_style='Body1',
                              theme_text_color='Secondary',
                              text=action,
                              size_hint_y=None,
                              valign='top')
            content.bind(texture_size=content.setter('size'))
            self.dialog = MDDialog(title="Notice: {}".format(user),
                                   content=content,
                                   size_hint=(.8, None),
                                   height=dp(200),
                                   auto_dismiss=False)

            self.dialog.add_action_button(
                "Dismiss", action=lambda *x: self.dialog.dismiss())
            self.dialog.open()
        else:
            self.msg_list.add_widget(
                MultiLineListItem(
                    text="[b][color=F44336]" + user + "[/color][/b] " + action,
                    font_style='Subhead',
                ))
            self.msg_list.parent.scroll_to(self.msg_list.children[0])
        Logger.info("IRC NOTICED: <%s> %s %s" % (user, channel, action))

    def nick_details(self, nick_list_item):
        self.app.connection.signedOn()
        nick_item_data = self.nick_data[nick_list_item.text]
        bs = MDListBottomSheet()
        bs.add_item("Whois ({})".format(nick_list_item.text), lambda x: x)
        bs.add_item(
            "{} ({}@{})".format(nick_item_data[7].split(' ')[1],
                                nick_item_data[3], nick_item_data[2]),
            lambda x: x)
        bs.add_item(
            "{} is connected via {}".format(nick_list_item.text,
                                            nick_item_data[4]), lambda x: x)
        bs.open()

    def __post_connection__(self, connection):
        connection.on_irc_unknown(self.on_irc_unknown)
        connection.on_noticed(self.on_noticed)

    def __post_joined__(self, connection):
        pass
示例#30
0
class ExportTable1(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    export_object = Export()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 4
    _data = None
    data_in_page = None

    def __init__(self, **kwargs):
        super(ExportTable1, self).__init__(**kwargs)
        self.pagination_next()
        self.call_load()

    def delete_data(self, id):
        try:
            self.export_object.id = id
            self.export_object.delete_export()
            self.pagination_next(self.current)
        except KeyError:
            print "Key Not Found"
        except _mysql_exceptions.IntegrityError:
            Snackbar(text=str("You Cannot Delete This Record")).show()

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def pagination_next(self, page=1):
        self.current = int(page)
        no_pages = int(
            math.ceil(
                float(self.export_object.count_export()) / float(self.offset)))
        if self.current <= no_pages:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.export_object.get_exports_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = False
        if self.current >= no_pages:
            deactivate = True
            self.current = no_pages
        else:
            deactivate = False
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        if self.current > 0:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.export_object.get_exports_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = True
            self.current = 1
        if self.current == 1:
            deactivate = True
        else:
            deactivate = False
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        for key in self._data:
            id = str(self.data_in_page.get(key)['id'])
            date = str(self.data_in_page.get(key)['date'])
            status = self.data_in_page.get(key)['status']
            destination = self.data_in_page.get(key)['destination']

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=destination))
            self.d.add_widget(DataLabel(text=date))
            self.d.add_widget(DataLabel(text=status))
            self.d.add_widget(option)

            super(ExportTable1, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, destination, date, status):
        self.export_object.id = id
        self.export_object.destination = destination
        self.export_object.date = date
        self.export_object.status = status
        self.export_object.update_export()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        dest = self.data_in_page.get(id)['destination']
        dat = str(self.data_in_page.get(id)['date'])
        stat = self.data_in_page.get(id)['status']
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        destination = DialogTextInput(dest)
        date = DialogTextInput(dat)
        status = DialogTextInput(stat)

        b.add_widget(
            MDLabel(id='destination',
                    text="Destination",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(destination)
        b.add_widget(MDLabel(text="Date", size_hint_x=None, width="90px"))
        b.add_widget(date)
        b.add_widget(
            MDLabel(id='date', text="Status", size_hint_x=None, width="90px"))
        b.add_widget(status)

        self.dialog = MDDialog(title="This is a test dialog",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save",
            action=lambda *x: self.save_edited_data(id, destination.text, date.
                                                    text, status.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def add_data(self, destination, date, status):
        self.export_object.destination = destination
        self.export_object.date = date
        self.export_object.status = status
        if destination != '' and date != '' and status != '':
            self.export_object.insert_export()
        else:
            Snackbar(text=" You Need To Fill All Fields ").show()
        self.call_load()
示例#31
0
class MainApp(App):
    theme_cls = ThemeManager()
    previous_date = ObjectProperty()
    title = "Decentralize oil field"
    mnemonic = StringProperty()
    address = StringProperty()
    passphrase = StringProperty()
    repeat_passphrase = StringProperty()
    enabled_mnemonic = BooleanProperty(True)
    enabled_address = BooleanProperty(True)
    instagram_last_fetched = StringProperty()

    def __init__(self, **kwargs):
        super(MainApp, self).__init__(**kwargs)
        #Window.bind(on_close=self.on_stop)

    def stop(self, *largs):
        # Open the popup you want to open and declare callback if user pressed `Yes`
        # popup = ExitPopup(title=TEXT_ON_CLOSE_APPLICATION,
        #                   content=Button(text=TEXT_ON_CLOSE_APPLICATION_BUTTON_CLOSE),
        #                   size=(400, 400), size_hint=(None, None)
        #                   )
        # popup.bind(on_confirm=partial(self.close_app, *largs))
        # popup.open()
        return

    def build(self):
        self.main_widget = Builder.load_file(
            os.path.join(os.path.dirname(__file__), "./latest.kv"))
        self.theme_cls.theme_style = 'Dark'

        # self.theme_cls.theme_style = 'Dark'

        # self.main_widget.ids.text_field_error.bind(
        #     on_text_validate=self.set_error_message,
        #     on_focus=self.set_error_message)
        self.update_instagram_images_list()
        self.bottom_navigation_remove_mobile(self.main_widget)
        #__list = Factory.Lists()
        return self.main_widget

    def update_instagram_images_list(self):
        thumbnails = get_instagram_thumbnails()
        for image in thumbnails:

            item = TwoLineAvatarIconListItem(
                text=f"Top Liker [ {image['top_likers'][0]} ]",
                secondary_text=f"Total likes {image['likes']}")
            item.add_widget(ContactPhoto(source=image["disk_name"]))
            item.add_widget(MessageButton(id=image["id"]))
            self.main_widget.ids.scroll.add_widget(item)

            # new_widget = Factory.ThreeLineAvatarIconListItemCheckbox(
            #         text=f'id-{image["id"]}')
            # new_widget.add_widget(AvatarSampleWidget(source=image["disk_name"]))

        self.instagram_last_fetched = "Last Fetched from Instagram " + self.instagram_last(
        )
        return

    def bottom_navigation_remove_mobile(self, widget):
        # Removes some items from bottom-navigation demo when on mobile
        if DEVICE_TYPE == 'mobile':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_2)
        if DEVICE_TYPE == 'mobile' or DEVICE_TYPE == 'tablet':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_1)

    def show_example_snackbar(self, snack_type):
        if snack_type == 'simple':
            Snackbar(text="This is a snackbar!").show()
        elif snack_type == 'button':
            Snackbar(text="This is a snackbar",
                     button_text="with a button!",
                     button_callback=lambda *args: 2).show()
        elif snack_type == 'verylong':
            Snackbar(
                text=
                "This is a very very very very very very very long snackbar!"
            ).show()

    def show_example_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="This is a dialog with a title and some text. "
                          "That's pretty awesome right!",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="This is a test dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def loading_box(self):
        content = MDLabel(
            font_style='Body1',
            theme_text_color='Secondary',
            text=
            "Please wait while we are fetching your instagram, Hang tight!!!",
            size_hint_y=None,
            valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="This is a long test dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=True)

        # self.dialog.add_action_button("Dismiss",
        #                               action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        return

    def get_time_picker_data(self, instance, time):
        self.root.ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        self.time_dialog = MDTimePicker()
        self.time_dialog.bind(time=self.get_time_picker_data)
        if self.root.ids.time_picker_use_previous_time.active:
            try:
                self.time_dialog.set_time(self.previous_time)
            except AttributeError:
                pass
        self.time_dialog.open()

    def set_previous_date(self, date_obj):
        self.previous_date = date_obj
        self.root.ids.date_picker_label.text = str(date_obj)

    def show_example_date_picker(self):
        if self.root.ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

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

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

    def set_error_message(self, *args):
        if len(self.root.ids.text_field_error.text) == 2:
            self.root.ids.text_field_error.error = True
        else:
            self.root.ids.text_field_error.error = False

    def on_close(self):
        print("Clicked on closing application")
        Window.close()
        return True

    def on_start(self):
        print(self.main_widget.ids.scr_mngr)
        if store.get("mnemonic"):
            self.main_widget.ids.login_box.remove_widget(
                self.main_widget.ids.button_mnemonic)
            self.main_widget.ids.login_box.remove_widget(
                self.main_widget.ids.button_save_mnemonic)
            #self.main_widget.ids.login_box.remove_widget(self.main_widget.ids.address)
            self.main_widget.ids.login_box.remove_widget(
                self.main_widget.ids.repeat_passphrase)

            self.main_widget.ids.login_box.remove_widget(
                self.main_widget.ids.mnemonic)

            #self.main_widget.ids.login_box.add_widget(self.main_widget.ids.repeat_passphrase)
        else:
            self.main_widget.ids.login_box.remove_widget(
                self.main_widget.ids.button_login)

        return

    def on_instagram_login(self, username, password):
        try:
            instagram_object = instagram_login(username.text, password.text)
            #self.loading_box()
            #Snackbar(text="Please wait for sometime, lets us fetch your Insta Handle").show()

            max_id, posts = get_all_posts(instagram_object)

            Logger.info("Now fetching images from instagram")
            save_instagram(posts)
            # with open("instagram.data","wb") as f:
            #     pickle.dump(posts, f)
            store.put("instagram",
                      max_id=max_id,
                      time_zone=time.tzname,
                      last_fetch_utc=datetime.datetime.utcnow().timestamp(),
                      last_fetch_local=datetime.datetime.now(
                          datetime.timezone.utc).astimezone().isoformat())

        except Exception as e:
            Logger.error(e)
            Snackbar(
                text="Please check your instragram username and password again"
            ).show()
        return

    def instagram_last(self):
        try:
            data = store.get("instagram")
            print(f"Instagram data stored in local storage {data}")
            print(
                f"Instagram Last fectehd locally is {data['last_fetch_local']}"
            )

            result = datetime.datetime.fromtimestamp(
                data["last_fetch_utc"]).strftime("%d %B, %Y")
            print(f"Human readable last fecthed {result}")
            return result
        except Exception as e:
            print(f"Error in lest fecthed dtiem stamp UTC {e.__str__()}")
            return ""

    def on_show_mnemonic(self):
        """
        Show mnemonic after fetching it from local storage 
        """
        self.main_widget.ids.login_box.add_widget(
            self.main_widget.ids.mnemonic)

    def on_login(self, passphrase):
        encrypted = store.get("mnemonic")
        encrypted_mnemonic = encrypted["value"]
        salt = encrypted["salt"]

        scrypt_key, salt = generate_scrypt_key(passphrase.text,
                                               bytes.fromhex(salt))
        print(
            f"scrypt_key from password {scrypt_key.hex()} and salt is {salt.hex()}"
        )

        print(f"Encrypted Mnemonic is {encrypted_mnemonic}")

        try:
            result = aes_decrypt(scrypt_key, bytes.fromhex(encrypted_mnemonic))
        except Exception as e:
            print("Error ")
            print(e)
            Snackbar(text="Password entered is wrong").show()

        print(result)
        store.put("password", value=passphrase.text)
        return

    def on_save(self, passphrase, repeat_passphrase):
        if not self.mnemonic:
            Snackbar(text="PLease generate a New mnemonic").show()
            return
        if passphrase.text != repeat_passphrase.text or not passphrase.text:
            Snackbar(text="Passphrases must match").show()
            return

        if len(passphrase.text) < 8:
            Snackbar(
                text="Passphrases must be at least 8 characters long").show()
            return

        scrypt_key, salt = generate_scrypt_key(passphrase.text)
        encrypted_mnemonic = aes_encrypt(scrypt_key, self.mnemonic)

        store.put("mnemonic", value=encrypted_mnemonic.hex(), salt=salt.hex())
        store.put("address", value=self.address)
        return

    def generate_mnemonic(self):
        """
        Make an api request with the data to confirm the user registraion
        After succesful registration reset the form 
        """
        #TODO form validation with cerberus
        #TODO Check if macid is available from the host or not
        #TODO check if ip address

        r = requests.get(f"http://{store.get('GO_API')}/get_mnemonic")
        mnemonic = r.json()["data"]["mnemonic"]
        zeroth_private_key = r.json()["data"]["zeroth_private_key"]
        zeroth_public_key = r.json()["data"]["zeroth_public_key"]

        master_private_key = r.json()["data"]["master_private_key"]
        master_public_key = r.json()["data"]["master_public_key"]

        self.mnemonic = mnemonic
        self.address = hashlib.sha256(zeroth_public_key.encode()).hexdigest()
        return
示例#32
0
class CategoriesSearchTable(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    data_object = Category()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 11
    _data = None
    search_result = dict()
    sql = ''

    def __init__(self, **kwargs):
        kwargs['size_hint_y'] = None
        super(CategoriesSearchTable, self).__init__(**kwargs)
        self.bind(minimum_height=self.setter('height'))
        self.pagination_next()
        self.call_load()

    def filter(self, name):
        self.sql = "SELECT * FROM categories WHERE name REGEXP '{}' ORDER BY name".format(
            name)
        s = self.data_object.execute(self.sql)
        name = dict()
        for val in s:
            name[val['name']] = val
        self.search_result = name
        self.pagination_next()

    def delete_data(self, id):
        try:
            self.data_object.id = id
            self.data_object.delete_category()
            self.pagination_next(self.current)
        except KeyError:
            print "Key Not Found"

    def generate_pdf(self, dt):
        sorted_list = sorted(self.search_result)
        th = Thread(target=generate_pdf,
                    args=(sorted_list, self.search_result))
        th.start()

    def generate_excel_sheet(self, dt):
        id = list()
        name = list()

        # result = list(sup.execute('SELECT * FROM suppliers'))

        # print self.search_result.values()

        for v in self.search_result.values():
            id.append(int(v.get('id')))
            name.append(v.get('name'))

        data_dict = {
            # '1_ID': id,
            '2_Name': name,
        }

        # generate_excel(data_dict, excel_file_name="supplier_report4")

        th = Thread(
            target=generate_excel,
            args=(data_dict,
                  "ExcelReports\\categories_report\\categories_report_" +
                  str(datetime.today()).replace(" ", "_").replace(":", "_")))
        th.start()

    def make_excel(self):
        Clock.schedule_once(self.generate_excel_sheet)

    def make_report(self):
        Clock.schedule_once(self.generate_pdf)

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def calc_pages(self, pages, num_pages, num_page):
        pages_dict = dict()
        pages_lens = list()
        num = 0
        while num <= len(self.pages):
            pages_lens.append(num)
            num = num + self.offset
        pages_lens.append(len(self.pages))
        for num in range(0, num_pages):
            pages_dict[num + 1] = pages[pages_lens[num]:pages_lens[num + 1]]
        page_count = len(pages_dict.keys())
        return num_page, page_count, pages_dict[num_page]

    def pagination_next(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        # self.pages = list(self.data_object.get_categories())
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == page_count:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        # self.pages = list(self.data_object.get_categories())
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == 1:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        for key in self._data:
            id = str(self.search_result.get(key)['id'])
            name = str(self.search_result.get(key)['name'])

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=name))
            self.d.add_widget(option)

            super(CategoriesSearchTable, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, name):
        self.data_object.id = id
        self.data_object.name = name
        self.data_object.update_category()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        name = self.data_object.get_categories().get(id)['name']
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        name_wid = DialogTextInput(name)

        b.add_widget(
            MDLabel(id='Name', text="Name", size_hint_x=None, width="90px"))
        b.add_widget(name_wid)

        self.dialog = MDDialog(title="Update Category",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save", action=lambda *x: self.save_edited_data(id, name_wid.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        self.pagination_next()
        self.call_load()
示例#33
0
class KitchenSink(App):
    theme_cls = ThemeManager()

    menu_items = [
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
    ]

    def build(self):
        main_widget = Builder.load_string(main_widget_kv)
        # self.theme_cls.theme_style = 'Dark'

        main_widget.ids.text_field.bind(on_text_validate=self.set_error_message, on_focus=self.set_error_message)
        return main_widget

    def show_example_snackbar(self, type):
        if type == "simple":
            Snackbar.make("This is a snackbar!")
        elif type == "button":
            Snackbar.make("This is a snackbar", button_text="with a button!", button_callback=lambda *args: 2)
        elif type == "verylong":
            Snackbar.make("This is a very very very very very very very long " "snackbar!", button_text="Hello world")

    def show_example_dialog(self):
        content = MDLabel(
            font_style="Body1",
            theme_text_color="Secondary",
            text="This is a dialog with a title and some text. That's pretty awesome right!",
            valign="top",
        )

        content.bind(size=content.setter("text_size"))
        self.dialog = MDDialog(
            title="This is a test dialog", content=content, size_hint=(0.8, None), height=dp(200), auto_dismiss=False
        )

        self.dialog.add_action_button("Dismiss", action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def theme_swap(self):
        self.theme_cls.theme_style = "Dark" if self.theme_cls.theme_style == "Light" else "Light"

    def show_example_bottom_sheet(self):
        bs = MDListBottomSheet()
        bs.add_item("Here's an item with text only", lambda x: x)
        bs.add_item("Here's an item with an icon", lambda x: x, icon="md-cast")
        bs.add_item("Here's another!", lambda x: x, icon="md-nfc")
        bs.open()

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

    def set_error_message(self, *args):
        if len(self.root.ids.text_field.text) == 0:
            self.root.ids.text_field.error = True
            self.root.ids.text_field.error_message = "Some text is required"
        else:
            self.root.ids.text_field.error = False

    def on_pause(self):
        return True

    def on_stop(self):
        pass