import os, sys, pyglet
from mutagen import File
from PyQt4 import QtGui, QtCore
from load_data import load_stuff

WX, WY = 300,300

BASE_DIR, PLAYLIST, INTSETTING, SONGTAGS = load_stuff()
DEBUG = 0
class Music(object):
    def __init__(self, filename):
        self.music = File(filename)
        self.url = filename
        if filename.endswith('.mp3'): a = ['mp3','TIT2','TPE1','TALB','TCON','TDRC']
        elif filename.endswith('.m4a'): a = ['m4a','\xa9nam','\xa9ART','\xa9alb','\xa9gen','\xa9day']
        elif filename.endswith('.mp4'): a = ['mp4','\xa9nam','\xa9ART','\xa9alb','\xa9gen','\xa9day']
        elif filename.endswith('.flac'): a = ['flac','Title','Artist','Album','Genre','Date']
        self.type,self.title,self.artist,self.album,self.genre,self.year= a[0],a[1],a[2],a[3],a[4],a[5]

    def _titleArtist(self):
        try:
            t, a = self.music[self.title], self.music[self.artist]
            if self.type == 'm4a' or self.type == 'mp4' or self.type == 'flac':
                return a[0] + ' - ' + t[0]
            return a + ' - ' + t
        except: #if no title and artist tags detected, filename will be shown
            u, replace_title_artist, x, y = self.url, '', 0, 4
            if self.type == 'flac': y = 5
            for i in range(len(u)):
                if u[i] == '/': x += 1
                if u[i] == '/' and x == u.count('/'): replace_title_artist += u[ i+1:len(u) - y ]
                # if u[i] == '\\': x += 1
                # if u[i] == '\\' and x == u.count('\\'): replace_title_artist += u[ i+1:len(u) - y ]
            return replace_title_artist

    def _coverArt(self):
        try:
            image = QtGui.QImage()
            if  self.type == 'mp3': image.loadFromData(self.music.tags['APIC:'].data)
            elif self.type == 'm4a' or self.type == 'mp4': image.loadFromData(self.music['covr'][0])
            elif self.type == 'flac': image.loadFromData(self.music.pictures[0].data)
        except: image.load('images/3.jpg') #if no image embeded on songs
        return image.scaled( WX, WY, aspectRatioMode=QtCore.Qt.IgnoreAspectRatio )

    def set_coverart(self, address):
        if self.type == 'mp3':
            from mutagen.id3 import APIC
            self.music.tags['APIC:'] = APIC(encoding=3,mime=u'image/jpeg',type=3,desc=u'',data=open(address, 'rb').read())
        elif self.type == 'flac':
            from mutagen.flac import Picture
            i = Picture()
            i.type, i.desc, i.mime, i.data = 3, '', 'image/jpeg', open(address, 'rb').read()
            self.music.clear_pictures()
            self.music.add_picture( i )
        elif self.type == 'm4a':
            from mutagen.m4a import M4ACover
            image = []
            image.append( M4ACover( open(address, 'rb').read() ) )
            self.music['covr'] = image
        self.music.save()

    def set_simplfier(self, self_temp, MOD, new_name):
        if type(new_name) == int:
            self.music[self_temp] = MOD
            self.music.save()
            return

        # if value after filter out empty space string is not none
        if filter(lambda x : x != ' ', new_name):
            if self.type == 'mp3':self.music[self_temp] = MOD
            else: self.music[ self_temp ] = [ new_name ]
            self.music.save()

    def set_title(self,newname):
        from mutagen.id3 import TIT2
        self.set_simplfier(self_temp=self.title, MOD=TIT2(encoding=3, text=newname), new_name=newname)
    def set_artist(self,newname):
        from mutagen.id3 import TPE1
        self.set_simplfier(self_temp=self.artist, MOD=TPE1(encoding=3, text=newname), new_name=newname)
    def set_album(self,newname):
        from mutagen.id3 import TALB
        self.set_simplfier(self_temp=self.album, MOD=TALB(encoding=3, text=newname), new_name=newname)
    def set_genre(self,newname):
        from mutagen.id3 import TCON
        self.set_simplfier(self_temp=self.genre, MOD=TCON(encoding=3, text=newname), new_name=newname)
    def set_year(self,newname):
        from mutagen.id3 import TDRC
        self.set_simplfier(self_temp=self.year, MOD=TDRC(encoding=3, text=newname), new_name=int(newname))

    def get_simplifer(self, self_temp):
        try:
            string = self.music[self_temp]
            if type(string) == int:
                return int( string )
            if self.type == 'mp3':
                return  string
            return string[0]
        except: return ''

    def _title(self): return str(self.get_simplifer( self.title ))
    def _artist(self): return self.get_simplifer( self.artist )
    def _album(self): return self.get_simplifer( self.album )
    def _genre(self): return self.get_simplifer( self.genre )
    def _year(self): return self.get_simplifer( self.year )

    def _mskb(self):
        l = int( self.music.info.length )
        m, s, k =  l / 60, l % 60, self.music.info.sample_rate / 1000.
        if self.type != 'flac' : b = self.music.info.bitrate / 1000. #b = k bit per second
                #'bit rate = sample rate x bit depth(bits per sample) x channels'
        else: b = self.music.info.sample_rate * self.music.info.bits_per_sample * self.music.info.channels / 1000.
        return m, s, k, b

    def get(self): return '%s' % self._titleArtist()

    def _get(self):
        m, s, k, b = self._mskb()
        return '%s\nAlbum: %s Length: %.f:%02d, %.f kbps' % (
               self._titleArtist() ,
                 self._album() ,
                m, s, b)

    def __get(self):
        m, s, k, b = self._mskb()
        return '%s\nAlbum: %s, Genre: %s, Year: %s\nLength: %.f:%.f, %.f kbps, %.f KHz' % (
               self._titleArtist(),
                self._album(),
                 self._genre(),
                self._year(),
                m, s, b, k)

class Main(QtGui.QMainWindow):

    changed = QtCore.pyqtSignal(QtCore.QMimeData)

    def __init__(self,parent=None):
        super(Main, self).__init__(  parent
                  # QtCore.Qt.FramelessWindowHint |
                  # QtCore.Qt.WindowTitleHint |
                  # QtCore.Qt.WindowMaximizeButtonHint |
                  # QtCore.Qt.WindowMinMaxButtonsHint |
                  # QtCore.Qt.BypassGraphicsProxyWidget |
                  # QtCore.Qt.WindowModal |
                  # QtCore.Qt.WindowShadeButtonHint
                  # QtCore.Qt.WindowSystemMenuHint
                )
        self.isPlaying = True
        self.currentSongTotalTime = 0
        self.currentPlayingSongTime = 0
        self.currentTime = 0
        self.initiate = True
        self.currentPlayingRow = INTSETTING['currentPlayingRow']
        self.currentVolume = INTSETTING['volume']
        if INTSETTING['repeat'] == 0: self.isRepeat = False
        else: self.isRepeat = True
        if INTSETTING['random'] == 0: self.isRandom = False
        else: self.isRandom = True
        self.sources = []
        self.shuffleList = []
        self.shuffleListPopped = []
        self.cresendo = 0
        self.player = pyglet.media.Player()
        self.imageLabel = QtGui.QLabel()

        self.seekBarTimer = QtCore.QTimer(self)
        self.seekBarTimer.timeout.connect(self.update)

        self.timerVolume = QtCore.QTimer(self)
        self.timerVolume.timeout.connect(self.updateCresendo)
        self.timerVolume.start(50)

        self.setWindowTitle('KlaYeR')
        self.createActions()
        self.createMenus()
        # self.createToolBars()
        self.setAcceptDrops(True)
        self.initiate_GUI()
        self.count = 0
        self.statusBar().addWidget(QtGui.QLabel("All Green."))
        if INTSETTING['X'] == 0 and INTSETTING['W'] == 1366:
            self.showMaximized()
        else: self.setGeometry(INTSETTING['X'],INTSETTING['Y'],INTSETTING['W'],INTSETTING['H'])
        self.changeStyle('Cleanlooks')
        qwww = """
                    QToolBar {
                    border-color: none;
                    border-width: none;
                    border-style: none;
                    border-radius: 0px;
                    padding: 0;
                    background-color: none;
                    }
                    QToolButton:hover {
                    border-color: rgba(0,0,0,19);
                    border-width: 1px;
                    border-style: solid;
                    border-radius: 4px;
                    padding: 0;
                    background-color: rgba(255,168,81,255);
                    }
                    QWidget {
                    background-color: white;
                    selection-color: rgba(255, 255, 255, 255);
                    selection-background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #FF8000, stop:1 #FFFFFF);;
                    color: rgba(55, 55, 55, 255);
                    font-family: Helvetica;
                    }

                    QDockWidget {
                    /*margin: 5px;*/
                    /*border: 10px solid white;*/
                    /*border-radius: 5px;*/
                    titlebar-close-icon: url(close.png);
                    titlebar-normal-icon: url(undock.png);
                    color: rgba(55, 55, 55, 0);
                    }

                    QDockWidget::title {
                    text-align: center; /* align the text to the left */
                    background: rgba(250,250,250,255);
                    /*border:1px solid #FCFCFC;*/
                    /*border-radius: 5px;*/
                    color: rgba(55, 55, 55, 0);
                    }

                    QDockWidget::close-button, QDockWidget::float-button {
                    border: 1px solid transparent;
                    /*background: darkgray;*/
                    color: rgba(55, 55, 55, 0);
                    padding: 0px;
                    }

                    QDockWidget::close-button:hover, QDockWidget::float-button:hover {
                    background: gray;
                    color: rgba(55, 55, 55, 0);
                    }

                    QDockWidget::close-button:pressed, QDockWidget::float-button:pressed {
                    color: rgba(55, 55, 55, 0);
                    padding: 1px -1px -1px 1px;
                    }

                    QPushButton{
                    /*min-width: 80px;*/
                    }
                    QPushButton[checkable="false"] {
                    border: 2px solid rgba(0,0,0,0);
                    padding:4px;
                    border-radius: 8px;
                    background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                   stop: 0 #dadbde, stop: 1 #f6f7fa);
                    }
                    QPushButton[checkable="false"]:hover {border-color: rgba(255,168,81,255);}

                    QPushButton[checkable="false"]:pressed {background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                  stop: 0 rgba(0,0,0,11), stop: 1 rgba(0,0,0,33));}

                    QPushButton[checkable="true"] {
                    border-color: none;
                    border-style: solid;
                    padding:4px;
                    background-color: none;
                    }
                    QPushButton[checkable="true"]:hover {
                    background-color: rgba(255,168,81,128);
                    border-radius: 4px;
                    }
                    QPushButton[checkable="true"]:open {
                    border-color: rgba(0,0,0,19);
                    border-width: 1px;
                    border-style: solid;
                    padding:4px;
                    border-radius: 4px;
                    background-color: rgba(255,168,81,255);}

                    QPushButton:flat {
                    border: none;  /*no border for a flat push button */
                    }

                    QScrollBar:horizontal {
                    /*border: 2px solid white;*/
                    background: white;
                    height: 15px;
                    margin: 0px 0px 0 0px;
                    /*subcontrol-origin: margin;*/
                    }

                    QScrollBar::handle:horizontal {
                    background: #DADADA;
                    min-width: 20px;
                    }

                    QScrollBar::add-line:horizontal {
                    background: none;
                    width: 0px;
                    /*subcontrol-position: right;*/
                    /*subcontrol-origin: margin;*/
                    /*border: 2px solid black;*/
                    }

                    QScrollBar::sub-line:horizontal {
                    background: none;
                    width: 0px;
                    /*subcontrol-position: top right;
                    subcontrol-origin: margin;
                    border: 2px solid black;
                    position: absolute;
                    right: 20px;*/
                    }

                    QScrollBar:left-arrow:horizontal, QScrollBar::right-arrow:horizontal {
                    /*     width: 3px;
                    height: 3px;*/
                    background: none;
                    }

                    QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {
                    background: none;
                    }

                    QScrollBar:vertical {
                    /*border: 2px solid white;*/
                    background: white;
                    width: 15px;
                    margin: 0 0 0 0;
                    subcontrol-origin: margin;
                    }
                    QScrollBar::handle:vertical {
                    background: #DADADA;
                    min-height: 20px;
                    }
                    QScrollBar::add-line:vertical {
                    /*border: 2px solid #FFFFFF;*/
                    background: none;
                    height: 0px;
                    /*subcontrol-position: left;*/
                    /*subcontrol-origin: margin;*/
                    }

                    QScrollBar::sub-line:vertical {
                    /*border: 2px solid #FFFFFF;*/
                    background: none;
                    height: 0px;
                    /*subcontrol-position: left;*/
                    /*subcontrol-origin: margin;*/
                    }
                    QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
                    /*border: 2px solid grey;*/
                    /*width: 3px;
                    height: 3px;*/
                    background: none;
                    }

                    QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
                    background: none;
                    }

                    QSlider::groove:horizontal {
                    border: 1px solid #FFFFFF;
                    height: 8px; /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #E9E9E9, stop:1 #FFFFFF);
                    border-radius: 6px;
                    margin: 2px 0;
                    }

                    QSlider::handle:horizontal {
                    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #FF8000, stop:1 #FFC488);
                    border: 1px solid #FF8000;
                    width: 15px;
                    margin: -2px 0; /* handle is placed by default on the contents rect of the groove. Expand outside the groove */
                    border-radius: 5px;
                    }
                    /*QSlider::add-page:horizontal {
                    background: white;
                    }*/

                    QSlider::sub-page:horizontal {
                    border: 1px solid #FFFFFF;
                    height: 8px; /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #FF8000, stop:1 #FFCB97);
                    border-radius: 6px;
                    margin: 2px 0;
                    }

                    QTabWidget::pane { /* The tab widget frame */
                    border-top: 2px solid #FFFFFF;
                    }

                    QTabWidget::tab-bar {
                    left: 5px; /* move to the right by 5px */
                    }

                    /* Style the tab using the tab sub-control. Note that
                    it reads QTabBar _not_ QTabWidget */
                    QTabBar::tab {
                    /* background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                             stop: 0 #FFBA75, stop: 0.4 #FFBC9B,
                             stop: 0.5 #FFA477, stop: 1.0 #FFB591);*/
                    border: 2px solid #FFFFFF;
                    border-bottom-color: #FFFFFF; /* same as the pane color */
                    /*border-top-left-radius: 6px;*/
                    /*border-top-right-radius: 6px;*/
                    min-width: 12ex;
                    padding: 2px;
                    }

                    QTabBar::tab:selected, QTabBar::tab:hover {

                    background: #FFCFB9;
                    }

                    QTabBar::tab:selected {
                    border-color: #FF9F71;
                    border-bottom-color: #FFFFFF; /* same as pane color */
                    }

                    QTabBar::tab:!selected {
                    margin-top: 2px; /* make non-selected tabs look smaller */
                    }

        """
        QtGui.qApp.setStyleSheet(qwww)
        self.restoreState(INTSETTING['loadState'])
        self.show()

        'initiate load playlist'
        if PLAYLIST: #initiately load playlist
            self.addSources(SONGTAGS, PLAYLIST)
            self.loadPlaylist()
        if self.sources:
            self.goShuffle()
        if self.currentPlayingRow >= len(self.sources):
            self.currentPlayingRow = 0
        try:
            self.play()
        except: pass

    @QtCore.pyqtSlot()
    def on_pushButton_clicked(self):
        try:
            self.dialogTextBrowser.exec_()
        except: pass

    def initiate_GUI(self):
        'north 1'
        self.playbackControl = QtGui.QToolBar()
        self.reload_actionPuase()
        # self.playbackControl.setMaximumSize(150,18)
        # North_level_1 = QtGui.QHBoxLayout()
        # North_level_1.addStretch()
        # North_level_1.addWidget(self.playbackControl)
        # North_level_1.addStretch()

        'north 2'
        loopButton = QtGui.QPushButton(QtGui.QIcon('images/repeat.png'), '')
        loopButton.setCheckable(True)
        loopButton.setChecked(self.isRepeat)
        loopButton.clicked[bool].connect(self.repeat)
        # loopButton.setMinimumSize(70,12)
        shuffleButton = QtGui.QPushButton(QtGui.QIcon('images/shuffle.png'), '')
        shuffleButton.setCheckable(True)
        shuffleButton.setChecked(self.isRandom)
        shuffleButton.clicked[bool].connect(self.random)
        # shuffleButton.setMinimumSize(70,12)
        self.volumeBar = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        self.volumeBar.setFocusPolicy(QtCore.Qt.NoFocus)
        self.volumeBar.setRange(-1,100)
        self.volumeBar.setValue(self.currentVolume)
        self.volumeBar.setMaximumSize(100, 50)
        self.volumeBar.valueChanged.connect(self.volume)
        # self.volumeBar.setMinimumSize(80,12)
        self.volumeIcon = QtGui.QToolBar()
        # self.volumeIcon.setMinimumSize(15,15)
        if self.currentVolume > 0: self.volumeIcon.addAction(self.unmutedIcon)
        else: self.volumeIcon.addAction(self.mutedIcon)
        North_level_2 = QtGui.QHBoxLayout()
        North_level_2.addWidget(self.volumeBar)
        North_level_2.addWidget(self.volumeIcon)
        North_level_2.addStretch()
        North_level_2.addWidget(self.playbackControl)
        North_level_2.addStretch()
        North_level_2.addWidget(loopButton)
        North_level_2.addWidget(shuffleButton)

        'center 1'
        self.coverartDock = QtGui.QDockWidget("Cover Art", self)
        self.coverartDock.setObjectName("Cover Art")
        self.coverartDock.setWidget(self.imageLabel)

        'here'
        self.playlistDock = QtGui.QDockWidget("Playlist", self)
        tabWidget = QtGui.QTabWidget()
        tabWidget.setMovable(True)
        self.playlistDock.setObjectName("Playlist")
        self.Playlist = QtGui.QListWidget(self.playlistDock)
        self.Playlist2 = QtGui.QListWidget(self.playlistDock)
        tabWidget.addTab(self.Playlist, 'P_1')
        tabWidget.addTab(self.Playlist2, 'P_2')
        self.playlistDock.setWidget(tabWidget)
        'there'

        # self.playlistDock.setMinimumSize(320,290)

        self.Playlist.doubleClicked.connect(self.play) #double click to play a song
        self.Playlist.clicked.connect(self.TagEditor) #double click to play a song

        Center_level_1 = QtGui.QHBoxLayout()
        Center_level_1.addWidget(self.coverartDock)
        Center_level_1.addWidget(self.playlistDock)

        'south 1'
        self.seekBar = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        # self.seekBar.sliderMoved.connect(self.seek)
        self.seekBar.sliderReleased.connect(self.seekingUnmute)
        self.seekBar.sliderPressed.connect(self.seekingMute)

        self.tagEditorButton = QtGui.QPushButton(self)
        self.tagEditorButton.setText("Edit Tag")
        self.tagEditorButton.clicked.connect(self.on_pushButton_clicked)

        deleteButton = QtGui.QPushButton(self)
        deleteButton.setText("Drop Song")
        deleteButton.clicked.connect(self.deleteRow)

        clearPlsButton = QtGui.QPushButton('Clear PLS', self)
        clearPlsButton.clicked.connect(self.clearPlaylist)
        # buttonExit = QtGui.QPushButton('Exit', self)
        # buttonExit.clicked.connect(self.closeEvent)
        South_level_1 = QtGui.QHBoxLayout()
        South_level_1.addWidget(self.seekBar)
        South_level_1.addWidget(self.tagEditorButton)
        South_level_1.addWidget(clearPlsButton)
        South_level_1.addWidget(deleteButton)

        mainLayout = QtGui.QVBoxLayout()
        # mainLayout.addLayout(North_level_1)
        mainLayout.addLayout(North_level_2)
        mainLayout.addLayout(Center_level_1)
        # mainLayout.addLayout(South_level_1)
        main2Layout = QtGui.QVBoxLayout()
        main2Layout.addLayout(South_level_1)

        mainWidget = QtGui.QWidget()
        mainWidget.setLayout(mainLayout)
        main2Widget = QtGui.QWidget()
        main2Widget.setLayout(main2Layout)
        # self.setMenuWidget(mainWidget)
        self.topDock = QtGui.QDockWidget("Control", self, QtCore.Qt.FramelessWindowHint)
        self.topDock.setObjectName("Control")
        self.topDock.setWidget(mainWidget)
        self.topDock.setMaximumSize(1360,58)

        self.bottomDock = QtGui.QDockWidget("Flow", self)
        self.bottomDock.setObjectName("Flow")
        self.bottomDock.setWidget(main2Widget)
        self.bottomDock.setMaximumSize(1360,55)
        # self.bottomDock.setMinimumSize(300,70)
        self.viewMenu.addAction(self.coverartDock.toggleViewAction())
        self.viewMenu.addAction(self.playlistDock.toggleViewAction())
        self.viewMenu.addAction(self.topDock.toggleViewAction())
        self.viewMenu.addAction(self.bottomDock.toggleViewAction())
        # self.setCentralWidget(mainWidget)

        # setFloating (self, bool floating)
        # coverartDock.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)
        # self.coverartDock.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea)
        # self.playlistDock.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)
        # self.bottomDock.setAllowedAreas(QtCore.Qt.BottomDockWidgetArea)
        # self.topDock.setAllowedAreas(QtCore.Qt.TopDockWidgetArea)
        # self.tabifyDockWidget(playlistDock,playlistDock)
        self.addDockWidget(QtCore.Qt.TopDockWidgetArea, self.topDock)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.coverartDock)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea , self.playlistDock)
        self.addDockWidget(QtCore.Qt.BottomDockWidgetArea , self.bottomDock)
        # self.setCentralWidget(self.playlistDock)
        self.setDockNestingEnabled(False)
    def TagEditor(self, index=None):
        if index:
            i = index.row()
            self.i = index.row()
            music = Music(self.sources[i][0])

        self.dialogTextBrowser = QtGui.QDialog(self)
        packagesGroup = QtGui.QGroupBox()
        nameLabel = QtGui.QLabel("Title: " )
        nameEdit = QtGui.QLineEdit('%s' % music._title())
        artistLabel = QtGui.QLabel("Artist: " )
        artistEdit = QtGui.QLineEdit('%s' % music._artist())
        albumLabel = QtGui.QLabel("Album: " )
        albumEdit = QtGui.QLineEdit('%s' % music._album())
        genreLabel = QtGui.QLabel("Genre: " )
        genreEdit = QtGui.QLineEdit('%s' % music._genre())
        yearLabel = QtGui.QLabel("Year: " )
        yearEdit = QtGui.QLineEdit('%s' % music._year())
        artLabel = QtGui.QLabel("CoverArt: " )
        art = QtGui.QLabel()
        art.setPixmap(QtGui.QPixmap.fromImage(music._coverArt() ))
        art.setMaximumSize(WX, WY)
        self.image = QtGui.QImage()
        self.path = ''

        def addPic():
            u, file_url, x = music.url, '', 0
            for i in range(len(u)):
                file_url += u[i]
                if u[i] == '/': x += 1
                if u[i] == '/' and x == u.count('/'): break
            path = QtGui.QFileDialog.getOpenFileName(self, 'Select your picture', file_url)
            if path.endswith('.jpg') or path.endswith('.png') or path.endswith('.jpeg'):
                self.path = path
                self.image.load(self.path) #if no image embeded on songs
                a = self.image.scaled( 200, 200, aspectRatioMode=QtCore.Qt.IgnoreAspectRatio )
                art.setPixmap(QtGui.QPixmap.fromImage( a ))

        def accept():
            music.set_title( nameEdit.text() )
            music.set_artist( artistEdit.text() )
            music.set_album( albumEdit.text() )
            music.set_genre( genreEdit.text())
            music.set_year( yearEdit.text()  )
            if self.path != '': music.set_coverart(self.path)
            self.sources[i][1] = music.get()
            self.loadPlaylist()
            if self.currentPlayingRow == i:
                self.imageLabel.setPixmap(QtGui.QPixmap.fromImage( music._coverArt() ))
            self.dialogTextBrowser.close()

        addPicButton = QtGui.QPushButton('CoverArt', self)
        addPicButton.clicked.connect(addPic)

        packagesLayout = QtGui.QGridLayout()
        packagesLayout.addWidget(nameLabel, 0, 0)
        packagesLayout.addWidget(nameEdit, 0, 1)
        packagesLayout.addWidget(artistLabel, 1, 0)
        packagesLayout.addWidget(artistEdit, 1, 1)
        packagesLayout.addWidget(albumLabel, 2, 0)
        packagesLayout.addWidget(albumEdit, 2, 1)
        packagesLayout.addWidget(genreLabel, 3, 0)
        packagesLayout.addWidget(genreEdit, 3, 1)
        packagesLayout.addWidget(yearLabel, 4, 0)
        packagesLayout.addWidget(yearEdit, 4, 1)
        packagesLayout.addWidget(artLabel, 5, 0)
        packagesLayout.addWidget(addPicButton, 5, 0)
        packagesLayout.addWidget(art, 5, 1)
        packagesGroup.setLayout(packagesLayout)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(packagesGroup)
        mainLayout.addSpacing(12)
        mainLayout.addStretch(1)
        widget = QtGui.QWidget()
        widget.setLayout(mainLayout)

        pagesWidget = QtGui.QStackedWidget()
        pagesWidget.addWidget(widget)
        horizontalLayout = QtGui.QHBoxLayout()
        horizontalLayout.addWidget(pagesWidget, 1)

        buttonBox = QtGui.QDialogButtonBox()
        buttonBox.setOrientation(QtCore.Qt.Horizontal)
        buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        buttonBox.accepted.connect(accept)
        buttonBox.rejected.connect(self.dialogTextBrowser.reject)
        buttonsLayout = QtGui.QHBoxLayout()
        buttonsLayout.addStretch(1)
        buttonsLayout.addWidget(buttonBox)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addLayout(horizontalLayout)
        mainLayout.addLayout(buttonsLayout)
        # mainLayout.addStretch(1)
        # mainLayout.addSpacing(12)

        self.dialogTextBrowser.setWindowTitle('Tag Editor')
        self.dialogTextBrowser.setLayout(mainLayout)

    'this method mainly to reload playlist'
    def loadPlaylist(self):
        self.Playlist.clear()
        for j in range(len(self.sources)):
            p = QtGui.QListWidgetItem( str(j + 1) + '. ' + self.sources[j][1])
            if j == self.currentPlayingRow:
                # self.Playlist.setCurrentRow( j )
                try:
                    music = Music( self.sources[ j ][0] )
                    p.setText( str(j + 1) + '. ' + music._get() )
                    p.setTextColor( QtGui.QColor(255, 255, 255,155) )
                    p.setFont( QtGui.QFont('Helvetica', 11) )
                    p.setBackgroundColor( QtGui.QColor(255,168,81,155) )
                except: pass
                # self.Playlist.setItemSelected( p, True)
            self.Playlist.addItem( p )

    def addSources(self, SONGTAGS, PLAYLIST):
        for i, newsource in enumerate(PLAYLIST):
            try:
                # music = Music(newsource)
                # fileinfo = music.get()
                path = newsource
                fileinfo = SONGTAGS[i]
                self.sources.append([ path, fileinfo ])
            except: pass

    def deleteRow(self):
        try:
            del self.sources[self.i]
            if self.i <= self.currentPlayingRow:
                self.currentPlayingRow -= 1
            self.loadPlaylist()
            self.Playlist.setCurrentRow( self.i )
            p = self.Playlist.item( self.i )
            self.Playlist.setItemSelected( p, True)
        except: pass

    def clearPlaylist(self):
        if self.sources:
            self.currentPlayingRow = 0
            self.sources = []
            self.seekBarTimer.stop()
            self.seekBar.setValue(0)
            self.player.delete()
            self.setWindowTitle('KlaYeR')
            self.imageLabel.clear()
            self.Playlist.clear()

    def seek(self, time=None):
        self.currentTime = float(time)
        try: self.player.seek(time)
        except: pass
    def reload_actionPlay(self):
        self.playbackControl.clear()
        self.playbackControl.addAction(self.previousAction)
        # self.playbackControl.addAction(self.stopAction)
        self.playbackControl.addAction(self.playAction)
        self.playbackControl.addAction(self.nextAction)

    def reload_actionPuase(self):
        self.playbackControl.clear()
        self.playbackControl.addAction(self.previousAction)
        # self.playbackControl.addAction(self.stopAction)
        self.playbackControl.addAction(self.pauseAction)
        self.playbackControl.addAction(self.nextAction)

    def play_continue(self):
        if self.sources:
            self.isPlaying = not self.isPlaying
            self.reload_actionPuase()
            self.seekBarTimer.start(500)
            self.timerVolume.start(50)
            self.player.play()

    def pause(self):
        if self.sources:
            self.isPlaying = not self.isPlaying
            self.reload_actionPlay()
            self.timerDescendoForPause = QtCore.QTimer(self)
            self.timerDescendoForPause.timeout.connect(self.updateDescendoForPause)
            self.timerDescendoForPause.start(50)

    def stop(self):
        try:
            if self.player.playing:
                self.timerDescendoForStop = QtCore.QTimer(self)
                self.timerDescendoForStop.timeout.connect(self.updateDescendoForStop)
                self.timerDescendoForStop.start(50)
                if not self.sources:
                    self.player.delete()
                self.reload_actionPlay()

        except: pass

    def update(self):
        if self.currentTime == 0: self.count = 0
        temp = '' + self.title_roll[self.count]
        for i in range(self.count, len(self.title_roll)-1):
            temp += self.title_roll[i+1]
        for i in range(self.count):
            temp += self.title_roll[i]
        self.count+=1
        if self.count >= len(self.title_roll): self.count = 0
        self.setWindowTitle( temp )
        # if self.coverartDock.isVisible() and not self.playlistDock.isVisible() or self.playlistDock.isFloating():
        #     self.resize(10,10)
        # if (not self.coverartDock.isVisible() or self.coverartDock.isFloating()) and ( not self.playlistDock.isVisible() or self.playlistDock.isFloating()):
        #     self.resize(10,10)
        self.seekBar.setValue(self.currentTime)
        self.currentTime += 0.5
        previousPlayedRow = None
        if self.currentTime + 2  >= self.currentSongTotalTime:
            if not self.isRepeat and not self.isRandom and self.currentPlayingRow +2 <= len(self.sources):
                previousPlayedRow = self.currentPlayingRow
                self.currentPlayingRow += 1
            elif not self.isRepeat and not self.isRandom and self.currentPlayingRow +1 == len(self.sources):
                previousPlayedRow = self.currentPlayingRow
                self.currentPlayingRow = 0

            elif not self.isRepeat and self.isRandom:
                previousPlayedRow = self.currentPlayingRow
                try:
                    if self.isRandom and len(self.shuffleList) > 0:
                        self.shuffleListPopped.append(self.currentPlayingRow)
                        self.currentPlayingRow = self.shuffleList.pop()
                    elif self.isRandom and len(self.shuffleList) == 0:

                        self.shuffleListPopped = []
                        self.goShuffle()
                        self.shuffleListPopped.append(self.currentPlayingRow)
                        self.currentPlayingRow = self.shuffleList.pop()
                except: return
            elif self.isRepeat and self.isRandom:
                previousPlayedRow = self.currentPlayingRow
                try:
                    self.currentPlayingRow = self.shuffleList.pop()
                    self.shuffleListPopped.append(self.currentPlayingRow)
                except: return

            self.play(action=previousPlayedRow)

    def next(self):
        if self.sources:
            if not self.player.playing: self.reload_actionPlay()

            previousPlayedRow = self.currentPlayingRow

            # if next song is available
            if self.currentPlayingRow +2 <= len(self.sources) and not self.isRandom:
                self.currentPlayingRow += 1
                self.play(action=previousPlayedRow)

            # if next song is not available
            elif self.currentPlayingRow +1 == len(self.sources) and not self.isRandom:
                self.currentPlayingRow = 0
                self.play(action=previousPlayedRow)

            if self.isRandom and len(self.shuffleList) > 0:
                self.shuffleListPopped.append(self.currentPlayingRow)
                self.currentPlayingRow = self.shuffleList.pop()
                self.play(action=previousPlayedRow)

            #when shuffle list is empty
            elif self.isRandom and len(self.shuffleList) == 0:
                self.shuffleListPopped = []
                self.goShuffle()
                self.shuffleListPopped.append(self.currentPlayingRow)
                self.currentPlayingRow = self.shuffleList.pop()
                self.play(action=previousPlayedRow)

    def previous(self):
        if self.sources:
            if not self.player.playing: self.reload_actionPlay()

            previousPlayedRow = self.currentPlayingRow
            if self.currentPlayingRow  > 0 and not self.isRandom:
                self.currentPlayingRow -= 1
                self.play(action=previousPlayedRow)
            elif self.currentPlayingRow  == 0 and not self.isRandom:
                self.currentPlayingRow = len(self.sources) - 1
                self.play(action=previousPlayedRow)

            if self.isRandom and len(self.shuffleListPopped) > 0:
                self.shuffleList.append(self.currentPlayingRow)
                self.currentPlayingRow = self.shuffleListPopped.pop()
                self.play(action=previousPlayedRow)

    def dropEvent(self, event):
        import sys
        want2playauto = False
        if not self.sources:
            want2playauto = True
        mimeData = event.mimeData()
        paths = mimeData.urls()
        if paths:
            newpaths, newtags = [], []
            for path in paths:
                path = path.toString()
                path =path[8::]
                try:
                    music = Music(path)
                    newtags.append( music.get() )
                    newpaths.append(path)
                except:
                        for dirname, dirnames, filenames in os.walk(path):
                            for filename in filenames:
                                b = dirname + '\\' + filename
                                b = b.replace('\\','/')
                                if b.endswith('mp3') or b.endswith('m4a') or b.endswith('flac'):
                                    music = Music(b)
                                    newtags.append( music.get() )
                                    newpaths.append(b)

            self.addSources(newtags, newpaths)
            self.loadPlaylist()
            self.goShuffle()
        if want2playauto:
            self.currentTime = 0
            self.play(action='autoplay')

    def addFiles(self):
        want2playauto = False
        if not self.sources:
            want2playauto = True
        'remember last time visited URL'
        BASE_DIR = ''
        try:
            with open('config/url.ky', 'r') as config:
                BASE_DIR = config.read().decode("UTF-8")
        except: pass
        'if BASE_DIR is empty, dialog location will set on this sourcecode\' folder'
        if BASE_DIR == '':
            BASE_DIR = os.path.dirname(os.path.dirname(__file__))

        paths = QtGui.QFileDialog.getOpenFileNames(self, 'Add Music', BASE_DIR)

        if paths:
            newpaths = []
            newtags = []
            for path in paths:
                path = path.replace('\\','/')
                self.addMusicUrl = path
                try:
                    music = Music(path)
                    newtags.append( music.get() )
                    newpaths.append(path)
                except: pass
                try:
                    x, temp = 0, ''
                    for i in range(len(self.addMusicUrl)):
                        temp += self.addMusicUrl[i]
                        if self.addMusicUrl[i] == '\\':
                            x+=1
                        if self.addMusicUrl[i] == '\\' and x == self.addMusicUrl.count('\\'):
                            break
                    with open('config/url.ky', 'w') as config:
                        config.write(temp.encode("UTF-8"))
                except: pass

            self.addSources(newtags, newpaths)
            self.loadPlaylist()
            self.goShuffle()
        if want2playauto:
            self.currentTime = 0
            self.play(action='autoplay')

    def goShuffle(self):
        self.shuffleList = [x for x in range(0,len(self.sources))]
        from random import shuffle
        shuffle(self.shuffleList)

    def play(self, index=None, action=None):
        prev = None
        if self.sources: #if sources list consists of songs
            if type(action) == int: prev = action

            if index: #if user doubleclick detected
                prev = self.currentPlayingRow
                self.currentPlayingRow = index.row()

            try:
                #to delete switching song in faster pace/rate
                self.timerDescendo.stop()
                self.p.delete()
            except: pass

            #load previous tag info
            if type(prev) == int:
                music2 = Music( ( self.sources[ prev ][0] ) )

            if type(prev) == int and not self.initiate and self.player.time > 0.1 and self.player.playing:
                self.p = pyglet.media.Player()
                q = pyglet.media.load( self.sources[prev][0] )
                self.p.queue(q)
                self.p.seek( self.player.time + 0.02 )
                self.p.volume = self.player.volume / 1.5
                self.p.play()
                self.timerDescendo = QtCore.QTimer(self)

                self.rate = self.p.volume / 12.
                self.timerDescendo.timeout.connect(self.updateDescendo)
                self.timerDescendo.start(220)

            elif self.player.time <= 0.1:
                self.player.pause()
            while self.player.volume >= 0:
                self.player.volume = self.player.volume - 0.001
            self.player.delete()

            #load current playing tag info
            music = Music( ( self.sources[ self.currentPlayingRow ][0] ) )

            self.Playlist.setCurrentRow( self.currentPlayingRow )

            'set image for cover art'
            self.imageLabel.setPixmap( QtGui.QPixmap.fromImage( music._coverArt() ) )
            self.imageLabel.setMaximumSize(WX, WY)

            'settings for seekbar'
            self.currentTime = 0
            self.seekBar.setValue(0)
            self.currentSongTotalTime = music.music.info.length
            self.seekBar.setRange( 0, int( self.currentSongTotalTime - 2 ) )
            self.player.queue( pyglet.media.load( self.sources[ self.currentPlayingRow ][0] ) )

            'init the player'
            'load the last playing time of the song'
            if not index and self.initiate:
                self.initiate = False
                self.currentTime = INTSETTING['currentTime']
                self.seekBar.setValue(self.currentTime)
                self.player.seek(self.currentTime)

            self.seekBarTimer.stop()
            self.cresendo = 0

            if self.isPlaying:
                self.seekBarTimer.start(500)
                self.timerVolume.start(50)
                self.player.play()
            self.title_roll = ' ' + music._title() +' '+ '##########'*3
            self.setWindowTitle( self.title_roll )
            if action != 'autoplay':
                try:
                    w = self.Playlist.item( prev )
                    w.setText( str(prev + 1) + '. ' + music2.get() )
                    w.setTextColor( QtGui.QColor(55, 55, 55, 255) )
                    w.setFont( QtGui.QFont('Helvetica', 10) )
                    w.setBackgroundColor( QtGui.QColor(255, 255, 255, 255) )
                except: pass
                q = self.Playlist.item( self.currentPlayingRow )
                q.setText( str(self.currentPlayingRow + 1) + '. ' + music._get() )
                q.setTextColor( QtGui.QColor(255, 255, 255,155) )
                q.setFont( QtGui.QFont('Helvetica', 11) )
                q.setBackgroundColor( QtGui.QColor(255,168,81,255) )

    def repeat(self, varbool):
        self.isRepeat = varbool

    def random(self, varbool):
        self.isRandom = varbool

    def volume(self, time=None):
        if time:
            self.player.volume = time /100.
            self.currentVolume = time
            self.volumeIcon.clear()
            if time <= 0: self.volumeIcon.addAction(self.mutedIcon)
            else: self.volumeIcon.addAction(self.unmutedIcon)

    def muted(self):
        self.volumeIcon.clear()
        self.volumeIcon.addAction(self.mutedIcon)
        self.lastVolume = self.currentVolume
        self.volumeBar.setValue(-1)
        self.player.volume = 0

    def unmuted(self):
        self.volumeIcon.clear()
        self.volumeIcon.addAction(self.unmutedIcon)
        self.volumeBar.setValue(self.lastVolume)
        self.player.volume = self.lastVolume

    def seekingMute(self):
        self.seekBarTimer.stop()

    def seekingUnmute(self):

        try:
            self.currentTime = float(self.seekBar.sliderPosition())
            self.player.seek( self.currentTime )
            self.player.play()
            self.seekBarTimer.start(500)
            self.playbackControl.clear()
            self.playbackControl.addAction(self.previousAction)
            self.playbackControl.addAction(self.stopAction)
            self.playbackControl.addAction(self.pauseAction)
            self.playbackControl.addAction(self.nextAction)
        except: pass

    def updateDescendoForStop(self):
        if self.cresendo > 0:
            self.cresendo -= 5.2
            self.player.volume = self.cresendo / 100.
        else:
            self.timerDescendoForStop.stop()
            self.seekBarTimer.stop()
            self.currentTime = 0
            self.seekBar.setValue( 0 )
            try:
                self.player.pause()
                self.player.seek( 0 )
            except: pass

    def updateDescendoForPause(self):
        if self.cresendo > 0:
            self.cresendo -= 5.2
            self.player.volume = self.cresendo / 100.
        else:
            self.player.pause()
            self.timerDescendoForPause.stop()
            self.seekBarTimer.stop()

    def updateDescendo(self):
        self.p.volume -= self.rate
        if self.p.volume < 0.:
            self.p.pause()
            self.p.delete()
            self.timerDescendo.stop()

    def updateCresendo(self):
        if self.cresendo < self.currentVolume and not self.volumeBar.isSliderDown():
            if self.cresendo < self.currentVolume / 6:
                self.cresendo += 0.9
            else:
                self.cresendo += 2.8
            self.player.volume = self.cresendo / 100.
        else:

            self.timerVolume.stop()

    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.addFilesAct)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.quitAct)

        self.editMenu = self.menuBar().addMenu("&Edit")
        self.editMenu.addAction(self.editorAct)
        self.editMenu.addAction(self.deleteAction)
        self.viewMenu = self.menuBar().addMenu("&View")

        # self.menuBar().addSeparator()

        self.helpMenu = self.menuBar().addMenu("&Help")
        self.helpMenu.addAction(self.aboutAct)

    def createToolBars(self):
        self.fileToolBar = self.addToolBar("Option")
        self.fileToolBar.addAction(self.addFilesAct)
        self.fileToolBar.addAction(self.addFilesAct)
        self.fileToolBar.addAction(self.aboutAct)
        self.fileToolBar.addAction(self.quitAct)

        self.fileToolBar.setIconSize(QtCore.QSize(50, 25))
        self.fileToolBar.setMovable(False)
        # self.fileToolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        # self.editToolBar = self.addToolBar("Edit")

    # def createStatusBar(self):
    #     self.statusBar().showMessage("KlaYeR all green.")

    # def createDockWindows(self): pass

    def dragLeaveEvent(self, event):
        self.clear()
        event.accept()

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            self.move(event.globalPos() - self.dragPosition)
            event.accept()

    def dragEnterEvent(self, event):
        event.acceptProposedAction()
        self.changed.emit(event.mimeData())

    # def dragMoveEvent(self, event):
    #     event.acceptProposedAction()

    def changeStyle(self, styleName):
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create(styleName))
        # self.changePalette()

    def about(self):
        text = """
        <h2 style="font:red">??shit.</h2>
        <hr/>
        <p>hello <strong>folks</strong>.</p>
        <hr/>
        <img height="150" width="150"src="images/1.jpg"/>
        <hr/>
        <a href="http://www.helloworldhaha.com.ex">Visit my website.</a>
        """
        QtGui.QMessageBox.about(self, "About", text)

    def createActions(self):
        self.addFilesAct = QtGui.QAction(
            QtGui.QIcon('images/new.png'),
            "&Add Files",
            self,
            shortcut='Ctrl+A',
            statusTip="Add the music files",
            triggered=self.addFiles
            )
        self.editorAct = QtGui.QAction(
            QtGui.QIcon('images/new.png'),
            "Edit",
            self,
            shortcut='Ctrl+E',
            statusTip="Editor",
            triggered=self.on_pushButton_clicked
            )

        self.quitAct = QtGui.QAction(
            QtGui.QIcon('images/new.png'),
            "&Quit",
            self,
            shortcut="Ctrl+Q",
            statusTip="Quit the application",
            triggered=self.closeEvent
            )
        self.aboutAct = QtGui.QAction(
            QtGui.QIcon('images/new.png'),
            "&About",
            self,
            statusTip="Show the application's About",
            triggered=self.about
            )
        self.playAction = QtGui.QAction(
                self.style().standardIcon(QtGui.QStyle.SP_MediaPlay), "Play",
                self, shortcut="Space",
                statusTip="You can press [ Space ] to activate",
                triggered=self.play_continue)

        self.pauseAction = QtGui.QAction(
                self.style().standardIcon(QtGui.QStyle.SP_MediaPause),
                "Pause", self, shortcut="Space",
                statusTip="You can press [ Space ] to activate",
                triggered=self.pause)

        self.stopAction = QtGui.QAction(
                self.style().standardIcon(QtGui.QStyle.SP_MediaStop), "Stop",
                self, shortcut="Ctrl+S",
                statusTip="You can press [ Ctrl+S ] to activate",
                triggered=self.stop)

        self.nextAction = QtGui.QAction(
                self.style().standardIcon(QtGui.QStyle.SP_MediaSkipForward),
                "Next", self, shortcut="m",
                statusTip="You can press [ M ] to activate",
                triggered=self.next)

        self.previousAction = QtGui.QAction(
                self.style().standardIcon(QtGui.QStyle.SP_MediaSkipBackward),
                "Previous", self, shortcut="n",
                statusTip="You can press [ N ] to activate",
                triggered=self.previous)

        self.mutedIcon = QtGui.QAction(
                self.style().standardIcon(QtGui.QStyle.SP_MediaVolumeMuted),
                "Unmute", self, shortcut="z",
                statusTip="You can press [ Z ] to activate",
                triggered=self.unmuted)

        self.unmutedIcon = QtGui.QAction(
                self.style().standardIcon(QtGui.QStyle.SP_MediaVolume),
                "Mute", self, shortcut="z",
                statusTip="You can press [ Z ] to activate",
                triggered=self.muted)

        self.deleteAction = QtGui.QAction(
                self.style().standardIcon(QtGui.QStyle.SP_MediaVolume),
                "Delete", self, shortcut="Delete",
                statusTip="You can press [ Delete ] to activate",
                triggered=self.deleteRow)
    def savingData(self):
        # try:
        #     x, temp = 0, ''
        #     for i in range(len(self.addMusicUrl)):
        #         temp += self.addMusicUrl[i]
        #         if self.addMusicUrl[i] == '\\':
        #             x+=1
        #         if self.addMusicUrl[i] == '\\' and x == self.addMusicUrl.count('\\'):
        #             break
        #     with open('config/url.ky', 'w') as config:
        #         config.write(temp.encode("UTF-8"))
        # except: pass

        with open('config/pls.ky', 'w', encoding='utf-8') as config:
                for source in self.sources:
                    config.write(source[0]+'\n')
        with open('config/intsetting.ky', 'w', encoding='utf-8') as config:
            config.write(str(self.currentVolume) + '\n')
            config.write(str(self.currentPlayingRow) + '\n')

            if self.isRepeat:
                config.write(str(1) + '\n')
            else:
                config.write(str(0) + '\n')
            if self.isRandom:
                config.write(str(1) + '\n')
            else:
                config.write(str(0) + '\n')
            if self.sources:
                config.write(str(self.currentTime) + '\n')
            else:
                config.write(str(0) + '\n')
            rec = self.geometry()
            config.write(str(rec.left()) + '\n')
            config.write(str(rec.top()) + '\n')
            config.write(str(rec.width()) + '\n')
            config.write(str(rec.height()))

        with open('config/songname.ky', 'w', encoding='utf-8') as config:
            for name in self.sources:
                config.write(name[1]+'\n')

    def closeEvent(self, event=None):

        self.savingData()
        while self.player.volume >= 0:
            self.player.volume = self.player.volume - 0.001
        save = self.saveState()
        with open('config/state.ky', 'wb') as config:
            config.write(save)
        QtGui.qApp.quit()
        # if self.trayIcon.isVisible():
            # self.hide()
            # event.ignore()

def main():

    a = QtGui.QApplication(sys.argv)
    b = Main()
    sys.exit(a.exec_())

if __name__ == '__main__':
    main()


import re

piano_file = "./piano_melody_sequence.dat"
string_file = "./string_melody_sequence.dat"
guitar_file = "./guitar_melody_sequence.dat"
other_file = "./other_melody_sequence.dat"

out_guitar_file = "./guitar_accompany_sequence_processed.dat"
out_melody_file = "./guitar_melody_sequence_processed.dat"

with open(piano_file) as pf, open(guitar_file) as gf, open(string_file) as sf, open(other_file) as of:
    plines = pf.readlines()
    glines = gf.readlines()
    slines = sf.readlines()
    olines = of.readlines()

mlines = []
idx = 0
for pl, sl, ol in zip(plines, slines, olines):
    mlines.append(pl.strip()+' '+sl.strip()+'\n')
    idx += 1

idx = 0
temp_glines = []
temp_mlines = []
count = 0

mlines_new = []
glines_new = []

for gl, ml in zip(glines, mlines):
    if len(gl.strip()) == 0 or len(ml.strip()) == 0:
        temp_glines.append(gl)
        temp_mlines.append(ml)
        count += 1
    else:
        if 0 < count and count < 100:
            glines_new.extend(temp_glines)
            mlines_new.extend(temp_mlines)

        glines_new.append(gl)
        mlines_new.append(ml)

        if count > 0:
            temp_glines = []
            temp_mlines = []
            count = 0

    idx += 1

glines = []
mlines = []
gsongs = []
msongs = []
for gl, ml in zip(glines_new, mlines_new):
    gsongs.append(gl)
    msongs.append(ml)

    if re.match(r'\\', gl.strip()):
        if len(gsongs) >= 500:
            glines.extend(gsongs)
            mlines.extend(msongs)
            gsongs = []
            msongs = []
        else:
            gsongs = []
            msongs = []

with open(out_guitar_file, 'w') as gf, open(out_melody_file, 'w') as mf:
    for l in glines:
        gf.write(l)

    for l in mlines:
        mf.write(l)


""" this module store all tools and functions needed for this app"""
from typing import Dict, List
import logging
from logging.handlers import RotatingFileHandler

# Logging settings
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
file_handler = RotatingFileHandler('activity.log', 'a', 1000000, 1)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging.DEBUG)
logger.addHandler(stream_handler)

def matchingStrings(sentence : str, query : str) -> Dict[str,int]:
    """
        Method that gives all occurences in a sentence for a given query,
        only return occurences of strings contained in that query, like a filter
        Args:
            - sentence (str) : strings, chain of strings separated with a simple comma
            - query (str): scenario name specified in settings file
    """

    match_result = dict()
    sentence = sentence.split(",")
    queries = query.split(",")

    logger.debug('STRING :: %s',sentence)
    logger.debug('QUERY :: %s',queries)
    for word in queries:
        match_result[word] = sentence.count(word)
    print(match_result)
    return match_result


import codecs
import os
import re
import sys

from distutils.core import setup, Extension

if (sys.version_info >= (2, 6, 0)):
    raise ValueError("This extension should not be used with "
                     + "Python 2.6 or later (already built in), "
                     + "and has not been tested with Python 2.3.4 "
                     + "or earlier.")
elif (sys.version_info < (2, 3, 5)):
    sys.stderr.write("Warning:  This code has not been tested "
                     + "with versions of Python less than 2.3.5.\n")

def find_file(filename, std_dirs, paths):
    """Searches for the directory where a given file is located,
    and returns a possibly-empty list of additional directories, or None
    if the file couldn't be found at all.

    'filename' is the name of a file, such as readline.h or libcrypto.a.
    'std_dirs' is the list of standard system directories; if the
        file is found in one of them, no additional directives are needed.
    'paths' is a list of additional locations to check; if the file is
        found in one of them, the resulting list will contain the directory.
    """

    # Check the standard locations
    for dir in std_dirs:
        f = os.path.join(dir, filename)
        print('looking for', f)
        if os.path.exists(f):
            return []

    # Check the additional directories
    for dir in paths:
        f = os.path.join(dir, filename)
        print('looking for', f)
        if os.path.exists(f):
            return [dir]

    # Not found anywhere
    return None

def find_library_file(compiler, libname, std_dirs, paths):
    result = compiler.find_library_file(std_dirs + paths, libname)
    if result is None:
        return None

    # Check whether the found file is in one of the standard directories
    dirname = os.path.dirname(result)
    for p in std_dirs:
        # Ensure path doesn't end with path separator
        p = p.rstrip(os.sep)
        if p == dirname:
            return []

    # Otherwise, it must have been in one of the additional directories,
    # so we have to figure out which one.
    for p in paths:
        # Ensure path doesn't end with path separator
        p = p.rstrip(os.sep)
        if p == dirname:
            return [p]
    else:
        assert False, "Internal error: Path not found in std_dirs or paths"

def find_ssl():

    # Detect SSL support for the socket module (via _ssl)
    from distutils.ccompiler import new_compiler

    compiler = new_compiler()
    inc_dirs = compiler.include_dirs + ['/usr/include']

    search_for_ssl_incs_in = [
        '/usr/local/ssl/include',
        '/usr/contrib/ssl/include/',
    ]
    ssl_incs = find_file('openssl/ssl.h', inc_dirs, search_for_ssl_incs_in)
    if ssl_incs is not None:
        krb5_h = find_file('krb5.h', inc_dirs,
                           ['/usr/kerberos/include'])
        if krb5_h:
            ssl_incs += krb5_h

    ssl_libs = find_library_file(compiler, 'ssl',
        ['/usr/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu'],
        ['/usr/local/lib', '/usr/local/ssl/lib', '/usr/contrib/ssl/lib/'])

    if (ssl_incs is not None and ssl_libs is not None):
        return ssl_incs, ssl_libs, ['ssl', 'crypto']

    raise Exception("No SSL support found")

if (sys.version_info >= (2, 5, 1)):
    socket_inc = "./ssl/2.5.1"
else:
    socket_inc = "./ssl/2.3.6"

link_args = []
if sys.platform == 'win32':

    # Assume the openssl libraries from GnuWin32 are installed in the
    # following location:
    gnuwin32_dir = os.environ.get("GNUWIN32_DIR", r"C:\Utils\GnuWin32")

    # Set this to 1 for a dynamic build (depends on openssl DLLs)
    # Dynamic build is about 26k, static is 670k
    dynamic = int(os.environ.get("SSL_DYNAMIC", 0))

    ssl_incs = [os.environ.get("C_INCLUDE_DIR") or os.path.join(gnuwin32_dir, "include")]
    ssl_libs = [os.environ.get("C_LIB_DIR") or os.path.join(gnuwin32_dir, "lib")]
    libs = ['ssl', 'crypto', 'wsock32']
    if not dynamic:
        libs = libs + ['gdi32', 'gw32c', 'ole32', 'uuid']
        link_args = ['-static']
else:
    ssl_incs, ssl_libs, libs = find_ssl()

def read(*parts):
    here = os.path.abspath(os.path.dirname(__file__))
    return codecs.open(os.path.join(here, *parts), 'r').read()

def find_version(*file_paths):
    version_file = read(*file_paths)
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

setup(name='ssl',
      version=find_version('ssl', '__init__.py'),
      description='SSL wrapper for socket objects (2.3, 2.4, 2.5 compatible)',
      long_description=read('README.rst'),
      license='Python (MIT-like)',
      author='See long_description for details',
      author_email='distutils-sig@python.org',
      url='https://github.com/pypa/ssl',
      packages=['ssl'],
      ext_modules=[Extension('ssl._ssl2', ['ssl/_ssl2.c'],
                             include_dirs=ssl_incs + [socket_inc],
                             library_dirs=ssl_libs,
                             libraries=libs,
                             extra_link_args=link_args)]
      )


# coding: utf-8

# # Programme for WSD to improve the quality of word alignment in Anusaaraka
# - This programme is designed for words having multiple glosses and that's why before integrating this with upcoming ENG-HIN wordnet Dictionary, we have tested it with 50 word and it's gloss taken from wordnet.
# - Once the work of building Wordnet ENG-HIN dictionary is done, this programme can be tested with our dictionary and if it won't work that much effectively then with the passage of time programme can be improved for the betterment of our module.
# ### Prerequisite to understand this programme :
#
# - read about word embeddings
# - word2vec, glove ELMo and more related to word embeddings to understand this programme concept.
#
# #### For more, You can go through this link : [Link](https://www.analyticsvidhya.com/blog/2019/03/learn-to-use-elmo-to-extract-features-from-text/)
#

# In[ ]:

import scipy
import nltk
import allennlp
dir(allennlp)
elmo=allennlp
from allennlp.commands.elmo import ElmoEmbedder
elmo = ElmoEmbedder(options_file = 'elmo_2x4096_512_2048cnn_2xhighway_options.json' , weight_file = 'elmo_2x4096_512_2048cnn_2xhighway_weights.hdf5')

#print("\nBank,Break,Address,Bar,Harbour,Pass,Date,Kingdom,Rock,Hit,Light,Catch,Dark,Cut,Bark,Force,Score,\nService,Crash,Blow,Beat,Head,Shade,Model,Cover,Balance,Clear,Rule,Flat,Point,Cabinet,Bulb,\nToast,Post,Act,Sense,Tap,Press,Flesh,Bow,Race,Star,Deck,Pipe,Note,Pirate,Bat,Play,Moniter,Story")
while True:
    ifile=open("wordnet_glosses.txt","r")
    word=input("Enter Wsd Word:")
    stri=" "
    c=0
    data = []
    while stri:
        r=ifile.readline()
        if (r==""):
            break
        a=r.split("~")
        if (word==a[0]):
            sentence3=input("Enter user sentence:")
            tokens3 = nltk.word_tokenize(sentence3)
            vector3 = elmo.embed_sentence(tokens3)
            for k in tokens3:
                if(word.upper()==k.upper()):
                    wsd3=k
                    break
            for chk in a[1:]:
                get = []
                print (" glosses are:"+chk)
                sentence1=chk
                tokens1 = nltk.word_tokenize(sentence1)
                vector1 = elmo.embed_sentence(tokens1)
                for i in tokens1:
                    if(word.upper()==i.upper()):
                        wsd1=i
                        break
                similarity_distance1=scipy.spatial.distance.cosine(vector1[2][tokens1.index(i)], vector3[2][tokens3.index(k)])
                data.append(similarity_distance1)
                print(similarity_distance1)
            c+=1

            ofile=open("hindi.txt","r")
            stri1=" "
            while stri1:
                h=ofile.readline()
                if (h==""):
                    break
                b=h.split("~")
                if (word==b[0]):
                    print("Hindi Translation of Wsd Word in this case is :"+b[data.index(min(data))])
                    break

    if(c==0):
        print("Not Present")
    choice=input("Want to enter more words(yes/no):")
    if(choice=="yes"):
        continue
    elif(choice=="no"):
        break
ifile.close()
ofile.close()


def stringParaDicionario(palavra):
    d = {}
    for c in palavra:
        if c in d.keys():
            d[c] = d[c] + 1
        else:
            d[c] = 1

    return d

print(stringParaDicionario("asdfg"))
print(stringParaDicionario("the quick brown fox jumps over the lazy dog"))


'''
Description: See Title
Author: Alexander Brown
Date: 2/5/2018
'''

import multiprocessing

import sys
import csv
import os
from os import listdir
from os.path import isfile, join

def get_file_list(directory):
    file_list = [directory + '/' + f for f in listdir(directory) if isfile(join(directory, f))]
    return file_list

def generate_bin_dict(num_of_intervals):
    bin_dict = {}
    x = 1
    while x <= num_of_intervals:
        bin_dict[x] = 0
        x += 1

    return bin_dict

def find_nth_occurrence_rindex(search_string, find_string, nth):
    start = 0
    end = len(search_string)
    while nth > 0:
        index = search_string.rindex(find_string, start, end)
        end = index - 1
        nth -= 1
    return index

def generate_chr_dict():
    directory = r"I:\Melanoma\Cat_Cap_Chrs"
    chr_files = [directory + '/' + f for f in listdir(directory)]
    chr_dict = {'chr1_':None, 'chr2_':None, 'chr3_':None, 'chr4_':None, 'chr5_':None, 'chr6_':None, 'chr7_':None, 'chr8_':None, 'chr9_':None, 'chr10_':None,
		'chr11_':None, 'chr12_':None, 'chr13_':None, 'chr14_':None, 'chr15_':None, 'chr16_':None, 'chr17_':None, 'chr18_':None, 'chr19_':None, 'chr20_':None,
                'chr21_':None, 'chr22_':None, 'chrX_':None, 'chrY_':None, 'chrM_':None}

    maxInt = sys.maxsize
    decrement = True
    while decrement:
        decrement = False
        try:
            csv.field_size_limit(maxInt)
        except OverflowError:
            maxInt = int(maxInt/10)
            decrement = True

    for chr_file in chr_files:
        directory_index = find_nth_occurrence_rindex(chr_file, "/", 1)
        underscore_index = find_nth_occurrence_rindex(chr_file, "_", 2)
        chr_file_chr = chr_file[directory_index+1:underscore_index+1]
        for chr_key in chr_dict:
            if chr_key == chr_file_chr:
                chr_fh = csv.reader(open(chr_file, "r"), delimiter = '\t')
                first_line = next(chr_fh)
                second_line = next(chr_fh)
                chr_dict[chr_key] = ''.join(second_line)
    return chr_dict

def generate_dyad_dict(dyad_file):
    chr_dict = {'chr1_':None, 'chr2_':None, 'chr3_':None, 'chr4_':None, 'chr5_':None, 'chr6_':None, 'chr7_':None, 'chr8_':None, 'chr9_':None, 'chr10_':None,
		'chr11_':None, 'chr12_':None, 'chr13_':None, 'chr14_':None, 'chr15_':None, 'chr16_':None, 'chr17_':None, 'chr18_':None, 'chr19_':None, 'chr20_':None,
                'chr21_':None, 'chr22_':None, 'chrX_':None, 'chrY_':None, 'chrM_':None}
    for chr_key in chr_dict:
        chr_dict[chr_key] = []

    chr_to_chr_dict = {'chr1':'chr1_', 'chr2':'chr2_', 'chr3':'chr3_', 'chr4':'chr4_', 'chr5':'chr5_', 'chr6':'chr6_', 'chr7':'chr7_', 'chr8':'chr8_', 'chr9':'chr9_', 'chr10':'chr10_',
		'chr11':'chr11_', 'chr12':'chr12_', 'chr13':'chr13_', 'chr14':'chr14_', 'chr15':'chr15_', 'chr16':'chr16_', 'chr17':'chr17_', 'chr18':'chr18_', 'chr19':'chr19_', 'chr20':'chr20_',
                'chr21':'chr21_', 'chr22':'chr22_', 'chrX':'chrX_', 'chrY':'chrY_', 'chrMT':'chrM_'}

    dyad_reader = csv.reader(open(dyad_file, "r"), delimiter = '\t')
    for dyad_line in dyad_reader:
        chromosome = chr_to_chr_dict[dyad_line[0]]
        start_pos = int(dyad_line[1]) - 74 #-73 for nucleosome, -1 to tally dipyrimidine correctly
        end_pos = int(dyad_line[2]) + 74 #+73 fpr nucleosome, +1 to tally dipyrimidine correctly
        crd_list = [start_pos, end_pos]
        chr_dict[chromosome].append(crd_list)

    for chr_key in chr_dict:
        chr_dict[chr_key].sort()
    return chr_dict

def bisect_search(a_list, query):
    low_bound = 0
    high_bound = len(a_list)-1
    guess = round(((high_bound - low_bound)/2) + low_bound)
    exist = 1

    left_flank_start = a_list[guess][0]
    right_flank_end = a_list[guess][1]-1

    while not left_flank_start <= query <= right_flank_end:
        previous_guess = guess

        if right_flank_end < query:
            low_bound = guess
            guess = round(((high_bound - low_bound)/2) + low_bound)
        if left_flank_start > query:
            high_bound = guess
            guess = round(((high_bound - low_bound)/2) + low_bound)
        if guess == previous_guess:
            exist = 0
            break

        left_flank_start = a_list[guess][0]
        right_flank_end = a_list[guess][1]-1
    return guess, exist

def make_value_indices_list(guess, a_list, query):
    left_flank_start = a_list[guess][0]
    right_flank_end = a_list[guess][1] -1#-1 because of end

    try:
        while left_flank_start <= query <= right_flank_end and guess > -1:
            guess -= 1
            left_flank_start = a_list[guess][0]
            right_flank_end = a_list[guess][1] -1#-1 because of end

    except IndexError:
        pass
    guess += 1
    low_bound = guess

    left_flank_start = a_list[guess][0]
    right_flank_end = a_list[guess][1] -1#-1 because of end
    try:
        while left_flank_start <= query <= right_flank_end:
            guess += 1
            left_flank_start = a_list[guess][0]
            right_flank_end = a_list[guess][1] -1#-1 because of end

    except IndexError:
        pass
    guess -= 1
    high_bound = guess
    index_list = []
    while low_bound <= high_bound:
        index_list.append(low_bound)
        low_bound += 1
    return index_list

def work_horse(mut_file, dyad_dict, mut_tally_dict, dinuc_tally_dict):
    chr_to_chr_dict = {'1':'chr1_', '2':'chr2_', '3':'chr3_', '4':'chr4_', '5':'chr5_', '6':'chr6_', '7':'chr7_', '8':'chr8_', '9':'chr9_', '10':'chr10_',
		'11':'chr11_', '12':'chr12_', '13':'chr13_', '14':'chr14_', '15':'chr15_', '16':'chr16_', '17':'chr17_', '18':'chr18_', '19':'chr19_', '20':'chr20_',
                '21':'chr21_', '22':'chr22_', 'X':'chrX_', 'Y':'chrY_', 'MT':'chrM_'}

    dinuc_list = ['TT', 'TC', 'CT', 'CC', 'AA', 'AG', 'GA', 'GG']
    T_C_list = ["TT", "TC", "CT", "CC"]
    A_G_list = ["AA", "AG", "GA", "GG"]

    mut_reader = csv.reader(open(mut_file, "r"), delimiter = '\t')
    for line in mut_reader:
        chromosome = line[0] #so that it matches the key for the dyad_dict
        if chromosome == "chrM_": # it is currently empty
            continue
        mut_pos = int(line[1]) - 1
        lesion_count = int(float(line[2]))
        try:
            dyad_list = dyad_dict[chromosome]
        except KeyError:
            print(chromosome)
            continue

        if len(dyad_list) == 0:
            continue

        guess, exist = bisect_search(dyad_list, mut_pos)
        if exist == 0:
            continue

        index_list = make_value_indices_list(guess, dyad_list, mut_pos)
        for index in index_list:
            dyad_ranges = dyad_list[index]
            start_pos = dyad_ranges[0]
            end_pos = dyad_ranges[1]

            bp_index = mut_pos - start_pos + 1
            mut_tally_dict[bp_index] += lesion_count

def stable_away(chr_dict, dyad_dict, mut_tally_dict, dinuc_tally_dict, number_of_intervals, outfile):
    outfile.write("Bin" + '\t' + "Lesion_Tally" + '\n')
    key = 1
    while key <= number_of_intervals:
        new_line = '\t'.join([str(s) for s in [key, mut_tally_dict[key]]])
        outfile.write(new_line + '\n')
        key += 1

def different_horse(mut_files, dyad_dict):
    example_file = mut_files[0]
    directory_index_1 = find_nth_occurrence_rindex(example_file, "\\", 1)
    directory_index_2 = find_nth_occurrence_rindex(example_file, "/", 1)
    outfile_name = example_file[directory_index_1+1 : directory_index_2] + "_Strong_Dyad_Lesions_And_Dinuc_Tallies.txt"
#    outfile = open(outfile_name, "w")

    number_of_intervals = 149
    mut_tally_dict = generate_bin_dict(number_of_intervals)
    dinuc_tally_dict = generate_bin_dict(number_of_intervals)
    for mut_file in mut_files:
        work_horse(mut_file, dyad_dict, mut_tally_dict, dinuc_tally_dict)

    return mut_tally_dict

def retrieve_nuc_count(dyad_dict):
    count = 0
    for chromosome in dyad_dict:
        for dyad in dyad_dict[chromosome]:
            count += 1
    return count

def saddle_up(dyad_file):
    files_0hr = get_file_list(r"I:\Melanoma\Wyrick_Lesions\0hr_C_sorted_BEDs")
    files_80J = get_file_list(r"I:\Melanoma\Wyrick_Lesions\80J_C_sorted_BEDs")

    dyad_dict = generate_dyad_dict(dyad_file)

    tally_dict_0hr = different_horse(files_0hr, dyad_dict)
    tally_dict_80J = different_horse(files_80J, dyad_dict)

    outfile_directory = r"I:\Melanoma_2018_Nuc_Project\Lesions_mCPDs\Transcript_Nucleosome_Tallies"
    directory_index = find_nth_occurrence_rindex(dyad_file, "/", 1)
    extension_index = find_nth_occurrence_rindex(dyad_file, ".", 1)
    outfile_suffix = dyad_file[directory_index+1:extension_index]

    outfile = open(outfile_directory + "\\" + outfile_suffix + "mCPD_0hr_by_80J_Strong_Dyad_Lesions_And_Dinuc_Tallies.txt", "w")
    nuc_count = retrieve_nuc_count(dyad_dict)
    header = '\t'.join(["Bin", "0hr_Lesion_Tally", "80J_Lesion_Tally", "0hr_by_80J_Tally", "Nuc_Count:", str(nuc_count)])
    outfile.write(header + '\n')
    len_of_dict = len(tally_dict_0hr)
    i=1
    while i < len_of_dict+1:
        count_0hr = tally_dict_0hr[i]
        count_80J = tally_dict_80J[i]
        try:
            normalized_value = count_0hr/count_80J
        except ZeroDivisionError:
            normalized_value = 0
        new_line = '\t'.join([str(s) for s in [i, count_0hr, count_80J, normalized_value]])
        outfile.write(new_line + '\n')
        i += 1

#if __name__ == '__main__':
if multiprocessing.current_process().name == 'MainProcess':
    dyad_directory = r"I:\Melanoma_2018_Nuc_Project\Transcript_Sorted_Nucleosomes"
    dyad_files = get_file_list(dyad_directory)

    jobs = []
    for dyad_file in dyad_files:
        p = multiprocessing.Process(target=saddle_up, args=(dyad_file, ))
        jobs.append(p)
        p.start()
    for p in jobs:
        p.join()


import datetime
import os
import pickle
import warnings
from itertools import tee

import lightgbm
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold
from tqdm import tqdm

from tools.utils.features import (get_all_features, load_features,
                                  select_features)
from tools.utils.logs import dec_timer, log_evaluation, sel_log
from tools.utils.samplings import value_resampling
from tools.utils.visualizations import save_importance

warnings.simplefilter(action='ignore', category=FutureWarning)

NES_DIR = './mnt/inputs/nes_info/'
FEATURE_DIR = './mnt/inputs/features/'

@dec_timer
def t006_lgb_train(args, script_name, configs, logger):
    '''
    policy
    ------------
    * use original functions only if there's no pre-coded functions
        in useful libraries such as sklearn.

    todos
    ------------
    * load features
    * train the model
    * save the followings
        * logs
        * oofs
        * importances
        * trained models
        * submissions (if test mode)

    '''
    # -- Load train data
    sel_log('loading training data ...', None)
    trn_ids = pd.read_pickle(
        NES_DIR + 'trn_ID_code.pkl.gz', compression='gzip')
    tst_ids = pd.read_pickle(
        NES_DIR + 'tst_ID_code.pkl.gz', compression='gzip')
    target = pd.read_pickle(
        NES_DIR + 'target.pkl.gz', compression='gzip')
    if args.debug:
        sample_idxes = trn_ids.reset_index(
            drop=True).sample(
            random_state=71,
            frac=0.05).index
        target = target.iloc[sample_idxes].reset_index(drop=True)
        trn_ids = trn_ids.iloc[sample_idxes].reset_index(drop=True)

    # load features
    if configs['train']['all_features']:
        _features = get_all_features(FEATURE_DIR)
    else:
        _features = configs['features']
    trn_tst_df = load_features(_features, FEATURE_DIR, logger=logger)\
        .set_index('ID_code')

    # feature selection if needed
    if configs['train']['feature_selection']:
        trn_tst_df = select_features(trn_tst_df,
                                     configs['train']['feature_select_path'],
                                     configs['train']['metric'],
                                     configs['train']['feature_topk'])
    # split train and test
    sel_log(f'now splitting the df to train and test ones ...', None)
    features_df = trn_tst_df.loc[trn_ids].reset_index(drop=True)
    test_features_df = trn_tst_df.loc[tst_ids].reset_index(drop=True)

    # -- Split using group k-fold w/ shuffling
    # NOTE: this is not stratified, I wanna implement it in the future
    if configs['train']['fold_type'] == 'skf':
        skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=4221)
        folds = skf.split(features_df, target)
        configs['train']['single_model'] = False
    else:
        print(f"ERROR: wrong fold_type, {configs['train']['fold_type']}")
    folds, pred_folds = tee(folds)

    # -- Make training dataset
    # print shape
    sel_log(f'used features are {features_df.columns.tolist()}', logger)
    sel_log(f'the shape features_df is {features_df.shape}', logger)

    # -- CV
    # Set params
    PARAMS = configs['lgbm_params']
    PARAMS['nthread'] = os.cpu_count()

    sel_log('start training ...', None)

    with open('e071_e036_t006_w_pair_augmentation_7_7_2019-04-05-17-35-24_0.92357_models.pkl', 'rb') as fin:
        cv_model = pickle.load(fin)

    # --- Make submission file
    if args.test:
        if configs['train']['single_model']:
            # train single model
            best_iter = np.mean(
                [booster.best_iteration for booster in cv_model])
            single_train_set = lightgbm.Dataset(features_df, target.values)
            single_booster = lightgbm.train(
                params=PARAMS,
                num_boost_round=int(best_iter * 1.3),
                train_set=single_train_set,
                verbose_eval=1000,
                callbacks=[log_evaluation(logger, period=1000)],
            )
            # re-save model for prediction
            # cv_model.append(single_booster)

        # -- Prediction
        sel_log('predicting for test ...', None)
        preds = []
        preds_no_rank = []
        reals = np.load('./mnt/inputs/nes_info/real_samples_indexes.npz.npy')
        # for booster in tqdm(cv_model.boosters):
        for booster in tqdm(cv_model):
            pred = booster.predict(test_features_df.values, num_iteration=None)
            pred = pd.Series(pred)
            # rank avg only using real part
            preds_no_rank.append(pred.copy())
            pred.iloc[reals] = pred.iloc[reals].rank() / reals.shape
            preds.append(pred)
        if len(cv_model) > 1:
            target_values = np.mean(preds, axis=0)
            target_values_no_rank = np.mean(preds_no_rank, axis=0)
        else:
            target_values = preds[0]
            target_values_no_rank = preds[0]
        # blend single model
        if configs['train']['single_model']:
            pred = single_booster.predict(
                test_features_df.values, num_iteration=None)
            pred = pd.Series(pred)
            target_values = (target_values + (pred.rank() / pred.shape)) / 2

        # -- Make submission file
        sel_log(f'loading sample submission file ...', None)
        sub_df = pd.read_csv(
            './mnt/inputs/origin/sample_submission.csv.zip',
            compression='zip')
        sub_df.target = target_values
        sub_df_no_rank = pd.read_csv(
            './mnt/inputs/origin/sample_submission.csv.zip',
            compression='zip')
        sub_df_no_rank.target = target_values_no_rank

        # print stats
        submission_filename_no_rank = f'./mnt/submissions/temp.csv'
        sub_df_no_rank.to_csv(
            submission_filename_no_rank,
            index=False)
    return None, None, None


from pandas_datareader import data, wb
import datetime

from pandas_datareader._utils import RemoteDataError

start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2013, 1, 27)
try:
    res = data.DataReader("IBM", 'yahoo', start, end)
    print(res)
except RemoteDataError as e:
    print("Incorrect name.")


import logging
logger = logging.getLogger(__name__)

from functools import reduce
import math
import platform
import sys
import uuid

from six.moves.urllib.parse import urljoin as sys_urljoin
from six import iteritems

_simple_id = 1000

def make_id():
    global _simple_id
    from . import settings
    if settings.simple_ids(False):
        _simple_id += 1
        new_id = _simple_id
    else:
        new_id = uuid.uuid4()
    return str(new_id)

def urljoin(*args):
    return reduce(sys_urljoin, args)

def get_json(request):
    """request from requests library handles backwards compatability for
    requests < 1.0
    """
    if hasattr(request.json, '__call__'):
        return request.json()
    else:
        return request.json

def encode_utf8(u):
    if sys.version_info[0] == 2:
        u = u.encode('utf-8')
    return u

def decode_utf8(u):
    if sys.version_info[0] == 2:
        u = u.decode('utf-8')
    return u

_scales = [1e0, 1e3, 1e6, 1e9]
_units = ['s', 'ms', 'us', 'ns']

def scale_delta(time):
    if time > 0.0:
        order = min(-int(math.floor(math.log10(time)) // 3), 3)
    else:
        order = 3

    return time*_scales[order], _units[order]

def is_py3():
    return sys.version_info[0] == 3

def is_pypy():
    return platform.python_implementation() == "PyPy"

def convert_references(json_obj):
    from .plot_object import PlotObject
    from .properties import HasProps
    def convert(obj):
        if isinstance(obj, PlotObject):
            return obj.ref
        elif isinstance(obj, HasProps):
            return obj.to_dict()
        else:
            return obj
    def helper(json_obj):
        if isinstance(json_obj, list):
            for idx, x in enumerate(json_obj):
                json_obj[idx] = convert(x)
        if isinstance(json_obj, dict):
            for k, x in iteritems(json_obj):
                json_obj[k] = convert(x)
    json_apply(json_obj, helper)
    return json_obj

def dump(objs, docid, changed_only=True):
    """ Dump a sequence of objects into JSON

        Args:
            changed_only (bool, optional) : whether to dump only attributes
                that have had their values changed at some point (default: True)
    """
    json_objs = []
    for obj in objs:
        ref = obj.ref
        ref["attributes"] = obj.vm_serialize(changed_only=changed_only)
        ref["attributes"].update({"id": ref["id"], "doc" : docid})
        json_objs.append(ref)
    return json_objs

def nice_join(seq, sep=", "):
    seq = [str(x) for x in seq]

    if len(seq) <= 1:
        return sep.join(seq)
    else:
        return "%s or %s" % (sep.join(seq[:-1]), seq[-1])

def publish_display_data(data, source='bokeh'):
    """Compatibility wrapper for IPython publish_display_data which removes the
    `source` (first) argument in later versions.

    Parameters
    ----------
    source : str
    data : dict
    """
    import IPython.core.displaypub as displaypub
    try:
        displaypub.publish_display_data(source, data)
    except TypeError:
        displaypub.publish_display_data(data)

def is_ref(frag):
    return isinstance(frag, dict) and \
           frag.get('type') and \
           frag.get('id')

def json_apply(fragment, check_func, func):
    """recursively searches through a nested dict/lists
    if check_func(fragment) is True, then we return
    func(fragment)
    """
    if check_func(fragment):
        return func(fragment)
    elif isinstance(fragment, list):
        output = []
        for val in fragment:
            output.append(json_apply(val, check_func, func))
        return output
    elif isinstance(fragment, dict):
        output = {}
        for k, val in fragment.items():
            output[k] = json_apply(val, check_func, func)
        return output
    else:
        return fragment

def resolve_json(fragment, models):
    check_func = is_ref
    def func(fragment):
        if fragment['id'] in models:
            return models[fragment['id']]
        else:
            logging.error("model not found for %s", fragment)
            return None
    return json_apply(fragment, check_func, func)


"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".

Replace this with more appropriate tests for your application.
"""

from django.test import TestCase
from data_challenge.views import parseAndSave, getRevenue
from data_challenge.models import Customer, Item, Merchant, Transaction

class SimpleTest(TestCase):
    """
    Aptana replaces tabs with four spaces, so you'll see a lot of data.split("    ") instead of data.split("\t")
    for the data that I'm making manually in these test.
    """

    def test_save(self):
        name = "Snake Plissken"
        description = "$10 off $20 of food"
        price = 10.3
        quantity = 43
        address = "987 Fake Street"
        merchantName = "Bob's Pizza"

        # Make sure that we aren't saving the same entities multiple times
        # Together, these two parseAndSave calls should only persist a single customer, item, and merchant
        parseAndSave([name, description, price, quantity, address, merchantName])
        parseAndSave([name, description, price, quantity, address, merchantName])

        # This will throw an exception if the models haven't been persisted properly,
        # or if they have been persisted multiple times
        customer = Customer.objects.get(name=name)
        item = Item.objects.get(description=description, price=price)
        merchant = Merchant.objects.get(address=address, name=merchantName)

        # This should return 2 objects
        self.assertEqual(2, len(Transaction.objects.filter(customer=customer, item=item, merchant=merchant, quantity=quantity)))

    def test_parse_line_customer(self):
        name = "Fooo Bar"
        customer = parseAndSave([name, "$20 Sneakers for $5", "5.0", "1", "123 Fake St", "Sneaker Store Emporium"])[0]
        self.assertEqual(customer.name, name)

    def test_parse_line_item(self):
        description = "holy porkchops batman!"
        price = 32.1
        item = parseAndSave(["The Oatmeal", description, str(price), "13", "College Ave", "CTB"])[1]
        self.assertEqual(item.description, description)
        self.assertEqual(item.price, price)

    def test_parse_line_merchant(self):
        name = "Collegetown Bagles"
        address = "142 College Ave Ithaca NY"
        merchant = parseAndSave(["The Oatmeal", "yeahh", "4334.23", "13", address, name])[2]
        self.assertEqual(merchant.name, name)
        self.assertEqual(merchant.address, address)

    def test_parse_line_transaction(self):
        quantity = 808
        customer, item, merchant, transaction = parseAndSave(["The Oatmeal", "yeahh", "4334.23", str(quantity), "12 44th Street New York City", "Jamba Juice"])
        self.assertEqual(transaction.customer, customer)
        self.assertEqual(transaction.item, item)
        self.assertEqual(transaction.merchant, merchant)
        self.assertEqual(transaction.quantity, quantity)

    def parseLines(self, data):
        [parseAndSave(line.split("    ")) for line in data.splitlines()]

    def test_get_revenue(self):
        prices = (23, 43, 808, 21)
        quantities = (1, 20, 43, 99)

        # This double string formatting is not the prettiest thing in the world... I wonder if there's a better way to do it
        data = ("""Snake Plissken    $10 off $20 of food    %f    %%d    987 Fake St    Bob's Pizza
Amy Pond    $30 of awesome for $10    %f    %%d    456 Unreal Rd    Tom's Awesome Shop
Marty McFly    $20 Sneakers for $5    %f    %%d    123 Fake St    Sneaker Store Emporium
Snake Plissken    $20 Sneakers for $5    %f    %%d    123 Fake St    Sneaker Store Emporium""" % prices) % quantities

        self.parseLines(data)

        revenue = sum((quantity * price for quantity, price in zip(quantities, prices)))
        self.assertEqual(revenue, getRevenue(Transaction.objects.all()))

        # If all the transactions happen again, we should record twice as much revenue
        self.parseLines(data)
        self.assertEqual(revenue * 2, getRevenue(Transaction.objects.all()))

    def test_get_revenue_sample_data(self):
        data = """Snake Plissken    $10 off $20 of food    10.0    2    987 Fake St    Bob's Pizza
Amy Pond    $30 of awesome for $10    10.0    5    456 Unreal Rd    Tom's Awesome Shop
Marty McFly    $20 Sneakers for $5    5.0    1    123 Fake St    Sneaker Store Emporium
Snake Plissken    $20 Sneakers for $5    5.0    4    123 Fake St    Sneaker Store Emporium"""

        self.parseLines(data)

        self.assertEqual(95, getRevenue(Transaction.objects.all()))


#-*- coding: utf-8 -*-
import os
import sys
import unittest
sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))

from test_lsh_h5.base.H5Base import H5Base
from test_lsh_h5.base.H5RunSystemEnv import H5RunSystemEnv
from test_lsh_h5.modules.login.LoginTest import LoginTest
from test_lsh_h5.modules.register.RegisterTest import RegisterTest
from test_lsh_h5.modules.mypage.MyPageTest import MyPageTest
from test_lsh_h5.modules.homepage.HomePageTest import HomePageTest
from test_lsh_h5.modules.shopping_cart_page.ShoppingCartPageTest import ShoppingCartPageTest
from test_lsh_h5.modules.classifypage.ClassifyPageTest import ClassifyPageTest

#base_dir=str(os.path.dirname(os.path.dirname(__file__)))

class TestH5(unittest.TestCase):
    def setUp(self):
        self.enverionment = sys.argv[1]  # app环境
        h5SysPath = H5RunSystemEnv()
        self.h5Confpath = h5SysPath.getPath(sys.argv[2])[0] #appConf路径
        self.testCasePath = h5SysPath.getPath(sys.argv[2])[1] #appTestCase路径
        self.testResultsPath = h5SysPath.getPath(sys.argv[2])[2] #appTestResults路径
        h5Base = H5Base(self.enverionment,self.h5Confpath,"")
        self.host = h5Base.getHost()

    def tearDown(self):
        pass

    def getargvs(self,name):
        h5Base = H5Base(self.enverionment,self.h5Confpath,name)
        testCaseDoc = h5Base.getTestCaseDoc()
        args=(self.enverionment,self.host,self.h5Confpath,self.testCasePath,testCaseDoc,self.testResultsPath)
        return args
    #测试登录
    def testLogin(self):
        #h5Base = H5Base(self.enverionment,self.h5Confpath,"login")
        #testCaseDoc = h5Base.getTestCaseDoc()#获得登录testcase文件
        loginTest = LoginTest(*self.getargvs("login"))#登录测试
        loginTest.loginTest()

    #测试注册
    def testRegister(self):
        #h5Base = H5Base(self.enverionment,self.h5Confpath,"register")
        #testCaseDoc = h5Base.getTestCaseDoc()#获得注册testcase文件
        registerTest = RegisterTest(*self.getargvs("register"))#注册测试
        registerTest.registerTest()

    #测试app首页
    def testHomePage(self):
        #h5Base=H5Base(self.enverionment,self.h5Confpath,"homepage")
        #testCaseDoc = h5Base.getTestCaseDoc()#获得首页testcase文件
        homepageTest=HomePageTest(*self.getargvs("homepage"))
        homepageTest.HomePageTest()

    #测试我的页面
    def testMyPage(self):
        #h5Base=H5Base(self.enverionment,self.h5Confpath,"mypage")

        #testCaseDoc = h5Base.getTestCaseDoc()#获得我的页面testcase文件
        mypageTest=MyPageTest(*self.getargvs("mypage"))
        mypageTest.MyPageTest()
    #测试购物车页面接口
    def testShoppingCartPage(self):

        #h5Base=H5Base(self.enverionment,self.h5Confpath,"shopping_cart_page")

        #testCaseDoc = h5Base.getTestCaseDoc()#获得购物车页面testcase文件
        shoppingCartpageTest=ShoppingCartPageTest(*self.getargvs("shopping_cart_page"))
        shoppingCartpageTest.ShoppingCartPageTest()
    #测试分类页接口
    def testClassifyPage(self):

        #h5Base=H5Base(self.enverionment,self.appConfpath,"classifypage")

        #testCaseDoc = h5Base.getTestCaseDoc()#获得分类页面testcase文件
        classifyPageTest=ClassifyPageTest(*self.getargvs("classifypage"))
        classifyPageTest.ClassifyPageTest()

    """ def createsuite(self):
        testunit=unittest.TestSuite()
        discover=unittest.defaultTestLoader.discover(base_dir,pattern='test*.py', top_level_dir=None)
        for test_suite in discover:
            for testsuit in test_suite:
                testunit.addTest(testsuit)
        return testunit"""

if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTest(TestH5("testLogin"))
    suite.addTest(TestH5("testHomePage"))
    #suite.addTest(TestH5("testRegister"))

    '''suite.addTest(TestApp("testRegister"))
    suite.addTest(TestApp("testHomePage"))
    suite.addTest(TestApp("testMyPage"))
    suite.addTest(TestApp("testShoppingCartPage"))
    suite.addTest(TestApp("testClassifyPage"))'''

    runner = unittest.TextTestRunner()
    runner.run(suite)


"""
Conduct ensemble learning.
"""

__author__ = 'Ruimin Ma, Daheng Wang'
__email__ = 'rma4@nd.edu, dwang8@nd.edu'
__version__ = 'Dev-0312'

import numpy as np
import os

import keras.callbacks as callbacks
from keras.callbacks import Callback
import metrics

class SnapshotModelCheckpoint(Callback):
    """
		n_epochs: number of epochs the model will be trained
		n_snapshots: number of times the weights of the model will be saved
		fn_prefix: prefix for the filename of the weights
	"""

    def __init__(self, n_epochs, n_snapshots, fn_prefix='Model'):
        super(SnapshotModelCheckpoint, self).__init__()

        self.check = n_epochs // n_snapshots
        self.fn_prefix = fn_prefix

    def on_epoch_end(self, epoch, logs={}):
        if epoch != 0 and (epoch + 1) % self.check == 0:
            filepath = self.fn_prefix + "-%d.h5" % ((epoch + 1) // self.check)
            self.model.save_weights(filepath, overwrite=True)

class SnapshotCallbackBuilder:

    def __init__(self, n_epochs, n_snapshots, init_lr=0.1):
        self.n_epochs = n_epochs
        self.n_snapshots = n_snapshots
        self.init_lr = init_lr

    def get_callbacks(self, model_prefix='Model'):
        """
            model_prefix: prefix fpr the filename of the weights.

			Returns:
				[ModelCheckpoint, LearningRateScheduler, SnapshotModelCheckpoint]
		"""
        if not os.path.exists('weights/'):
            os.makedirs('weights/')

        callback_list = [callbacks.ModelCheckpoint("weights/%s-Best.h5" % model_prefix,
                                                   monitor="metrics.mean_iou_1", save_best_only=True,
                                                   save_weights_only=True),
                         callbacks.LearningRateScheduler(schedule=self._cosine_anneal_schedule),
                         SnapshotModelCheckpoint(self.n_epochs, self.n_snapshots,
                                                 fn_prefix='weights/%s' % model_prefix)]
        return callback_list

    def _cosine_anneal_schedule(self, t):
        cos_inner = np.pi * (t % (self.n_epochs // self.n_snapshots))
        cos_inner /= self.n_epochs // self.n_snapshots
        cos_out = np.cos(cos_inner) + 1
        return float(self.init_lr / 2 * cos_out)


from flask import Flask
app = Flask(__name__)

@app.route('/<num1>')
def warn(num1):
    return "two numbers are required"

@app.route('/<num1>/<num2>')
def multiply(num1, num2):
    try:
        num1, num2 = int(num1), int(num2)
    except ValueError:
        return "only int in accepted"

    return str(num1 * num2)

if __name__ == '__main__':
    app.run(debug=True)


from  selenium import  webdriver
import  time
values =['abc','def','selenium']
#执行循环

for serch in values:
    driver=webdriver.Firefox()
    driver.get("http://www.baidu.com")
    driver.find_element_by_id("kw").send_keys(serch)
    time.sleep(3)
    driver.quit()