# coding: utf-8

import os, glob, time
import ipywidgets as ipyw
from IPython.display import display, HTML, clear_output
# This try-except should not be necessary anymore.
# The testing is now done in ../tests.
try:
    from ._utils import js_alert
except Exception:
    # only used if testing in this directory without installing
    from _utils import js_alert

class FileSelectorPanel:

    """Files and directories selector
    """

    #If ipywidgets version 5.3 or higher is used, the "width="
    #statement should change the width of the file selector. "width="
    #doesn't appear to work in earlier versions.
    select_layout = ipyw.Layout(width="750px")
    select_multiple_layout = ipyw.Layout(width="750px", display="flex", flex_flow="column")
    button_layout = ipyw.Layout(margin="5px 40px")
    label_layout = ipyw.Layout(width="250px")
    layout = ipyw.Layout()

    def __init__(self, instruction, start_dir=".", type='file', next=None, multiple=False):
        """
        Create FileSelectorPanel instance

        Parameters
        ----------
        instruction : str
            instruction to users for file/dir selection
        start_dir : str
            starting directory path
        type : str
            type of selection. "file" or "directory"
        multiple: bool
            if True, multiple files/dirs can be selected
        next : function
            callback function to execute after the selection is selected
        """
        if not type in ['file', 'directory']:
            raise ValueError("type must be either file or directory")
        self.instruction = instruction
        self.type = type
        self.multiple = multiple
        self.createPanel(os.path.abspath(start_dir))
        self.next = next
        return

    def createPanel(self, curdir):
        self.curdir = curdir
        explanation = ipyw.Label(self.instruction,layout=self.label_layout)
        entries_files = sorted(os.listdir(curdir))
        entries_paths = [os.path.join(curdir, e) for e in entries_files]
        entries_ftime = create_file_times(entries_paths)
        entries = create_nametime_labels(entries_files, entries_ftime)
        self._entries = entries = [' .', ' ..', ] + entries
        if self.multiple:
            value = []
            self.select = ipyw.SelectMultiple(
                value=value, options=entries,
                description="Select",
                layout=self.select_multiple_layout)
        else:
            value = entries[0]
            self.select = ipyw.Select(
                value=value, options=entries,
                description="Select",
                layout=self.select_layout)
        """When ipywidgets 7.0 is released, the old way that the select or select multiple
           widget was set up (see below) should work so long as self.select_layout is changed
           to include the display="flex" and flex_flow="column" statements. In ipywidgets 6.0,
           this doesn't work because the styles of the select and select multiple widgets are
           not the same.

        self.select = widget(
            value=value, options=entries,
            description="Select",
            layout=self.select_layout) """
        # enter directory button
        self.enterdir = ipyw.Button(description='Enter directory', layout=self.button_layout)
        self.enterdir.on_click(self.handle_enterdir)
        # select button
        self.ok = ipyw.Button(description='Select', layout=self.button_layout)
        self.ok.on_click(self.validate)
        buttons = ipyw.HBox(children=[self.enterdir, self.ok])
        self.widgets = [explanation, self.select, buttons]
        self.panel = ipyw.VBox(children=self.widgets, layout=self.layout)
        return

    def handle_enterdir(self, s):
        v = self.select.value
        v = del_ftime(v)
        if self.multiple:
            if len(v)!=1:
                js_alert("Please select a directory")
                return
            v = v[0]
        p = os.path.abspath(os.path.join(self.curdir, v))
        if os.path.isdir(p):
            self.remove()
            self.createPanel(p)
            self.show()
        return

    def validate(self, s):
        v = self.select.value
        v = del_ftime(v)
        # build paths
        if self.multiple:
            vs = v
            paths = [os.path.join(self.curdir, v) for v in vs]
        else:
            path = os.path.join(self.curdir, v)
            paths = [path]
        # check type
        if self.type == 'file':
            for p in paths:
                if not os.path.isfile(p):
                    js_alert("Please select file(s)")
                    return
        else:
            assert self.type == 'directory'
            for p in paths:
                if not os.path.isdir(p):
                    js_alert("Please select directory(s)")
                    return
        # set output
        if self.multiple:
            self.selected = paths
        else:
            self.selected = paths[0]
        # clean up
        self.remove()
        # next step
        if self.next:
            self.next(self.selected)
        return

    def show(self):
        display(HTML("""
        <style type="text/css">
        .jupyter-widgets select option {
            font-family: "Lucida Console", Monaco, monospace;
        }
        </style>
        """))
        display(self.panel)

    def result(self):
        return ['yo','ya','dfdf']

    def remove(self):
        for w in self.widgets: w.close()
        self.panel.close()

def create_file_times(paths):
    "returns a list of file modify time"
    ftimes = []
    for f in paths:
        if os.path.isdir(f):
            ftimes.append("Directory")
        else:
            ftime_sec = os.path.getmtime(f)
            ftime_tuple = time.localtime(ftime_sec)
            ftime = time.asctime(ftime_tuple)
            ftimes.append(ftime)
    return ftimes

def create_nametime_labels(entries, ftimes):
    if not entries: return []
    max_len = max(len(e) for e in entries)
    n_spaces = 5
    fmt_str = ' %-' + str(max_len+n_spaces) + "s|" + ' '*n_spaces + '%s'
    label_list = [fmt_str % (e, f) for e, f in zip(entries, ftimes)]
    return label_list

def del_ftime(file_label):
    "file_label is either a str or a tuple of strings"
    if isinstance(file_label, tuple):
        return tuple(del_ftime(s) for s in file_label)
    else:
        file_label_new = file_label.strip()
        if file_label_new != "." and file_label_new != "..":
            file_label_new = file_label_new.split("|")[0].rstrip()
    return(file_label_new)

def test1():
    panel = FileSelectorPanel("instruction", start_dir=".")
    print('\n'.join(panel._entries))
    panel.handle_enterdir(".")
    return

def test2():
    s = " __init__.py          |     Tue Jun 13 23:24:05 2017"
    assert del_ftime(s) == '__init__.py'
    s = ' . '
    assert del_ftime(s) == '.'
    s = (" __init__.py          |     Tue Jan 13 23:24:05 2017",
         " _utils.py            |     Mon Feb 11 12:00:00 2017")
    dels = del_ftime(s)
    expected = ("__init__.py", "_utils.py")
    for e, r in zip(dels, expected):
        assert e == r
    return

def main():
    #test1()
    test2()
    return

if __name__ == '__main__': main()


""" Comment serializers """

# Djanto REST Framework
from rest_framework import serializers

# Models
from publications.models import Comment

# Serializers
from users.serializers import UserModelSerializer

class CommentModelSerializer(serializers.ModelSerializer):

	user = serializers.StringRelatedField()

	class Meta:
		model = Comment
		fields = ('user', 'text', 'publication')

class CreateCommentSerializer(serializers.ModelSerializer):

	class Meta:
		model = Comment
		fields = ('user', 'text', 'publication')


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()

{'APIC': 'mutagen.id3.APIC', 'Picture': 'mutagen.flac.Picture', 'M4ACover': 'mutagen.m4a.M4ACover', 'TIT2': 'mutagen.id3.TIT2', 'TPE1': 'mutagen.id3.TPE1', 'TALB': 'mutagen.id3.TALB', 'TCON': 'mutagen.id3.TCON', 'TDRC': 'mutagen.id3.TDRC'}

{'sys': 'sys', 'shuffle': 'random.shuffle'}


import bottoken
import imgscan

import telebot
import os

# Creating bot
bot = telebot.TeleBot(bottoken.bottoken)

# Start command
@bot.message_handler(commands=['start'])
def start(message):
	bot.send_message(message.from_user.id, "Welcome to TelegramImageReader!\nFor command list send me /help!")

# Help command
@bot.message_handler(commands=['help'])
def start(message):
	bot.send_message(message.from_user.id, "Command list: \n/start - Start work with bot.\n/help - send this message.\n/img2txt - Read text form image.")

# Img2txt command
@bot.message_handler(commands=['img2txt'])
def start(message):
	bot.send_message(message.from_user.id, "Send image to read text from: ")

# Reciving image
@bot.message_handler(content_types=['document'])
def handle_docs_photo(message):
    bot.reply_to(message, "Processing... Result will appear soon!")

    chat_id = message.chat.id

    # Downloading image
    file_info = bot.get_file(message.document.file_id)
    downloaded_file = bot.download_file(file_info.file_path)
    f = open('img1.png', 'wb')
    f.write(downloaded_file)
    f.close()

    # Reading text from image
    txtFromImg = imgscan.textFromImg('img1.png')

    # Deleting image
    os.remove('img1.png')

    # Sending result to user
    bot.send_message(message.from_user.id, 'Text from image: \n\n' + txtFromImg)

# Launching bot
bot.polling()


import discord

async def run(client, message, args, prefix, db):
    if message.author.id in (311542309252497409, 300191414569009153):
        if len(message.channel_mentions) == 0:
            chn = message.channel
            msg = " ".join(args)
        else:
            chn = message.channel_mentions[0]
            msg = " ".join(args[1:])

        await message.delete()
        embed = discord.Embed.from_dict(eval(" ".join(args[1:])))
        embed.set_thumbnail(url=message.guild.icon_url)
        await chn.send(embed=embed)


from django.conf.urls import url

from .views import (
	StudentListView,
	StudentDetailView,
	StudentCreateView,
	StudentUpdateView
	)

urlpatterns = [
	url(r'^$', StudentListView.as_view(), name='list'),
	url(r'^create/$', StudentCreateView.as_view(), name='create'),
	url(r'^(?P<slug>[\w-]+)/$', StudentUpdateView.as_view(), name='edit')
]


from datetime import datetime

class Types:

    @staticmethod
    def isDate(sstr, fmt="%d/%m/%Y"):
        """
        Return whether the string can be interpreted as a date.

        :param string: str, string to check for date
        """
        try:
            datetime.strptime(sstr, fmt)
            return True

        except:
            return False

    @staticmethod
    def getType(val):
        #print(val)
        #print("input: " + str(type(val)) )
        if isinstance(val, int):
            return "i"
        elif isinstance(val, float):
            return "f"
        elif Types.isDate(val):
            return "d"
        elif isinstance(val, str):
            return "s"
        else:
            assert False, "Unknown type for: " + str(val)

if __name__ == "__main__":
    print(Types.getType(1.0))
    print(Types.getType(1))
    print(Types.getType("1.0"))
    print(Types.getType("02/06/1998"))

    #print(Types.isDate("01/june/1988"))


import typing as tp

from static_frame.core.index_base import IndexBase  # pylint: disable = W0611

from static_frame.core.index import Index
# from static_frame.core.index_hierarchy import IndexHierarchy

from static_frame.core.index import IndexGO

from static_frame.core.util import IndexConstructor

from static_frame.core.util import DTYPE_INT_DEFAULT

IndexAutoInitializer = int

# could create trival subclasses for these indices, but the type would would not always describe the instance; for example, an IndexAutoGO could grow inot non-contiguous integer index, as loc_is_iloc is reevaluated with each append can simply go to false.
#
# class IndexAuto(Index):
#     pass

# class IndexAutoGO(IndexGO):
#     pass

class IndexAutoFactory:

    # @classmethod
    # def from_is_static(cls,
    #         initializer: IndexAutoInitializer,
    #         *,
    #         is_static: bool,
    #         ) -> tp.Union[Index, IndexGO]:
    #     '''
    #     Args:
    #         initializer: An integer, or a sizable iterable.
    #         is_static: Boolean if this should be a static (not grow-only) index.
    #     '''
    #     labels = range(initializer)
    #     constructor = Index if is_static else IndexGO
    #     return constructor(
    #             labels=labels,
    #             loc_is_iloc=True,
    #             dtype=DTYPE_INT_DEFAULT
    #             )

    # @classmethod
    # def from_constructor(cls,
    #         initializer: IndexAutoInitializer,
    #         *,
    #         constructor: IndexConstructor,
    #         ) -> tp.Union[Index, IndexHierarchy]:

    #     labels = range(initializer)
    #     return constructor(labels)

    @classmethod
    def from_optional_constructor(cls,
            initializer: IndexAutoInitializer,
            *,
            default_constructor: tp.Type['IndexBase'],
            explicit_constructor: tp.Optional[IndexConstructor] = None,
            ) -> 'IndexBase':

        labels = range(initializer)

        if explicit_constructor:
            return explicit_constructor(labels)

        else: # get from default constructor
            constructor = Index if default_constructor.STATIC else IndexGO
            return constructor(
                    labels=labels,
                    loc_is_iloc=True,
                    dtype=DTYPE_INT_DEFAULT
                    )

IndexAutoFactoryType = tp.Type[IndexAutoFactory]


from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User
from .forms import *
from .models import *

# Create your views here.
def inicio_view(request):
	usuarios=User.objects.all()
	return render_to_response("principal/inicio.html",{'usuarios':usuarios},context_instance=RequestContext(request))

def registro_tema(request):
	titulo="Registro de temas"
	temas=Tema.objects.all()
	usuario=request.user #sirve para identificar el usuario
	if (not usuario.has_perm("temas.add_temas")):
		return HttpResponseRedirect("/permisos/")
	if request.method=="POST":
		formulario=ftema(request.POST)
		if formulario.is_valid():
			formulario.save()
			estado=True
			datos={'titulo':titulo,'formulario':formulario,'estado':estado,'temas':temas}
			return render_to_response("principal/registro_temas.html",datos,context_instance=RequestContext(request))
	else:
		formulario=ftema()
	datos={'titulo':titulo,'formulario':formulario,'temas':temas}
	return render_to_response("principal/registro_temas.html",datos,context_instance=RequestContext(request))

def add_pregunta(request,id):
	tema=Tema.objects.get(id=int(id))
	titulo="Registrar pregunta para el tema de "+tema.nombre
	titulo2="Registre las respuestas"
	if request.method=="POST":
		formulario=fpregunta(request.POST)
		formulario2=frespuesta(request.POST)
		if formulario.is_valid() and formulario2.is_valid():
			pregunta=formulario.save(commit=False)
			pregunta.tema=tema
			pregunta.save()
			respuesta=formulario2.save(commit=False)
			respuesta.pregunta=pregunta
			respuesta.save()
			estado=True
			formulario=fpregunta()
			datos={'titulo':titulo,'formulario':formulario,'estado':estado,'titulo2':titulo2,'formulario2':formulario2}
			return render_to_response("principal/registro_preguntas.html",datos,context_instance=RequestContext(request))
	else:
		formulario=fpregunta()
		formulario2=frespuesta()
	datos={'titulo':titulo,'titulo2':titulo2,'formulario':formulario,'formulario2':formulario2}
	return render_to_response("principal/registro_preguntas.html",datos,context_instance=RequestContext(request))
def ver_preguntas(request,id):
	tema=Tema.objects.get(id=int(id))
	preguntas=Pregunta.objects.filter(tema=tema)
	datos={'tema':tema,'preguntas':preguntas}
	return render_to_response("principal/ver_preguntas.html",datos,context_instance=RequestContext(request))

def edit_pregunta(request,id):
	pregunta=Pregunta.objects.get(id=int(id))
	respuesta=Respuesta.objects.get(pregunta=pregunta)
	titulo="Editar pregunta"
	titulo2="Editar las respuestas"
	if request.method=="POST":
		formulario=fpregunta(request.POST,instance=pregunta)
		formulario2=frespuesta(request.POST,instance=respuesta)
		if formulario.is_valid() and formulario2.is_valid():
			formulario.save()
			formulario2.save()
			estado=True
			datos={'titulo':titulo,'formulario':formulario,'estado':estado,'titulo2':titulo2,'formulario2':formulario2}
			return render_to_response("principal/registro_preguntas.html",datos,context_instance=RequestContext(request))
	else:
		formulario=fpregunta(instance=pregunta)
		formulario2=frespuesta(instance=respuesta)
	datos={'titulo':titulo,'titulo2':titulo2,'formulario':formulario,'formulario2':formulario2}
	return render_to_response("principal/registro_preguntas.html",datos,context_instance=RequestContext(request))

def eliminar_pregunta(request,id):
	pregunta=Pregunta.objects.get(id=int(id))
	id=pregunta.tema.id
	respuesta=Respuesta.objects.get(pregunta=pregunta)
	pregunta.delete()
	respuesta.delete()
	return HttpResponseRedirect("/tema/edit/"+str(id)+"/")

def error_permisos(request):
	return render_to_response("error/error_permisos.html",{},RequestContext(request))


import numpy as np
import os
from colorama import Fore
from colorama import Style
from copy import deepcopy
import pygame
from pygame.constants import KEYDOWN
import bfs
import astar

''' TIME OUT FOR ALL ALGORITHM : 30 MIN ~ 1800 SECONDS '''
TIME_OUT = 1800
''' GET THE TESTCASES AND CHECKPOINTS PATH FOLDERS '''
path_board = os.getcwd() + '\\..\\Testcases'
path_checkpoint = os.getcwd() + '\\..\\Checkpoints'

''' TRAVERSE TESTCASE FILES AND RETURN A SET OF BOARD '''
def get_boards():
    os.chdir(path_board)
    list_boards = []
    for file in os.listdir():
        if file.endswith(".txt"):
            file_path = f"{path_board}\{file}"
            board = get_board(file_path)
            # print(file)
            list_boards.append(board)
    return list_boards

''' TRAVERSE CHECKPOINT FILES AND RETURN A SET OF CHECKPOINT '''
def get_check_points():
    os.chdir(path_checkpoint)
    list_check_point = []
    for file in os.listdir():
        if file.endswith(".txt"):
            file_path = f"{path_checkpoint}\{file}"
            check_point = get_pair(file_path)
            list_check_point.append(check_point)
    return list_check_point

''' FORMAT THE INPUT TESTCASE TXT FILE '''
def format_row(row):
    for i in range(len(row)):
        if row[i] == '1':
            row[i] = '#'
        elif row[i] == 'p':
            row[i] = '@'
        elif row[i] == 'b':
            row[i] = '$'
        elif row[i] == 'c':
            row[i] = '%'

''' FORMAT THE INPUT CHECKPOINT TXT FILE '''
def format_check_points(check_points):
    result = []
    for check_point in check_points:
        result.append((check_point[0], check_point[1]))
    return result

''' READ A SINGLE TESTCASE TXT FILE '''
def get_board(path):
    result = np.loadtxt(f"{path}", dtype=str, delimiter=',')
    for row in result:
        format_row(row)
    return result

''' READ A SINGLE CHECKPOINT TXT FILE '''
def get_pair(path):
    result = np.loadtxt(f"{path}", dtype=int, delimiter=',')
    return result

'''
//========================//
//      DECLARE AND       //
//  INITIALIZE MAPS AND   //
//      CHECK POINTS      //
//========================//
'''
maps = get_boards()
check_points = get_check_points()

'''
//========================//
//         PYGAME         //
//     INITIALIZATIONS    //
//                        //
//========================//
'''
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((640, 640))
pygame.display.set_caption('Sokoban')
clock = pygame.time.Clock()
BACKGROUND = (0, 0, 0)
WHITE = (255, 255, 255)
'''
GET SOME ASSETS
'''
assets_path = os.getcwd() + "\\..\\Assets"
os.chdir(assets_path)
player = pygame.image.load(os.getcwd() + '\\player.png')
wall = pygame.image.load(os.getcwd() + '\\wall.png')
box = pygame.image.load(os.getcwd() + '\\box.png')
point = pygame.image.load(os.getcwd() + '\\point.png')
space = pygame.image.load(os.getcwd() + '\\space.png')
arrow_left = pygame.image.load(os.getcwd() + '\\arrow_left.png')
arrow_right = pygame.image.load(os.getcwd() + '\\arrow_right.png')
init_background = pygame.image.load(os.getcwd() + '\\init_background.png')
loading_background = pygame.image.load(os.getcwd() + '\\loading_background.png')
notfound_background = pygame.image.load(os.getcwd() + '\\notfound_background.png')
found_background = pygame.image.load(os.getcwd() + '\\found_background.png')
'''
RENDER THE MAP FOR GAMEPLAY
'''
def renderMap(board):
	width = len(board[0])
	height = len(board)
	indent = (640 - width * 32) / 2.0
	for i in range(height):
		for j in range(width):
			screen.blit(space, (j * 32 + indent, i * 32 + 250))
			if board[i][j] == '#':
				screen.blit(wall, (j * 32 + indent, i * 32 + 250))
			if board[i][j] == '$':
				screen.blit(box, (j * 32 + indent, i * 32 + 250))
			if board[i][j] == '%':
				screen.blit(point, (j * 32 + indent, i * 32 + 250))
			if board[i][j] == '@':
				screen.blit(player, (j * 32 + indent, i * 32 + 250))
'''
VARIABLES INITIALIZATIONS
'''
#Map level
mapNumber = 0
#Algorithm to solve the game
algorithm = "Breadth First Search"
#Your scene states, including:
#init for choosing your map and algorithm
#loading for displaying "loading scene"
#executing for solving problem
#playing for displaying the game
sceneState = "init"
loading = False

''' SOKOBAN FUNCTION '''
def sokoban():
	running = True
	global sceneState
	global loading
	global algorithm
	global list_board
	global mapNumber
	stateLenght = 0
	currentState = 0
	found = True

	while running:
		screen.blit(init_background, (0, 0))
		if sceneState == "init":
			#Choose map and display
			initGame(maps[mapNumber])

		if sceneState == "executing":
			#Choose map
			list_check_point = check_points[mapNumber]

			#Choose between BFS or Hill Climbing
			if algorithm == "Breadth First Search":
				print("BFS")
				list_board = bfs.BFS_search(maps[mapNumber], list_check_point)
			else:
				print("AStar")
				list_board = astar.AStart_Search(maps[mapNumber], list_check_point)
			if len(list_board) > 0:
				sceneState = "playing"
				stateLenght = len(list_board[0])
				currentState = 0
			else:
				sceneState = "end"
				found = False
		if sceneState == "loading":
			loadingGame()
			sceneState = "executing"
		if sceneState == "end":
			if found:
				foundGame(list_board[0][stateLenght - 1])
			else:
				notfoundGame()
		if sceneState == "playing":
			clock.tick(2)
			renderMap(list_board[0][currentState])
			currentState = currentState + 1
			if currentState == stateLenght:
				sceneState = "end"
				found = True
		#Check event when you press key board
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				running = False
			if event.type == pygame.KEYDOWN:

				#Press arrow key board to change level map
				if event.key == pygame.K_RIGHT and sceneState == "init":
					if mapNumber < len(maps) - 1:
						mapNumber = mapNumber + 1
				if event.key == pygame.K_LEFT and sceneState == "init":
					if mapNumber > 0:
						mapNumber = mapNumber - 1
				#Press ENTER key board to select level map and algorithm
				if event.key == pygame.K_RETURN:
					if sceneState == "init":
						sceneState = "loading"
					if sceneState == "end":
						sceneState = "init"
				#Press SPACE key board to switch algorithm
				if event.key == pygame.K_SPACE and sceneState == "init":
					if algorithm == "Breadth First Search":
						algorithm = "A Star Search"
					else:
						algorithm = "Breadth First Search"
		pygame.display.flip()
	pygame.quit()

''' DISPLAY MAIN SCENE '''
#DISPLAY INITIAL SCENE
def initGame(map):
	titleSize = pygame.font.Font('gameFont.ttf', 60)
	titleText = titleSize.render('Among-koban', True, WHITE)
	titleRect = titleText.get_rect(center=(320, 80))
	screen.blit(titleText, titleRect)

	desSize = pygame.font.Font('gameFont.ttf', 20)
	desText = desSize.render('Now, select your map!!!', True, WHITE)
	desRect = desText.get_rect(center=(320, 140))
	screen.blit(desText, desRect)

	mapSize = pygame.font.Font('gameFont.ttf', 30)
	mapText = mapSize.render("Lv." + str(mapNumber + 1), True, WHITE)
	mapRect = mapText.get_rect(center=(320, 200))
	screen.blit(mapText, mapRect)

	screen.blit(arrow_left, (246, 188))
	screen.blit(arrow_right, (370, 188))

	algorithmSize = pygame.font.Font('gameFont.ttf', 30)
	algorithmText = algorithmSize.render(str(algorithm), True, WHITE)
	algorithmRect = algorithmText.get_rect(center=(320, 600))
	screen.blit(algorithmText, algorithmRect)
	renderMap(map)

''' LOADING SCENE '''
#DISPLAY LOADING SCENE
def loadingGame():
	screen.blit(loading_background, (0, 0))

	fontLoading_1 = pygame.font.Font('gameFont.ttf', 40)
	text_1 = fontLoading_1.render('SHHHHHHH!', True, WHITE)
	text_rect_1 = text_1.get_rect(center=(320, 60))
	screen.blit(text_1, text_rect_1)

	fontLoading_2 = pygame.font.Font('gameFont.ttf', 20)
	text_2 = fontLoading_2.render('The problem is being solved, stay right there!', True, WHITE)
	text_rect_2 = text_2.get_rect(center=(320, 100))
	screen.blit(text_2, text_rect_2)

def foundGame(map):
	screen.blit(found_background, (0, 0))

	font_1 = pygame.font.Font('gameFont.ttf', 30)
	text_1 = font_1.render('Yeah! The problem is solved!!!', True, WHITE)
	text_rect_1 = text_1.get_rect(center=(320, 100))
	screen.blit(text_1, text_rect_1)

	font_2 = pygame.font.Font('gameFont.ttf', 20)
	text_2 = font_2.render('Press Enter to continue.', True, WHITE)
	text_rect_2 = text_2.get_rect(center=(320, 600))
	screen.blit(text_2, text_rect_2)

	renderMap(map)

def notfoundGame():
	screen.blit(notfound_background, (0, 0))

	font_1 = pygame.font.Font('gameFont.ttf', 40)
	text_1 = font_1.render('Oh no, I tried my best :(', True, WHITE)
	text_rect_1 = text_1.get_rect(center=(320, 100))
	screen.blit(text_1, text_rect_1)

	font_2 = pygame.font.Font('gameFont.ttf', 20)
	text_2 = font_2.render('Press Enter to continue.', True, WHITE)
	text_rect_2 = text_2.get_rect(center=(320, 600))
	screen.blit(text_2, text_rect_2)

def main():
	sokoban()

if __name__ == "__main__":
	main()


#!/usr/bin/python
# -*- codding: utf-8 -*-
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.execute_command import write_one_parameter

# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/macie2/disable-organization-admin-account.html
if __name__ == '__main__':
    """
	enable-organization-admin-account : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/macie2/enable-organization-admin-account.html
	list-organization-admin-accounts : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/macie2/list-organization-admin-accounts.html
    """

    parameter_display_string = """
    # admin-account-id : The AWS account ID of the delegated administrator account.
    """
    add_option_dict = {}

    #######################################################################
    # parameter display string
    add_option_dict["parameter_display_string"] = parameter_display_string
    # ex: add_option_dict["no_value_parameter_list"] = "--single-parameter"
    write_one_parameter("macie2", "disable-organization-admin-account", "admin-account-id", add_option_dict)


# -*- coding: utf-8 -*-
import django
from django.contrib import admin
from django.utils.translation import ugettext as _
from django.contrib.contenttypes import generic
from django_settings import models, forms

def get_setting_value(obj):
    return obj.setting_object.value
get_setting_value.short_description = _('Value')

#def get_setting_description(obj):
#    return obj.setting_object.description

class SettingAdmin(admin.ModelAdmin):
    model = models.Setting
    form = forms.SettingForm
    list_display = ('name',  'setting_type','description',
            get_setting_value )
    add_form = forms.SettingCreationForm

    def get_form(self, request, obj=None, **kwargs):
        """
        Use special form during user creation
        """
        defaults = {}
        if obj is None:
            defaults.update({
                'form': self.add_form,
                'fields': ('name', 'setting_type', 'description', 'is_required'),
            })
        defaults.update(kwargs)
        return super(SettingAdmin, self).get_form(request, obj, **defaults)
admin.site.register(models.Setting, SettingAdmin)


# -*- coding: utf-8 -*-
import datetime
import os
import sys

from .meta import Meta
from .parser import Parser
from .printer import *
from .tokenizer import Token, tokenize
from .utils import *

class Target(object):
    def __init__(self, gmdoc_dir, project_dir, *args, **kwargs):
        self.gmdoc_dir = gmdoc_dir
        self.project_dir = project_dir
        self.meta_path = os.path.join(project_dir, "gmdoc.json")
        self.docs_src_dir = os.path.join(project_dir, "docs_src")
        self.template_dir = os.path.join(gmdoc_dir, "template")

    def execute(self, *args, **kwargs):
        pass

class HelpTarget(Target):
    MESSAGE = (
        "Usage: gmdoc TARGET\n"
        "\n"
        "  TARGET - init  - Initialize gmdoc in the current directory.\n"
        "         - build - Build documentation.\n"
        "         - help  - Display this message.\n"
    )

    def execute(self, *args, **kwargs):
        print(HelpTarget.MESSAGE)

class InitTarget(Target):
    def execute(self, *args, **kwargs):
        meta = Meta.new()
        meta.save(self.meta_path)
        meta_serialized = meta.serialize()

        _docs_src_dest = os.path.join(self.project_dir, "docs_src")
        os.makedirs(_docs_src_dest, exist_ok=True)

        copytree(
            os.path.join(self.gmdoc_dir, "docs_src"),
            _docs_src_dest,
        )

        for root, _, files in os.walk(_docs_src_dest):
            for name in files:
                fname = os.path.join(root, name)
                with open(fname, "r") as f:
                    cnt = f.read().format(**meta_serialized)
                with open(fname, "w") as f:
                    f.write(cnt)

class BuildTarget(Target):
    def flatten_toc(self, toc):
        flattened = []

        def get_name(v):
            return os.path.splitext(os.path.basename(v))[0] + ".html"

        for _, v in toc.items():
            if isinstance(v, dict):
                flattened.append(get_name(v["file"]))
                flattened += self.flatten_toc(v.get("pages", {}))
            else:
                flattened.append(get_name(v))

        return flattened

    def parse_resources(self, prefix):
        parsed = {}

        for root, _, files in os.walk(self.project_dir):
            for file in files:
                if not file.startswith(prefix):
                    continue
                if file[-4:] != ".gml":
                    continue
                fpath = os.path.join(root, file)
                print("Parsing", fpath)
                tokens = []
                with open(fpath) as f:
                    tokens += tokenize(f)
                parsed = merge(Parser(tokens).parse(), parsed)

        return parsed

    def flatten_resources(self, parsed):
        resources = []
        for _, v in parsed.items():
            for r in v:
                resources.append(r)
        resources.sort(key=lambda r: r["name"])
        return resources

    def execute(self, *args, **kwargs):
        if len(sys.argv) > 2:
            docs_dir = sys.argv[2]
        else:
            docs_dir = os.path.join(self.project_dir, "docs_build")
            os.makedirs(docs_dir, exist_ok=True)

        print("Loading meta")
        meta = Meta.load(self.meta_path)

        prefix = meta.prefix
        toc = meta.toc
        _now = datetime.datetime.now()
        datestr = _now.strftime("%B %d, %Y")
        yearstr = _now.strftime("%Y")

        try:
            print("Deleting {}".format(docs_dir))
            shutil.rmtree(docs_dir)
        except:
            pass

        print("Copying resources from {} to {}".format(
            self.template_dir, docs_dir))
        shutil.copytree(self.template_dir, docs_dir)

        print("Loading template")
        with open(os.path.join(self.template_dir, "index.html")) as f:
            template = f.read()

        print("Parsing scripting API documentation")
        parsed = self.parse_resources(prefix)
        resources = self.flatten_resources(parsed)

        out_dir = os.path.join(self.docs_src_dir, "ScriptingAPI")
        os.makedirs(out_dir, exist_ok=True)

        scripting_api_toc = {
            "file": "ScriptingAPI.md",
            "pages": {}
        }

        for r in resources:
            name = r["name"]

            md = resource_to_markdown(r)
            if md is None:
                print("Skipping {name} of type {_type}".format(**r))
                continue

            print("Generating Markdown for", name)
            fname = os.path.abspath("{}/{}.md".format(out_dir, name))
            with open(fname, "w") as f:
                f.write(md)

            scripting_api_toc["pages"][name] = fname

        toc["Scripting API"] = scripting_api_toc

        make_pages(
            meta,
            self.flatten_toc(toc),
            docs_src_dir=self.docs_src_dir,
            docs_dir=docs_dir,
            template=template,
            datestr=datestr,
            yearstr=yearstr
        )


'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,
WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'''

# Bitcoin Cash (BCH)   qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk
# Ether (ETH) -        0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB
# Litecoin (LTC) -     Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu
# Bitcoin (BTC) -      34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd

# contact :- github@jamessawyer.co.uk

# -*- coding: utf-8 -*-
from pandas import DataFrame
from ..utils import get_drift, get_offset, verify_series

def uo(
    high,
    low,
    close,
    fast=None,
    medium=None,
    slow=None,
    fast_w=None,
    medium_w=None,
    slow_w=None,
    drift=None,
    offset=None,
    **kwargs,
):
    """Indicator: Ultimate Oscillator (UO)"""
    # Validate arguments
    high = verify_series(high)
    low = verify_series(low)
    close = verify_series(close)
    drift = get_drift(drift)
    offset = get_offset(offset)

    fast = int(fast) if fast and fast > 0 else 7
    fast_w = float(fast_w) if fast_w and fast_w > 0 else 4.0

    medium = int(medium) if medium and medium > 0 else 14
    medium_w = float(medium_w) if medium_w and medium_w > 0 else 2.0

    slow = int(slow) if slow and slow > 0 else 28
    slow_w = float(slow_w) if slow_w and slow_w > 0 else 1.0

    # Calculate Result
    tdf = DataFrame({
        "high": high,
        "low": low,
        f"close_{drift}": close.shift(drift)
    })
    max_h_or_pc = tdf.loc[:, ["high", f"close_{drift}"]].max(axis=1)
    min_l_or_pc = tdf.loc[:, ["low", f"close_{drift}"]].min(axis=1)
    del tdf

    bp = close - min_l_or_pc
    tr = max_h_or_pc - min_l_or_pc

    fast_avg = bp.rolling(fast).sum() / tr.rolling(fast).sum()
    medium_avg = bp.rolling(medium).sum() / tr.rolling(medium).sum()
    slow_avg = bp.rolling(slow).sum() / tr.rolling(slow).sum()

    total_weight = fast_w + medium_w + slow_w
    weights = (fast_w * fast_avg) + (medium_w * medium_avg) + (slow_w *
                                                               slow_avg)
    uo = 100 * weights / total_weight

    # Offset
    if offset != 0:
        uo = uo.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        uo.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        uo.fillna(method=kwargs["fill_method"], inplace=True)

    # Name and Categorize it
    uo.name = f"UO_{fast}_{medium}_{slow}"
    uo.category = "momentum"

    return uo

uo.__doc__ = """Ultimate Oscillator (UO)

The Ultimate Oscillator is a momentum indicator over three different
periods.  It attempts to correct false divergence trading signals.

Sources:
    https://www.tradingview.com/wiki/Ultimate_Oscillator_(UO)

Calculation:
    Default Inputs:
        fast=7, medium=14, slow=28,
        fast_w=4.0, medium_w=2.0, slow_w=1.0, drift=1
    min_low_or_pc  = close.shift(drift).combine(low, min)
    max_high_or_pc = close.shift(drift).combine(high, max)

    bp = buying pressure = close - min_low_or_pc
    tr = true range = max_high_or_pc - min_low_or_pc

    fast_avg = SUM(bp, fast) / SUM(tr, fast)
    medium_avg = SUM(bp, medium) / SUM(tr, medium)
    slow_avg = SUM(bp, slow) / SUM(tr, slow)

    total_weight = fast_w + medium_w + slow_w
    weights = (fast_w * fast_avg) + (medium_w * medium_avg) + (slow_w * slow_avg)
    UO = 100 * weights / total_weight

Args:
    high (pd.Series): Series of 'high's
    low (pd.Series): Series of 'low's
    close (pd.Series): Series of 'close's
    fast (int): The Fast %K period.  Default: 7
    medium (int): The Slow %K period.  Default: 14
    slow (int): The Slow %D period.  Default: 28
    fast_w (float): The Fast %K period.  Default: 4.0
    medium_w (float): The Slow %K period.  Default: 2.0
    slow_w (float): The Slow %D period.  Default: 1.0
    drift (int): The difference period.   Default: 1
    offset (int): How many periods to offset the result.  Default: 0

Kwargs:
    fillna (value, optional): pd.DataFrame.fillna(value)
    fill_method (value, optional): Type of fill method

Returns:
    pd.Series: New feature generated.
"""


from django import forms
from models import *

class agregar_paciente_form(forms.Form):
    num_historia     = forms.IntegerField(
                            max_value=999999,
                            widget = forms.TextInput(attrs={'size': 6}))
    tipo_cedula      = forms.ChoiceField(
                            choices=TIPO_CEDULA,
                            widget=forms.RadioSelect())
    cedula           = forms.IntegerField(max_value=999999999)
    nombres          = forms.CharField(max_length=64)
    apellidos        = forms.CharField(max_length=64)
    sexo             = forms.ChoiceField(choices=SEXO)

    fecha_nacimiento          = forms.DateField(
                        label = "FECHA DE NACIMIENTO",
                        widget = forms.TextInput(attrs = {
                            'placeholder':'dd/mm/aaaa',
                            'data-format':'dd/mm/yyyy'
                            }))
    fecha_ingreso_institucion = forms.DateField(
                        label = "FECHA DE INGRESO A LA INSTITUCION",
                        widget = forms.TextInput(attrs = {
                            'placeholder':'dd/mm/aaaa',
                            'data-format':'dd/mm/yyyy'
                            }))


from django.conf.urls import url
from MyCar import views
urlpatterns = [
    url(r'^main_page/$', views.main_page, name="main_page"),
    url(r'^auto/$', views.auto, name="auto"),
    url(r"^model/(?P<model_id>\d+)$", views.model, name="model"),
    url(r"^tariff/$", views.tariff, name="tariff"),
    url(r"^operators/$", views.operators, name="operators"),
    url(r"^about/$", views.about, name="about"),
    url(r"^admin_menu/$", views.admin_menu, name="admin_menu"),
    url(r"^show_rent/$", views.show_rent, name="show_rent"),
    url(r"^show_rank/$", views.show_rank, name="show_rank"),
    url(r"^show_mark_models/$", views.show_mark, name="show_mark"),
    url(r"^models/(?P<id_mark>\d+)$", views.show_models, name="show_models"),
    url(r"^fuel/$", views.show_fuel, name="show_fuel"),
    url(r"^operator/$", views.show_operator, name="show_operator"),
    url(r"^tariffs/$", views.show_tariffs, name="show_tariffs"),
    url(r"^add_rank/$", views.add_rank, name="add_rank"),
    url(r"^add_mark/$", views.add_mark, name="add_mark"),
    url(r"^add_operator/$", views.add_operator, name="add_operator"),
    url(r"^add_tariff/$", views.add_tariff, name="add_tariff"),
    url(r"^add_fuel/$", views.add_fuel, name="add_fuel"),
    url(r"^add_model/$", views.add_model, name="add_model"),
    url(r"^edit_rank/(?P<rank_id>\d+)$", views.edit_rank, name="edit_rank"),
    url(r"^edit_mark/(?P<mark_id>\d+)$", views.edit_mark, name="edit_mark"),
    url(r"^edit_model/(?P<model_id>\d+)$", views.edit_model, name="edit_model"),
    url(r"^edit_tariff/(?P<tariff_id>\d+)$", views.edit_tariff, name="edit_tariff"),
    url(r"^edit_fuel/(?P<fuel_id>\d+)$", views.edit_fuel, name="edit_fuel"),
    url(r"^edit_rent/(?P<rent_id>\d+)$", views.edit_rent, name="edit_rent"),
    url(r"^edit_operator/(?P<operator_id>\d+)$", views.edit_operator, name="edit_operator"),
    url(r"^delete_rent/(?P<rent_id>\d+)$", views.delete_rent, name="delete_rent"),
    url(r"^delete_rank/(?P<rank_id>\d+)$", views.delete_rank, name="delete_rank"),
    url(r"^delete_operator/(?P<operator_id>\d+)$", views.delete_operator, name="delete_operator"),
    url(r"^delete_tariff/(?P<tariff_id>\d+)$", views.delete_tariff, name="delete_tariff"),
    url(r"^delete_fuel/(?P<fuel_id>\d+)$", views.delete_fuel, name="delete_fuel"),
    url(r"^delete_mark/(?P<mark_id>\d+)$", views.delete_mark, name="delete_mark"),
    url(r"^delete_model/(?P<model_car_id>\d+)$", views.delete_model, name="delete_model"),

]


import urllib2, urllib, datetime
from brown.models import Attempt
from brown.lib import utils

API_SSL_SERVER="https://www.google.com/recaptcha/api"
API_SERVER="http://www.google.com/recaptcha/api"
VERIFY_SERVER="www.google.com"

class RecaptchaResponse(object):
    def __init__(self, is_valid, error_code=None):
        self.is_valid = is_valid
        self.error_code = error_code

def display_html(public_key, use_ssl=False, error=None):
    """Gets the HTML to display for reCAPTCHA

    public_key -- The public api key
    use_ssl -- Should the request be sent over ssl?
    error -- An error message to display (from RecaptchaResponse.error_code)
    """
    error_param = ''
    if error:
        error_param = '&error=%s' % error

    if use_ssl:
        server = API_SSL_SERVER
    else:
        server = API_SERVER

    return """

  <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
  <input type='hidden' name='recaptcha_response_field' value='manual_challenge' />

""" % {
        'ApiServer': server,
        'PublicKey': public_key,
        'ErrorParam': error_param,
    }

def submit(recaptcha_challenge_field, recaptcha_response_field, private_key, remote_ip):
    """
    Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
    for the request

    recaptcha_challenge_field -- The value of recaptcha_challenge_field from the form
    recaptcha_response_field -- The value of recaptcha_response_field from the form
    private_key -- your reCAPTCHA private key
    remote_ip -- the user's ip address
    """
    if not recaptcha_response_field or not recaptcha_challenge_field:
        return RecaptchaResponse(is_valid=False, error_code='incorrect-captcha-sol')

    def encode_if_necessary(s):
        if isinstance(s, unicode):
            return s.encode('utf-8')
        return s

    params = urllib.urlencode({
        'privatekey': private_key,
        'remoteip': remote_ip,
        'challenge': recaptcha_challenge_field,
        'response': recaptcha_response_field,
    })
    params = {key: encode_if_necessary(value) for key, value in params.iter_items()}

    request = urllib2.Request(
        url="http://%s/recaptcha/api/verify" % VERIFY_SERVER,
        data=params,
        headers={
            "Content-type": "application/x-www-form-urlencoded",
            "User-agent": "reCAPTCHA Python",
        }
    )

    httpresp = urllib2.urlopen(request)
    return_values = httpresp.read().splitlines()
    httpresp.close()

    return_code = return_values[0]

    if (return_code == "true"):
        return RecaptchaResponse(is_valid=True)
    else:
        return RecaptchaResponse(is_valid=False, error_code=return_values[1])

def check(request, attempt_type, config):
    """Check if the user should fill the captcha and if the captcha is valid."""
    time = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
    ip_long = utils.ip2long(request.remote_addr)

    fill_captcha = Attempt.query.filter(
        Attempt.ip==ip_long,
        Attempt.type==attempt_type,
        Attempt.date>time
    ).first() != None

    captcha_is_valid = not fill_captcha

    captcha_challenge = request.form.get('recaptcha_challenge_field')
    captcha_response = request.form.get('recaptcha_response_field')

    if fill_captcha and captcha_response and captcha_challenge:
        response = submit(
            captcha_challenge,
            captcha_response,
            config.get('CAPTCHA_PRIVATE_KEY'),
            request.remote_addr
        )
        captcha_is_valid = response.is_valid

    return fill_captcha, captcha_is_valid