Exemple #1
0
 def timeout(self):
     """ 타임아웃 이벤트가 발생하면 호출되는 메서드 """
     # 어떤 타이머에 의해서 호출되었는지 확인
     sender = self.sender()
     if self.in_processing:
         return
     # 메인 타이머
     if id(sender) == id(self.timer):
         current_time = QTime.currentTime().toString("hh:mm:ss")
         # 상태바 설정
         state = ""
         if self.kiwoom.get_connect_state() == 1:
             state = self.server_gubun + " 서버 연결중"
         else:
             state = "서버 미연결"
         self.statusbar.showMessage("현재시간: " + current_time + " | " + state)
         # log
         if self.kiwoom.msg:
             self.logTextEdit.append(self.kiwoom.msg)
             self.kiwoom.msg = ""
     elif id(sender) == id(self.timer_stock):
         automatic_order_time = QTime.currentTime().toString("hhmm")
         # 자동 주문 실행
         # 1100은 11시 00분을 의미합니다.
         print("current time: %d" % int(automatic_order_time))
         if self.is_automatic_order and int(automatic_order_time) >= 900 and int(automatic_order_time) <= 930:
             self.is_automatic_order = False
             self.automatic_order()
             self.set_automated_stocks()
     # 실시간 조회 타이머
     else:
         if self.realtimeCheckBox.isChecked():
             self.inquiry_balance()
    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return QVariant()
        if index.row() >= len(self.songs) or index.row() < 0:
            return QVariant()

        song = self.songs[index.row()]
        if role in (Qt.DisplayRole, Qt.ToolTipRole):
            if index.column() == 0:
                return self._source_name_map.get(song.source, '').strip()
            elif index.column() == 1:
                return song.title
            elif index.column() == 2:
                m, s = parse_ms(song.duration)
                duration = QTime(0, m, s)
                return duration.toString('mm:ss')
            elif index.column() == 3:
                return song.artists_name
            elif index.column() == 4:
                return song.album_name
        elif role == Qt.TextAlignmentRole:
            if index.column() == 0:
                return Qt.AlignCenter | Qt.AlignBaseline
        elif role == Qt.EditRole:
            return 1
        elif role == Qt.UserRole:
            return song
        return QVariant()
Exemple #3
0
    def update_duration(self, current_duration):
        """Calculate the time played and the length of the song.

        Both of these times are sent to duration_label() in order to display the
        times on the toolbar.
        """
        duration = self.duration

        if current_duration or duration:
            time_played = QTime((current_duration / 3600) % 60, (current_duration / 60) % 60,
                                (current_duration % 60), (current_duration * 1000) % 1000)
            song_length = QTime((duration / 3600) % 60, (duration / 60) % 60, (duration % 60),
                                (duration * 1000) % 1000)

            if duration > 3600:
                time_format = "hh:mm:ss"
            else:
                time_format = "mm:ss"

            time_display = "{} / {}" .format(time_played.toString(time_format), song_length.toString(time_format))

        else:
            time_display = ""

        self.duration_label.setText(time_display)
Exemple #4
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.updateTimer = QTimer(self)
        self.demoStartTime = QTime()
        self.fpsTime = QTime()
        self.background = QPixmap()

        self.scene = None
        self.mainSceneRoot = None
        self.frameTimeList = []
        self.fpsHistory = []

        self.currentFps = Colors.fps
        self.fpsMedian = -1
        self.fpsLabel = None
        self.pausedLabel = None
        self.doneAdapt = False
        self.useTimer = False
        self.updateTimer.setSingleShot(True)
        self.companyLogo = None
        self.qtLogo = None

        self.setupWidget()
        self.setupScene()
        self.setupSceneItems()
        self.drawBackgroundToPixmap()
Exemple #5
0
    def __init__(self, parent=None):
        super(GLWidget, self).__init__(parent)

        midnight = QTime(0, 0, 0)
        random.seed(midnight.secsTo(QTime.currentTime()))

        self.object = 0
        self.xRot = 0
        self.yRot = 0
        self.zRot = 0
        self.image = QImage()
        self.bubbles = []
        self.lastPos = QPoint()

        self.trolltechGreen = QColor.fromCmykF(0.40, 0.0, 1.0, 0.0)
        self.trolltechPurple = QColor.fromCmykF(0.39, 0.39, 0.0, 0.0)

        self.animationTimer = QTimer()
        self.animationTimer.setSingleShot(False)
        self.animationTimer.timeout.connect(self.animate)
        self.animationTimer.start(25)

        self.setAutoFillBackground(False)
        self.setMinimumSize(200, 200)
        self.setWindowTitle("Overpainting a Scene")
Exemple #6
0
    def addClicked(self, fileNames):
        """Fill the playlist with fileNames' info."""
        if fileNames is None:
            return
        self.playlistTable.setSortingEnabled(False)
        songsToAdd = len(fileNames)
        for name, row in zip(fileNames, range(songsToAdd)):
            currentRow = row + self.playlist.mediaCount() - songsToAdd
            self.playlistTable.insertRow(currentRow)

            artist = self.playerCore.getArtist(name)[0]
            title = self.playerCore.getTitle(name)[0]
            album = self.playerCore.getAlbum(name)[0]
            seconds = self.playerCore.getDuration(name)
            duration = QTime(0, seconds // 60, seconds % 60)
            duration = duration.toString('mm:ss')

            rowInfo = [artist, title, album, duration]
            for info, index in zip(rowInfo, range(4)):
                cell = QTableWidgetItem(info)
                self.playlistTable.setItem(currentRow, index, cell)
                font = QFont(info, weight=QFont.Normal)
                cell.setFont(font)
                cell.setTextAlignment(Qt.AlignCenter)
        self.playlistTable.setSortingEnabled(True)

        for index in range(4):
            self.playlistTable.resizeColumnToContents(index)
    def tick(self):
        if self.paused or not self.effect:
            return

        t = self.tickTimer.msecsTo(QTime.currentTime())
        self.tickTimer = QTime.currentTime()
        self.effect.tick(t / 10.0)
Exemple #8
0
 def update_state(self, ms):
     """update current state in progress Label
     :param ms: time mm:ss
     """
     m, s = parse_ms(ms)
     position = QTime(0, m, s)
     position_text = position.toString('mm:ss')
     self.setText(position_text + '/' + self.duration_text)
Exemple #9
0
 def set_duration(self, ms):
     """set duration text
     :param ms: time mm:ss
     """
     m, s = parse_ms(ms)  # deal minute and second to QTime arguments
     duration = QTime(0, m, s)
     print(m,s)
     self.duration_text = duration.toString('mm:ss')
Exemple #10
0
 def checkDeadDateTime(self):
     print(QDate.currentDate())
     print(QTime.currentTime())
     datetime=QDateTime(QDate.currentDate(),QTime.currentTime())
     if(datetime<=self.deaddatetime):
         return True
     else:
         return False
Exemple #11
0
class AutoSaver(QObject):
    """
    Class implementing the auto saver.
    """
    AUTOSAVE_IN = 1000 * 3
    MAXWAIT = 1000 * 15
    
    def __init__(self, parent, save):
        """
        Constructor
        
        @param parent reference to the parent object (QObject)
        @param save slot to be called to perform the save operation
        @exception RuntimeError raised, if no parent is given
        """
        super(AutoSaver, self).__init__(parent)
        
        if parent is None:
            raise RuntimeError("AutoSaver: parent must not be None.")
        
        self.__save = save
        
        self.__timer = QBasicTimer()
        self.__firstChange = QTime()
    
    def changeOccurred(self):
        """
        Public slot handling a change.
        """
        if self.__firstChange.isNull():
            self.__firstChange.start()
        
        if self.__firstChange.elapsed() > self.MAXWAIT:
            self.saveIfNeccessary()
        else:
            self.__timer.start(self.AUTOSAVE_IN, self)
    
    def timerEvent(self, evt):
        """
        Protected method handling timer events.
        
        @param evt reference to the timer event (QTimerEvent)
        """
        if evt.timerId() == self.__timer.timerId():
            self.saveIfNeccessary()
        else:
            super(AutoSaver, self).timerEvent(evt)
    
    def saveIfNeccessary(self):
        """
        Public method to activate the save operation.
        """
        if not self.__timer.isActive():
            return
        
        self.__timer.stop()
        self.__firstChange = QTime()
        self.__save()
 def load_settings(self, settings):
     if settings is not None:
         cue = Application().cue_model.get(settings['target_id'])
         if cue is not None:
             self.cue_id = settings['target_id']
             self.seekEdit.setTime(
                 QTime.fromMSecsSinceStartOfDay(settings['time']))
             self.seekEdit.setMaximumTime(
                 QTime.fromMSecsSinceStartOfDay(cue.media.duration))
             self.cueLabel.setText(cue.name)
Exemple #13
0
 def updateDurationInfo(self, currentInfo):
   duration = self.duration
   tStr = ""
   if currentInfo or duration:
     currentTime = QTime((currentInfo/3600)%60, (currentInfo/60)%60, currentInfo%60, (currentInfo*1000)%1000)
     totalTime = QTime((duration/3600)%60, (duration/60)%60, duration%60, (duration*1000)%1000);
     format = 'hh:mm:ss' if duration > 3600 else 'mm:ss'
     # tStr = currentTime.toString(format) + " / " + totalTime.toString(format)
     tStr = currentTime.toString(format)
   else:
     Str = ""
   self.music.songTime.setText(tStr)
Exemple #14
0
 def added(self, added):
     """Saves music info in musicOrder."""
     for name, index in zip(
             self.musicOrder[self.playlist.mediaCount() - added:],
             range(self.playlist.mediaCount() - added,
                   len(self.musicOrder))):
         name = name[0]
         artist = self.getArtist(name)[0]
         title = self.getTitle(name)[0]
         album = self.getAlbum(name)[0]
         seconds = self.getDuration(name)
         duration = QTime(0, seconds // 60, seconds % 60)
         duration = duration.toString('mm:ss')
         self.musicOrder[index].extend(
             [artist, title, album, duration])
Exemple #15
0
 def __init__(self, parent=None):
     """
     Constructor
     
     @param parent referenec to the parent object (QObject)
     """
     super(Connection, self).__init__(parent)
     
     self.__greetingMessage = self.tr("undefined")
     self.__username = self.tr("unknown")
     self.__serverPort = 0
     self.__state = Connection.WaitingForGreeting
     self.__currentDataType = Connection.Undefined
     self.__numBytesForCurrentDataType = -1
     self.__transferTimerId = 0
     self.__isGreetingMessageSent = False
     self.__pingTimer = QTimer(self)
     self.__pingTimer.setInterval(PingInterval)
     self.__pongTime = QTime()
     self.__buffer = QByteArray()
     self.__client = None
     
     self.readyRead.connect(self.__processReadyRead)
     self.disconnected.connect(self.__disconnected)
     self.__pingTimer.timeout.connect(self.__sendPing)
     self.connected.connect(self.__sendGreetingMessage)
Exemple #16
0
    def add_item(self, song_model):
        music_item = QTableWidgetItem(song_model.title)
        album_item = QTableWidgetItem(song_model.album_name)
        artist_item = QTableWidgetItem(song_model.artists_name)
        m, s = parse_ms(song_model.length)
        duration = QTime(0, m, s)
        length_item = QTableWidgetItem(duration.toString())

        row = self.rowCount()
        self.setRowCount(row + 1)
        self.setItem(row, 1, music_item)
        self.setItem(row, 2, artist_item)
        self.setItem(row, 3, album_item)
        self.setItem(row, 4, length_item)

        self.songs.append(song_model)
Exemple #17
0
    def set_settings(self):
        if self.traffic_id:
            query = """SELECT Position, Data, Table_Data, Note FROM staff_worker_traffic WHERE Id = %s"""
            sql_traffic = my_sql.sql_select(query, (self.traffic_id, ))
            if "mysql.connector.errors" in str(type(sql_traffic)):
                QMessageBox.critical(self, "Ошибка sql получения записей", sql_traffic.msg, QMessageBox.Ok)
                return False
            self.le_position.setText(str(sql_traffic[0][0]))
            self.dt_date.setDateTime(sql_traffic[0][1])
            self.le_note.setText(sql_traffic[0][3])
            if sql_traffic[0][2]:
                self.dt_tabel_date.setDateTime(sql_traffic[0][2])
            else:
                min = sql_traffic[0][1].minute
                if 0 <= min <= 15:
                    tab_date = sql_traffic[0][1].replace(minute=0)
                elif 16 <= min <= 45:
                    tab_date = sql_traffic[0][1].replace(minute=30)
                else:
                    tab_date = sql_traffic[0][1].replace(minute=0)
                    hour_up = sql_traffic[0][1].hour + 1
                    if hour_up < 24:
                        tab_date = tab_date.replace(hour=hour_up)
                    else:
                        day = sql_traffic[0][1].day
                        tab_date = tab_date.replace(day=day + 1, hour=hour_up-24)

                self.dt_tabel_date.setDateTime(tab_date)

        else:
            date = self.select_date or QDateTime.currentDateTime()
            datetime = QDateTime(date, QTime.currentTime())
            self.dt_date.setDateTime(datetime)
            self.dt_tabel_date.setDateTime(datetime)
Exemple #18
0
 def __init__(self, mode=QPrinter.ScreenResolution):
     """
     Constructor
     
     @param mode mode of the printer (QPrinter.PrinterMode)
     """
     super(Printer, self).__init__(mode)
     
     self.setMagnification(Preferences.getPrinter("Magnification"))
     if Preferences.getPrinter("ColorMode"):
         self.setColorMode(QPrinter.Color)
     else:
         self.setColorMode(QPrinter.GrayScale)
     if Preferences.getPrinter("FirstPageFirst"):
         self.setPageOrder(QPrinter.FirstPageFirst)
     else:
         self.setPageOrder(QPrinter.LastPageFirst)
     self.setPageMargins(
         Preferences.getPrinter("LeftMargin") * 10,
         Preferences.getPrinter("TopMargin") * 10,
         Preferences.getPrinter("RightMargin") * 10,
         Preferences.getPrinter("BottomMargin") * 10,
         QPrinter.Millimeter
     )
     printerName = Preferences.getPrinter("PrinterName")
     if printerName:
         self.setPrinterName(printerName)
     self.time = QTime.currentTime().toString(Qt.LocalDate)
     self.date = QDate.currentDate().toString(Qt.LocalDate)
     self.headerFont = Preferences.getPrinter("HeaderFont")
Exemple #19
0
def main():
    if settings.get('log:errors'):
        log_filename = settings.get('log:filename')
        if log_filename:
            try:
                log_file = open(log_filename,"w")
                print ('Redirecting stderr/stdout... to %s' % log_filename)
                sys.stderr = log_file
                sys.stdout = log_file
            except IOError:
                print("Lector could not open log file '%s'!\n" % log_filename \
                      + " Redirecting will not work.")
        else:
            print("Log file is not set. Please set it in settings.")

    app = QApplication(sys.argv)
    opts = [str(arg) for arg in app.arguments()[1:]]
    if '--no-scanner' in opts:
        scanner = False
    else:
        scanner = True
    qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime()))

    locale = settings.get('ui:lang')
    if not locale:
        locale = QLocale.system().name()
    qtTranslator = QTranslator()
    if qtTranslator.load(":/translations/ts/lector_" + locale, 'ts'):
        app.installTranslator(qtTranslator)

    window = Window(scanner)
    window.show()
    app.exec_()
Exemple #20
0
    def showTime(self):
        time = QTime.currentTime()
        text = time.toString('hh:mm')
        if (time.second() % 2) == 0:
            text = text[:2] + ' ' + text[3:]

        self.display(text)
Exemple #21
0
 def _process_finished(self, code, status):
     frmt = OutputWidget.Format.NORMAL
     if status == QProcess.NormalExit == code:
         text = translations.TR_PROCESS_EXITED_NORMALLY % code
     else:
         text = translations.TR_PROCESS_INTERRUPTED
         frmt = OutputWidget.Format.ERROR
     self.outputw.append_text(text, frmt)
     if self.__current_process is self.main_process:
         tformat = QTime(0, 0, 0, 0).addMSecs(
             self.__elapsed.elapsed() + 500)
         time = tformat.toString("h:mm:ss")
         if time.startswith("0:"):
             # Don't display zero hours
             time = time[2:]
         self.outputw.append_text(translations.TR_ELAPSED_TIME.format(time))
     self.outputw.setReadOnly(True)
Exemple #22
0
 def utc(self, rise_set, what):
     ''' Convert sun rise/set from UTC to local time
         'rise_set' is 'Sunrise' or 'Sunset when it is for weatherdata
         or the index of hour in day forecast when dayforecast'''
     listtotime = ''
     # Create a list ['h', 'm', 's'] and pass it to QTime
     if what == 'weatherdata':
         listtotime = self.weatherdata[rise_set].split('T')[1].split(':')
     elif what == 'dayforecast':
         listtotime = self.tree_day[4][rise_set].get('from').split(
             'T')[1].split(':')
     suntime = QTime(int(listtotime[0]), int(listtotime[1]), int(
         listtotime[2]))
     # add the diff UTC-local in seconds
     utc_time = suntime.addSecs(time.localtime().tm_gmtoff)
     utc_time_str = utc_time.toString()
     return utc_time_str
    def select_cue(self):
        if self.cueDialog.exec_() == self.cueDialog.Accepted:
            cue = self.cueDialog.selected_cues()[0]

            self.cue_id = cue.id
            self.seekEdit.setMaximumTime(
                QTime.fromMSecsSinceStartOfDay(cue.media.duration))
            self.cueLabel.setText(cue.name)
    def on_resetPushButton_clicked(self):

        self.timer.stop()
        self.shiverTimer = QTime(0, 0, 0)
        self.timerLCDNumber.display(self.shiverTimer.toString(self._FORMAT))

        if self.stortPushButton.text() == self._STOP:
            self.stortPushButton.setText(self._START)
Exemple #25
0
 def onTimeChanged(self, time):
     c_time = QTime.currentTime()
     if (c_time > time):
         self.ui.timeEdit.setTime(c_time)
         return
     diff = Alarm.__get_diff(self.ui.timeEdit.time().addSecs(60))
     print("TIME CHANGED", time, diff)
     self.timer.timer.start(diff + (60*1000))
    def updateClock(self):
        time = QTime.currentTime()
        if settings.fullscreenSettings.get("clock-show-seconds", True):
            timeStr = time.toString("hh:mm:ss")
        else:
            timeStr = time.toString("hh:mm")

        self.setText(timeStr)
    def updateClock(self):

        # What time is it ?
        cur = QTime.currentTime()

        self.from_time_updater = True
        self.ui.timeEdit.setTime(cur)
        self.from_time_updater = False
    def _widgets(self):

        self.shiverTimer = QTime(0, 0, 0)
        self.timer = QTimer()
        self.timerLCDNumber = QLCDNumber()
        self.timerLCDNumber.setDigitCount(12)
        self.timerLCDNumber.display("00:00:00.000")
        self.stortPushButton = QPushButton(self._START)
        self.resetPushButton = QPushButton(self._RESET)
Exemple #29
0
 def saveIfNeccessary(self):
     """
     Public method to activate the save operation.
     """
     if not self.__timer.isActive():
         return
     
     self.__timer.stop()
     self.__firstChange = QTime()
     self.__save()
Exemple #30
0
 def handle_time_update(self):
     time = QTime.currentTime()
     if self.mode == "hour":
         self.setRotation(time.hour() * 360. / 12.
                          + time.minute() * 360. / (60*12))
     elif self.mode == "minute":
         self.setRotation(time.minute() * 360. / 60.
                          + time.second() / 60. * 360. / 60.)
     elif self.mode == "second":
         self.setRotation(time.second() * 360. / 60.)
Exemple #31
0
def get_total_seconds(t: QTime) -> int:
    return t.hour() * 3600 + t.minute() * 60 + t.second()
Exemple #32
0
        minuteTime = timef.minute()
        hourTime = timef.hour()
        secTime = timef.second()
        print(str(hourTime)+" : "+str(minuteTime))
        print("next")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow_V2()
    win.showFullScreen()
    sys.exit(app.exec_())
'''

now = QDate.currentDate()

print(now.toString(Qt.ISODate))
print(now.toString(Qt.DefaultLocaleLongDate))

datetime = QDateTime.currentDateTime()

print(datetime.toString())

timef = QTime.currentTime()

print(timef.toString(Qt.DefaultLocaleLongDate))
'''
while True:
    timef =QTime.currentTime()
    print(timef.toString(Qt.DefaultLocaleLongDate))
'''
        pass


class GraphicsView(QGraphicsView):
    def resizeEvent(self, e):
        pass


if __name__ == "__main__":

    import sys
    import math

    app = QApplication(sys.argv)

    qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime()))

    scene = QGraphicsScene(-200, -200, 400, 400)

    for i in range(10):
        item = ColorItem()
        angle = i * 6.28 / 10.0
        item.setPos(math.sin(angle) * 150, math.cos(angle) * 150)
        scene.addItem(item)

    robot = Robot()
    robot.setTransform(QTransform.fromScale(1.2, 1.2), True)
    robot.setPos(0, -20)
    scene.addItem(robot)

    view = GraphicsView(scene)
 def durationChanged(self, duration):
     self.positionSlider.setRange(0, duration)
     mtime = QTime(0, 0, 0, 0)
     mtime = mtime.addMSecs(self.mediaPlayer.duration())
     self.elbl.setText(mtime.toString())
Exemple #35
0
#!/usr/bin/python3

from PyQt5.QtCore import QDate, QTime, QDateTime, Qt

d1 = QDate(2017, 12, 9)
t1 = QTime(18, 50, 59)

dt1 = QDateTime(d1, t1, Qt.LocalTime)

#locale = QLocale(QLocale.English, QLocale.UnitedKingdom)

#curr_locale = QLocale()
#print(curr_locale.nativeCountryName(), curr_locale.name(), curr_locale.nativeLanguageName())

print("Datetime: {0}".format(dt1.toString()))
print("Date: {0}".format(d1.toString()))
print("Time: {0}".format(t1.toString()))        
    def setup_Ui(self,text):
        self.setObjectName("View_Menu_Second_Page")
        self.resize(800, 600)
        self.label = QtWidgets.QLabel(self)
        self.label.setGeometry(QtCore.QRect(230, 20, 321, 51))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.BlueButton = QtWidgets.QPushButton(self)
        self.BlueButton.setGeometry(QtCore.QRect(630, 180, 96, 96))
        self.BlueButton.setStyleSheet("#BlueButton {\n"
"    background-color: #303d5e;\n"
"    /*minimum size*/\n"
"    min-width: 96px;\n"
"    max-width: 96px;\n"
"    min-height: 96px;\n"
"    max-height: 96px;\n"
"    border-radius: 48px; /*Round*/\n"
"    color: #FFFFFF;\n"
"}\n"
"#BlueButton:hover {\n"
"    background-color: #516cb0;\n"
"}\n"
"#BlueButton:pressed {\n"
"    background-color: #04070f;\n"
"}")
        self.BlueButton.setObjectName("BlueButton")
        self.label_2 = QtWidgets.QLabel(self)
        self.label_2.setGeometry(QtCore.QRect(50, 100, 711, 51))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self)
        self.label_3.setGeometry(QtCore.QRect(100, 300, 571, 291))
        self.label_3.setText("")
        self.label_3.setPixmap(QtGui.QPixmap("./Pictures/"+text+".png"))
        self.label_3.setScaledContents(True)
        self.label_3.setObjectName("label_3")
        self.dateEdit = QtWidgets.QDateEdit(self)
        self.dateEdit.setGeometry(QtCore.QRect(120, 200, 241, 81))
        font = QtGui.QFont()
        font.setFamily("MV Boli")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.dateEdit.setFont(font)
        self.dateEdit.setCalendarPopup(True)
        self.dateEdit.setDate(QDate.currentDate())
        self.dateEdit.setObjectName("dateEdit")
        self.timeEdit = QtWidgets.QTimeEdit(self)
        self.timeEdit.setTime(QTime.currentTime())
        self.timeEdit.setGeometry(QtCore.QRect(360, 200, 241, 81))
        font = QtGui.QFont()
        font.setFamily("MV Boli")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.timeEdit.setFont(font)
        self.timeEdit.setObjectName("timeEdit")
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", text))
        self.BlueButton.setText(_translate("Form", "Submit"))
        self.label_2.setText(_translate("Form", "Please Select The Date and Time You Would Like To View"))
Exemple #37
0
 def updateWorkEndTime(self):
     self.workEndTime = QTime(
         self.workHoursSpinBox.value(),
         self.workMinutesSpinBox.value(),
         self.workSecondsSpinBox.value(),
     )
Exemple #38
0
 def setDuration(self, duration):
     self.te_duration.setTime(QTime(0, duration, 0))
Exemple #39
0
 def on_position_changed(self, position):
     m, s = parse_ms(position)
     t = QTime(0, m, s)
     self.position_label.setText(t.toString('mm:ss'))
Exemple #40
0
 def on_duration_changed(self, duration):
     m, s = parse_ms(duration)
     t = QTime(0, m, s)
     self.duration_label.setText(t.toString('mm:ss'))
 def updateTime(self):
     if self.useInternalTime.isChecked():
         now = self.internalTime
     else:
         now = QTime.currentTime()
     self.timeEdit.setTime(now)
class PyClockSetup(QtWidgets.QDialog):
    hexColor = '#ffffff'
    serialData = ''
    internalTime = QTime.currentTime()

    def __init__(self, parent=None):
        super(PyClockSetup, self).__init__()

        self.serial = QSerialPort(self)
        uic.loadUi('pyclocksetup.ui', self)
        self.show()

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateTime)
        self.timer.start(1000)

        self.serial = QSerialPort(self)
        self.cp.colorChanged.connect(self.changeColor)
        self.connectButton.clicked.connect(self.serialConnect)
        self.setClockButton.clicked.connect(self.setClock)
        self.blinkingDots.toggled.connect(self.setBlinkingDots)
        self.leadingZero.toggled.connect(self.setLeadingZero)
        self.autoBrightness.toggled.connect(self.setAutoBrightness)
        self.segmentTest.toggled.connect(self.setSegmentTest)
        self.brightnessSlider.valueChanged.connect(self.changeBrightness)

        self.colorLabel.setStyleSheet('QLabel {background-color: #ffffff; }')

        availablePorts = QSerialPortInfo.availablePorts()
        for port in availablePorts:
            self.serialPorts.addItem(port.portName())

    def serialConnect(self):
        try:
            self.serial.close()
        except:
            pass
        port = self.serialPorts.currentText()
        self.serial.setPortName(port)
        if self.serial.open(QtCore.QIODevice.ReadWrite):
            self.serial.setBaudRate(115200)
            self.serial.readyRead.connect(self.serialRead)
        else:
            QtWidgets.QMessageBox.warning(self, 'Warning', \
                    'Cannot connect to {}.'.format(port))
            return

    def changeColor(self, hex):
        self.hexColor = hex
        self.colorLabel.setStyleSheet(
            'QLabel {{background-color: {}; }}'.format(hex))
        (r, g, b, _) = QtGui.QColor(hex).getRgb()
        print('rgb = ', r, g, b)

        brightness = self.brightnessSlider.value() / 100.0
        r = r / self.redDiv.value() * brightness
        b = b / self.blueDiv.value() * brightness
        g = g / self.greenDiv.value() * brightness

        str = 'color={},{},{}\n'.format(int(r), int(g), int(b))
        print(str)
        self.serial.write(str.encode())

    def changeBrightness(self):
        self.changeColor(self.hexColor)

    def setClock(self):
        str = 'time=' + self.timeEdit.time().toString("hh:mm:ss")
        print(str)
        self.serial.write(str.encode())

    def setBlinkingDots(self):
        str = 'blink={}'.format((0, 1)[self.blinkingDots.isChecked()])
        print(str)
        self.serial.write(str.encode())

    def setLeadingZero(self):
        str = 'zero={}'.format((0, 1)[self.leadingZero.isChecked()])
        print(str)
        self.serial.write(str.encode())

    def setAutoBrightness(self):
        str = 'auto={}'.format((0, 1)[self.autoBrightness.isChecked()])
        print(str)
        self.serial.write(str.encode())

    def setSegmentTest(self):
        str = 'test={}'.format((0, 1)[self.segmentTest.isChecked()])
        print(str)
        self.serial.write(str.encode())

    def updateTime(self):
        if self.useInternalTime.isChecked():
            now = self.internalTime
        else:
            now = QTime.currentTime()
        self.timeEdit.setTime(now)

    @QtCore.pyqtSlot()
    def serialRead(self):
        s = self.serial.readAll()
        try:
            self.serialData += bytes(s).decode('utf-8')
        except:
            print("decoding error...")

        if '\n' in self.serialData:
            print(self.serialData)
            self.internalTime = QTime.fromString(self.serialData.rstrip('\n'))
            print('Internal time: ', self.internalTime.toString())
            self.serialData = ''
class Pricing_Template_Main(QThread):
    """
    Runs in thread.
    """

    txtProgress = pyqtSignal(str)
    countProgress = pyqtSignal(int)
    currStatus = pyqtSignal(list)

    def __init__(self, src_folder, tgt_folder, keyword, templates, pt_model):
        super(Pricing_Template_Main, self).__init__()

        self._src_folder = src_folder
        self._tgt_folder = tgt_folder
        self._keyword = keyword
        self._l_templates = templates
        self._pt_model = pt_model

        self.timer = QTime()
        self.elapsed_time = None

        self.is_running = True
        self._progress_count = 0
        self._abort_flg = False
        self._cancel_flg = False
        self._main_dir = os.getcwd()

        self.src_price_cnt = 0
        self.temp_price_cnt = 0
        self.src_scales_cnt = 0
        self.temp_scales_cnt = 0
        self.src_minf_cnt = 0
        self.temp_minf_cnt = 0

        self.start_row = self._pt_model._config['StartRow']

    def run(self):
        ''' 
        Read source file to DataFrame and Excel file (for validation)
        Filter dataframe per Usage Type
        Perform Mappings
        Populate the validated dataframe to template
        '''

        # Read source files and load to dataframe

        # Start timer

        self.timer.start()

        self.txtProgress.emit('Loading source files to dataframes.')

        success = False
        while not success:
            try:

                self.df_price_all = self._pt_model.read_source_to_DF(
                    self._keyword, self._src_folder, 'Pricing')
                df_scales_all = self._pt_model.read_source_to_DF(
                    self._keyword, self._src_folder, 'Scales')
                df_minf_all = self._pt_model.read_source_to_DF(
                    self._keyword, self._src_folder, 'MINF')

                success = True
            except Exception as e:

                self.currStatus.emit([self._keyword, 'Load Source', str(e)])

                response = None
                while response is None:
                    response = self._pt_model.replyBtn
                    time.sleep(1)

                if response == QMessageBox.Close:
                    self._abort_flg = True
                    self._pt_model.replyBtn = None
                    success = True

        if not self._abort_flg:

            #Loop on the templates found

            for i in self._l_templates:

                usage_type = i[0]
                ''' 
                Get current status
                c = Completed
                i = Ignored
                NULL = Not started (default)
                '''

                if self._cancel_flg: break

                status = self._pt_model.get_template_status(usage_type)

                if status == '':

                    self.txtProgress.emit('Processing ' + usage_type)

                    # Get template worksheets

                    template_file = self._pt_model.get_template_filename(
                        usage_type)
                    template_filename = template_file.split('\\')[-1]

                    # Load Template Workbook

                    self.txtProgress.emit(
                        'Loading Pricing Template to dataframe.')

                    success = False
                    while not success:
                        try:
                            temp_workbook = self._pt_model.load_workbook(
                                template_file)
                            temp_worksheets = self._pt_model.get_worksheets(
                                temp_workbook)
                            success = True
                        except Exception as e:

                            self.currStatus.emit(
                                [usage_type, 'Load Template',
                                 str(e)])

                            response = None
                            while response is None:
                                response = self._pt_model.replyBtn
                                time.sleep(1)

                            if response == QMessageBox.Abort:
                                self._abort_flg = True
                                self._pt_model.replyBtn = None
                                break
                            elif response == QMessageBox.Retry:
                                self._pt_model.replyBtn = None
                            elif response == QMessageBox.Ignore:
                                self._pt_model.update_template_status(
                                    usage_type, 'i')
                                self._pt_model.replyBtn = None
                                continue
                            elif response == QMessageBox.Close:
                                self._abort_flg = True
                                self._pt_model.replyBtn = None
                                break

                    # Filter & Validate Usage type

                    df_price = self._pt_model.filter_df(
                        usage_type, self.df_price_all)
                    df_scales = self._pt_model.filter_df(
                        usage_type, df_scales_all)
                    df_minf = self._pt_model.filter_df(usage_type, df_minf_all)

                    # Prep Source data frame

                    # Drop column fld_Contract_Type

                    df_price.drop('fld_Contract_Type', axis=1, inplace=True)

                    # Rename Column names in dataframe

                    df_price.rename(
                        columns={
                            'Partner_Number': 'fld_Business_Partner',
                            'BillingMaterial_ID_ToBe':
                            'fld_OTC_Billing_Material_ID',
                            'fld_Requestor': 'fld_Requester',
                            'fld_Price': 'fld_Price_Amount',
                            'fld_Pricing_Bundle_ID': 'fld_Bundle_ID',
                            'fld_Pricing_Contract_Type': 'fld_Contract_Type',
                            'fld_Pricing_Contract_SubType':
                            'fld_Contract_Sub_Type',
                            'fld_SSCALE_ID': 'fld_Shared_Scale_ID',
                            'fld_SSCALE_BP': 'fld_Shared_Scale_BP',
                            #'fld_Reach_Indicator': 'fld_Reach_Ind',
                            'fld_Flight_Range_Code': 'fld_Flight_Range'
                        },
                        inplace=True)

                    # Add columns to dataframe
                    # Common Audit Fields

                    df_price['fld_Created_By'] = ''
                    df_price['fld_Last_Upd'] = ''
                    df_price['fld_Last_Upd_By'] = 'DATA MIG'
                    df_price['fld_Created'] = ''

                    self.txtProgress.emit(
                        'Processing ' + usage_type +
                        ' - Filtering and Validating dataframe.')

                    #Loop on the template worksheet

                    for sheet in temp_worksheets:

                        success = False
                        while not success:

                            try:

                                if ('price' in sheet.title.lower()
                                        and 'scale' not in sheet.title.lower()
                                    ) or ('minq' in sheet.title.lower()
                                          or 'caps' in sheet.title.lower()
                                          or 'flight' in sheet.title.lower()):

                                    self.src_price_cnt = df_price.shape[0]

                                    if not df_price.empty and not self._cancel_flg:

                                        # Mappings for CAP, Flight range and MINQ

                                        if 'minq' in sheet.title.lower(
                                        ) or 'caps' in sheet.title.lower(
                                        ) or 'flight' in sheet.title.lower():

                                            self.txtProgress.emit(
                                                'Started: Processing ' +
                                                usage_type +
                                                ' - Additional mappings for ' +
                                                sheet.title + '.')

                                            df_price['fld_Counter_ID'] = '*'
                                            df_price['fld_Frequency'] = '*'
                                            df_price[
                                                'fld_Type_of_Calendar'] = '*'
                                            df_price['fld_Min_Quantity'] = '*'
                                            df_price[
                                                'fld_Scale_Frequency'] = '*'
                                            df_price[
                                                'fld_Reference_Date'] = df_price[
                                                    'fld_Start_Date']
                                            df_price['fld_Range'] = '*'
                                            df_price['fld_Scale_Price'] = '*'
                                            df_price['fld_Unit_Price'] = '*'
                                            df_price['fld_CAP'] = '*'
                                            df_price[
                                                'fld_Billing_Material'] = df_price[
                                                    'fld_OTC_Billing_Material_ID']

                                            df_price['fld_ID'] = '*'
                                            df_price['fld_Lower_Bound'] = '*'
                                            df_price['fld_Upper_Bound'] = '*'
                                            df_price[
                                                'fld_Flight_Range_Label'] = '*'

                                            self.txtProgress.emit(
                                                'Finished: Processing ' +
                                                usage_type +
                                                ' - Additional mappings for ' +
                                                sheet.title + '.')
                                            time.sleep(3)

                                        # Get Mappings

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Getting mappings for ' +
                                            sheet.title + '.')

                                        l_mapping = self._pt_model.get_template_mappings(
                                            usage_type, sheet, df_price,
                                            'Price')

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Getting mappings for ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        if 'flight' in sheet.title.lower():
                                            start_row = 3
                                        else:
                                            start_row = self.start_row

                                        # Prepare the worksheet

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')

                                        #self._pt_model.prepare_worksheet(sheet, start_row, self.src_price_cnt)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        # Populate data from dataframe to worksheet

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Populating worksheet ' +
                                            sheet.title + '.')

                                        #self.temp_price_cnt = self._pt_model.populate_worksheet(sheet, df_price, l_mapping, start_row)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Populating worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        # Format worksheet

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Formatting worksheet ' +
                                            sheet.title + '.')

                                        #self._pt_model.format_worksheet(sheet, start_row)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Formatting worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                    else:

                                        if 'flight' in sheet.title.lower():
                                            start_row = 3
                                        else:
                                            start_row = self.start_row

                                        # Prepare the worksheet

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')

                                        self._pt_model.prepare_worksheet(
                                            sheet, start_row, 0)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        #Insert empty mapping logs

                                        key_tab = 'Price' + '-' + sheet.title

                                        self._pt_model.append_template_logs(
                                            usage_type, 2, key_tab, [])

                                        if self._cancel_flg: return

                                elif 'scale' in sheet.title.lower():

                                    if not df_scales.empty and not self._cancel_flg:

                                        #Merge DataFrame with Price DataFrame

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Merging scales dataframe to Price.'
                                        )

                                        merged_price_scale_df = self._pt_model.merge_scale_price_df(
                                            df_scales, df_price)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Merging scales dataframe to Price.'
                                        )
                                        time.sleep(3)

                                        # Mapping logic for Type of calendar and reference_date

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Applying additional scales logic.'
                                        )

                                        conditions = [
                                            (merged_price_scale_df[
                                                'Condition_Type'] == 'ZCUY') |
                                            (merged_price_scale_df[
                                                'Condition_Type'] == 'ZCUA'),
                                            (merged_price_scale_df[
                                                'Condition_Type'] == 'ZCUM') |
                                            (merged_price_scale_df[
                                                'Condition_Type'] == 'ZCUX')
                                        ]

                                        choices = ['Yearly', 'Monthly']
                                        merged_price_scale_df[
                                            'fld_Scale_Frequency'] = np.select(
                                                conditions,
                                                choices,
                                                default='*')

                                        merged_price_scale_df[
                                            'fld_Type_of_Calendar'] = merged_price_scale_df[
                                                [
                                                    'Condition_Type',
                                                    'fld_Start_Date'
                                                ]].apply(lambda x: 'Natural'
                                                         if x['Condition_Type'
                                                              ] == 'ZCUM' or
                                                         x['Condition_Type'
                                                           ] == 'ZCUM' else
                                                         ('Natural' if
                                                          (x['Condition_Type'
                                                             ] == 'ZCUY' or
                                                           x['Condition_Type'
                                                             ] == 'ZCUA') and
                                                          x['fld_Start_Date'
                                                            ][:8][4:] == '0101'
                                                          else 'Rolling'),
                                                         axis=1)

                                        merged_price_scale_df[
                                            'fld_Reference_Date'] = merged_price_scale_df[
                                                [
                                                    'fld_Type_of_Calendar',
                                                    'fld_Start_Date'
                                                ]].apply(lambda x: x[
                                                    'fld_Start_Date'] if x[
                                                        'fld_Type_of_Calendar'
                                                    ] == 'Rolling' else 'NA',
                                                         axis=1)

                                        #Add/rename columns to dataframe

                                        merged_price_scale_df[
                                            'fld_Minimum_Fee'] = '*'
                                        merged_price_scale_df[
                                            'fld_Minimum_Fee_BM'] = '*'

                                        merged_price_scale_df.rename(
                                            columns={
                                                'MAPPING_TABLE':
                                                'fld_Mapping_Table',
                                                'RANGE': 'fld_Range',
                                                'SCALE_PRICE':
                                                'fld_Scale_Price',
                                            },
                                            inplace=True)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Applying additional scales logic.'
                                        )
                                        time.sleep(3)

                                        # Get Mappings

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Getting mappings for ' +
                                            sheet.title + '.')

                                        l_mapping = self._pt_model.get_template_mappings(
                                            usage_type, sheet,
                                            merged_price_scale_df, 'Scales')

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Getting mappings for ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        # Prepare the worksheet

                                        self.src_scales_cnt = merged_price_scale_df.shape[
                                            0]

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')

                                        #self._pt_model.prepare_worksheet(sheet, self.start_row, self.src_scales_cnt)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        # Populate data from dataframe to worksheet

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Populating worksheet ' +
                                            sheet.title + '.')

                                        #self.temp_scales_cnt = self._pt_model.populate_worksheet(sheet, merged_price_scale_df, l_mapping, self.start_row)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Populating worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        # Format worksheet

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Formatting worksheet ' +
                                            sheet.title + '.')

                                        #self._pt_model.format_worksheet(sheet, self.start_row)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Formatting worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                    else:

                                        # Prepare the worksheet

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')

                                        self._pt_model.prepare_worksheet(
                                            sheet, self.start_row, 0)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        #Insert empty mapping logs

                                        key_tab = 'Scales' + '-' + sheet.title

                                        self._pt_model.append_template_logs(
                                            usage_type, 2, key_tab, [])

                                        if self._cancel_flg: return

                                elif 'minf' in sheet.title.lower():

                                    if not df_minf.empty and not self._cancel_flg:

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Preparing MINQ dataframe ' +
                                            sheet.title + '.')

                                        # Drop not needed columns added on price dataframe

                                        df_price.drop([
                                            'fld_Counter_ID', 'fld_Frequency',
                                            'fld_Type_of_Calendar',
                                            'fld_Reference_Date',
                                            'fld_Billing_Material'
                                        ],
                                                      axis=1,
                                                      inplace=True)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Preparing MINQ dataframe ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        #Merge DataFrame with Price DataFrame

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Merging MINF dataframe to Price.'
                                        )

                                        df_price_req = df_price[[
                                            'Short_Text_Key',
                                            'fld_Business_Partner',
                                            'HybrisProduct_ID',
                                            'fld_OTC_Billing_Material_ID',
                                            'fld_MF_Counter', 'fld_Discount',
                                            'fld_Discount_Type',
                                            'fld_Discount_Description',
                                            'fld_Item_Category'
                                        ]]

                                        #Merge DataFrame with Price DataFrame

                                        merged_price_minf_df = self._pt_model.merge_minf_price_df(
                                            df_minf, df_price_req)

                                        #Rename columns
                                        merged_price_minf_df.rename(
                                            columns={
                                                'Start_Date':
                                                'fld_Reference_Date',
                                                'Frequency': 'fld_Frequency',
                                                'Currency': 'fld_Currency',
                                                'fld_OTC_Billing_Material_ID':
                                                'fld_Billing_Material',
                                                'Minimum_Fee': 'fld_Min_Fee',
                                                'fld_MF_Counter':
                                                'fld_Counter_ID',
                                            },
                                            inplace=True)

                                        merged_price_minf_df[
                                            'fld_Type_of_Calendar'] = '*'

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Merging MINF dataframe to Price.'
                                        )
                                        time.sleep(3)

                                        # Get Mappings

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Getting mappings for ' +
                                            sheet.title + '.')

                                        l_mapping = self._pt_model.get_template_mappings(
                                            usage_type, sheet,
                                            merged_price_minf_df, 'MINF')

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Getting mappings for ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        # Prepare the worksheet

                                        self.src_minf_cnt = merged_price_minf_df.shape[
                                            0]

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')

                                        #self._pt_model.prepare_worksheet(sheet, self.start_row, self.src_minf_cnt)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        # Populate data from dataframe to worksheet

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Populating worksheet ' +
                                            sheet.title + '.')

                                        #self.temp_minf_cnt = self._pt_model.populate_worksheet(sheet, merged_price_minf_df, l_mapping, self.start_row)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Populating worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        # Format worksheet

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')

                                        #self._pt_model.format_worksheet(sheet, self.start_row)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                    else:

                                        # Prepare the worksheet

                                        self.txtProgress.emit(
                                            'Started: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')

                                        #self._pt_model.prepare_worksheet(sheet, self.start_row, 0)

                                        self.txtProgress.emit(
                                            'Finished: Processing ' +
                                            usage_type +
                                            ' - Preparing worksheet ' +
                                            sheet.title + '.')
                                        time.sleep(3)

                                        #Insert empty mapping logs

                                        key_tab = 'MINF' + '-' + sheet.title

                                        self._pt_model.append_template_logs(
                                            usage_type, 2, key_tab, [])

                                        if self._cancel_flg: return

                                success = True

                            except Exception as e:

                                self.currStatus.emit([
                                    usage_type, 'Populate Worksheet',
                                    sheet.title,
                                    str(e)
                                ])

                                response = None
                                while response is None:
                                    response = self._pt_model.replyBtn
                                    time.sleep(1)

                                    if response == QMessageBox.Abort:
                                        self._abort_flg = True
                                        self._pt_model.replyBtn = None
                                        return
                                    elif response == QMessageBox.Retry:
                                        self._pt_model.replyBtn = None
                                    elif response == QMessageBox.Ignore:
                                        self._pt_model.update_template_status(
                                            usage_type, 'i')
                                        self._pt_model.replyBtn = None
                                        success = True
                                    elif response == QMessageBox.Close:
                                        self._abort_flg = True
                                        self._pt_model.replyBtn = None
                                        return

                    if self._cancel_flg: break

                    #Update Status
                    self._pt_model.update_template_status(usage_type, 'c')

                    #Price Counts

                    self.txtProgress.emit('Started: Processing ' + usage_type +
                                          ' - Generating Data Counts.')

                    if not df_price.empty and not self._abort_flg:

                        data = {
                            'Source': self.src_price_cnt,
                            'Template': self.temp_price_cnt
                        }
                        self._pt_model.append_template_logs(
                            usage_type, 3, 'Price', data)

                    else:

                        data = {'Source': 0, 'Template': 0}
                        self._pt_model.append_template_logs(
                            usage_type, 3, 'Price', data)

                    #Scales Counts

                    if not df_scales.empty and not self._abort_flg:

                        data = {
                            'Source': self.src_scales_cnt,
                            'Template': self.temp_scales_cnt
                        }
                        self._pt_model.append_template_logs(
                            usage_type, 3, 'Scales', data)

                    else:
                        data = {'Source': 0, 'Template': 0}
                        self._pt_model.append_template_logs(
                            usage_type, 3, 'Scales', data)

                    #MinFee Counts

                    if not df_minf.empty and not self._abort_flg:

                        data = {
                            'Source': self.src_minf_cnt,
                            'Template': self.temp_minf_cnt
                        }
                        self._pt_model.append_template_logs(
                            usage_type, 3, 'MINF', data)

                    else:
                        data = {'Source': 0, 'Template': 0}
                        self._pt_model.append_template_logs(
                            usage_type, 3, 'MINF', data)

                    if self._cancel_flg: break

                    self.txtProgress.emit('Finished: Processing ' +
                                          usage_type +
                                          ' - Generating Data Counts.')
                    time.sleep(3)

                    #Save to workbook in output folder

                    status = self._pt_model.get_template_status(usage_type)

                    if status == 'c':

                        success = False
                        while not success:
                            try:
                                self.txtProgress.emit(
                                    'Started: Processing ' + usage_type +
                                    ' - Saving Workbook to Output Folder.')

                                output_filename = self._tgt_folder + "\\" + template_filename

                                temp_workbook.save(output_filename)

                                self.txtProgress.emit(
                                    'Started: Processing ' + usage_type +
                                    ' - Saving Workbook to Output Folder.')
                                time.sleep(3)

                                success = True
                            except Exception as e:

                                self.currStatus.emit([
                                    usage_type, 'Save Template',
                                    output_filename,
                                    str(e)
                                ])

                                response = None
                                while response is None:
                                    response = self._pt_model.replyBtn
                                    time.sleep(1)

                                if response == QMessageBox.Abort:
                                    self._abort_flg = True
                                    self._pt_model.replyBtn = None
                                    success = True
                                elif response == QMessageBox.Retry:
                                    self._pt_model.replyBtn = None
                                elif response == QMessageBox.Ignore:
                                    self._pt_model.update_template_status(
                                        usage_type, 'i')
                                    self._pt_model.replyBtn = None
                                    success = True
                                elif response == QMessageBox.Close:
                                    self._abort_flg = True
                                    self._pt_model.replyBtn = None
                                    success = True

                self._progress_count += 1
                self.countProgress.emit(self._progress_count)

            ####### Program End #########

            ### Display Elapsed Time ###

            self.update_elapsed_time()

            self.txtProgress.emit('Finished')

    def stop(self):
        self.is_running = False

    def update_elapsed_time(self):

        secs = self.timer.elapsed() / 1000
        mins = (secs / 60) % 60
        hours = (secs / 3600)
        seconds = secs % 60

        self.elapsed_time = str(hours).split('.')[0] + ' Hours ' + str(
            mins).split('.')[0] + ' Minutes ' + str(seconds).split(
                '.')[0] + ' Seconds'

    def get_all_usage_types(self):
        return list(self.df_price_all.USAGE_TYPE_CD.unique())[1:]
Exemple #44
0
def add_to_current_time(t: QTime) -> QTime:
    secs = get_total_seconds(t)
    return QTime.currentTime().addSecs(secs)
#!/usr/bin/python3
#QDate, QTime, QDateTime
# http://zetcode.com/gui/pyqt5/datetime/

from PyQt5.QtCore import QDate, QTime, QDateTime, Qt

now = QDate.currentDate()

print("1: ", now.toString(Qt.ISODate))
print("2: ", now.toString(Qt.DefaultLocaleLongDate))

datetime = QDateTime.currentDateTime()
print("3: ", datetime.toString())

time = QTime.currentTime()
print("4: ", time.toString(Qt.DefaultLocaleLongDate))




Exemple #46
0
 def handleLabel(self):
     self.lbl.clear()
     mtime = QTime(0, 0, 0, 0)
     self.time = mtime.addMSecs(self.mediaPlayer.position())
     self.lbl.setText(self.time.toString())
 def ShowTime(self):
     sender = self.sender()  # 이벤트 객체에 접근자
     cur = QTime.currentTime().toString("hh:mm:ss")
     if id(sender) == id(self.timer):  # 접근자와 timer가 같으면 화면에 표시
         self.lcd.display(cur)
def createMailModel(parent):
    model = QStandardItemModel(0, 3, parent)

    model.setHeaderData(SUBJECT, Qt.Horizontal, "Subject")
    model.setHeaderData(SENDER, Qt.Horizontal, "Sender")
    model.setHeaderData(DATE, Qt.Horizontal, "Date")

    addMail(
        model,
        "Happy New Year!",
        "Grace K. <*****@*****.**>",
        QDateTime(QDate(2006, 12, 31), QTime(17, 3)),
    )
    addMail(
        model,
        "Radically new concept",
        "Grace K. <*****@*****.**>",
        QDateTime(QDate(2006, 12, 22), QTime(9, 44)),
    )
    addMail(
        model,
        "Accounts",
        "*****@*****.**",
        QDateTime(QDate(2006, 12, 31), QTime(12, 50)),
    )
    addMail(
        model,
        "Expenses",
        "Joe Bloggs <*****@*****.**>",
        QDateTime(QDate(2006, 12, 25), QTime(11, 39)),
    )
    addMail(
        model,
        "Re: Expenses",
        "Andy <*****@*****.**>",
        QDateTime(QDate(2007, 1, 2), QTime(16, 5)),
    )
    addMail(
        model,
        "Re: Accounts",
        "Joe Bloggs <*****@*****.**>",
        QDateTime(QDate(2007, 1, 3), QTime(14, 18)),
    )
    addMail(
        model,
        "Re: Accounts",
        "Andy <*****@*****.**>",
        QDateTime(QDate(2007, 1, 3), QTime(14, 26)),
    )
    addMail(
        model,
        "Sports",
        "Linda Smith <*****@*****.**>",
        QDateTime(QDate(2007, 1, 5), QTime(11, 33)),
    )
    addMail(
        model,
        "AW: Sports",
        "Rolf Newschweinstein <*****@*****.**>",
        QDateTime(QDate(2007, 1, 5), QTime(12, 0)),
    )
    addMail(
        model,
        "RE: Sports",
        "Petra Schmidt <*****@*****.**>",
        QDateTime(QDate(2007, 1, 5), QTime(12, 1)),
    )

    return model
Exemple #49
0
    def __init__(self,
                 parent,
                 callback,
                 gid,
                 persepolis_setting,
                 video_finder_dictionary=None):
        super().__init__(persepolis_setting)

        self.parent = parent
        self.persepolis_setting = persepolis_setting
        self.video_finder_dictionary = video_finder_dictionary

        self.download_later_pushButton.hide()  # hide download_later_pushButton
        self.change_name_checkBox.hide()  # hide change_name_checkBox
        self.change_name_lineEdit.hide()  # hide change_name_lineEdit

        # add new QLineEdit and QLineEdit for audio link if we have video finder links
        if self.video_finder_dictionary:

            self.link_label_2 = QLabel(self.link_frame)
            self.link_horizontalLayout.addWidget(self.link_label_2)

            self.link_lineEdit_2 = QLineEdit(self.link_frame)
            self.link_horizontalLayout.addWidget(self.link_lineEdit_2)
            self.link_lineEdit_2.textChanged.connect(self.linkLineChanged)

            self.link_label.setText(
                QCoreApplication.translate("addlink_ui_tr", "Video Link: "))
            self.link_label_2.setText(
                QCoreApplication.translate("addlink_ui_tr", "Audio Link: "))

            # gid_1 >> video_gid , gid_2 >> audio_gid
            self.gid_1 = self.video_finder_dictionary['video_gid']
            self.gid_2 = self.video_finder_dictionary['audio_gid']

        else:

            self.gid_1 = gid

        self.callback = callback

        # detect_proxy_pushButton
        self.detect_proxy_pushButton.clicked.connect(self.detectProxy)

        # connect folder_pushButton
        self.folder_pushButton.clicked.connect(self.changeFolder)
        self.download_folder_lineEdit.setEnabled(False)

        self.ok_pushButton.setEnabled(False)
        self.link_lineEdit.textChanged.connect(self.linkLineChanged)

        # connect OK and canel button

        self.cancel_pushButton.clicked.connect(self.close)
        self.ok_pushButton.clicked.connect(self.okButtonPressed)

        #frames and checkBoxes
        self.proxy_frame.setEnabled(False)
        self.proxy_checkBox.toggled.connect(self.proxyFrame)

        self.download_frame.setEnabled(False)
        self.download_checkBox.toggled.connect(self.downloadFrame)

        self.limit_frame.setEnabled(False)
        self.limit_checkBox.toggled.connect(self.limitFrame)

        self.start_frame.setEnabled(False)
        self.start_checkBox.toggled.connect(self.startFrame)

        self.end_frame.setEnabled(False)
        self.end_checkBox.toggled.connect(self.endFrame)

        # get information from data base
        self.add_link_dictionary_1 = self.parent.persepolis_db.searchGidInAddLinkTable(
            self.gid_1)
        self.download_table_dict_1 = self.parent.persepolis_db.searchGidInDownloadTable(
            self.gid_1)

        if video_finder_dictionary:
            self.add_link_dictionary_2 = self.parent.persepolis_db.searchGidInAddLinkTable(
                self.gid_2)
            self.download_table_dict_2 = self.parent.persepolis_db.searchGidInDownloadTable(
                self.gid_2)

        # create a copy from add_link_dictionary for checking changes finally!
        self.add_link_dictionary_1_backup = {}
        for key in self.add_link_dictionary_1.keys():
            self.add_link_dictionary_1_backup[
                key] = self.add_link_dictionary_1[key]

        if video_finder_dictionary:
            self.add_link_dictionary_2_backup = {}
            for key in self.add_link_dictionary_2.keys():
                self.add_link_dictionary_2_backup[
                    key] = self.add_link_dictionary_2[key]

# initialization
# disable folder_frame when download is complete
        if self.video_finder_dictionary:
            if self.video_finder_dictionary[
                    'video_completed'] == 'yes' or self.video_finder_dictionary[
                        'audio_completed'] == 'yes':
                self.folder_frame.setEnabled(False)
        else:
            if self.download_table_dict_1['status'] == 'complete':
                self.folder_frame.setEnabled(False)

# link
        self.link_lineEdit.setText(self.add_link_dictionary_1['link'])

        if self.video_finder_dictionary:
            self.link_lineEdit_2.setText(self.add_link_dictionary_2['link'])

# ip_lineEdit initialization
        if self.add_link_dictionary_1['ip']:
            self.proxy_checkBox.setChecked(True)
            self.ip_lineEdit.setText(self.add_link_dictionary_1['ip'])
            # port_spinBox initialization
            try:
                self.port_spinBox.setValue(
                    int(self.add_link_dictionary_1['port']))
            except:
                pass
# proxy user lineEdit initialization
            try:
                self.proxy_user_lineEdit.setText(
                    self.add_link_dictionary_1['proxy_user'])
            except:
                pass
# proxy pass lineEdit initialization
            try:
                self.proxy_pass_lineEdit.setText(
                    self.add_link_dictionary_1['proxy_passwd'])
            except:
                pass

# download UserName initialization
        if self.add_link_dictionary_1['download_user']:
            self.download_checkBox.setChecked(True)
            self.download_user_lineEdit.setText(
                self.add_link_dictionary_1['download_user'])
            # download PassWord initialization
            try:
                self.download_pass_lineEdit.setText(
                    self.add_link_dictionary_1['download_passwd'])
            except:
                pass

# folder_path
        try:
            self.download_folder_lineEdit.setText(
                self.add_link_dictionary_1['download_path'])
        except:
            pass

# connections
        try:
            self.connections_spinBox.setValue(
                int(self.add_link_dictionary_1['connections']))
        except:
            pass

# get categories name and add them to add_queue_comboBox
        categories_list = self.parent.persepolis_db.categoriesList()
        for queue in categories_list:
            if queue != 'All Downloads':
                self.add_queue_comboBox.addItem(queue)

        # finding current queue and setting it!
        self.current_category = self.download_table_dict_1['category']

        current_category_index = self.add_queue_comboBox.findText(
            self.current_category)
        self.add_queue_comboBox.setCurrentIndex(current_category_index)

        # add_queue_comboBox event
        self.add_queue_comboBox.currentIndexChanged.connect(self.queueChanged)

        # limit speed
        limit = str(self.add_link_dictionary_1['limit_value'])
        if limit != '0':
            self.limit_checkBox.setChecked(True)
            limit_number = limit[0:-1]
            limit_unit = limit[-1]
            self.limit_spinBox.setValue(float(limit_number))
            if limit_unit == "K":
                self.limit_comboBox.setCurrentIndex(0)
            else:
                self.limit_comboBox.setCurrentIndex(1)

# start_time
        if self.add_link_dictionary_1['start_time']:
            # get hour and minute
            hour, minute = self.add_link_dictionary_1['start_time'].split(':')

            # set time
            q_time = QTime(int(hour), int(minute))
            self.start_time_qDataTimeEdit.setTime(q_time)

            self.start_checkBox.setChecked(True)
# end_time
        if self.add_link_dictionary_1['end_time']:
            # get hour and minute
            hour, minute = self.add_link_dictionary_1['end_time'].split(':')

            # set time
            q_time = QTime(int(hour), int(minute))
            self.end_time_qDateTimeEdit.setTime(q_time)

            self.end_checkBox.setChecked(True)

        # referer
        if self.add_link_dictionary_1['referer']:
            self.referer_lineEdit.setText(
                str(self.add_link_dictionary_1['referer']))

        if self.add_link_dictionary_1['header']:
            self.header_lineEdit.setText(
                str(self.add_link_dictionary_1['header']))

        if self.add_link_dictionary_1['user_agent']:
            self.user_agent_lineEdit.setText(
                str(self.add_link_dictionary_1['user_agent']))

        if self.add_link_dictionary_1['load_cookies']:
            self.load_cookies_lineEdit.setText(
                (self.add_link_dictionary_1['load_cookies']))

# set window size and position
        size = self.persepolis_setting.value('PropertiesWindow/size',
                                             QSize(520, 425))
        position = self.persepolis_setting.value('PropertiesWindow/position',
                                                 QPoint(300, 300))
        self.resize(size)
        self.move(position)
Exemple #50
0
 def _process_started(self):
     time_str = QTime.currentTime().toString("hh:mm:ss")
     text = time_str + " Running: " + self.process_name
     self.outputw.append_text(text)
     self.outputw.setReadOnly(False)
Exemple #51
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupTrayicon()
        self.setupVariables()
        self.setupUi()
        self.setupConnections()
        self.show()

    def setupVariables(self):
        settings = QSettings()
        self.workEndTime = QTime(
            int(settings.value(workHoursKey, 0)),
            int(settings.value(workMinutesKey, 25)),
            int(settings.value(workSecondsKey, 0)),
        )
        self.restEndTime = QTime(
            int(settings.value(restHoursKey, 0)),
            int(settings.value(restMinutesKey, 5)),
            int(settings.value(restSecondsKey, 0)),
        )
        self.timeFormat = "hh:mm:ss"
        self.time = QTime(0, 0, 0, 0)
        self.workTime = QTime(0, 0, 0, 0)
        self.restTime = QTime(0, 0, 0, 0)
        self.totalTime = QTime(0, 0, 0, 0)
        self.currentMode = Mode.work
        self.maxRepetitions = -1
        self.currentRepetitions = 0

    def setupConnections(self):
        """ Create button connections """
        self.startButton.clicked.connect(self.startTimer)
        self.startButton.clicked.connect(
            lambda: self.startButton.setDisabled(True))
        self.startButton.clicked.connect(
            lambda: self.pauseButton.setDisabled(False))
        self.startButton.clicked.connect(
            lambda: self.resetButton.setDisabled(False))
        self.pauseButton.clicked.connect(self.pauseTimer)
        self.pauseButton.clicked.connect(
            lambda: self.startButton.setDisabled(False))
        self.pauseButton.clicked.connect(
            lambda: self.pauseButton.setDisabled(True))
        self.pauseButton.clicked.connect(
            lambda: self.resetButton.setDisabled(False))
        self.pauseButton.clicked.connect(
            lambda: self.startButton.setText("continue"))
        self.resetButton.clicked.connect(self.resetTimer)
        self.resetButton.clicked.connect(
            lambda: self.startButton.setDisabled(False))
        self.resetButton.clicked.connect(
            lambda: self.pauseButton.setDisabled(True))
        self.resetButton.clicked.connect(
            lambda: self.resetButton.setDisabled(True))
        self.resetButton.clicked.connect(
            lambda: self.startButton.setText("start"))
        self.acceptTaskButton.pressed.connect(self.insertTask)
        self.deleteTaskButton.pressed.connect(self.deleteTask)
        """ Create spinbox  connections """
        self.workHoursSpinBox.valueChanged.connect(self.updateWorkEndTime)
        self.workMinutesSpinBox.valueChanged.connect(self.updateWorkEndTime)
        self.workSecondsSpinBox.valueChanged.connect(self.updateWorkEndTime)
        self.restHoursSpinBox.valueChanged.connect(self.updateRestEndTime)
        self.restMinutesSpinBox.valueChanged.connect(self.updateRestEndTime)
        self.restSecondsSpinBox.valueChanged.connect(self.updateRestEndTime)
        self.repetitionsSpinBox.valueChanged.connect(self.updateMaxRepetitions)
        """ Create combobox connections """
        self.modeComboBox.currentTextChanged.connect(self.updateCurrentMode)
        """ Create tablewidget connections """
        self.tasksTableWidget.cellDoubleClicked.connect(
            self.markTaskAsFinished)

    def setupUi(self):
        self.size_policy = sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                                    QSizePolicy.Expanding)
        """ Create tabwidget """
        self.tabWidget = QTabWidget()
        """ Create tab widgets """
        timerWidget = self.setupTimerTab()
        tasksWidget = self.setupTasksTab()
        statisticsWidget = self.setupStatisticsTab()
        """ add tab widgets to tabwidget"""
        self.timerTab = self.tabWidget.addTab(timerWidget, makeIcon("timer"),
                                              "Timer")
        self.tasksTab = self.tabWidget.addTab(tasksWidget, makeIcon("tasks"),
                                              "Tasks")
        self.statisticsTab = self.tabWidget.addTab(statisticsWidget,
                                                   makeIcon("statistics"),
                                                   "Statistics")
        """ Set mainwindows central widget """
        self.setCentralWidget(self.tabWidget)

    def setupTimerTab(self):
        settings = QSettings()
        self.timerContainer = QWidget(self)
        self.timerContainerLayout = QVBoxLayout(self.timerContainer)
        self.timerContainer.setLayout(self.timerContainerLayout)
        """ Create work groupbox"""
        self.workGroupBox = QGroupBox("Work")
        self.workGroupBoxLayout = QHBoxLayout(self.workGroupBox)
        self.workGroupBox.setLayout(self.workGroupBoxLayout)
        self.workHoursSpinBox = QSpinBox(
            minimum=0,
            maximum=24,
            value=int(settings.value(workHoursKey, 0)),
            suffix="h",
            sizePolicy=self.size_policy,
        )
        self.workMinutesSpinBox = QSpinBox(
            minimum=0,
            maximum=60,
            value=int(settings.value(workMinutesKey, 25)),
            suffix="m",
            sizePolicy=self.size_policy,
        )
        self.workSecondsSpinBox = QSpinBox(
            minimum=0,
            maximum=60,
            value=int(settings.value(workSecondsKey, 0)),
            suffix="s",
            sizePolicy=self.size_policy,
        )
        """ Create rest groupbox"""
        self.restGroupBox = QGroupBox("Rest")
        self.restGroupBoxLayout = QHBoxLayout(self.restGroupBox)
        self.restGroupBox.setLayout(self.restGroupBoxLayout)
        self.restHoursSpinBox = QSpinBox(
            minimum=0,
            maximum=24,
            value=int(settings.value(restHoursKey, 0)),
            suffix="h",
            sizePolicy=self.size_policy,
        )
        self.restMinutesSpinBox = QSpinBox(
            minimum=0,
            maximum=60,
            value=int(settings.value(restMinutesKey, 5)),
            suffix="m",
            sizePolicy=self.size_policy,
        )
        self.restSecondsSpinBox = QSpinBox(
            minimum=0,
            maximum=60,
            value=int(settings.value(restSecondsKey, 0)),
            suffix="s",
            sizePolicy=self.size_policy,
        )
        self.restGroupBoxLayout.addWidget(self.restHoursSpinBox)
        self.restGroupBoxLayout.addWidget(self.restMinutesSpinBox)
        self.restGroupBoxLayout.addWidget(self.restSecondsSpinBox)
        """ Create other groupbox"""
        self.otherGroupBox = QGroupBox("Other")
        self.otherGroupBoxLayout = QHBoxLayout(self.otherGroupBox)
        self.otherGroupBox.setLayout(self.otherGroupBoxLayout)
        self.repetitionsLabel = QLabel("Repetitions")
        self.repetitionsSpinBox = QSpinBox(
            minimum=0,
            maximum=10000,
            value=0,
            sizePolicy=self.size_policy,
            specialValueText="∞",
        )
        self.modeLabel = QLabel("Mode")
        self.modeComboBox = QComboBox(sizePolicy=self.size_policy)
        self.modeComboBox.addItems(["work", "rest"])
        self.otherGroupBoxLayout.addWidget(self.repetitionsLabel)
        self.otherGroupBoxLayout.addWidget(self.repetitionsSpinBox)
        self.otherGroupBoxLayout.addWidget(self.modeLabel)
        self.otherGroupBoxLayout.addWidget(self.modeComboBox)
        """ Create timer groupbox"""
        self.lcdDisplayGroupBox = QGroupBox("Time")
        self.lcdDisplayGroupBoxLayout = QHBoxLayout(self.lcdDisplayGroupBox)
        self.lcdDisplayGroupBox.setLayout(self.lcdDisplayGroupBoxLayout)
        self.timeDisplay = QLCDNumber(8, sizePolicy=self.size_policy)
        self.timeDisplay.setFixedHeight(100)
        self.timeDisplay.display("00:00:00")
        self.lcdDisplayGroupBoxLayout.addWidget(self.timeDisplay)
        """ Create pause, start and reset buttons"""
        self.buttonContainer = QWidget()
        self.buttonContainerLayout = QHBoxLayout(self.buttonContainer)
        self.buttonContainer.setLayout(self.buttonContainerLayout)
        self.startButton = self.makeButton("start", disabled=False)
        self.resetButton = self.makeButton("reset")
        self.pauseButton = self.makeButton("pause")
        """ Add widgets to container """
        self.workGroupBoxLayout.addWidget(self.workHoursSpinBox)
        self.workGroupBoxLayout.addWidget(self.workMinutesSpinBox)
        self.workGroupBoxLayout.addWidget(self.workSecondsSpinBox)
        self.timerContainerLayout.addWidget(self.workGroupBox)
        self.timerContainerLayout.addWidget(self.restGroupBox)
        self.timerContainerLayout.addWidget(self.otherGroupBox)
        self.timerContainerLayout.addWidget(self.lcdDisplayGroupBox)
        self.buttonContainerLayout.addWidget(self.pauseButton)
        self.buttonContainerLayout.addWidget(self.startButton)
        self.buttonContainerLayout.addWidget(self.resetButton)
        self.timerContainerLayout.addWidget(self.buttonContainer)
        return self.timerContainer

    def setupTasksTab(self):
        settings = QSettings()
        """ Create vertical tasks container """
        self.tasksWidget = QWidget(self.tabWidget)
        self.tasksWidgetLayout = QVBoxLayout(self.tasksWidget)
        self.tasksWidget.setLayout(self.tasksWidgetLayout)
        """ Create horizontal input container """
        self.inputContainer = QWidget()
        self.inputContainer.setFixedHeight(50)
        self.inputContainerLayout = QHBoxLayout(self.inputContainer)
        self.inputContainerLayout.setContentsMargins(0, 0, 0, 0)
        self.inputContainer.setLayout(self.inputContainerLayout)
        """ Create text edit """
        self.taskTextEdit = QTextEdit(
            placeholderText="Describe your task briefly.",
            undoRedoEnabled=True)
        """ Create vertical buttons container """
        self.inputButtonContainer = QWidget()
        self.inputButtonContainerLayout = QVBoxLayout(
            self.inputButtonContainer)
        self.inputButtonContainerLayout.setContentsMargins(0, 0, 0, 0)
        self.inputButtonContainer.setLayout(self.inputButtonContainerLayout)
        """ Create buttons """
        self.acceptTaskButton = QToolButton(icon=makeIcon("check"))
        self.deleteTaskButton = QToolButton(icon=makeIcon("trash"))
        """ Create tasks tablewidget """
        self.tasksTableWidget = QTableWidget(0, 1)
        self.tasksTableWidget.setHorizontalHeaderLabels(["Tasks"])
        self.tasksTableWidget.horizontalHeader().setStretchLastSection(True)
        self.tasksTableWidget.verticalHeader().setVisible(False)
        self.tasksTableWidget.setWordWrap(True)
        self.tasksTableWidget.setTextElideMode(Qt.ElideNone)
        self.tasksTableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tasksTableWidget.setSelectionMode(
            QAbstractItemView.SingleSelection)
        self.insertTasks(*settings.value(tasksKey, []))
        """ Add widgets to container widgets """
        self.inputButtonContainerLayout.addWidget(self.acceptTaskButton)
        self.inputButtonContainerLayout.addWidget(self.deleteTaskButton)
        self.inputContainerLayout.addWidget(self.taskTextEdit)
        self.inputContainerLayout.addWidget(self.inputButtonContainer)
        self.tasksWidgetLayout.addWidget(self.inputContainer)
        self.tasksWidgetLayout.addWidget(self.tasksTableWidget)
        return self.tasksWidget

    def setupStatisticsTab(self):
        """ Create statistics container """
        self.statisticsContainer = QWidget()
        self.statisticsContainerLayout = QVBoxLayout(self.statisticsContainer)
        self.statisticsContainer.setLayout(self.statisticsContainerLayout)
        """ Create work time groupbox """
        self.statisticsWorkTimeGroupBox = QGroupBox("Work Time")
        self.statisticsWorkTimeGroupBoxLayout = QHBoxLayout()
        self.statisticsWorkTimeGroupBox.setLayout(
            self.statisticsWorkTimeGroupBoxLayout)
        self.statisticsWorkTimeDisplay = QLCDNumber(8)
        self.statisticsWorkTimeDisplay.display("00:00:00")
        self.statisticsWorkTimeGroupBoxLayout.addWidget(
            self.statisticsWorkTimeDisplay)
        """ Create rest time groupbox """
        self.statisticsRestTimeGroupBox = QGroupBox("Rest Time")
        self.statisticsRestTimeGroupBoxLayout = QHBoxLayout()
        self.statisticsRestTimeGroupBox.setLayout(
            self.statisticsRestTimeGroupBoxLayout)
        self.statisticsRestTimeDisplay = QLCDNumber(8)
        self.statisticsRestTimeDisplay.display("00:00:00")
        self.statisticsRestTimeGroupBoxLayout.addWidget(
            self.statisticsRestTimeDisplay)
        """ Create total time groupbox """
        self.statisticsTotalTimeGroupBox = QGroupBox("Total Time")
        self.statisticsTotalTimeGroupBoxLayout = QHBoxLayout()
        self.statisticsTotalTimeGroupBox.setLayout(
            self.statisticsTotalTimeGroupBoxLayout)
        self.statisticsTotalTimeDisplay = QLCDNumber(8)
        self.statisticsTotalTimeDisplay.display("00:00:00")
        self.statisticsTotalTimeGroupBoxLayout.addWidget(
            self.statisticsTotalTimeDisplay)
        """ Add widgets to container """
        self.statisticsContainerLayout.addWidget(
            self.statisticsTotalTimeGroupBox)
        self.statisticsContainerLayout.addWidget(
            self.statisticsWorkTimeGroupBox)
        self.statisticsContainerLayout.addWidget(
            self.statisticsRestTimeGroupBox)
        return self.statisticsContainer

    def setupTrayicon(self):
        self.trayIcon = QSystemTrayIcon(makeIcon("tomato"))
        self.trayIcon.setContextMenu(QMenu())
        self.quitAction = self.trayIcon.contextMenu().addAction(
            makeIcon("exit"), "Quit", self.exit)
        self.quitAction.triggered.connect(self.exit)
        self.trayIcon.activated.connect(self.onActivate)
        self.trayIcon.show()

    def leaveEvent(self, event):
        super(MainWindow, self).leaveEvent(event)
        self.tasksTableWidget.clearSelection()

    def closeEvent(self, event):
        super(MainWindow, self).closeEvent(event)
        settings = QSettings()
        settings.setValue(workHoursKey, self.workHoursSpinBox.value())
        settings.setValue(
            workMinutesKey,
            self.workMinutesSpinBox.value(),
        )
        settings.setValue(
            workSecondsKey,
            self.workSecondsSpinBox.value(),
        )
        settings.setValue(restHoursKey, self.restHoursSpinBox.value())
        settings.setValue(
            restMinutesKey,
            self.restMinutesSpinBox.value(),
        )
        settings.setValue(
            restSecondsKey,
            self.restSecondsSpinBox.value(),
        )

        tasks = []
        for i in range(self.tasksTableWidget.rowCount()):
            item = self.tasksTableWidget.item(i, 0)
            if not item.font().strikeOut():
                tasks.append(item.text())
        settings.setValue(tasksKey, tasks)

    def startTimer(self):
        try:
            if not self.timer.isActive():
                self.createTimer()
        except:
            self.createTimer()

    def createTimer(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.updateTime)
        self.timer.timeout.connect(self.maybeChangeMode)
        self.timer.setInterval(1000)
        self.timer.setSingleShot(False)
        self.timer.start()

    def pauseTimer(self):
        try:
            self.timer.stop()
            self.timer.disconnect()
        except:
            pass

    def resetTimer(self):
        try:
            self.pauseTimer()
            self.time = QTime(0, 0, 0, 0)
            self.displayTime()
        except:
            pass

    def maybeStartTimer(self):
        if self.currentRepetitions != self.maxRepetitions:
            self.startTimer()
            started = True
        else:
            self.currentRepetitions = 0
            started = False
        return started

    def updateWorkEndTime(self):
        self.workEndTime = QTime(
            self.workHoursSpinBox.value(),
            self.workMinutesSpinBox.value(),
            self.workSecondsSpinBox.value(),
        )

    def updateRestEndTime(self):
        self.restEndTime = QTime(
            self.restHoursSpinBox.value(),
            self.restMinutesSpinBox.value(),
            self.restSecondsSpinBox.value(),
        )

    def updateCurrentMode(self, mode: str):
        self.currentMode = Mode.work if mode == "work" else Mode.rest

    def updateTime(self):
        self.time = self.time.addSecs(1)
        self.totalTime = self.totalTime.addSecs(1)
        if self.modeComboBox.currentText() == "work":
            self.workTime = self.workTime.addSecs(1)
        else:
            self.restTime = self.restTime.addSecs(1)
        self.displayTime()

    def updateMaxRepetitions(self, value):
        if value == 0:
            self.currentRepetitions = 0
            self.maxRepetitions = -1
        else:
            self.maxRepetitions = 2 * value

    def maybeChangeMode(self):
        if self.currentMode is Mode.work and self.time >= self.workEndTime:
            self.resetTimer()
            self.modeComboBox.setCurrentIndex(1)
            self.incrementCurrentRepetitions()
            started = self.maybeStartTimer()
            self.showWindowMessage(
                Status.workFinished if started else Status.repetitionsReached)
        elif self.currentMode is Mode.rest and self.time >= self.restEndTime:
            self.resetTimer()
            self.modeComboBox.setCurrentIndex(0)
            self.incrementCurrentRepetitions()
            started = self.maybeStartTimer()
            self.showWindowMessage(
                Status.restFinished if started else Status.repetitionsReached)

    def incrementCurrentRepetitions(self):
        if self.maxRepetitions > 0:
            self.currentRepetitions += 1

    def insertTask(self):
        task = self.taskTextEdit.toPlainText()
        self.insertTasks(task)

    def insertTasks(self, *tasks):
        for task in tasks:
            if task:
                rowCount = self.tasksTableWidget.rowCount()
                self.tasksTableWidget.setRowCount(rowCount + 1)
                self.tasksTableWidget.setItem(rowCount, 0,
                                              QTableWidgetItem(task))
                self.tasksTableWidget.resizeRowsToContents()
                self.taskTextEdit.clear()

    def deleteTask(self):
        selectedIndexes = self.tasksTableWidget.selectedIndexes()
        if selectedIndexes:
            self.tasksTableWidget.removeRow(selectedIndexes[0].row())

    def markTaskAsFinished(self, row, col):
        item = self.tasksTableWidget.item(row, col)
        font = self.tasksTableWidget.item(row, col).font()
        font.setStrikeOut(False if item.font().strikeOut() else True)
        item.setFont(font)

    def displayTime(self):
        self.timeDisplay.display(self.time.toString(self.timeFormat))
        self.statisticsRestTimeDisplay.display(
            self.restTime.toString(self.timeFormat))
        self.statisticsWorkTimeDisplay.display(
            self.workTime.toString(self.timeFormat))
        self.statisticsTotalTimeDisplay.display(
            self.totalTime.toString(self.timeFormat))

    def showWindowMessage(self, status):
        if status is Status.workFinished:
            self.trayIcon.showMessage("Break", choice(work_finished_phrases),
                                      makeIcon("tomato"))
        elif status is Status.restFinished:
            self.trayIcon.showMessage("Work", choice(rest_finished_phrases),
                                      makeIcon("tomato"))
        else:
            self.trayIcon.showMessage("Finished",
                                      choice(pomodoro_finished_phrases),
                                      makeIcon("tomato"))
            self.resetButton.click()

    def makeButton(self, text, iconName=None, disabled=True):
        button = QPushButton(text, sizePolicy=self.size_policy)
        if iconName:
            button.setIcon(makeIcon(iconName))
        button.setDisabled(disabled)
        return button

    def exit(self):
        self.close()
        app = QApplication.instance()
        if app:
            app.quit()

    def onActivate(self, reason):
        if reason == QSystemTrayIcon.Trigger:
            self.show()
Exemple #52
0
 def __add_current_time(self, text):
     """Add current time into text"""
     current_time_str = QTime.currentTime().toString('hh:mm:ss')
     message = current_time_str + " :: " + text
     return message
Exemple #53
0
class Board(QFrame):
    """
    Everything to handle the game: Drawing pieces and the board, Handling the mouse and the game logic
    """
    msg2Statusbar = pyqtSignal(str)

    # todo set the board with and height in square
    boardWidth = 8
    boardHeight = 8
    Speed = 300

    def __init__(self, parent):
        super().__init__(parent)
        self.init()

    def init(self):
        """
        Initialise all values

        :return:
        """
        self.boardArray = [[0, 3, 0, 3, 0, 3, 0, 3],
                           [3, 0, 3, 0, 3, 0, 3, 0],
                           [0, 3, 0, 3, 0, 3, 0, 3],
                           [1, 0, 1, 0, 1, 0, 1, 0],
                           [0, 1, 0, 1, 0, 1, 0, 1],
                           [2, 0, 2, 0, 2, 0, 2, 0],
                           [0, 2, 0, 2, 0, 2, 0, 2],
                           [2, 0, 2, 0, 2, 0, 2, 0]]
        # Timer initialization

        self.timer = QTimer()
        self.time = QTime(0, 0, 0)
        self.timer.timeout.connect(self.timerEventGame)

        self.timerPlayer = QTimer()
        self.timePlayer = QTime(0, 1, 0)
        self.timer.timeout.connect(self.timerEventPlayer)

        self.isWaitingAfterLine = False
        self.numLinesRemoved = 0
        # image de la piece de base m'voyez
        self.image = QImage(WHITE_PIECE)
        # self.setFocusPolicy(Qt.StrongFocus)
        self.isStarted = False
        self.isPaused = False
        self.reset_game()
        self.selected_piece = [-1, -1]
        self.player_turn = 1
        # nombre de piece = [nb de piece joueur 1, nb de piece jour 2]
        self.playersRemaining = [12, 12]
        # nombre de jump = [nb de jump joueur 1, nb de jump jour 2]
        self.playersJumps = [0, 0]
        self.scoreBoard = None
        self.status = FPLAYER
        # si le temps du joueur a timeout
        self.timePassed = False
        self.startTime = 0
        self.interval = 0
        # pour changer l'affichage si on jou contre une AI
        self.isAI = False
        self.winner = -1
        self.aiDifficulties = 2

    def timerEventGame(self):
        """
        This function allows to update the game timer and update the scoreBoard.

        :return: Nothing
        """
        # Update the game timer
        self.time = self.time.addSecs(1)
        # Update de UI of the scoreBoard
        self.scoreBoard.updateUI()

    def initPlayerTimer(self):
        """
        Init the player timer when the player begin his turn.

        :return: Nothing
        """
        self.timerPlayer = QTimer()
        self.timePlayer = QTime(0, 1, 0)

    def startTimerInter(self, interval):
        """
        Start the player timer with an given interval.

        :param interval: The interval from which time must resume
        :return: Nothing
        """
        self.timerPlayer.start(interval)

    def startTimerPlayer(self):
        """"
        Function to start a player timer with an interval of 1000.
        """
        self.interval = 1000
        self.startTime = time.time()
        self.timerPlayer.start(1000)

    def timerEventPlayer(self):
        """
        This function allows to update the timer of the player one.

        :return: Nothing
        """
        self.timePlayer = self.timePlayer.addSecs(-1)
        if self.timerPlayer.isActive():
            if self.timePlayer.minute() * 60 + self.timePlayer.second() < 1:
                self.timePassed = True
                self.timerPassedEndGame()
        self.scoreBoard.updateUI()

    def setScoreBoard(self, scoreBoard):
        """
        This function allows to get the scoreBoard class to use it later in the code.

        :param scoreBoard: The class scoreBoard
        :return: Nothing
        """
        self.scoreBoard = scoreBoard

    def print_board_array(self):
        """
        Prints the boardArray in an attractive way

        :return: Nothing
        """

        print("boardArray:")
        print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in self.boardArray]))

    def mouse_pos_to_col_row(self, event):
        """
        Convert the mouse click event to a row and column.

        :param event: The click event
        :return: The click's position with the following format: [x, y] (Example: [3, 4])
        """

        return [int(event.x() / self.square_width()), int(event.y() / self.square_height())]

    def square_width(self):
        """
        This function allows to return the width of one square in the board.

        :return: The width of one square in the board.
        """
        return self.contentsRect().width() / Board.boardWidth

    def square_height(self):
        """
        This function allows to return the height of one square in the board.

        :return: The height of one square in the board
        """

        return self.contentsRect().height() / Board.boardHeight

    def start(self):
        """starts game"""
        if self.isPaused:
            return

        self.isStarted = True
        self.isWaitingAfterLine = False
        self.numLinesRemoved = 0
        self.reset_game()
        self.timer.start(1000)
        self.startTimerPlayer()
        # self.timerPlayer.start(1000)

    def pause(self):
        """pauses game"""

        if not self.isStarted:
            return

        self.isPaused = not self.isPaused

        if self.isPaused:
            self.timerPlayer.stop()
            self.timer.stop()
            self.status = "Game paused"
            elapsedTime = self.startTime - time.time()
            self.startTime -= elapsedTime
            self.interval -= int(elapsedTime * 1000)

        else:
            self.timer.start()
            self.startTimerInter(self.interval)
            if self.player_turn == 1:
                self.status = FPLAYER
            elif self.isAI:
                self.status = AIPLAYER
            else:
                self.status = SPLAYER
            self.scoreBoard.updateUI()

        self.update()

    def paintEvent(self, event):
        """paints the board and the pieces of the game"""
        painter = QPainter(self)
        self.draw_board_squares(painter)
        self.draw_pieces(painter)

    def new_place(self, turn, row, col, change):
        """
        Change the piece place

        :param turn:
        :param row:
        :param col:
        :param change:
        :return:
        """
        self.boardArray[row][col] = self.boardArray[self.selected_piece[1]][self.selected_piece[0]]
        if (row == 0 and self.boardArray[row][col] == 2) or (row == 7 and self.boardArray[row][col] == 3):
            self.boardArray[row][col] += 2
        self.boardArray[self.selected_piece[1]][self.selected_piece[0]] = 1
        if change == 1:
            self.selected_piece = [-1, -1]
        else:
            self.selected_piece = [col, row]
        self.player_turn = turn
        self.scoreBoard.updateUI()

    def first_player_take(self, row, col):
        """
        Take a piece for the first player

        :param row:
        :param col:
        :return:
        """
        p = 2
        change = 1
        b = 0
        r = self.selected_piece[1]
        c = self.selected_piece[0]
        if self.boardArray[r][c] == 2 and r > 1 and c > 1 and self.boardArray[r - 2][c - 2] == 1 and \
                        self.boardArray[r - 1][c - 1] == 3:
            b = 1
        elif self.boardArray[r][c] == 2 and r > 1 and c < 6 and self.boardArray[r - 2][c + 2] == 1 and \
                        self.boardArray[r - 1][c + 1] == 3:
            b = 1
        if b == 0 and self.player_turn == 1 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] - 1 \
                and (col == self.selected_piece[0] + 1 or col == self.selected_piece[0] - 1):
            self.new_place(2, row, col, change)
        elif self.player_turn == 1 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] - 2 \
                and col == self.selected_piece[0] + 2 and self.boardArray[row + 1][col - 1] == 3:
            self.boardArray[row + 1][col - 1] = 1
            self.playersRemaining[1] -= 1
            if self.playersRemaining[1] == 0:
                self.timePassed = True
                self.player_turn = 2
                self.timerPassedEndGame()
            self.playersJumps[0] += 1
            if row > 1 and col > 1 and self.boardArray[row - 2][col - 2] == 1 and self.boardArray[row - 1][col - 1] == 3:
                p = 1
                change = 0
            elif row > 1 and col < 6 and self.boardArray[row - 2][col + 2] == 1 and self.boardArray[row - 1][col + 1] == 3:
                p = 1
                change = 0
            self.new_place(p, row, col, change)
        elif self.player_turn == 1 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] - 2 \
                and col == self.selected_piece[0] - 2 and self.boardArray[row + 1][col + 1] == 3:
            self.boardArray[row + 1][col + 1] = 1
            self.playersRemaining[1] -= 1
            if self.playersRemaining[1] == 0:
                self.timePassed = True
                self.player_turn = 2
                self.timerPassedEndGame()
            self.playersJumps[0] += 1
            if row > 1 and col > 1 and self.boardArray[row - 2][col - 2] == 1 and self.boardArray[row - 1][col - 1] == 3:
                p = 1
                change = 0
            elif row > 1 and col < 6 and self.boardArray[row - 2][col + 2] == 1 and self.boardArray[row - 1][col + 1] == 3:
                p = 1
                change = 0
            self.new_place(p, row, col, change)

    def second_player_take(self, row, col):
        """
        Take a piece for the second player

        :param row:
        :param col:
        :return:
        """
        p = 1
        change = 1
        b = 0
        r = self.selected_piece[1]
        c = self.selected_piece[0]
        if self.boardArray[r][c] == 3 and r < 6 and c > 1 and self.boardArray[r + 2][c - 2] == 1 and \
                        self.boardArray[r + 1][c - 1] == 2:
            b = 1
        elif self.boardArray[r][c] == 3 and r < 6 and c < 6 and self.boardArray[r + 2][c + 2] == 1 and \
                        self.boardArray[r + 1][c + 1] == 2:
            b = 1
        if b == 0 and self.player_turn == 2 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] + 1 \
                and (col == self.selected_piece[0] + 1 or col == self.selected_piece[0] - 1):
            self.new_place(p, row, col, change)
        elif self.player_turn == 2 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] + 2 \
                and col == self.selected_piece[0] + 2 and self.boardArray[row - 1][col - 1] == 2:
            self.boardArray[row - 1][col - 1] = 1
            self.playersRemaining[0] -= 1
            if self.playersRemaining[0] == 0:
                self.timePassed = True
                self.player_turn = 1
                self.timerPassedEndGame()
            self.playersJumps[1] += 1
            if row < 6 and col > 1 and self.boardArray[row + 2][col - 2] == 1 and self.boardArray[row + 1][col - 1] == 2:
                p = 2
                change = 0
            elif row < 6 and col < 6 and self.boardArray[row + 2][col + 2] == 1 and self.boardArray[row + 1][col + 1] == 2:
                p = 2
                change = 0
            self.new_place(p, row, col, change)
        elif self.player_turn == 2 and self.boardArray[row][col] == 1 and row == self.selected_piece[1] + 2 \
                and col == self.selected_piece[0] - 2 and self.boardArray[row - 1][col + 1] == 2:
            self.boardArray[row - 1][col + 1] = 1
            self.playersRemaining[0] -= 1
            if self.playersRemaining[0] == 0:
                self.timePassed = True
                self.player_turn = 1
                self.timerPassedEndGame()
            self.playersJumps[1] += 1
            if row < 6 and col > 1 and self.boardArray[row + 2][col - 2] == 1 and self.boardArray[row + 1][col - 1] == 2:
                p = 2
                change = 0
            elif row < 6 and col < 6 and self.boardArray[row + 2][col + 2] == 1 and self.boardArray[row + 1][col + 1] == 2:
                p = 2
                change = 0
            self.new_place(p, row, col, change)

    def mousePressEvent(self, event):
        """
        Get the pos clicked and call the game logic
        :param event:
        :return:
        """
        if not self.isPaused:
            clicked = self.mouse_pos_to_col_row(event)
            if clicked:
                self.logicGame(clicked)

    def AI(self):
        """
        Creates the AI class with the array board.
        Then, it get the positions choosed by the AI.
        Finally it call the logic Game to move the piece.

        :return: Nothing
        """

        self.selected_piece = [-1, -1]
        self.ai = AI(self.boardArray)
        positions = self.ai.MinMaxDecision(self.aiDifficulties)
        self.logicGame([positions[0][1], positions[0][0]])
        self.logicGame([positions[1][1], positions[1][0]])

    def timerPassedEndGame(self):
        """
        When a player take a lot of time to play (1 minutes)

        :return: -1 (value for the end of the game)
        """
        self.status = ENDGAME
        self.timerPlayer.stop()
        self.timer.stop()
        if self.player_turn == 1:
            if not self.isAI:
                self.winner = 2
            else:
                self.winner = 3
        else:
            self.winner = 1
        # self.scoreBoard.updateUI()
        # self.init()
        return -1

    def logicGame(self, positions):
        """
        Game logic to manage pieces moves
        :param positions:
        :return:
        """
        row = positions[1]
        col = positions[0]
        if self.timePassed:
            return self.timerPassedEndGame()
        if self.player_turn == 1:
            self.status = FPLAYER
        elif self.isAI:
            self.status = AIPLAYER
        else:
            self.status = SPLAYER

        if self.selected_piece == [-1, -1]:
            if self.player_turn == 1:
                b = 0
                for r in range(0, len(self.boardArray)):
                    for c in range(0, len(self.boardArray[0])):
                        if self.boardArray[r][c] == 2 and r > 1 and c > 1 and self.boardArray[r - 2][c - 2] == 1 and self.boardArray[r - 1][c - 1] == 3:
                            b = 1
                        elif self.boardArray[r][c] == 2 and r > 1 and c < 6 and self.boardArray[r - 2][c + 2] == 1 and self.boardArray[r - 1][c + 1] == 3:
                            b = 1
                if self.boardArray[row][col] == self.player_turn + 1:
                    if (b == 0 and row > 0 and col > 0 and self.boardArray[row - 1][col - 1] == 1) \
                            or (b == 0 and row > 0 and col < 7 and self.boardArray[row - 1][col + 1] == 1):
                        self.selected_piece = positions
                    elif row > 1 and col > 1 and self.boardArray[row - 2][col - 2] == 1 and self.boardArray[row - 1][col - 1] == 3:
                        self.selected_piece = positions
                    elif row > 1 and col < 6 and self.boardArray[row - 2][col + 2] == 1 and self.boardArray[row - 1][col + 1] == 3:
                        self.selected_piece = positions
            elif self.player_turn == 2:
                b = 0
                for r in range(0, len(self.boardArray)):
                    for c in range(0, len(self.boardArray[0])):
                        if self.boardArray[r][c] == 3 and r < 6 and c > 1 and self.boardArray[r + 2][c - 2] == 1 and self.boardArray[r + 1][c - 1] == 2:
                            b = 1
                        elif self.boardArray[r][c] == 3 and r < 6 and c < 6 and self.boardArray[r + 2][c + 2] == 1 and self.boardArray[r + 1][c + 1] == 2:
                            b = 1
                if self.boardArray[row][col] == self.player_turn + 1:
                    if (b == 0 and row < 7 and col > 0 and self.boardArray[row + 1][col - 1] == 1) \
                        or (b == 0 and row < 7 and col < 7 and self.boardArray[row + 1][col + 1] == 1):
                        self.selected_piece = positions
                    elif row < 6 and col > 1 and self.boardArray[row + 2][col - 2] == 1 and self.boardArray[row + 1][col - 1] == 2:
                        self.selected_piece = positions
                    elif row < 6 and col < 6 and self.boardArray[row + 2][col + 2] == 1 and self.boardArray[row + 1][col + 1] == 2:
                        self.selected_piece = positions

        else:
            if self.selected_piece == positions:
                self.selected_piece = [-1,-1]
                return
            self.first_player_take(row, col)
            self.second_player_take(row, col)
            if self.player_turn == 1:
                self.status = FPLAYER
            else:
                self.status = SPLAYER
            self.initPlayerTimer()
            self.startTimerPlayer()
            if self.player_turn == 2 and self.isAI:
                self.AI()

    def keyPressEvent(self, event):
        """processes key press events if you would like to do any"""
        if not self.isStarted or self.curPiece.shape() == Piece.NoPiece:
            super(Board, self).keyPressEvent(event)
            return
        key = event.key()
        if key == Qt.Key_P:
            self.pause()
            return
        if self.isPaused:
            return
        elif key == Qt.Key_Left:
            self.try_move(self.curPiece, self.curX - 1, self.curY)
        elif key == Qt.Key_Right:
            self.try_move(self.curPiece, self.curX + 1, self.curY)
        elif key == Qt.Key_Down:
            self.try_move(self.curPiece.rotateRight(), self.curX, self.curY)
        elif key == Qt.Key_Up:
            self.try_move(self.curPiece.rotateLeft(), self.curX, self.curY)
        elif key == Qt.Key_Space:
            self.dropDown()
        elif key == Qt.Key_D:
            self.oneLineDown()
        else:
            super(Board, self).keyPressEvent(event)

    def timerEvent(self, event):
        """handles timer event"""

        #todo adapter this code to handle your timers
        if event.timerId() == self.timer.timerId():
            pass
        else:
            super(Board, self).timerEvent(event)

    def reset_game(self):
        """clears pieces from the board"""

        # 2d int/Piece array to story the state of the game
        # 2 pion blanc, 3 pion noir
        self.boardArray = [[0, 3, 0, 3, 0, 3, 0, 3],
                           [3, 0, 3, 0, 3, 0, 3, 0],
                           [0, 3, 0, 3, 0, 3, 0, 3],
                           [1, 0, 1, 0, 1, 0, 1, 0],
                           [0, 1, 0, 1, 0, 1, 0, 1],
                           [2, 0, 2, 0, 2, 0, 2, 0],
                           [0, 2, 0, 2, 0, 2, 0, 2],
                           [2, 0, 2, 0, 2, 0, 2, 0]]
        self.selected_piece = [-1, -1]
        # self.print_board_array()

    def try_move(self, new_x, new_y):
        """tries to move a piece"""

    def draw_board_squares(self, painter):
        """
        This function allows to draw all the square on the board.

        :param painter: The painter
        :return: Nothing
        """

        # todo set the default colour of the brush
        images = [QImage(WHITE_SQUARE), QImage(BLACK_SQUARE)]
        idx = 0
        for row in range(0, Board.boardHeight):
            for col in range(0, Board.boardWidth):
                #painter.save()
                # Todo set this value equal the transformation you would like in the column direction (x)
                colTransformation = col * self.square_width()

                # Todo set this value equal the transformation you would like in the column direction (y)
                row_transformation = row * self.square_height()

                final_image = images[idx].scaled(self.square_width(), self.square_height())
                painter.drawImage(colTransformation, row_transformation, final_image)
                #painter.restore()
                idx = 1 if idx == 0 else 0
            idx = 1 if idx == 0 else 0

    def color_brush_white(self, row, col, i):
        """
        Set the brush color for white pieces
        :param row:
        :param col:
        :param i:
        :return:
        """
        brush_color = Qt.black
        if self.player_turn == 1 and self.selected_piece[1] == row and self.selected_piece[0] == col:
            brush_color = QColor.fromRgb(100, 255, 100)
        elif self.player_turn == 1 and self.selected_piece == [-1, -1]:
            if i > 0 and row > 0 and col > 0 and self.boardArray[row - 1][col - 1] == 1:
                brush_color = Qt.white
            elif i > 0 and row > 0 and col < 7 and self.boardArray[row - 1][col + 1] == 1:
                brush_color = Qt.white
            elif row > 1 and col > 1 and self.boardArray[row - 2][col - 2] == 1 and self.boardArray[row - 1][col - 1] == 3:
                brush_color = Qt.white
            elif row > 1 and col < 6 and self.boardArray[row - 2][col + 2] == 1 and self.boardArray[row - 1][col + 1] == 3:
                brush_color = Qt.white
        return brush_color

    def color_brush_black(self, row, col, i):
        """
        Set the brush color for black pieces
        :param row:
        :param col:
        :param i:
        :return:
        """
        brush_color = Qt.black
        if self.player_turn == 2 and self.selected_piece[1] == row and self.selected_piece[0] == col:
            brush_color = QColor.fromRgb(100, 100, 255)
        elif self.player_turn == 2 and self.selected_piece == [-1, -1]:
            if i > 0 and row < 7 and col > 0 and self.boardArray[row + 1][col - 1] == 1:
                brush_color = QColor.fromRgb(255, 0, 255)
            elif i > 0 and row < 7 and col < 7 and self.boardArray[row + 1][col + 1] == 1:
                brush_color = QColor.fromRgb(255, 0, 255)
            elif row < 6 and col > 1 and self.boardArray[row + 2][col - 2] == 1 and self.boardArray[row + 1][col - 1] == 2:
                brush_color = QColor.fromRgb(255, 0, 255)
            elif row < 6 and col < 6 and self.boardArray[row + 2][col + 2] == 1 and self.boardArray[row + 1][col + 1] == 2:
                brush_color = QColor.fromRgb(255, 0, 255)
        return brush_color

    def draw_pieces(self, painter):
        """draw the prices on the board"""
        brush_color = QColor.fromRgb(200, 200, 200)
        images = [QImage(WHITE_PIECE), QImage(BLACK_PIECE), QImage(WHITE_KING), QImage(BLACK_KING), QImage(BLACK_SQUARE)]
        idx = 0
        i = 0
        y = 1
        while i < 2:
            for row in range(0, len(self.boardArray)):
                for col in range(0, len(self.boardArray[0])):
                    #painter.save()
                    col_transformation = col * self.square_width()
                    row_transformation = row * self.square_height()
                    ## Todo victoire quand bloquer

                    if self.boardArray[row][col] == 2:
                        brush_color = self.color_brush_white(row, col, i)
                        idx = 0
                    elif self.boardArray[row][col] == 1:
                        brush_color = Qt.black
                        idx = 4
                    elif self.boardArray[row][col] == 3:
                        brush_color = self.color_brush_black(row, col, i)
                        idx = 1
                    elif self.boardArray[row][col] == 4:
                        brush_color = self.color_brush_white(row, col, i)
                        idx = 2
                    elif self.boardArray[row][col] == 5:
                        brush_color = self.color_brush_black(row, col, i)
                        idx = 3
                    elif self.boardArray[row][col] == 6:
                        brush_color = QColor.fromRgb(128, 128, 128)
                    if self.boardArray[row][col] != 0:
                        painter.setPen(brush_color)
                        if brush_color == Qt.white or brush_color == QColor.fromRgb(255, 0, 255):
                            y = 2
                        # Todo draw some the pieces as eclipses
                        radius_width = (self.square_width() / 10 * 8) / 2
                        radius_height = (self.square_height() / 10 * 8) / 2
                        center = QPoint(col_transformation + (self.square_width() / 2),
                                        row_transformation + (self.square_height() / 2))
                        if idx != 4:
                            painter.drawEllipse(center, radius_width, radius_height)
                            self.image = images[idx].scaled(radius_width * 2, radius_height * 2)
                            painter.drawImage(center.x() - radius_width, center.y() - radius_height, self.image)
                        #painter.restore()
                        self.update()
            i += y
 def positionChanged(self, position):
     self.positionSlider.setValue(position)
     mtime = QTime(0, 0, 0, 0)
     mtime = mtime.addMSecs(self.mediaPlayer.position())
     self.lbl.setText(mtime.toString())
Exemple #55
0
def delay():
    #QCoreApplication.processEvents(QEventLoop.AllEvents, 1)
    #QtWidgets.QApplication.processEvents(QEventLoop.AllEvents, 1)
    t = QTime.currentTime().addMSecs(1)
    while QTime.currentTime() < t:
        QCoreApplication.processEvents(QEventLoop.AllEvents, 1)
Exemple #56
0
 def on_pushButton_SetTime_clicked(self):
     tmStr = self._ui.lineEdit_Time.text()
     tm = QTime.fromString(tmStr, 'hh:mm:ss')
     self._ui.timeEdit.setTime(tm)
 def showTime(self):
     date = QDate.currentDate()
     time = QTime.currentTime()
     self.timeEdit.setTime(time)
     self.dateEdit.setDate(date)
Exemple #58
0
 def on_duration_changed(self, duration):
     duration = duration * 1000
     m, s = parse_ms(duration)
     t = QTime(0, m, s)
     self.progress_slider.set_duration(duration)
     self.duration_label.setText(t.toString('mm:ss'))
Exemple #59
0
 def startParty(self):
     self.partyStarted.emit(QTime.currentTime())
Exemple #60
0
 def updateRestEndTime(self):
     self.restEndTime = QTime(
         self.restHoursSpinBox.value(),
         self.restMinutesSpinBox.value(),
         self.restSecondsSpinBox.value(),
     )