Esempio n. 1
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()
        self.shopping_list = []
        self.list_view_model = QStandardItemModel()
        self.ui.shoppingListView.setModel(self.list_view_model)

        self.ui.addItemButton.clicked.connect(self.add_button_clicked)
Esempio n. 2
0
 def __init__(self):
     super(MyApp,self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.name = ''
     self.username = ''
     self.result_yes = ''
     self.result_no = ''
     self.ui.Button.clicked.connect(self.detect_emotion)
     self.ui.YesButton.clicked.connect(self.spotify_yes)
     self.ui.NoButton.clicked.connect(self.spotify_no)
Esempio n. 3
0
 def __init__(self):
     app = QtWidgets.QApplication(sys.argv)
     MainWindow = QtWidgets.QMainWindow()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(MainWindow)
     self.logic = Logic(self)
     self.thread = Thread(self.ui, self.logic)
     setupMenu(MainWindow, self.ui, self.logic, self.thread)
     MainWindow.show()
     setupActions(MainWindow, self.ui, self.logic)
     updateDisplay(self.ui, self.logic)
     sys.exit(app.exec_())
Esempio n. 4
0
    def __init__(self, tree: Tensor):
        # can recompile this without changing the code. Can apply Adapter
        self.app = QtWidgets.QApplication(sys.argv)
        self.MainWindow = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.MainWindow)

        # Setup data
        self.observerCollection = self.initObservers()
        self.tree = tree

        # setup connect
        self.ui.textEdit.textChanged.connect(self.inputChange)
Esempio n. 5
0
    def __init__(self, parent=None):
        """
        :rtype: object
        """
        QtWidgets.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setWindowIcon(QtGui.QIcon("icon/icon.png"))

        # Vairiables d'environnement
        self.mot = []
        self.trad = []
        self.difficultes = []
        self.modeinverse = False
        self.partie_en_cours = False

        # Menubar
        #       Fichier
        self.ui.actionNouvelle_liste_de_vocabulaire.triggered.connect(self.NouvelleListe)
        self.ui.actionOuvrir_une_liste_de_vocabulaire.triggered.connect(self.OuvrirListe)
        self.ui.actionModifier_une_liste_de_vocabulaire.triggered.connect(self.ModifierListe)
        self.ui.actionAfficher_une_liste_de_vocabulaire.triggered.connect(self.AffListe)
        self.ui.actionConvertir_une_liste_de_vocabualire_en_pdf.triggered.connect(self.ConvListPDF)
        self.ui.actionQuitter.triggered.connect(QtWidgets.QApplication.quit)
        #       Aide
        self.ui.action_propos.triggered.connect(self.APropos)

        # Boutons
        self.ui.prop1.clicked.connect(lambda: self.Reponse(1))
        self.ui.prop2.clicked.connect(lambda: self.Reponse(2))
        self.ui.prop3.clicked.connect(lambda: self.Reponse(3))
        self.ui.jcp.clicked.connect(lambda: self.Reponse(0))

        # CheckBox
        self.ui.modeinverse.clicked.connect(self.Inverse)

        # Ouvrir un fichier de vocabulaire
        self.chercher_fichier = SelectFile.SelectFile()
        self.filepath = self.chercher_fichier.getFileName()
        self.show()
        self.activateWindow()

        self.Jeu()
Esempio n. 6
0
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
               
        ## Syntax highlighting
        self.highlighter = highlighter.Highlighter(self.ui.orig_text.document())
        self.highlighter.modeRest()

        ## Connect the refresButton and F1 key to a message method.
        self.connect(self.ui.refresh, QtCore.SIGNAL("clicked()"), self.do_html)
        QtGui.QShortcut(QtGui.QKeySequence(self.VIEWACTIVATOR), 
                        self, self.do_html)
               
        ## SIGNALS AND SLOTS
        self.connect(self.ui.actionHelp, QtCore.SIGNAL("triggered()"), 
                    self.showHelp)
        
        ## STATUSBAR
        self.statusBar().showMessage("Welcome to WikiWriter, press F1 to update your Browser.")
Esempio n. 7
0
class MyApplication(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()
        self.shopping_list = []
        self.list_view_model = QStandardItemModel()
        self.ui.shoppingListView.setModel(self.list_view_model)

        self.ui.addItemButton.clicked.connect(self.add_button_clicked)

    @pyqtSlot()
    def add_button_clicked(self):
        text = self.ui.itemInputEdit.text()
        self.ui.itemInputEdit.clear()
        self.shopping_list.append(text)
        self.list_view_model.clear()

        for list_item in self.shopping_list:
            item = QStandardItem(list_item)
            self.list_view_model.appendRow(item)
Esempio n. 8
0
class Application:
    def __init__(self, tree: Tensor):
        # can recompile this without changing the code. Can apply Adapter
        self.app = QtWidgets.QApplication(sys.argv)
        self.MainWindow = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.MainWindow)

        # Setup data
        self.observerCollection = self.initObservers()
        self.tree = tree

        # setup connect
        self.ui.textEdit.textChanged.connect(self.inputChange)
        #self.ui.pushButton.clicked.connect(self.plot)

    def initObservers(self):
        collection = ObserversCollection()
        view = ObservableView(self.ui.label_4)
        collection.registerObserver(ObservableTable(self.ui.tableWidget, view))
        collection.registerObserver(view)
        return collection

    def inputChange(self, *args):  # trigger when textinput data changed
        # parse new Tree
        # self.tree = "abc"
        # notify
        self.tree = self.ui.textEdit.toPlainText()
        self.observerCollection.notifyObservers(self.tree)

    def display(self):
        self.MainWindow.show()
        sys.exit(self.app.exec_())

    def plot(self, *args):
        pass
Esempio n. 9
0
class TestApp(QtGui.QMainWindow, Ui_MainWindow):
    VIEWACTIVATOR = "F1" # To refresh the HTML View
    
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
               
        ## Syntax highlighting
        self.highlighter = highlighter.Highlighter(self.ui.orig_text.document())
        self.highlighter.modeRest()

        ## Connect the refresButton and F1 key to a message method.
        self.connect(self.ui.refresh, QtCore.SIGNAL("clicked()"), self.do_html)
        QtGui.QShortcut(QtGui.QKeySequence(self.VIEWACTIVATOR), 
                        self, self.do_html)
               
        ## SIGNALS AND SLOTS
        self.connect(self.ui.actionHelp, QtCore.SIGNAL("triggered()"), 
                    self.showHelp)
        
        ## STATUSBAR
        self.statusBar().showMessage("Welcome to WikiWriter, press F1 to update your Browser.")
        
        

    def do_html(self, orig_text=""):
        if orig_text=="" :
            SOURCE = unicode(self.ui.orig_text.document().toPlainText())
        else:
            SOURCE = orig_text
        #print SOURCE
        result = launch(SOURCE, full=True)
        #result = parse_text(SOURCE)

        f = codecs.open("view.html",'w','utf-8')
        f.write(TPL%result)
        f.close()
    
        self.ui.webView.setUrl(QtCore.QUrl.fromLocalFile(VIEW))
        
        # textedit
        self.ui.gen_text.setPlainText(result)
        
    def showHelp(self):
        helptext = """[[nowiki]]= header level 1[[/nowiki]]

= header level 1

----

[[nowiki]]== header level 2[[/nowiki]]

== header level 2

----

[[nowiki]]=== header level 3[[/nowiki]]

== header level 3

----

[[nowiki]]**bold**[[/nowiki]]  

**bold**

----

[[nowiki]]//italics//[[/nowiki]]  

//italics//

----

[[nowiki]]{{monospaced}}[[/nowiki]]

{{monospaced}}

----

[[nowiki]]--del--[[/nowiki]]

--del--

----

[[nowiki]]__underlined__[[/nowiki]]

__underlined__

----

[[nowiki]]//**bold** italics **--deleted--**//[[/nowiki]]  

//**bold** italics **--deleted--**//

----

[[nowiki]][http://twitter.com/|Twitter][[/nowiki]]  

[http://twitter.com/|Twitter]

----

[[nowiki]][[im http://assets0.twitter.com/images/twitter.png?1214697409|http://twitter.com/|center|Twitter image]][[/nowiki]]

[[im http://assets0.twitter.com/images/twitter.png?1214697409|http://twitter.com/|center|Twitter image]]

----"""

        self.ui.webView.setHtml(self.do_html(helptext))       
Esempio n. 10
0
class MyApp(QMainWindow):
    '''
    Class which returns the UI alongwith the logic implemented for the same.
    '''

    def __init__(self):
        super(MyApp,self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.name = ''
        self.username = ''
        self.result_yes = ''
        self.result_no = ''
        self.ui.Button.clicked.connect(self.detect_emotion)
        self.ui.YesButton.clicked.connect(self.spotify_yes)
        self.ui.NoButton.clicked.connect(self.spotify_no)

    def get_tweets(self, api):
        '''
        Get the tweets for a particular Twitter handle.
        '''

        self.ui.resultWindow.setText('')
        self.ui.resultWindow2.setText('')
        page = 1
        tweet_list = []
        while True:
            try:
                tweets = api.user_timeline(self.username, page=page)
                if not tweets:
                    return tweet_list
                for tweet in tweets:
                    if (datetime.now() - tweet.created_at).days < 1:
                        tweet_list.append(tweet.text)
                        self.name = tweet.user.name
                    else:
                        return tweet_list
                page += 1
                time.sleep(5)
            except tweepy.error.TweepError as e:
                return "{}".format(e)

    def spotify_yes(self):
        '''
        Get the results when the user has a Spotify account.
        '''

        if self.result_yes == '' or self.username == '':
            result = '**Please enter a valid Twitter Handle first!'
            self.ui.resultWindow.setText(result)

        else:
            self.ui.resultWindow2.setText(self.result_yes)
            self.ui.resultWindow2.setOpenExternalLinks(True)

    def spotify_no(self):
        '''
        Get the results when the user doesn't have a Spotify account.
        '''

        if self.result_no == '' or self.username == '':
            result = '**Please enter a valid Twitter Handle first!'
            self.ui.resultWindow.setText(result)
        else:
            self.ui.resultWindow2.setText(self.result_no)
            self.ui.resultWindow2.setOpenExternalLinks(True)

    def get_urls(self, emotion):
        '''
        Get the urls of playlists for an emotion.
        '''

        auth_url = 'https://accounts.spotify.com/api/token'
        headers = {
            'Content-type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic {}'.format(encoded)
        }
        data = {'grant_type': 'client_credentials'}

        r = requests.post(auth_url, data=data, headers=headers)
        access_token = r.json().get('access_token', None)

        spotify_url = 'https://api.spotify.com/v1/search'
        params = {
            'q': '{}'.format(emotion),
            'type': 'playlist',
            'limit': '5'
        }
        headers = {
            'Content-type': 'application/json',
            'Authorization': 'Bearer {}'.format(access_token)
        }

        r = requests.get(spotify_url, params=params, headers=headers)
        items = r.json().get('playlists').get('items', None)
        if items:
            url_list = [item['external_urls']['spotify'] for item in items]
        return url_list

    def detect_emotion(self):
        '''
        Function which is called after clicking the 'Know your mood' button on UI which then displays some appropriate message
        '''
        
        self.username = self.ui.twitter_name.text()
        if self.username == '':
            self.ui.resultWindow.setText('')
            self.ui.resultWindow2.setText('')
            result = """<html><body>
                        <p>**Please enter a valid Twitter Handle first!</p> 
                        </body></html>"""
            self.ui.resultWindow.setText(result)

        else:
            tweet_list = self.get_tweets(api)
            if isinstance(tweet_list, str):
                self.result_no, self.result_yes = '', ''
                result = """<html><body>
                            <p>**Error while extracting tweets from this Twitter handle!</p> 
                            <p>Please try another Twitter handle or check your Internet connection.</p>
                            </body></html>"""
                result = result.format(error=tweet_list)
                self.ui.resultWindow.setText(result)

            elif tweet_list:
                result_dict = {}
                try:
                    for tweet in tweet_list:
                        response = natural_language_understanding.analyze(
                        text=tweet,
                        features=Features(
                        emotion=EmotionOptions())).get_result()
                        
                        emotion_dict = response['emotion']['document']['emotion']
                        emotion = max(emotion_dict.keys(), key=(lambda key: emotion_dict[key]))

                        if result_dict.get(emotion, None):
                            result_dict[emotion] += 1
                        else:
                            result_dict[emotion] = 1

                    dominant_emotion = max(result_dict.keys(), key=(lambda key: result_dict[key])) if result_dict else None
                    
                    result = """<html><head></head><body>
                            <p>Hi <strong>{name}!</strong> Your dominant emotion is : {emotion}</p>
                            <p>We would like to suggest some music for you...</p>
                            </body></html>
                            """
                    result = result.format(name=self.name, emotion=dominant_emotion)
                    self.ui.resultWindow.setText(result)

                    playlist = music_dict[dominant_emotion]
                    url_list = self.get_urls(playlist['emotion'])
                    links = []
                    for i in range(len(url_list)):
                        links.append("<p><a href='{}'> Playlist {}</a></p>".format(url_list[i], i+1))
        
                    links = "".join(links)
                    self.result_yes = """<html><head></head><body>
                                <p>{msg}</p>
                                {links}
                                </body></html>"""
                    self.result_yes = self.result_yes.format(msg=playlist['message'], links=links)
                
                    self.result_no = """<html><head></head><body>
                                    <p> No worries! We have a playlist on YouTube waiting for you! </p>
                                    <p> <a href="{link}"> Your Playlist </a></body></html>"""
                    self.result_no = self.result_no.format(link=playlist['link'])
            
                except (watson_developer_cloud.watson_service.WatsonApiException, requests.exceptions.ConnectionError) as e:
                    self.ui.resultWindow.setText('')
                    self.ui.resultWindow2.setText('')
                    self.result_no, self.result_yes = '', ''
                    if str(e).startswith("('Connection aborted"):
                        result = """<html><body>
                                <p>**Please check your Internet connection!</p>
                                </body></html>"""
                    else:
                        result = """<html><body>
                                <p>Unsupported text language in one of the tweets of <strong>{name}</strong></p>
                                </body></html>"""
                    result = result.format(name=self.name)
                    self.ui.resultWindow.setText(result)
            else:
                self.ui.resultWindow.setText('')
                self.ui.resultWindow2.setText('')
                self.result_no, self.result_yes = '', ''
                result = """<html><body>
                            <p>No tweets found for Twitter handle <strong>{name}</strong> in the last 24 hours.</p>
                            </body></html>"""
                result = result.format(name=self.username)
                self.ui.resultWindow.setText(result)
Esempio n. 11
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.show()
Esempio n. 12
0
class MyApplication(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()
Esempio n. 13
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        """
        :rtype: object
        """
        QtWidgets.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setWindowIcon(QtGui.QIcon("icon/icon.png"))

        # Vairiables d'environnement
        self.mot = []
        self.trad = []
        self.difficultes = []
        self.modeinverse = False
        self.partie_en_cours = False

        # Menubar
        #       Fichier
        self.ui.actionNouvelle_liste_de_vocabulaire.triggered.connect(self.NouvelleListe)
        self.ui.actionOuvrir_une_liste_de_vocabulaire.triggered.connect(self.OuvrirListe)
        self.ui.actionModifier_une_liste_de_vocabulaire.triggered.connect(self.ModifierListe)
        self.ui.actionAfficher_une_liste_de_vocabulaire.triggered.connect(self.AffListe)
        self.ui.actionConvertir_une_liste_de_vocabualire_en_pdf.triggered.connect(self.ConvListPDF)
        self.ui.actionQuitter.triggered.connect(QtWidgets.QApplication.quit)
        #       Aide
        self.ui.action_propos.triggered.connect(self.APropos)

        # Boutons
        self.ui.prop1.clicked.connect(lambda: self.Reponse(1))
        self.ui.prop2.clicked.connect(lambda: self.Reponse(2))
        self.ui.prop3.clicked.connect(lambda: self.Reponse(3))
        self.ui.jcp.clicked.connect(lambda: self.Reponse(0))

        # CheckBox
        self.ui.modeinverse.clicked.connect(self.Inverse)

        # Ouvrir un fichier de vocabulaire
        self.chercher_fichier = SelectFile.SelectFile()
        self.filepath = self.chercher_fichier.getFileName()
        self.show()
        self.activateWindow()

        self.Jeu()

    def ConvListPDF(self):
        """
        Convertir une liste de vocabulaire en fichier PDF.
        :return: None
        """
        msg = QtWidgets.QMessageBox()
        msg.setWindowTitle("Information")
        msg.setText("Patience... Cette fonctionnalité n'est pas encore disponible...")
        msg.exec()

    def AffListe(self):
        """
        Afficher une liste de vocabulaire.
        :return: None
        """
        window = ListeWindow(self)
        window.show()

    def Inverse(self):
        """
        Activer / Désactiver le mode inversé.
        :return: None
        """
        if self.ui.modeinverse.isChecked():
            self.modeinverse = True
        else:
            self.modeinverse = False

        self.Jeu()

    def NouvelleListe(self):
        """
        Ouverture de la fenêtre Nouvelle liste.
        :return: None
        """
        window = NouveauWindow(self)
        window.show()

    def OuvrirListe(self):
        """
        Ouvrir une liste de vocabulaire.
        :return: None
        """
        self.chercher_fichier = SelectFile.SelectFile()
        self.filepath = self.chercher_fichier.getFileName()
        self.activateWindow()
        if self.filepath is not None: self.Jeu()

    def ModifierListe(self):
        """
        Ouverture de la fenêtre Modifier la liste.
        :return: None
        """
        window = ModifierWindow(self)
        window.show()

    def APropos(self):
        """
        Ouverture de la fenêtre À Propos.
        :return: None
        """
        window = AProposWindow(self)
        window.show()

    def ViderTout(self):
        """
        Remise de la fenêtre à son état initial.
        :return: None
        """
        self.ui.motvoca.setText("Mot de vocabulaire")
        self.ui.prop1.setText("Proposition 1")
        self.ui.prop2.setText("Proposition 2")
        self.ui.prop3.setText("Proposition 3")
        self.ui.score.setText("XX / YY")
        self.ui.modeinverse.setCheckState(False)
        self.modeinverse = False
        self.mot = []
        self.trad = []
        self.mot_q = []
        self.trad_q = []
        self.index = []
        self.difficultes = []
        self.index_q = -1
        self.propmot = ""
        self.proptrad = ["" for _ in range(3)]
        self.score = 0
        self.nb_mots = 0
        self.filepath = None
        self.partie_en_cours = False

    def Reponse(self, bouton):
        """
        Déclenchement de la réponse de l'utilisateur et vérification de la réponse.
        :param bouton: Numéro du bouton appuyé
        :return: None
        """
        if not self.partie_en_cours:    return

        correct = False

        if bouton == 0:
            window = FauxWindow(self)
            window.show()
        elif bouton == 1 and self.index_q == 0:
            correct = True
        elif bouton == 2 and self.index_q == 1:
            correct = True
        elif bouton == 3 and self.index_q == 2:
            correct = True

        if correct:
            self.mot_connus += 1
            del self.mot_q[self.index_mot_q]
            del self.trad_q[self.index_mot_q]

            self.UpdateScore()
        else:
            window = FauxWindow(self)
            window.show()
            self.difficultes.append([self.propmot, self.proptrad[self.index_q]])

        if self.TirerMots():
            msg = QtWidgets.QMessageBox()
            msg.setWindowTitle("Bravo!")
            if len(self.difficultes) != 0:
                msg.setText("Bravo! Tu connais tous les mots de vocabulaire de la liste!\nVoici les mots que tu ne connais pas parfaitements:")
            else:
                msg.setText("Bravo! Tu connais tous les mots de vocabulaire de la liste!\nVoici la liste que tu viens de réviser:")
                for i in range(self.nb_mots):   self.difficultes.append([self.mot[i], self.trad[i]])

            window = ListeWindow(self, self.difficultes)
            window.show()
            msg.exec()

            self.ViderTout()

    def UpdateMot(self):
        """
        Mettre à jour les traductions suggérés dans les boutons et le mot dans le label.
        :return: None
        """
        self.ui.prop1.setText(self.proptrad[0])
        self.ui.prop2.setText(self.proptrad[1])
        self.ui.prop3.setText(self.proptrad[2])
        self.ui.motvoca.setText(self.propmot)

    def UpdateScore(self):
        """
        Mettre à jour le score dans la fenêtre.
        :return: None
        """
        self.ui.score.setText("{0} / {1}".format(self.mot_connus, self.nb_mots))

    def TirerMots(self):
        """
        Tirer aléatoirement les 3 traductions suggérées.
        :return: Boolean
        """

        # Choix aléatoire des mots
        if len(self.mot_q) != 0:
            self.index = [randint(0, len(self.mot) - 1) for _ in range(3)]

            self.index_q = randint(0, 2)
            self.index_mot_q = randint(0, len(self.mot_q) - 1)
            index_mot = self.mot.index(self.mot_q[self.index_mot_q])

            while self.index[0] == self.index[1] or self.index[0] == self.index[2] or self.index[1] == self.index[2] or self.index[0] == index_mot or self.index[1] == index_mot or self.index[2] == index_mot:
                self.index = [randint(0, len(self.mot) - 1) for _ in range(3)]

            self.index[self.index_q] = self.index_mot_q

            self.propmot = self.mot_q[self.index_mot_q]
            self.proptrad = [self.trad[i] for i in self.index]
            self.proptrad[self.index_q] = self.trad_q[self.index_mot_q]

            self.UpdateMot()

            return False
        else:
            return True

    def Jeu(self):
        """
        Début du jeu.
        :return: None
        """
        # Récupérer les mots
        if self.ParseData():
            # Variables du jeu
            if self.modeinverse:
                temp = [mot for mot in self.mot]
                self.mot = [trad for trad in self.trad]
                self.trad = [mot for mot in temp]

            self.mot_q = [mot for mot in self.mot]
            self.trad_q = [trad for trad in self.trad]
            self.mot_connus = 0
            self.nb_mots = len(self.mot)

            # Score en cours
            self.UpdateScore()

            self.partie_en_cours = True

            self.TirerMots()

    def ParseData(self):
        """
        Aller chercher tous les mots et leurs signification dans le fichier.
        Retourne True si le fichier peut être lu, et false sinon.
        :return: Boolean
        """
        try:
            file = open(self.filepath, 'r')
            data = file.read().split("\n")
            data.remove("")
            file.close()

            self.mot = [d.split("|")[0] for d in data]
            self.trad = [d.split("|")[1] for d in data]

            if len(self.mot) > 2:   return True

            msg = QtWidgets.QMessageBox()
            msg.setWindowTitle("ERREUR")
            msg.setText("Impossible de charger la liste de vocabulaire, elle ne contient pas assez de mots!")
            msg.exec()

            return False
        except:
            return False