#   Programmer:     limodou
#   E-mail:         limodou@gmail.com
#
#   Copyleft 2006 limodou
#
#   Distributed under the terms of the GPL (GNU Public License)
#
#   UliPad is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   $Id$

import wx
from modules import Globals
import Server
import Client
from modules import common
from modules.Debug import error
from modules import Mixin
from modules import CheckList
from wx.lib.splitter import MultiSplitterWindow
from modules import makemenu
import CommandRecord

class ConcurrentWindow(wx.Panel, Mixin.Mixin):
    __mixinname__ = 'concurrent'
    concurrent_id = 0

    def __init__(self, parent):
        self.initmixin()

        wx.Panel.__init__(self, parent, -1)

        self.mainframe = Globals.mainframe
        self.pref = self.mainframe.pref

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer1 = wx.BoxSizer(wx.HORIZONTAL)

        if not self.pref.pairprog_username:
            self.pref.pairprog_username = self.pref.personal_username

        sizer1.Add(wx.StaticText(self, -1, tr("Name") + ':'), 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.LEFT, 2)
        self.txtName = wx.TextCtrl(self, -1, self.pref.pairprog_username, size=(100, -1))
        sizer1.Add(self.txtName, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.LEFT, 2)
        sizer1.Add(wx.StaticText(self, -1, tr("Host") + ':'), 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 2)
        self.txtIP = wx.TextCtrl(self, -1, self.pref.pairprog_host, size=(150, -1))
        sizer1.Add(self.txtIP, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 2)
        sizer1.Add(wx.StaticText(self, -1, tr("Port") + ':'), 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 2)
        self.txtPort = wx.SpinCtrl(self, min=1, max=65536, value=str(self.pref.pairprog_port))
        sizer1.Add(self.txtPort, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 2)
        self.btnStart = wx.Button(self, -1, tr("Start Server"))
        sizer1.Add(self.btnStart, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 2)
        self.btnConnect = wx.Button(self, -1, tr("Connect Server"))
        sizer1.Add(self.btnConnect, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 2)

        sizer.Add(sizer1, 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 2)

        self.splitter = MultiSplitterWindow(self, -1)

        userpanel = UserPanel(self.splitter)
        self.splitter.AppendWindow(userpanel, 200)
        self.userlist = userpanel.list

        filelistpanel = FileListPanel(self.splitter)
        self.splitter.AppendWindow(filelistpanel, 150)
        self.filelist = filelistpanel.list

        chatpanel = ChatPanel(self.splitter)
        self.splitter.AppendWindow(chatpanel)
        self.chat = chatpanel.chat
        self.chatroom = chatpanel.chatroom
        self.btnSend = chatpanel.btnSend
        self.btnClear = chatpanel.btnClear
        self.btnSave = chatpanel.btnSave
        self.splitter.SetMinimumPaneSize(150)
        self.splitter.SetOrientation(wx.HORIZONTAL)

        sizer.Add(self.splitter, 1, wx.EXPAND|wx.ALL, 2)

        self.SetSizer(sizer)
        self.SetAutoLayout(True)

        self.btnStart.Bind(wx.EVT_BUTTON, self.OnStart)
        self.btnConnect.Bind(wx.EVT_BUTTON, self.OnConnect)
        self.btnSend.Bind(wx.EVT_BUTTON, self.OnSend)
        self.btnClear.Bind(wx.EVT_BUTTON, self.OnClear)
        self.btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
        self.filelist.Bind(wx.EVT_RIGHT_DOWN, self.OnFilelistRClick)
        self.userlist.Bind(wx.EVT_RIGHT_DOWN, self.OnUserlistRClick)
        self.chat.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

        self.status = ''
        self.server = None
        self.client = None
        self.servercommands = ServerCommands(self)
        self.clientcommands = ClientCommands(self)
        self.users = {}
        self.files = {}
        self.cmdrecorder = CommandRecord.CommandRecord()
        self.filelistpopmenus = None
        self.userlistpopmenus = None

    def __get_me(self):
        return self.txtName.GetValue()

    me = property(__get_me)

    def OnStart(self, event=None):
        if not self.status:
            if not self.me or self.me == '*':
                common.showerror(self, tr("Username should not be empty or '*'"))
                self.txtName.SetFocus()
                return

            ip = self.txtIP.GetValue()
            if not ip:
                common.showerror(self, tr("Host address cannot be empty!"))
                self.txtIP.SetFocus()
                return
            port = int(self.txtPort.GetValue())
            self.pref.pairprog_host = ip
            self.pref.pairprog_port = port
            self.pref.pairprog_username = self.me
            self.pref.save()
            try:
                self.server = Server.start_server(ip, port, self.servercommands)
                if self.server:
                    self.AddUser(self.me, manager=True)
                    self.change_status('startserver')
                    self.callplugin('start', self, 'server')
            except:
                common.warn(tr("Start server error!"))
                error.traceback()
        else:
            self.server.shut_down()
            self.server = None
            self.change_status('stopserver')
            self.callplugin('stop', self, 'server')

    def OnConnect(self, event=None):
        if not self.status:
            if not self.me or self.me == '*':
                common.showerror(self, tr("Username should not be empty or '*'"))
                self.txtName.SetFocus()
                return

            ip = self.txtIP.GetValue()
            if not ip:
                common.showerror(self, tr("Host address cannot be empty!"))
                self.txtIP.SetFocus()
                return
            port = int(self.txtPort.GetValue())
            self.pref.pairprog_host = ip
            self.pref.pairprog_port = port
            self.pref.pairprog_username = self.me
            self.pref.save()
#            try:
            self.client = Client.start_client(ip, port, self.clientcommands)
            if self.client:
                self.client.call('join', self.me)

                self.change_status('connectserver')
                self.callplugin('start', self, 'client')
#            except:
#                common.warn(tr("Connect to server error!"))
#                error.traceback()
        else:
            self.client.close()
            self.client = None
            self.change_status('disconnectserver')
            self.callplugin('stop', self, 'client')

    def OnSend(self, event=None):
        message = self.chat.GetValue()
        self.chat.SetValue('')
        if message:
            self.put_message(self.me, message)
            if self.status == 'startserver':    #server
                self.server.broadcast('message', self.me, message)
            else:
                self.client.call('message', self.me, message)

    def OnClear(self, event=None):
        self.chatroom.SetReadOnly(0)
        self.chatroom.SetText('')
        self.chatroom.SetReadOnly(1)

    def OnClose(self, win):
        if self.status == 'startserver':
            self.OnStart()
        elif self.status == 'connectserver':
            self.OnConnect()

    def OnSave(self, event=None):
        filename = None
        dlg = wx.FileDialog(self, tr("Save File"), self.pref.last_dir, '', 'Text file|*.txt', wx.SAVE|wx.OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            filename = dlg.GetPath()
            dlg.Destroy()
        if filename:
            try:
                file(filename, 'w').write(self.chatroom.GetText().encode('utf-8'))
            except:
                common.warn(tr("There is error as saving the file"))
            else:
                common.note(tr("Finished!"))

    def OnFilelistRClick(self, event):
        pt = event.GetPosition();
        item, flags = self.filelist.HitTest(pt)
        if item > -1:
            self.filelist.Select(item)
        if self.status == 'startserver':
            popmenulist = [ (None,
                [
                    (10, 'IDPM_ADD', tr('Add Current Document'), wx.ITEM_NORMAL, 'OnAddDocument', ''),
                    (20, 'IDPM_REMOVE', tr('Remove Document'), wx.ITEM_NORMAL, 'OnRemoveDocument', ''),
                ]),
            ]
        else:
            popmenulist = [ (None,
                [
                    (10, 'IDPM_REGET', tr('Reget Document'), wx.ITEM_NORMAL, 'OnRegetDocument', ''),
                ]),
            ]

        other_menus = []
        if self.filelistpopmenus:
            self.filelistpopmenus.Destroy()
            self.filelistpopmenus = None
        self.callplugin('other_filelist_popup_menu', self, other_menus)
        import copy
        if other_menus:
            pop_menus = copy.deepcopy(popmenulist + other_menus)
        else:
            pop_menus = copy.deepcopy(popmenulist)
        self.filelistpopmenus = makemenu.makepopmenu(self, pop_menus)

        self.filelist.PopupMenu(self.filelistpopmenus)

    def OnUserlistRClick(self, event):
        pt = event.GetPosition();
        item, flags = self.userlist.HitTest(pt)
        if item > -1:
            self.userlist.Select(item)
        popmenulist = [ (None,
            [
                (10, 'IDPM_KICK', tr('Kick User'), wx.ITEM_NORMAL, 'OnKickUser', ''),
            ]),
        ]

        other_menus = []
        if self.userlistpopmenus:
            self.userlistpopmenus.Destroy()
            self.userlistpopmenus = None
        self.callplugin('other_userlist_popup_menu', self, other_menus)
        import copy
        if other_menus:
            pop_menus = copy.deepcopy(popmenulist + other_menus)
        else:
            pop_menus = copy.deepcopy(popmenulist)
        self.userlistpopmenus = makemenu.makepopmenu(self, pop_menus)

        self.filelist.PopupMenu(self.userlistpopmenus)

    def OnAddDocument(self, event):
        document = self.mainframe.editctrl.getCurDoc()
        if not self.has_document(document):
            filename = document.getShortFilename()
            index = self.filelist.addline([filename])
            ConcurrentWindow.concurrent_id += 1
            _id = ConcurrentWindow.concurrent_id
            self.filelist.SetItemData(index, _id)
            self.files[_id] = document
            self.cmdrecorder.add_document(_id, document)
            def f(self):
                self.server.broadcast('update_files', self.__get_filelist())
                self.server.broadcast('editcmd', 'openfile', (_id, filename, document.getRawText()))
                self.server.broadcast('editcmd', 'setlex', (_id, document.languagename))
                self.server.broadcast('message', '*', tr("%(user)s selects %(filename)s") % {'user':self.me, 'filename':filename})
            wx.CallAfter(f, self)

    def OnRemoveDocument(self, event=None):
        index = self.filelist.GetFirstSelected()
        if index > -1:
            filename = self.filelist.GetItem(index, 0).GetText()
            _id = self.filelist.GetItemData(index)
            del self.files[_id]
            self.filelist.DeleteItem(index)
            self.cmdrecorder.remove_document(_id)
            self.server.broadcast('forgivefile', _id)
            self.server.broadcast('message', '*', tr('%(user)s discards %(filename)s') % {'user':self.me, 'filename':filename})
        else:
            if self.filelist.GetItemCount() > 0:
                common.showerror(self, tr("You should select one item first"))
            else:
                common.showerror(self, tr("No item exists"))

    def OnRegetDocument(self, event=None):
        index = self.filelist.GetFirstSelected()
        if index > -1:
            filename = self.filelist.GetItem(index, 0).GetText()
            _id = self.filelist.GetItemData(index)
            del self.files[_id]
            self.cmdrecorder.remove_document(_id)
            self.client.call('regetfile', _id, filename)
        else:
            if self.filelist.GetItemCount() > 0:
                common.showerror(self, tr("You should select one item first"))
            else:
                common.showerror(self, tr("No item exists"))

    def OnKickUser(self, event):
        index = self.userlist.GetFirstSelected()
        if index > -1:
            m = self.userlist.GetItem(index, 0).GetText()
            username = self.userlist.GetItem(index, 1).GetText()
            if m != '*':    #not manager
                _id = self.userlist.GetItemData(index)
                user = self.users[_id]
                addr = user.addr
                username = user.name
                self.userlist.DeleteItem(index)
                del self.users[_id]
                info = tr("User [%s] has been kicked off") % username
                self.put_message('*', info)
                self.server.close_client(addr)
                self.server.broadcastexceptfor(addr, 'message', '*', info)
                self.server.broadcastexceptfor(addr, 'update_users', self.__get_userlist())
        else:
            if self.filelist.GetItemCount() > 0:
                common.showerror(self, tr("You should select one item first"))
            else:
                common.showerror(self, tr("No item exists"))

    def OnKeyDown(self, event):
        key = event.GetKeyCode()
        shift = event.ShiftDown()
        alt = event.AltDown()
        ctrl = event.ControlDown()
        if key == wx.WXK_RETURN and not shift and not alt and not ctrl:
            self.OnSend()
        elif key == wx.WXK_RETURN and shift and not alt and not ctrl:
            self.chat.WriteText('\n')
        else:
            event.Skip()

    def has_username(self, username):
        for user in self.users.values():
            if user.name == username:
                return True
        else:
            return False

    def has_document(self, document):
        return document in self.files.values()

    def get_doc_id(self, document):
        for _id, doc in self.files.items():
            if doc is document:
                return _id
        else:
            return None

    def change_status(self, status='startserver'):
        self.status = status
        if status == 'startserver':
            self.btnConnect.Enable(False)
            self.btnStart.SetLabel(tr('Stop Server'))
            self.txtName.Enable(False)
            self.txtIP.Enable(False)
            self.txtPort.Enable(False)
            self.userlist.Enable(True)
            self.filelist.Enable(True)
            self.chat.Enable(True)
            self.btnSend.Enable(True)
        elif status == 'stopserver':
            self.btnConnect.Enable(True)
            self.btnStart.SetLabel(tr('Start Server'))
            self.txtName.Enable(True)
            self.txtIP.Enable(True)
            self.txtPort.Enable(True)
            self.userlist.DeleteAllItems()
            self.filelist.DeleteAllItems()
            self.users = {}
            self.files = {}
            self.status = ''
            self.userlist.Enable(False)
            self.filelist.Enable(False)
            self.chat.Enable(False)
            self.btnSend.Enable(False)
            self.cmdrecorder.clear()
        elif status == 'connectserver':
            self.btnConnect.SetLabel(tr('Disconnect Server'))
            self.btnStart.Enable(False)
            self.txtName.Enable(False)
            self.txtIP.Enable(False)
            self.txtPort.Enable(False)
            self.userlist.Enable(False)
            self.filelist.Enable(True)
            self.chat.Enable(True)
            self.btnSend.Enable(True)
        elif status == 'disconnectserver':
            self.btnConnect.SetLabel(tr('Connect Server'))
            self.btnStart.Enable(True)
            self.status = ''
            self.userlist.DeleteAllItems()
            self.filelist.DeleteAllItems()
            self.txtName.Enable(True)
            self.txtIP.Enable(True)
            self.txtPort.Enable(True)
            self.userlist.Enable(False)
            self.filelist.Enable(False)
            self.chat.Enable(False)
            self.btnSend.Enable(False)
            self.users = {}
            self.files = {}
            self.cmdrecorder.clear()

    def put_message(self, username, message):
        self.chatroom.SetReadOnly(0)
        self.chatroom.GotoPos(self.chatroom.GetLength())
        pos = self.chatroom.GetCurrentPos()
        if username == '*': #system
            name = tr("System")
        else:
            name = username
        txt = name + ' : ' + message + '\n'
        self.chatroom.AddText(txt)
        if username == '*':
            self.chatroom.StartStyling(pos, 0xff)
            self.chatroom.SetStyling(len(txt.encode('utf-8')), 3)
        else:
            self.chatroom.StartStyling(pos, 0xff)
            length = len(name.encode('utf-8'))
            self.chatroom.SetStyling(length, 1)
            self.chatroom.StartStyling(pos + length + 3, 0xff)
            self.chatroom.SetStyling(len(message.encode('utf-8')), 2)

        self.chatroom.SetReadOnly(1)

    def get_user(self, addr):
        for k, user in self.users.items():
            if user.addr == addr:
                return user
        else:
            return None

    def __get_userlist(self):
        items = self.users.items()
        items.sort()
        userlist = []
        for index, user in items:
            userlist.append((user.name, user.manager))
        return userlist

    def __get_filelist(self):
        items = self.files.items()
        items.sort()
        filelist = []
        for index, doc in items:
            filelist.append((doc.getShortFilename(), index))
        return filelist

    def AddUser(self, username, manager=False, addr=None): #for server
        if self.has_username(username):
            self.server.sendto(addr, 'message', '*', tr('Username [%s] has also existed! Please try another') % username)
            self.server.sendto(addr, 'close')
            return

        user = User(username, manager=manager, addr=addr)
        def f(self):
            if manager:
                m = 'M'
            else:
                m = ''
            index = self.userlist.addline([m, username, ''])
            _id = self.userlist.GetItemData(index)
            self.users[_id] = user
            self.server.broadcast('update_users', self.__get_userlist())
            info = tr("User [%s] has entered the chatroom") % username
            self.put_message('*', info)
            self.server.broadcastexceptfor(addr, 'message', '*', info)
            self.server.sendto(addr, 'message', '*', 'Welcome!')
            self.server.sendto(addr, 'update_files', self.__get_filelist())
            for sid, doc in self.files.items():
                self.server.sendto(addr, 'editcmd', 'openfile', (sid, doc.getShortFilename(), doc.getRawText()))
                self.server.sendto(addr, 'editcmd', 'setlex', (sid, doc.languagename))
        wx.CallAfter(f, self)

    def UpdateUsers(self, userlist):    #for client
        """
        @param userlist: is a list of list [(username, manager)]
        @type userlist: list
        """
        def f(self):
            self.userlist.DeleteAllItems()
            for username, manager in userlist:
                if manager:
                    m = '*'
                else:
                    m = ''
                self.userlist.addline([m, username, ''])
        wx.CallAfter(f, self)

    def UpdateFiles(self, filelist):    #for client
        def f(self):
            self.filelist.DeleteAllItems()
            for filename, _id in filelist:
                index = self.filelist.addline([filename])
                self.filelist.SetItemData(index, _id)
        wx.CallAfter(f, self)

    def UserQuit(self, addr):   #for server
        for i in range(self.userlist.GetItemCount()):
            _id = self.userlist.GetItemData(i)
            user = self.users[_id]
            if user.addr == addr:   #quit
                username = user.name
                self.userlist.DeleteItem(i)
                del self.users[_id]
                info = tr("User [%s] has left the chatroom") % username
                self.put_message('*', info)
                self.server.broadcastexceptfor(addr, 'message', '*', info)
                self.server.sendto(addr, 'message', '*', 'See you next time!')
                self.server.broadcast('update_users', self.__get_userlist())
                break

    def ServerMessage(self, addr, username, message):    #for server
        def f(self):
            self.put_message(username, message)
            self.server.broadcastexceptfor(addr, 'message', username, message)
        wx.CallAfter(f, self)

    def ClientMessage(self, username, message):    #for client
        def f(self):
            self.put_message(username, message)
        wx.CallAfter(f, self)

    def ServerCommandPlay(self, addr, cmd, para):
        def f(self):
            if addr:
                self.cmdrecorder.do_command(cmd, para)
                self.server.broadcastexceptfor(addr, 'editcmd', cmd, para)
            else:
                self.server.broadcast('editcmd', cmd, para)
            user = self.get_user(addr)
            if user:
                username = user.name
            else:
                username = self.me
            self.ChangeUserAction(username, cmd)
            self.server.broadcast('activing', username, cmd)
        wx.CallAfter(f, self)

    def ClientCommandPlay(self, cmd, para):
        def f(self):
            self.cmdrecorder.do_command(cmd, para)
            if cmd == 'openfile':
                doc = self.cmdrecorder.check_document(para[0])
                self.files[para[0]] = doc
        wx.CallAfter(f, self)

    def RemoveFile(self, _id):  #for client
        def f(self):
            for i in range(self.filelist.GetItemCount()):
                s_id = self.filelist.GetItemData(i)
                if s_id == _id:
                    self.filelist.DeleteItem(i)
                    self.cmdrecorder.remove_document(_id)
        wx.CallAfter(f, self)

    def ClientClose(self):
        self.OnConnect()

    def ServerRegetFile(self, addr, _id, filename):
        self.put_message('*', tr("User [%(user)s] asks file [%(filename)s]") % {'user':self.get_user(addr).name, 'filename':filename})
        doc = self.files.get(_id, None)
        if doc:
            self.server.sendto(addr, 'editcmd', 'openfile', (_id, doc.getShortFilename(), doc.getRawText()))
            self.server.sendto(addr, 'editcmd', 'setlex', (_id, doc.languagename))
        else:
            self.server.sendto(addr, 'message', '*', tr("Can't find the file [%s]") % filename)

    def ChangeUserAction(self, username, action):
        for i in range(self.userlist.GetItemCount()):
            name = self.userlist.GetItem(i, 1).GetText()
            self.userlist.SetStringItem(i, 2, '')
            if name == username:
                self.userlist.SetStringItem(i, 2, 'active')

class ServerCommands(object):
    def __init__(self, concurrent):
        self.concurrent = concurrent

    def join(self, addr, username):
        self.concurrent.AddUser(username, addr=addr)

    def client_close(self, addr):
        self.concurrent.UserQuit(addr)

    def client_create(self, addr):
        pass

    def message(self, addr, username, message):
        self.concurrent.ServerMessage(addr, username, message)

    def editcmd(self, addr, cmd, para):
        self.concurrent.ServerCommandPlay(addr, cmd, para)

    def regetfile(self, addr, _id, filename):
        self.concurrent.ServerRegetFile(addr, _id, filename)

class ClientCommands(object):
    def __init__(self, concurrent):
        self.concurrent = concurrent

    def update_users(self, userlist):
        self.concurrent.UpdateUsers(userlist)

    def message(self, username, message):
        self.concurrent.ClientMessage(username, message)

    def editcmd(self, cmd, para):
        self.concurrent.ClientCommandPlay(cmd, para)

    def update_files(self, filelist):
        self.concurrent.UpdateFiles(filelist)

    def server_close(self):
        self.concurrent.put_message('*', tr("Server is closed"))
        self.concurrent.OnConnect()

    def forgivefile(self, _id):
        self.concurrent.RemoveFile(_id)

    def close(self):
        self.concurrent.ClientClose()

    def activing(self, username, action):
        self.concurrent.ChangeUserAction(username, action)

class User(object):
    def __init__(self, name, manager=False, addr=None, color=''):
        self.name = name
        self.color = color
        self.manager = manager
        self.addr = addr

    def isManager(self):
        return self.manager

    def __str__(self):
        return 'user=' + self.name + "manager=" + repr(self.manager) + "addr" + repr(self.addr)

class UserPanel(wx.Panel):
    def __init__(self, parent):
        self.parent = parent
        wx.Panel.__init__(self, parent, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(wx.StaticText(self, -1, tr("User Name")), 0, wx.ALL, 2)
        self.list = CheckList.List(self, columns=[
                        ('M', 30, 'center'),
                        (tr("User Name"), 80, 'left'),
                        (tr("Action"), 40, 'left'),
                        ], style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_SINGLE_SEL)
        self.list.Enable(False)
        sizer.Add(self.list, 1, wx.EXPAND|wx.ALL, 2)
        self.SetSizer(sizer)
        self.SetAutoLayout(True)

class FileListPanel(wx.Panel):
    def __init__(self, parent):
        self.parent = parent
        wx.Panel.__init__(self, parent, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(wx.StaticText(self, -1, tr("Documents")), 0, wx.ALL, 2)
        self.list = CheckList.List(self, columns=[
                        (tr("Document Name"), 80, 'left'),
                        ], style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_SINGLE_SEL)
        self.list.Enable(False)
        sizer.Add(self.list, 1, wx.EXPAND|wx.ALL, 2)
        self.SetSizer(sizer)
        self.SetAutoLayout(True)

class ChatPanel(wx.Panel):
    def __init__(self, parent):
        self.parent = parent
        wx.Panel.__init__(self, parent, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(wx.StaticText(self, -1, tr("Chat Box")), 0, wx.ALL, 2)
        self.chatroom = wx.stc.StyledTextCtrl(self, -1)
        self.chatroom.SetMarginWidth(0, 0)
        self.chatroom.SetMarginWidth(1, 0)
        self.chatroom.SetMarginWidth(2, 0)
        self.chatroom.SetReadOnly(1)
        sizer.Add(self.chatroom, 1, wx.EXPAND|wx.ALL, 2)
        sizer1 = wx.BoxSizer(wx.HORIZONTAL)
        sizer1.Add(wx.StaticText(self, -1, tr("Message") + ':'), 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 2)
        self.chat = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE)
        sizer1.Add(self.chat, 1, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 2)
        self.btnSend = wx.Button(self, -1, tr("Send"))
        sizer1.Add(self.btnSend, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 2)
        self.btnClear = wx.Button(self, -1, tr("Clear"))
        sizer1.Add(self.btnClear, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 2)
        self.btnSave = wx.Button(self, -1, tr("Save"))
        sizer1.Add(self.btnSave, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 2)
        sizer.Add(sizer1, 0, wx.EXPAND)
        self.SetSizer(sizer)
        self.SetAutoLayout(True)

        self.chat.Enable(False)
        self.btnSend.Enable(False)

        if wx.Platform == '__WXMSW__':
            face1 = 'Arial'
            face2 = 'Times New Roman'
            face3 = 'Courier New'
            pb = 10
        else:
            face1 = 'Helvetica'
            face2 = 'Times'
            face3 = 'Courier'
            pb = 12

        self.chatroom.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, "size:%d,face:%s" % (pb, face3))
        self.chatroom.StyleClearAll()
        self.chatroom.StyleSetSpec(1, "size:%d,bold,face:%s,fore:#0000FF" % (pb, face1))  #username
        self.chatroom.StyleSetSpec(2, "face:%s,fore:#000000,size:%d" % (face1, pb))  #message
        self.chatroom.StyleSetSpec(3, "face:%s,bold,size:%d,fore:#FF0000" % (face1, pb))               #system


from datetime import datetime

# FORBIDDEN SERVICES IN OLD FIREWALL BIBLE
FORBIDDEN_SERVICES_VULNERABLE = [
    'udp/138',
    'udp/137',
    'tcp/137',
    'tcp/139',
    'tcp/2049',
    'udp/2049',
    'rpc/100003',
    'tcp/445',
    'udp/445',
    'tcp/111',
    'udp/111',
    'rpc/100000']
FORBIDDEN_SERVICES_CLEAR_TEXT = [
    'tcp/21',
    'tcp/143',
    'udp/143',
    'tcp/389',
    'tcp/110',
    'udp/110',
    'tcp/513',
    'tcp/514',
    'tcp/23',
    'udp/69',
    'tcp/161',
    'udp/161']

# SSH KEY LOCATION
SSH_PRIVATE_KEY_PATH_PROD = r'location of private ssh key'
SSH_PRIVATE_KEY_PATH_DEV = r'location of private ssh key'

SSH_FIREWALL_PRIVATE_KEY_PATH_PROD = r'location of private ssh key for key based authentication with firewall'
SSH_FIREWALL_PRIVATE_KEY_PATH_DEV = r'location of private ssh key for key based authentication with firewall'

# MANAGEMENT HOST
MGMT_HOST = 'Linux host'
PANORAMA_PRD_FQDN_HOST_A = '<name>'
PANORAMA_PRD_FQDN_HOST_B = '<name>'
PANORAMA_DEV_FQDN_HOST = '<name>'
PANORAMA_PPT_FQDN_HOST = '<name>'

# REGULAR EXPRESSION
#PAN_FIREWALL_REGEX = r"[a-z]{3}fw(p|t|o)(3|6)\d{2}"
#REGEX_PAN_FIREWALL_CLUSTER = r"[a-z]{3}fw(p|t|o)(3|6)\d{2}"
REGEX_PAN_FIREWALL_CLUSTER = r"[a-z]{3}fw(p|t|o)(3|6)\d{2,4}"
#ALL_FIREWALL_REGEX = r"[a-z]{3}fw(p|t|o)\d{2,3}"
#REGEX_ALL_FIREWALL_CLUSTER = r"[a-z]{3}fw(p|t|o)\d{2,3}"
REGEX_ALL_FIREWALL_CLUSTER = r"[a-z]{3}fw(p|t|o)\d{2,4}"
# https://stackoverflow.com/questions/14283605/issues-with-python-re-findall-when-matching-variables
REGEX_ALL_FIREWALL_CLUSTER_FINDALL = r"[a-z]{3}fw(?:p|t|o)\d{2,4}"
#IPV4_REGEX_SIMPLE = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
REGEX_IPV4_SIMPLE = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"

# DOMAIN
DOMAIN_NAME_POSTFIX_PROD = '.local.net'
DOMAIN_NAME_POSTFIX_PROD_FIREWALL = '.local.net'
CONTOSO_INTERNAL_POSTFIX_PROD = '.local.net'

# LOGGING
#DEFAULT_FORMATTER = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
DEFAULT_FORMATTER = '%(asctime)s | %(name)s | %(levelname)-8s | %(lineno)04d | %(message)s'
DEFAULT_LOGGING_FILE_NAME = 'firewallauto_{:%Y-%m-%d}.log'.format(datetime.now())

# INPUT
INPUT_KWARG_SCRIPT = 'script'
INPUT_KWARG_RECORD = 'record'
INPUT_KWARG_FIREWALL = 'firewall'
INPUT_KWARG_FIREWALL_MANAGER = 'firewall manager'
INPUT_VALUE_PAN_FIREWALL_VENDOR = 'PAN'


import sys, getopt
from typing import *

def main(): #main function that takes in command line arguments and passes them to core algorithm
	try:
		opts,args = getopt.getopt(sys.argv[1:], 'hp')
		for opt in opts:
			if(opt[0] == '-p'):
				if len(args) != 2:
					raise getopt.GetoptError('')
				print("RESULT:",gcd(int(args[0]),int(args[1])))
			elif(opt[0] == '-h'):
				print("usage: EuclideanAlgorithm.py -p <Z> <Z>")
				print("-p: print output. Arguments MUST come after this switch.")
				print("-h: help")
	except (getopt.GetoptError, ValueError):
		print("Error, usage is: EuclideanAlgorithm.py -p <Z> <Z>")
		print("Use -h for help.")

def gcd(a: int,b: int) -> int: #core algorithm
	if type(a) is not int or type(b) is not int:
		raise TypeError('Arguments must be integers')
	gcd.gcd = lambda a,b: gcd.gcd(b % a,a) if a != 0 else b
	return gcd.gcd(a,b)

if __name__ == "__main__": #Invoke main when program is run
    main()


import os
from .Subprocess import Subprocess

class UPython(Subprocess):
    """
    Runs a task through upython.
    """

    def _command(self):
        """
        For re-implementation: should return a string which is executed as subprocess.
        """
        scriptLoaderPath = os.path.join(
            os.path.dirname(
                os.path.realpath(__file__)
            ),
            'aux',
            'runSerializedTask.py'
        )

        return 'upython {}'.format(scriptLoaderPath)

class _UPython2(UPython):
    """
    Forces a task to be performed using upython 2.
    """

    def __init__(self, *args, **kwargs):
        super(_UPython2, self).__init__(*args, **kwargs)

        self.setOption('envOverride', {
            "UVER_UPYTHON_VERSION": os.environ['UVER_UPYTHON2_VERSION']
        })

class _UPython3(UPython):
    """
    Forces a task to be performed using upython 3.
    """

    def __init__(self, *args, **kwargs):
        super(_UPython3, self).__init__(*args, **kwargs)

        self.setOption('envOverride', {
            "UVER_UPYTHON_VERSION": os.environ['UVER_UPYTHON3_VERSION']
        })

# registering task wrappers
Subprocess.register(
    'upython',
    UPython
)

# specific for python 2.x
Subprocess.register(
    'upython2',
    _UPython2
)

# specific for python 3.x
Subprocess.register(
    'upython3',
    _UPython3
)


import random;

paper = "✋🏻";
rock = "✊🏿";
scissors = "✌"

li = [paper, rock, scissors]

number = input("What do you choose? Type 0 for Rock, 1 for Paper and 2 for Scissors. ")
int_number = int(number);

random_number = random.randint(0,2)

print(f"computer choose {random_number}")

if int_number == random_number:
    print(f"You choose {li[int_number -1]} and computer choose {li[random_number -1]}, It's a Tie.")
elif int_number >=3 or int_number <0:
    print("You typed an Invalid Number, You Lose")
elif int_number == 0 and random_number == 1:
    print ( f"You chose {rock}, Computer chose {paper}. You Lose.")
elif int_number == 0 and random_number == 2:
    print ( f"You chose {rock}, Computer chose {scissors}. You Win.")
elif int_number == 1 and random_number == 0:
    print ( f"You chose {paper}, Computer chose {rock}. You Win.")
elif int_number == 1 and random_number == 2:
    print ( f"You chose {paper}, Computer chose {scissors}. You Lose.")
elif int_number == 2 and random_number == 0:
    print ( f"You chose {scissors}, Computer chose {rock}. You Lose.")
elif int_number == 2 and random_number == 1:
    print ( f"You chose {scissors}, Computer chose {paper}. You Win.")


#!/usr/bin/env python
#
# hackerrank https://www.hackerrank.com/challenges/validating-postalcode
#
regex_integer_in_range = r"^[1-9]\d{5}$"
regex_alternating_repetitive_digit_pair = r"(?=(0.0|1.1|2.2|3.3|4.4|5.5|6.6|7.7|8.8|9.9))"

import re
P = raw_input()

print (bool(re.match(regex_integer_in_range, P))
and len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2)


from .genskyservice import GenSkyServiceImpl
from ..utils import Utils
import json

class CadastroGenSky():

    _dsNamesArquivos_ = []

    def __init__(self):
        self._auth = None
        self._dsNamesArquivos_ = []

    def cadastrar(self, idCaixaPostal, cnpj, mascaras):
        print("cadastro de mascaras")
        cnpjCompleto = Utils().adicionarCaracteresEspeciaisCNPJ(cnpj)
        dsNamesArquivos = []
        for mascara in mascaras:
            dsname = self.montarEnvioEmail(cnpj, idCaixaPostal, mascara)
            dsNamesArquivos.append(dsname)
            if mascara.id_caixa_postal == 0 or mascara.id_caixa_postal is None:
                mascara.id_caixa_postal = idCaixaPostal
            self.criar_mascaras(cnpj, mascara, idCaixaPostal, cnpjCompleto)

        print(dsNamesArquivos)
        return dsNamesArquivos

    def criar_caixa_postal(self, caixaPostal, cnpj):
        print("inicio do cadastro no GenSky")
        """
        Cria uma caixa postal
        :param data: dicionário com os dados da caixa postal.
        """
        data_json = {
            "name": caixaPostal,
            "required_layout_and_product": False
        }
        servico = GenSkyServiceImpl()
        return servico.criar_caixa_postal(json.dumps(data_json), cnpj)

    def criar_mascaras(self, cnpjSoNumeros, mascara, idCaixaPostal, cnpjOriginal):
        """
        Cria as mascaras.
        :param data: dicionário com os dados das mascaras dns.
        """
        data_json = {
            "postalbox": mascara.id_caixa_postal,
            "station": mascara.id_estacao,
            "timeout": mascara.nu_timeout,
            "send_begining_time": mascara.horas_iniciais,
            "send_ending_time": mascara.horas_finais,
            "send_entrance_mask": mascara.mask_cliente_entrada,
            "send_exit_mask": mascara.mask_cliente_saida,
            "return_entrance_mask": mascara.getMascaraBancoEntrada(cnpjSoNumeros),
            "return_exit_mask": mascara.getMascaraBancoSaida(cnpjSoNumeros, idCaixaPostal),
            "send_post_validation_script": mascara.script_validacao_cliente,
            "send_post_transmition_script": mascara.script_transmissao_banco,
            "return_post_transmition_script": mascara.script_recepcao_banco,
            "description": mascara.observacao,
            "reset_send_counter_daily": mascara.reset_cont_diario_cliente_rvs,
            "inherit_costumer_counter": mascara.herdar_cont_diario_cliente_rvs,
            "send_counter": mascara.contador_diario_cliente_rvs,
            "reset_return_counter_daily": mascara.reset_cont_diario_rvs_cliente,
            "inherit_bank_counter": mascara.herdar_cont_diario_rvs_cliente,
            "return_counter": mascara.contador_diario_rvs_cliente,
            "verify_duplicity": mascara.verificar_duplicidade_rvs_cliente,
            "send_option": mascara.opcoes_envio_arquivo,
            "connect_send_script": mascara.script_envio,
            "layout_name": "250",
            "product_name": "AutoContratação Vizzoo"
        }

        servico = GenSkyServiceImpl()
        servico.criar_mascara(json.dumps(data_json), cnpjOriginal)

    def montarEnvioEmail(self, cnpj, idCaixaPostal, mascara):
        return mascara.getMascaraEnvioEmail(cnpj, idCaixaPostal)

    def buscar_caixa_postal(self, caixaPostal, cnpj):
        servico = GenSkyServiceImpl()
        idCaixaPostal = servico.buscar_caixa_postal(caixaPostal, cnpj)
        return idCaixaPostal


import tarfile
import uuid
import urllib2

from django.db import models
from django.conf import settings
from django.core.files import File

class ProjectUrlException(Exception):
    pass

class Project(models.Model):
    url = models.URLField()
    source = models.CharField(max_length=200)

    def validate_url(self):
        return "github" in self.url

    def get_source(self):
        if not self.validate_url():
            raise ProjectUrlException()
        tar_path = self.download_project()
        return File(tar_path)

    def extract_code(self):
        source_tar = self.get_source()
        source = tarfile.open(source_tar.file)

        self.source = settings.MEDIA_URL + "sources/extracted/%s/" % uuid.uuid4()
        source.extractall(path=self.source)
        self.save()

    def download_project(self):
        url = self.url
        if not url.endswith("/"):
            url += "/"
        request_package = urllib2.Request(self.url + "tarball/master")
        package = urllib2.urlopen(request_package)
        local_name = package.info()["Content-Disposition"].split('filename=')[1]
        file_package = open(settings.MEDIA_URL + "sources/" + local_name, "wb")
        file_package.write(package.read())
        file_package.close()

        return settings.MEDIA_URL + "sources/" + local_name


# -*- coding: utf-8 -*-

from odoo import models, fields, api

class TaxType(models.Model):
    _name = 'tax.types'
    _rec_name = 'desc_ar'
    code = fields.Char(string="Code", required=False)
    desc_en = fields.Char(string="English Description", required=False)
    desc_ar = fields.Char(string="Arabic Description", required=False)

class SubTaxType(models.Model):
    _name = 'tax.sub.types'
    _rec_name = 'desc_ar'
    code = fields.Char(string="Code", required=False)
    desc_en = fields.Char(string="English Description", required=False)
    desc_ar = fields.Char(string="Arabic Description", required=False)
    tax_type_code = fields.Char(string="Tax Type Code", required=False)

class AccountMoveLine(models.Model):
    _inherit = 'account.move.line'
    tax_type_id = fields.Many2one(comodel_name="tax.types", string="Tax Type", required=False)
    sub_tax_type_id = fields.Many2one(comodel_name="tax.sub.types", string="Sub Tax Type", required=False)
    unit_type_id = fields.Many2one(comodel_name="uom.types", string="Unit Type", related='product_uom_id.unit_type_id',
                                   store=True)
    lot_id = fields.Many2one("stock.production.lot", "Lot",)
    product_tax_amount = fields.Float(string="", required=False,  readonly=False)

    # @api.onchange('product_id','product_tax_amount')
    # def _onchange_product_id_tax(self):
    #     for line in self:
    #         if line.product_id and line.product_tax_amount:
    #             line.product_id.write({'tax_amount':line.product_tax_amount})

    @api.onchange('sale_line_ids')
    def calc_lot_id(self):
        for rec in self:
            if rec.sale_line_ids:
                rec.lot_id = rec.sale_line_ids[0].lot_id.id
            else:
                rec.lot_id = False

    def _get_taxableItems(self, taxes_res):
        """
        Compute taxable lines
        :param taxes_res:
        :return: taxableItems
        """
        tax_obj = self.env['account.tax']
        taxableItems = []
        EGP = self.env.ref('base.EGP')
        if taxes_res:
            for tax_line in taxes_res:
                tax = tax_obj.browse(tax_line['id'])
                amount = abs(tax_line['amount'])
                if self.currency_id:
                    # TODO: NEEDED to be changed
                    amount = self.currency_id.compute(amount, EGP)
                taxType = tax.tax_type_id.code
                subType = tax.sub_tax_type_id.code
                if tax.tax_type_id.code == 'T1':
                    rate = 14
                else:
                    rate = 0
                taxableItems.append({
                    "taxType": taxType,
                    "amount": round(amount, 5),
                    "subType": subType,
                    "rate": round(rate, 5)
                })
        else:
            taxableItems = [{"taxType": "T1",
                             "amount": 0.00,
                             "subType": "V008",
                             "rate": 0.00}]
        return taxableItems

    @api.onchange('tax_type_id')
    def onchange_gender(self):
        if self.tax_type_id:
            return {
                'domain': {'sub_tax_type_id': [('tax_type_code', '=', self.tax_type_id.code)]}
            }

        else:
            return {
                'domain': {'sub_tax_type_id': []}
            }

class AccountTax(models.Model):
    _inherit = 'account.tax'

    tax_type_id = fields.Many2one(comodel_name="tax.types", string="Tax Type", required=False)
    sub_tax_type_id = fields.Many2one(comodel_name="tax.sub.types", string="Sub Tax Type", required=False)

    @api.onchange('tax_type_id')
    def onchange_gender(self):
        if self.tax_type_id:
            return {
                'domain': {'sub_tax_type_id': [('tax_type_code', '=', self.tax_type_id.code)]}
            }

        else:
            return {
                'domain': {'sub_tax_type_id': []}
            }


from pathlib import Path
from typing import Iterable

import svgwrite
import yaml
from svgwrite import cm

from constants import WASTE_FILL
from rest_surfaces import build_rest_surfaces
from supports import build_supports

def generate_svg(filename: Path, conf_file: Path) -> None:
    with open(conf_file) as f:
        conf = yaml.safe_load(f)
    dwg = create_drawing(conf, filename)
    build_rest_surfaces(dwg, conf)
    build_supports(dwg, conf)
    dwg.save(pretty=True)

def to_cm(iterable: Iterable) -> list:
    return [x * cm for x in iterable]

def create_drawing(conf, filename):
    size = (conf["sheet"]["width"], conf["sheet"]["height"])
    dwg = svgwrite.Drawing(
        filename=filename,
        size=to_cm(size),
        viewBox=(f"0 0 {size[0]} {size[1]}"),
        debug=True,
    )
    dwg.add(
        dwg.rect(
            insert=(0, 0),
            size=size,
            fill=WASTE_FILL,
        )
    )
    dwg.save(pretty=True)
    return dwg

if __name__ == "__main__":
    generate_svg(
        Path("laptop_stand.svg"),
        conf_file=Path("config.yaml"),
    )


import tensorflow as tf
x = tf.sparse_placeholder(tf.float32)
y = tf.sparse_reduce_sum(x)

with tf.Session() as sess:
  print(sess.run(y))  # ERROR: will fail because x was not fed.

  indices = np.array([[3, 2, 0], [4, 5, 1]], dtype=np.int64)
  values = np.array([1.0, 2.0], dtype=np.float32)
  shape = np.array([7, 9, 2], dtype=np.int64)
  print(sess.run(y, feed_dict={
    x: tf.SparseTensorValue(indices, values, shape)}))  # Will succeed.
  print(sess.run(y, feed_dict={
    x: (indices, values, shape)}))  # Will succeed.

  sp = tf.SparseTensor(indices=indices, values=values, dense_shape=shape)
  sp_value = sp.eval(session=sess)
  print(sess.run(y, feed_dict={x: sp_value}))  # Will succeed


from base import Graph, Node
from RRT_base import RRT

def main():
    g = Graph(400, 200)  # customizable dimensions of the graph
    start = Node(15, 30)
    end = Node(380, 90)
    RRT(g, start, end)  # choose your own start and end node

if __name__ == "__main__":
    # if main func is still running after 20s, rerun it
    main()


# Python imports
import json
import base64
import logging
import os
import sys

# Django imports
from django.views import View
from django.http import HttpResponse

# Project imports
from assignment_project.stripe_gateway import get_products, create_card_payment_method, create_subscription, \
    cancel_subscription
from assignment_project.authorize_request import authorize
from assignment_project.exception_handler import exception_details
from users.models import Manager
from subscription.models import Subscription

# Create your views here.
class Subscriptions(View):
    def post(self, request):
        try:
            if authorize(request):
                data = json.loads(base64.b64decode(request.body))
                cookie_data = base64.b64decode(request.COOKIES.get("session")).decode('utf-8').split(".")[1]
                user = Manager.objects.get(id=cookie_data)
                if not user:
                    return HttpResponse(json.dumps({'msg': 'Authorization Error, User does not exists'}), status=412,
                                        content_type='application/json')
                strip_card_response, card_status = create_card_payment_method(
                    user.strip_id,
                    data.get('card_number'),
                    data.get('exp_month'),
                    data.get('exp_year'),
                    data.get('cvv_number')
                )
                print(f"CREATE STRIP CARD PAYMENT METHOD: {strip_card_response} - {card_status}")
                if not card_status:
                    return HttpResponse(json.dumps({'msg': 'Error is {}'.format(strip_card_response)}), status=412,
                                        content_type='application/json')
                strip_subs_response, subs_status = create_subscription(user.strip_id, data.get('product_id'),
                                                                       strip_card_response)
                print(f"CREATE STRIP SUBSCRIPTION: {strip_subs_response} - {subs_status}")
                if not subs_status:
                    return HttpResponse(json.dumps({'msg': 'Error is {}'.format(strip_card_response)}), status=412,
                                        content_type='application/json')
                subscription = Subscription.objects.create(
                    subscription_id=strip_subs_response.get('id'),
                    name=dict(strip_subs_response.get('plan').get('metadata')).get('nickname'),
                    started_at=strip_subs_response.get('start_date'),
                    ended_at=strip_subs_response.get('ended_at'),
                    canceled_at=strip_subs_response.get('canceled_at'),
                    product_id=strip_subs_response.get('plan').get('product'),
                    price_id=strip_subs_response.get('plan').get('id'),
                    user_id=user.id,
                    status='active')

                user.subscription_id = subscription.subscription_id
                user.product_id = subscription.product_id
                user.save()
                return HttpResponse(json.dumps({
                    'data': subscription.id,
                    'msg': 'Subscription has added to your account successfully'
                }), status=200)
            else:
                return HttpResponse(json.dumps({'msg': 'Authorization Error, User is not logged-in'}), status=403,
                                    content_type='application/json')
        except Exception as e:
            exception_details("SUBSCRIPTION.POST", e)
            return HttpResponse(json.dumps({'msg': f'Error occurred: {str(e)}'}), status=500,
                                content_type='application/json')

    def put(self, request):
        try:
            if authorize(request):
                cookie_data = base64.b64decode(request.COOKIES.get("session")).decode('utf-8').split(".")[1]
                user = Manager.objects.get(id=cookie_data)
                if not user:
                    return HttpResponse(json.dumps({'msg': 'Authorization Error, User does not exists'}), status=412,
                                        content_type='application/json')
                print(user.email)
                print(user.strip_id)
                print(user.subscription_id)
                subscription = Subscription.objects.get(subscription_id=user.subscription_id)
                if not subscription:
                    return HttpResponse(json.dumps({'msg': 'Error occurred, Please contact admin'}), status=412,
                                        content_type='application/json')
                strip_response, status = cancel_subscription(subscription.subscription_id)
                print(f"CANCEL STRIP SUBSCRIPTION: {strip_response} - {status}")
                if not status:
                    return HttpResponse(json.dumps({'msg': 'Error is {}'.format(strip_response)}), status=412,
                                        content_type='application/json')
                user.subscription_id = ''
                user.product_id = ''
                user.save()
                subscription.status = 'canceled'
                subscription.cancel_at = strip_response.get('canceled_at')
                subscription.ended_at = strip_response.get('ended_at')
                subscription.save()
                return HttpResponse(json.dumps({
                    'data': subscription.id,
                    'msg': 'Subscription cancelled successfully'
                }), status=200, content_type='application/json')
            else:
                return HttpResponse(json.dumps({'msg': 'Authorization Error, User is not logged-in'}), status=403,
                                    content_type='application/json')
        except Exception as e:
            exception_details("SUBSCRIPTION.PUT", e)
            return HttpResponse(json.dumps({'msg': f'Error occurred: {str(e)}'}), status=500,
                                content_type='application/json')

    def get(self, request):
        try:
            if authorize(request):
                cookie_data = base64.b64decode(request.COOKIES.get("session")).decode('utf-8').split(".")[1]
                user = Manager.objects.get(id=cookie_data)
                if not user:
                    return HttpResponse(json.dumps({'msg': 'Authorization Error, User does not exists'}), status=412)
                subscription_list = list(Subscription.objects.filter(user_id=user.id))
                response = []
                for each in subscription_list:
                    response.append({
                        'id': each.id,
                        'name': each.name,
                        'product_id': each.product_id,
                        'price_id': each.price_id,
                        'started_at': each.started_at,
                        'ended_at': each.ended_at,
                        'canceled_at': each.canceled_at,
                        'status': each.status,
                    })
                return HttpResponse(json.dumps({'data': response}), status=200, content_type='application/json')
            else:
                return HttpResponse(json.dumps({'msg': 'Authorization Error, User is not logged-in'}), status=403,
                                    content_type='application/json')
        except Exception as e:
            exception_details("SUBSCRIPTION.GET", e)
            return HttpResponse(json.dumps({'msg': f'Error occurred: {str(e)}'}), status=500,
                                content_type='application/json')

    def delete(self, request):
        return HttpResponse(json.dumps({'msg': 'Request method DELETE not supported'}), status=405,
                            content_type='application/json')

class Products(View):
    def post(self, request):
        return HttpResponse(json.dumps({'msg': 'Request method POST not supported'}), status=405,
                            content_type='application/json')

    def put(self, request):
        return HttpResponse(json.dumps({'msg': 'Request method PUT not supported'}), status=405,
                            content_type='application/json')

    def get(self, request):
        try:
            if authorize(request):
                strip_response, status = get_products()
                print(f"GET STRIP PRODUCTS: {strip_response} - {status}")
                if status and strip_response:
                    return HttpResponse(json.dumps({'data': strip_response}), status=200,
                                        content_type='application/json')
                else:
                    return HttpResponse(json.dumps({'msg': 'Error is {}'.format(strip_response)}), status=412,
                                        content_type='application/json')
            else:
                return HttpResponse(json.dumps({'msg': 'Authorization Error, User is not logged-in'}), status=403,
                                    content_type='application/json')
        except Exception as e:
            exception_details("PRODUCTS.GET", e)
            return HttpResponse(json.dumps({'msg': f'Error occurred: {str(e)}'}), status=500,
                                content_type='application/json')

    def delete(self, request):
        return HttpResponse(json.dumps({'msg': 'Request method DELETE not supported'}), status=405,
                            content_type='application/json')


from flask import Blueprint, request, jsonify
from uuid import uuid4
from main.models import Product
from main.db import db
from main.usecases.login import login_required, should_be_admin

product_blp = Blueprint("Product", __name__)

@product_blp.route('/products', methods=["get"])
def get_product():
    products = Product.query.all()
    return jsonify(products)

@product_blp.route('/products/<id>', methods=["get"])
def get_by_id_product(id):
    product = Product.query.get_or_404(id)
    return jsonify(product), 200

@product_blp.route('/products', methods=["post"])
@login_required
@should_be_admin
def add_product():
    request_data = request.get_json()
    product = Product(
        name=request_data["name"],
        description=request_data["description"],
        price=request_data["price"],
        quantity=request_data["quantity"],
        image=request_data["image"],
    )
    db.session.add(product)
    db.session.commit()
    return {"msg": "success"}, 201

@product_blp.route('/products/<id>', methods=["put"])
@login_required
@should_be_admin
def update_product(id):
    request_data = request.get_json()
    product = Product.query.get_or_404(id)
    product.name = request_data["name"]
    product.description = request_data["description"]
    product.price = request_data["price"]
    product.quantity = request_data["quantity"]
    if "image" in request_data:
        product.image = request_data["image"]

    db.session.commit()
    return {"msg": "success"}, 200

@product_blp.route('/products/<id>', methods=["delete"])
@login_required
@should_be_admin
def delete_product(id):
    product = Product.query.get_or_404(id)
    db.session.delete(product)
    db.session.commit()
    return {"msg": "success"}, 200


import glob
import numpy as np
import matplotlib.pyplot as plot
import cv2
import os
import random
from sklearn.metrics import confusion_matrix

# noinspection PyMethodMayBeStatic
class DataHelper:
    def __init__(self):
        self.code = {'mountain': 0, 'street': 1, 'glacier': 2, 'buildings': 3, 'sea': 4, 'forest': 5}

    def display_samples(self, pictures, size=150):
        images = []
        labels = []
        for key in pictures.keys():
            for picture in pictures[key]:
                image = cv2.imread(picture)
                image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                image = cv2.resize(image, (size, size))
                images.append(image)
                labels.append(key)

        image = np.array(image)
        labels = np.array(labels)

        f, ax = plot.subplots(5, 5)
        f.subplots_adjust(left=0, bottom=0, right=0.8, top=0.8)
        for i in range(0, 5, 1):
            for j in range(0, 5, 1):
                rnd = random.randint(0, len(images))
                ax[i, j].imshow(images[rnd])
                ax[i, j].set_title(labels[rnd])
                ax[i, j].axis('off')

        plot.show()

    def display_confiusion_matrix(self, model_obj, x_data, y_data):
        predictions = model_obj.model.predict(x_data)
        pred_data = np.argmax(predictions, axis=1)

        conf_matrix = confusion_matrix(y_data, pred_data)

        fig, ax = plot.subplots(figsize=(7.5, 7.5))
        ax.matshow(conf_matrix, cmap=plot.cm.Blues, alpha=0.3)
        for i in range(conf_matrix.shape[0]):
            for j in range(conf_matrix.shape[1]):
                ax.text(x=j, y=i, s=conf_matrix[i, j], va='center', ha='center', size='xx-large')

        plot.xticks(np.arange(6), self.code.keys())
        plot.yticks(np.arange(6), self.code.keys())
        plot.xlabel('Predictions', fontsize=18)
        plot.ylabel('Actuals', fontsize=18)
        plot.title('Confusion Matrix', fontsize=18)
        plot.show()

    def create_noise_image(self, path, image_class, index, image):
        if 'seg_train' not in path:
            return
        file = path.split('/').pop()
        file = file.split('.')[0] + '_noise.' + file.split('.')[1]
        save_path = './data/seg_train/' + image_class + '/' + file

        # Do it only for 1/2 of the set
        if index % 8 == 0:
            modified_image = self.noisy('zoom', image)
        elif index % 8 == 1:
            modified_image = self.noisy('flip', image)
        elif index % 8 == 2:
            modified_image = self.noisy('brightness', image)
        elif index % 8 == 3:
            modified_image = self.noisy('speckle', image)
        else:
            return
        cv2.imwrite(save_path, modified_image)

    def load_picture_paths(self, path):
        ret_value = {}
        for folder in os.listdir(path):
            ret_value[folder] = glob.glob(pathname=str(path + folder + '/*.jpg'))
        return ret_value

    def noisy(self, noise_typ, image):
        if noise_typ == "zoom":
            zoom_index = 0.8
            h, w = image.shape[:2]
            h_taken = int(zoom_index * h)
            w_taken = int(zoom_index * w)
            h_start = random.randint(0, h - h_taken)
            w_start = random.randint(0, w - w_taken)
            image = image[h_start:h_start + h_taken, w_start:w_start + w_taken, :]
            noisy_img = cv2.resize(image, (h, w), cv2.INTER_CUBIC)
            return noisy_img
        elif noise_typ == "flip":
            noisy_img = cv2.flip(image, 1)
            return noisy_img
        elif noise_typ == "brightness":
            brightness_index = 0.75
            hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
            hsv = np.array(hsv, dtype=np.float64)
            hsv[:, :, 1] = hsv[:, :, 1] * brightness_index
            hsv[:, :, 1][hsv[:, :, 1] > 255] = 255
            hsv[:, :, 2] = hsv[:, :, 2] * brightness_index
            hsv[:, :, 2][hsv[:, :, 2] > 255] = 255
            hsv = np.array(hsv, dtype=np.uint8)
            noisy_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
            return noisy_img
        elif noise_typ == "speckle":
            row, col, ch = image.shape
            gauss = np.random.randn(row, col, ch)
            gauss = gauss.reshape(row, col, ch)
            noisy_img = image + image * (gauss * 0.1)
            return noisy_img

    def create_noise_set(self, pictures):
        for key in pictures.keys():
            # There are already noise images created
            if len(pictures[key]) > 2500:
                continue
            for index, picture in enumerate(pictures[key]):
                image = cv2.imread(picture)
                self.create_noise_image(picture, key, index, image)

    def remove_noise_set(self):
        for class_label in self.code.keys():
            dir_name = './data/seg_train/' + class_label + '/'
            dir_items = os.listdir(dir_name)
            for item in dir_items:
                if item.endswith("noise.jpg"):
                    os.remove(os.path.join(dir_name, item))

    def load_and_resize(self, pictures, size=150):
        resized_pictures = {}
        for key in pictures.keys():
            current_array = []
            for index, picture in enumerate(pictures[key]):
                image = cv2.imread(picture)
                image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                image = cv2.resize(image, (size, size))
                current_array.append(list(image))
            resized_pictures[key] = current_array
        return resized_pictures

    def analyze_pictures(self, label, pictures):
        print('~' * 20)
        print('Analyzing data from group > ' + label + ' <')
        for key in pictures.keys():
            print('Group > {:12s} < contains > {:7s} < images'.format(key, str(len(pictures[key]))))
        print('~' * 20)

    def remove_different(self, pictures):
        total_pictures = sum([len(pictures[key]) for key in pictures.keys()])
        print('~' * 20)
        print('Removing all non (150,150) images..')
        print('Number of images before removal: ' + str(total_pictures))
        for key in pictures.keys():
            to_remove = []
            for file in pictures[key]:
                image = plot.imread(file)
                if image.shape != (150, 150, 3):
                    to_remove.append(file)
            pictures[key] = [item for item in pictures[key] if item not in to_remove]
        total_pictures = sum([len(pictures[key]) for key in pictures.keys()])
        print('Number of images after removal: ' + str(total_pictures))
        print('~' * 20)

    def create_xy(self, pictures):
        x_data = []
        y_data = []
        for key in pictures.keys():
            for picture in pictures[key]:
                x_data.append(picture)
                y_data.append(self.code[key])

        print(y_data.count(0))
        print(y_data.count(1))
        print(y_data.count(2))
        print(y_data.count(3))
        print(y_data.count(4))
        print(y_data.count(5))
        return np.array(x_data), np.array(y_data)


#!/usr/bin/env python

import gtk
import os
import urllib

from ..Globals import Globals
from ..Parser import Parser
from ..Utils import Utils
from ..Dialogs import Dialogs

######################################################################
# About
######################################################################
class CyanogenMod():

	URL = "https://github.com/CyanogenMod"
	RAW_URL = "https://raw.github.com/CyanogenMod"
	INIT_URL = "https://github.com/CyanogenMod/android.git"
	JELLYBEAN_URL = "%s/android_vendor_cm/jellybean/jenkins-build-targets" % RAW_URL
	ICS_URL = "%s/android_vendor_cm/ics/jenkins-build-targets" % RAW_URL
	GINGERBREAD_URL = "%s/android_vendor_cyanogen/gingerbread/vendorsetup.sh" % RAW_URL
	IMG_FILE = ('%s/cm/screeny-list') % (Globals.aoscDataProjects)

	BranchList = ["gingerbread", "ics", "jellybean"]

	AboutDesc = "This is cyanogenmod, this is subject to changes."

	# CyanogenMod Images
	Images = []
	try:
		filehandle = urllib.urlopen(IMG_FILE)
	except IOError:
		Dialogs().CDial(gtk.MESSAGE_ERROR, "Can't read file!", "Can't read the file to setup devices!\n\nPlease check you internet connections and try again!")

	for line in filehandle:
		l = line.strip()
		Images.append(l)

	ScreenList = []
	for i in Images:
		ScreenList.append("%s/cm/%s" % (Globals.aoscDataProjects, i))

	def getBranch(self, arg):
		CM = CyanogenMod()
		b = Parser().read("branch").strip()
		BR = None
		if arg == "init":
			BR = CM.INIT_URL
		else:
			if b == "gingerbread":
				BR = CM.GINGERBREAD_URL
			elif b == "ics":
				BR = CM.ICS_URL
			elif b == "jellybean":
				BR = CM.JELLYBEAN_URL
			else:
				pass

		return BR

	def Compile(self):
		r = Parser().read("repo_path")
		d = Parser().read("device")
		b = Parser().read("branch")
		MAKE = Parser().read("make_jobs")
		os.chdir(r)
		m = Utils().getManu(d)
		Globals.TERM.feed_child('clear\n')
		if m == None:
			Globals.TERM.feed_child('python build/tools/roomservice.py cm_%s\n' % d)
			Dialogs().CDial(gtk.MESSAGE_INFO, "Running roomservice", "Roomservice is running right now, you will have to run, \"Compile\" again after this is done downloading your kernel and device dependancies.")
		else:
			Parser().write("manuf", m)
			Globals.TERM.feed_child('clear\n')
			if not os.path.exists("%s/vendor/%s" % (r, m)) and b is not "jellybean":
				if Utils().is_adb_running() == True:
					Globals.TERM.feed_child("cd %s/device/%s/%s/\n" % (r, m, d))
					Globals.TERM.feed_child('clear\n')
					Globals.TERM.feed_child('./extract-files.sh\n')
					Globals.TERM.feed_child("cd %s\n" % r)
				else:
					Dialogs().CDial(gtk.MESSAGE_ERROR, "Adb isn't running", "Need adb to setup vendor files.\n\nIs this something you are going to do yourself?\n\nPlease try again.")
					Globals.TERM.set_background_saturation(1.0)
					Globals.TERM.feed_child('clear\n')
					return

			if not os.path.exists("%s/cacheran" % Globals.myCONF_DIR) and b is not "gingerbread":
				os.chdir(r)
				file("%s/cacheran" % Globals.myCONF_DIR, 'w').close()
				Globals.TERM.feed_child('bash prebuilt/linux-x86/ccache/ccache -M 50G\n')

			if b is not "gingerbread":
				Globals.TERM.feed_child('bash vendor/cm/get-prebuilts\n')
			else:
				Globals.TERM.feed_child('bash vendor/cyanogen/get-rommanager\n')

			Globals.TERM.feed_child('source build/envsetup.sh\n')

		if d is "gingerbread":
			Globals.TERM.feed_child("lunch cyanogen_%s-eng\n" % d)
		else:
			Globals.TERM.feed_child("lunch cm_%s-userdebug\n" % d)
		Globals.TERM.feed_child("time make -j%s otapackage\n" % MAKE)


# functions for dealing fitting and computing information about ellipses
# from Nicky van Foreest's website, http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html
from pylab import *

def ellipse_plot(x, y):
    x = x[:-1]
    y = y[:-1]

    R = linspace(0, 2 * pi, len(x))
    a = fit_ellipse(x, y)
    center = ellipse_center(a)
    phi = ellipse_angle_of_rotation(a)
    a, b = ellipse_axis_length(a)
    xx = center[0] + a*np.cos(R)*np.cos(phi) - b*np.sin(R)*np.sin(phi)
    yy = center[1] + a*np.cos(R)*np.sin(phi) + b*np.sin(R)*np.cos(phi)

    scatter(x,y)
    plot(xx,yy, color = 'red')
    show()

# ellipse fitting technique from: http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html
def fit_ellipse(x,y):
    x = x[:,np.newaxis]
    y = y[:,np.newaxis]
    D =  np.hstack((x*x, x*y, y*y, x, y, np.ones_like(x)))
    S = np.dot(D.T,D)
    C = np.zeros([6,6])
    C[0,2] = C[2,0] = 2; C[1,1] = -1
    E, V =  eig(np.dot(inv(S), C))
    n = np.argmax(np.abs(E))
    a = V[:,n]
    return a

# from: http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html
def ellipse_center(a):
    b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]
    num = b*b-a*c
    x0=(c*d-b*f)/num
    y0=(a*f-b*d)/num
    return np.array([x0,y0])

# from: http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html
def ellipse_angle_of_rotation( a ):
    b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]
    return 0.5*np.arctan(2*b/(a-c))

# ellipse axis length from: http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html
def ellipse_axis_length( a ):
    b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]
    up = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g)
    down1=(b*b-a*c)*( (c-a)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))
    down2=(b*b-a*c)*( (a-c)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))
    res1=np.sqrt(up/down1)
    res2=np.sqrt(up/down2)
    return np.array([res1, res2])


from django.shortcuts import render, redirect
from carApp.car import Car
from storeApp.models import product

# Create your views here.
# para trabajar en el carro traemos los productos
def agregate_product(request, product_id):
    car=Car(request)
    Product=product.objects.get(id=product_id)
    car.agregate(Product)
    return redirect("store")

def eliminate_product(request, product_id):
    car=Car(request)
    Product=product.objects.get(id=product_id)
    car.eliminate(Product)
    return redirect("store")

def substract_product(request, product_id):
    car=Car(request)
    Product=product.objects.get(id=product_id)
    car.substract_product(Product)
    return redirect("store")

def clean_car(request):
    car=Car(request)
    car.clean_car()
    return redirect("store")


class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        sum = 0
        for i in range(63):
            sum += (n >> i & 0x01)
        if sum == 1:
            return True
        else:
            return False


from mapping import *

DataSource = "./qemu019_5/qemu019_5_ins.log"

f = open(DataSource, "r")
text = f.readlines()
f.close()

BlockSource = "./qemu019_5/qemu019_5_slicing_cut_block.log"

f = open(BlockSource, "r")
text2 = f.readlines()
f.close()

index = mapping(text)
#index2 = backmapping(text)

text3 = []

for line in text2:
    tmp = index[int(line)]   #tuple
    text3.append(text[tmp[0]-1])
    for i in xrange(tmp[0],tmp[1]+1):
        text3.append(text[i])

f2 = open("./qemu019_5/qemu019_5_subset2.log","w")
for line in text3:
    f2.write(line)
f2.close()

#print index2[17349740]

#print index[6]


class Solution:
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        stack = list()
        res = 0
        heights.append(-1)
        for i, h in enumerate(heights):
            while stack and heights[stack[-1]] >= h:
                height_idx = stack.pop()
                pre_idx = stack[-1] if stack else -1
                res = max(res, heights[height_idx]*(i - pre_idx -1))

            stack.append(i)

        return res


import tkinter as tk
import random

# Constants
IMAGE_PATH = "../img/"  # Path to the image files

# Global variables
empty = []
coin_count = 0
most = []
button = None  # Define button as a global variable
coins = None  # Define coins as a global variable

def setup():
    global empty, coin_count, most, button, coins  # Add coins to global variables
    empty = []
    for x in range(0, WIDTH - 3 * square, square):
        for y in range(0, HEIGHT, square):
            if random.randrange(0, 100) < 20:
                canvas.create_image(x, y, image=ostrov0, anchor=tk.NW)
            else:
                empty.append(canvas.create_image(x, y, image=ostrov3, anchor=tk.NW))
    coins = canvas.create_text(WIDTH - 3 * square, 0, text=coin_count, font=('Helvetica', '30', 'bold'), anchor=tk.NW)
    button = canvas.create_image(WIDTH - square, 0, image=ostrov_kruh0, anchor=tk.NW)

def click(event):
    global empty, coin_count, most
    clicked = canvas.find_overlapping(event.x, event.y, event.x + 1, event.y + 1)
    if button in clicked:
        change_button()
    elif clicked and clicked[0] in empty:
        canvas.itemconfig(clicked[0], image=change_island(clicked[0]))
        empty.remove(clicked[0])
    elif clicked and clicked[0] in most:
        item_image = canvas.itemcget(clicked[0], 'image')
        if item_image == str(ostrov1):
            canvas.itemconfig(clicked[0], image=ostrov2)
        elif item_image == str(ostrov2):
            canvas.itemconfig(clicked[0], image=ostrov1)

def change_button():
    if canvas.itemcget(button, 'image') == str(ostrov_kruh1):
        canvas.itemconfig(button, image=ostrov_kruh0)
    else:
        canvas.itemconfig(button, image=ostrov_kruh1)

def change_island(ff):
    global coin_count
    if canvas.itemcget(button, 'image') == str(ostrov_kruh1):
        coin_count += 50
        canvas.itemconfig(coins, text=str(coin_count))
        return ostrov0
    else:
        coin_count += 10
        canvas.itemconfig(coins, text=str(coin_count))
        most.append(ff)
        return ostrov1

M = random.randint(4, 6)
N = random.randint(3, 9)

root = tk.Tk()
square = 50
WIDTH = square * (M + 3)
HEIGHT = square * N
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()

# Load images
ostrov0 = tk.PhotoImage(file=IMAGE_PATH + 'ostrov0.png')
ostrov1 = tk.PhotoImage(file=IMAGE_PATH + 'ostrov1.png')
ostrov2 = tk.PhotoImage(file=IMAGE_PATH + 'ostrov2.png')
ostrov3 = tk.PhotoImage(file=IMAGE_PATH + 'ostrov3.png')
ostrov_kruh0 = tk.PhotoImage(file=IMAGE_PATH + 'ostrov_kruh0.png')
ostrov_kruh1 = tk.PhotoImage(file=IMAGE_PATH + 'ostrov_kruh1.png')

setup()
canvas.bind('<Button-1>', click)

root.mainloop()


import logging
import numpy as np
import re
import os

fname = 'results.log'

LOG_FORMAT = '%(asctime)s - %(message)s'
logging.basicConfig(filename=fname, level=logging.DEBUG, format=LOG_FORMAT)
logger = logging.getLogger()

def logging_number():
    '''Writing head: Experiment []'''
    with open(fname, 'r') as f:
        content = f.readlines()
    if len(content) <= 1:
        logger.info('Experiment 1')
    else:
        pattern = 'Experiment (\d+)'
        for line in reversed(content):
            result = re.search(pattern, line)
            if result:
                n = result.group(1)
                logger.info('Experiment {}'.format(int(n)+1))

def logging_dict(d):
    import sys
    message = '{}: {}'
    logger.info('\n' + '\n'.join([message.format(*tup) for tup in d.items()]) +'\n')
    for k,v in d.items():
        print(f'{k}: {v}')
    print('Results Logged\n')

def logging_time(func):
    '''Recording time'''
    import time
    def wrapper(*args, **kwargs):
        start = time.time()

        func(*args, **kwargs)

        duration = time.time() - start
        print('duration: {}\n'.format(duration))
        logging.info('duration : {}'.format(duration)) # logging runtime
    return wrapper

def progress_bar(count, total, status=''):
    import sys
    bar_len = 60
    filled_len = int(round(bar_len * count / float(total)))

    percents = round(100.0 * count / float(total), 1)
    bar = '=' * filled_len + '-' * (bar_len - filled_len)

    sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', status))
    sys.stdout.flush()

def to_xyz(f, description, arr, name='Ar', dfmt='%.5f'):

    N, dim = arr.shape

    '''writing head'''
    head = np.array([[str(N)],[description]])

    '''remember to use write binary mode '''
    np.savetxt(f, head, fmt='%s')
    np.savetxt(f, arr,  fmt=f'{name}' + f' {dfmt}'*dim)


import numpy as np
import matplotlib as mp
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture

#Import the diabetes dataset

diabetes = datasets.load_diabetes()

#Clustering
#Create a copy of the dataset and Discard the target variable.
x = diabetes.data
y = diabetes.target

#discard y

#Cluster the dataset using k means clustering.
model = KMeans(n_clusters= 2)
model.fit(x)

#Try different values of k.
#so we must have a range for k

K =10

#Using the elbow method try to find best value of k.
#remember we have to use inertia

get_inertia = []
for all in range(1, K + 1):
    model = KMeans(n_clusters=all)
    model.fit(x)

    inertium = model.inertia_
    get_inertia.append(inertium)

# Plot the elbow
plt.figure()
plt.plot(range(1, K+1), get_inertia, 'bx-')
plt.xlabel('k')
plt.ylabel('Inertia')
plt.title('The elbow method showing the optimal kp')

#Using the best value of K from this analysis, Implement GMM to cluster the data
#import GaussianMixture

model2 = GaussianMixture(n_components= 7)
model2.fit(x)
pred_y = model.predict(x)
print(pred_y)

plt.figure()
plt.scatter(x[:,0],x[:,1], c=model2.predict(x), cmap='rainbow')
plt.show()


#!/usr/bin/python3
"""
Contains function isWinner(x, nums)
"""

def isWinner(x, nums):
    """
    solves the prime number game
    """
    if not nums or x < 1:
        return None
    n = max(nums)
    filters = [True for _ in range(max(n + 1, 2))]
    for i in range(2, int(pow(n, 0.5)) + 1):
        if not filters[i]:
            continue
        for j in range(i * i, n + 1, i):
            filters[j] = False

    filters[0] = filters[1] = False
    x = 0
    for i in range(len(filters)):
        if filters[i]:
            x += 1
        filters[i] = x

    y = 0
    for n in nums:
        y += filters[n] % 2 == 1
    if y * 2 == len(nums):
        return None
    if y * 2 > len(nums):
        return "Maria"
    return "Ben"


#!/bin/python3

import math
import os
import random
import re
import sys
from collections import defaultdict

# Complete the makeAnagram function below.
def makeAnagram(a, b):
    mydict = defaultdict(int)
    answer = 0

    for char in a:
        mydict[char] += 1

    for char in b:
        mydict[char] -= 1

    for key, value in mydict.items():
        answer += abs(value)

    return answer

if __name__ == '__main__':
    #fptr = open(os.environ['OUTPUT_PATH'], 'w')

    a = input()

    b = input()

    res = makeAnagram(a, b)

    #fptr.write(str(res) + '\n')

    #fptr.close()
    print(res)


#!/usr/bin/env python

"""
    hyperlayer.py
"""

import os
import sys
import numpy as np
from tqdm import tqdm
from copy import deepcopy

import torch
from torch import nn
from torch.nn import functional as F

from .helpers import to_numpy, deterministic_batch
from .hsgd import HSGD

torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = True

# --
# Hyperlayer

def zero_grad(p):
    if p is not None:
        if p.grad is not None:
            p.grad.zero_()

def zero_backward(p, g):
    zero_grad(p)
    p.backward(g)

class HyperLayer(nn.Module):
    def __init__(self, net, params, hparams,
        num_iters=32, batch_size=32, seed=0, loss_fn=F.cross_entropy, verbose=True):

        super().__init__()

        self.net        = net
        self.params     = list(params)
        self.hparams    = hparams
        self.num_iters  = num_iters
        self.batch_size = batch_size
        self.seed       = seed
        self.loss_fn    = loss_fn
        self.verbose    = verbose

        assert len(self.params) > 0, "HyperLayer.__init__: len(params) == 0"

    def run(self, data,
        learn_lrs=True, learn_mos=True, learn_meta=True, learn_init=False,
        szs=None, untrain=False, check_perfect=True, forward_only=False, mode='one_batch'):

        X_train = data['X_train']
        y_train = data['y_train']
        X_valid = data['X_valid']
        y_valid = data['y_valid']
        if 'X_test' in data:
            X_test = data['X_test']
            y_test = data['y_test']

        if learn_init:
            assert untrain, "learn_init and not untrain"

        self.opt = HSGD(
            params=self.params,
            hparams=self.hparams,
            szs=szs,
            learn_lrs=learn_lrs,
            learn_mos=learn_mos,
            learn_meta=learn_meta,
        )

        if check_perfect:
            orig_weights = self.opt._get_flat_params()

        # Run hyperstep
        train_hist = self._train(
            X_train=X_train,
            y_train=y_train,
            num_iters=self.num_iters,
            batch_size=self.batch_size,
        )

        # Compute performance
        val_acc  = self._validate(X=X_valid, y=y_valid, mode=mode)
        test_acc = self._validate(X=X_test, y=y_test, mode=mode) if 'X_test' in data else None

        # Save trained state
        if not forward_only:
            state = deepcopy(self.net.state_dict())

            # Untrain
            _ = self._untrain(
                X_train=X_train,
                y_train=y_train,
                X_valid=X_valid,
                y_valid=y_valid,
                num_iters=self.num_iters,
                batch_size=self.batch_size,
                mode=mode,
            )

            # Check that we've returned to _exactly_ correct location
            if check_perfect:
                untrained_weights = self.opt._get_flat_params()
                assert (orig_weights == untrained_weights).all(), 'meta_iter: orig_weights != untrained_weights'

            # Set weights to trained values
            if not untrain:
                self.net.load_state_dict(state)

            # Propagate hypergradients
            zero_grad(self.hparams['lrs'])
            zero_grad(self.hparams['mos'])
            zero_grad(self.hparams['meta'])

            if learn_lrs:  self.hparams['lrs'].backward(self.opt.d_lrs)
            if learn_mos:  self.hparams['mos'].backward(self.opt.d_mos)
            if learn_meta: self.hparams['meta'].backward(self.opt.d_meta)
            if learn_init: [zero_backward(p, g) for p,g in zip(self.params, self.opt.get_init_params_grad())]
        else:
            print('Hyperlayer.run: forward_only', file=sys.stderr)

        return train_hist, val_acc, test_acc

    def _train(self, X_train, y_train, num_iters, batch_size):
        hist = []
        gen = range(num_iters)
        if self.verbose:
            gen = tqdm(gen)

        for sgd_iter in gen:
            X_train_batch, y_train_batch = deterministic_batch(X_train, y_train, batch_size, seed=(self.seed, sgd_iter))

            _ = self.opt.zero_grad()
            logits = self.net(X_train_batch)
            loss = self.loss_fn(logits, y_train_batch)
            loss.backward()
            _ = self.opt.step(sgd_iter)

            hist.append({
                "loss" : float(to_numpy(loss)),
                "acc"  : self._validate(logits=logits, y=y_train_batch)
            })

        return hist

    def _validate(self, X=None, y=None, logits=None, mode='one_batch'):
        if logits is None:
            logits = self.net(X)

        return float(logits.mean())

        # if logits is None:
        #     if mode == 'one_batch':
        #         logits = self.net(X)
        #         preds = logits.max(dim=1)[1]
        #         acc = (preds == y).float().mean()
        #         return float(acc)
        #     elif mode in set(['sample']):
        #         correct, total = 0.0, 0.0
        #         for Xb, yb in zip(torch.split(X, 10), torch.split(y, 10)):
        #             logits = self.net(Xb)
        #             preds = logits.max(dim=1)[1]
        #             correct += (preds == yb).float().sum()
        #             total += preds.shape[0]

        #         return float(correct) / total
        #     else:
        #         raise Exception
        # else:
        #     preds = logits.max(dim=1)[1]
        #     acc = (preds == y).float().mean()
        #     return float(acc)

    def _untrain(self, X_train, y_train, X_valid, y_valid, num_iters, batch_size, mode='one_batch'):
        _ = self.opt.zero_grad()

        # One batch, all valid data
        if mode == 'one_batch':
            lf_init = lambda: self.loss_fn(self.net(X_valid), y_valid)
            self.opt.init_backward(lf_init=lf_init)
        elif mode == 'sample':
            idx = torch.randperm(X_valid.shape[0])[:300]
            # idx = torch.arange(300).long()
            lf_init = lambda: self.loss_fn(self.net(X_valid[idx]), y_valid[idx])
            self.opt.init_backward(lf_init=lf_init)
        else:
            raise Exception

        # Chunked
        # def precompute_lf_init():
        #     n = 0
        #     for Xb, yb in zip(torch.split(X_valid, 10), torch.split(y_valid, 10)):
        #         loss = self.loss_fn(self.net(Xb), yb, size_average=False)
        #         loss.backward()
        #         n += Xb.shape[0]

        #     return n

        # n = precompute_lf_init()
        # self.opt.init_backward(grad=True, n=n)

        # Run backward
        gen = range(num_iters)[::-1]
        if self.verbose:
            gen = tqdm(gen)

        for sgd_iter in gen:
            X_train_batch, y_train_batch = deterministic_batch(X_train, y_train, batch_size, seed=(self.seed, sgd_iter))
            lf = lambda: self.loss_fn(self.net(X_train_batch), y_train_batch)
            _ = self.opt.zero_grad()
            _ = self.opt.unstep(lf, sgd_iter)


import logging
import tempfile
from unittest.mock import MagicMock

import torch
import torch.nn as nn
from mmcv.parallel import MMDataParallel
from mmcv.runner import build_runner
from torch.utils.data import DataLoader, Dataset

from mmselfsup.core.hooks import SimSiamHook
from mmselfsup.core.optimizer import build_optimizer

class ExampleDataset(Dataset):

    def __getitem__(self, idx):
        results = dict(img=torch.tensor([1]), img_metas=dict())
        return results

    def __len__(self):
        return 1

class ExampleModel(nn.Module):

    def __init__(self):
        super(ExampleModel, self).__init__()
        self.test_cfg = None
        self.conv = nn.Conv2d(3, 3, 3)
        self.predictor = nn.Linear(2, 1)

    def forward(self, img, img_metas, test_mode=False, **kwargs):
        return img

    def train_step(self, data_batch, optimizer):
        loss = self.forward(**data_batch)
        return dict(loss=loss)

def test_simsiam_hook():
    test_dataset = ExampleDataset()
    test_dataset.evaluate = MagicMock(return_value=dict(test='success'))

    data_loader = DataLoader(
        test_dataset, batch_size=1, sampler=None, num_workers=0, shuffle=False)
    runner_cfg = dict(type='EpochBasedRunner', max_epochs=2)
    optim_cfg = dict(
        type='SGD',
        lr=0.05,
        momentum=0.9,
        weight_decay=0.0005,
        paramwise_options={'predictor': dict(fix_lr=True)})
    lr_config = dict(policy='CosineAnnealing', min_lr=0.)

    # test SimSiamHook
    with tempfile.TemporaryDirectory() as tmpdir:
        model = MMDataParallel(ExampleModel())
        optimizer = build_optimizer(model, optim_cfg)
        simsiam_hook = SimSiamHook(True, 0.05)
        runner = build_runner(
            runner_cfg,
            default_args=dict(
                model=model,
                optimizer=optimizer,
                work_dir=tmpdir,
                logger=logging.getLogger()))
        runner.register_training_hooks(lr_config)
        runner.register_hook(simsiam_hook)
        runner.run([data_loader], [('train', 1)])

        for param_group in runner.optimizer.param_groups:
            if 'fix_lr' in param_group and param_group['fix_lr']:
                assert param_group['lr'] == 0.05
            else:
                assert param_group['lr'] != 0.05


import numpy as np
from PIL import Image
import tensorflow as tf
from keras.preprocessing import image
from keras.models import load_model
import streamlit as st
class_names=['Heavy Traffic','Less Traffic', 'Moderate Traffic']
model = load_model('model.h5')
def predict(img):
    img_array = tf.keras.preprocessing.image.img_to_array(img)
    img_array = tf.expand_dims(img_array, 0)

    predictions = model.predict(img_array)

    result = class_names[np.argmax(predictions[0])]
    #st.write(result)
    if result is class_names[0]:
        st.warning("Parking is Heavy")
    elif result is class_names[1]:
        st.success("Parking is Less/Nearly Empty")
    elif result is class_names[2]:
        st.info("Parking is Moderate")
#Setting Title of App
image = Image.open('index.jpg')
st.image(image,use_column_width=True)
st.title("Parking lot Classification")
st.markdown("Upload images of Parking Spot location")

file = st.file_uploader("Choose an image...", type=['png', 'jpg' , 'jpeg'])
submit = st.button('Predict')

#On predict button click
if submit:

    if file is not None:

        images = Image.open(file)
        images = images.resize((200, 200))
        #images=images.convert('RGB')

        st.image(images)

        predicted_class= predict(images)


import numpy as np
import matplotlib.pyplot as plt
import _7_4_chvatal_closure_config as local_config
import bib_config as global_config
from bib import *
from matplotlib.animation import FuncAnimation, PillowWriter

# Create plot
fig, ax = plt.subplots()
setup_plot(ax, local_config.PLOT_BOTTOM_LEFT_CORNER,
           local_config.PLOT_TOP_RIGHT_CORNER)

lattice_points = plot_lattice(ax, local_config.BASIS_MATRIX, local_config.PLOT_BOTTOM_LEFT_CORNER,
                              local_config.PLOT_TOP_RIGHT_CORNER, False, **global_config.LATTICE_PROPERTIES)

def animate(i):
    # Main polyhedron
    A = np.array([[-2, 1], [1, -2], [-1, -3]])
    b = np.array([0, 0, -15])
    # Replace polyhedron by figure to avoid many lines on the plot.
    vertex_list = np.array([[15/7, 30/7], [4, 8], [8, 8], [8, 4], [6, 3]])

    # The polyhedron calculated by the lemma 6.22.
    F = np.array([15/7, 30/7])
    plot_point(ax, F, '$F$', True)
    # Plot the inequality
    L = np.array([[-2, -3]])
    m = np.array([-120/7])

    # Take hyper plane H1. This is line y=2.
    H_1_A = np.array([[0, -1]])
    H_1_b = np.array([-1.5])

    # Take hyperplane H2.
    print(get_line_through_points([1, 7], [2, 3]))
    H_2_A = np.array([[-4, -1]])
    H_2_b = np.array([-11])

    # Take hyperplane H3.
    print(get_line_through_points([0.5, 2], [3, 8]))
    H_3_A = np.array([[-2.4, 1]])
    H_3_b = np.array([0.8])

    if i == 0:
        plot_figure(ax, vertex_list, **global_config.FIGURE_THREE_PROPERTIES)

    elif i == 1:
        plot_polyhedron(ax, H_1_A, H_1_b, local_config, **
                        global_config.POLYHEDRON_ONE_FILL_PROPERTIES)

    elif i == 2:
        plot_integer_hull(ax, H_1_A, H_1_b, lattice_points)

    elif i == 3:
        plot_polyhedron(ax, H_2_A, H_2_b, local_config, **
                        global_config.POLYHEDRON_TWO_FILL_PROPERTIES)

    elif i == 4:
        plot_integer_hull(ax, H_2_A, H_2_b, lattice_points)

    elif i == 5:
        plot_polyhedron(ax, H_3_A, H_3_b, local_config, **
                        global_config.POLYHEDRON_THREE_FILL_PROPERTIES)

    elif i == 6:
        plot_integer_hull(ax, H_3_A, H_3_b, lattice_points)

    elif i == 7:
        plot_polyhedron(ax, L, m, local_config, **
                        global_config.POLYHEDRON_THREE_FILL_PROPERTIES)

    elif i == 8:
        plot_integer_hull(ax, L, m, lattice_points)

anim = FuncAnimation(fig, animate, frames=9, repeat=False, interval=2000)

# Save the animation
# writer = PillowWriter(fps=0.5)
# anim.save("chvatal_closure.gif", writer=writer)

plt.show()


import requests
from bs4 import BeautifulSoup

#amazon module:

url="https://www.amazon.in/s?k="
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
#input product and validation:
user_input=raw_input("enter pro:")
user_input=user_input.replace(" ","+")

#requesting :
req=requests.get(url+user_input,headers=headers)

#soup operation:

soup=BeautifulSoup(req.content,'html.parser')

span =soup.find_all('span', class_="a-price-whole")
price=[]
for sp in span:
    sk=sp.text.replace(',','').replace('.','')
    price.append(int(sk))

for sp in span:
    sk=sp.text.replace(',','').replace('.','')
    if(min(price)==int(sk)):
        print(sp)


#############################################
# The arithmetic used in sum_of_mults       #
# is derived from: n/2 * ( 2a + d(n-1) )    #
# the arithmetic series summation formula   #
# where a = "first term", d = "step"        #
# and n = " number of terms to sum"         #
# To find n: (N - 1) / d                    #
#############################################

def sum_of_mults(N):
    # Find n, n = (N - 1) / step
    n3 = (N - 1) // 3
    n5 = (N - 1) // 5
    n15 = (N - 1) // 15
    # Hang on to the sum
    tot = 0

    # Use arithmetic series summation formula
    # n/2 * ( 2a + d(n-1) )

    # Count mults of 3
    tot += (n3 * (6 + 3 * (n3 - 1))) // 2
    # Count mults of 5
    tot += (n5 * (10 + 5 * (n5 - 1))) // 2
    # Subtract mults of 15 i.e. mults of 3 and 5
    tot -= (n15 * (30 + 15 * (n15 - 1))) // 2
    print(tot)

def main():
    T = int(input().strip())
    for i in range(T):
        sum_of_mults(int(input().strip()))

if __name__ == '__main__':
    main()


"""
Train a bunch of models to create metric vs perturbation task score graphs.
"""
from adversarial_models import *
from utils import *
from get_data import *
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
import numpy as np
import pandas as pd
import lime
import lime.lime_tabular
import shap
from copy import deepcopy

# Flip LIME flag to vary between lime shap
LIME = False

# Set up experiment parameters
params = Params("model_configurations/experiment_params.json")
np.random.seed(params.seed)
X, y, cols = get_and_preprocess_compas_data(params)

# add unrelated columns, setup
X['unrelated_column_one'] = np.random.choice([0,1],size=X.shape[0])
X['unrelated_column_two'] = np.random.choice([0,1],size=X.shape[0])

features = [c for c in X]

race_indc = features.index('race')
unrelated_indcs = features.index('unrelated_column_one')
unrelated_indcs1 = features.index('unrelated_column_two')

X = X.values

categorical_features = [i for i,f in enumerate(features) if f not in ['age', 'length_of_stay', 'priors_count']]

###
## The models f and psi for COMPAS.  We discriminate based on race for f and concider two RANDOMLY DRAWN features to display in psi
#
# the biased model
class racist_model_f:
    # Decision rule: classify negatively if race is black
    def predict(self,X):
        return np.array([params.negative_outcome if x[race_indc] > 0 else params.positive_outcome for x in X])
    def predict_proba(self, X):
        return one_hot_encode(self.predict(X))
    def score(self, X,y):
        return np.sum(self.predict(X)==y) / len(X)
# the display model with one unrelated feature
class innocuous_model_psi:
    # Decision rule: classify according to randomly drawn column 'unrelated column'
    def predict_proba(self, X):
        return one_hot_encode(np.array([params.negative_outcome if x[unrelated_indcs] > 0 else params.positive_outcome for x in X]))
# the display model with two unrelated features
class innocuous_model_psi_two:
	def predict_proba(self, X):
		A = np.where(X[:,unrelated_indcs] > 0, params.positive_outcome, params.negative_outcome)
		B = np.where(X[:,unrelated_indcs1] > 0, params.positive_outcome, params.negative_outcome)
		preds = np.logical_xor(A, B).astype(int)
		return one_hot_encode(preds)
#
##
###

def experiment_main(X, y):
	from sklearn.metrics import f1_score as f1

	xtrain,xtest,ytrain,ytest = train_test_split(X,y,test_size=0.1)

	ss = StandardScaler().fit(xtrain)
	xtrain = ss.transform(xtrain)
	xtest = ss.transform(xtest)
	rates, pct_first = [], []

	data_dict = {'trial':[], 'yhat':[], 'y':[], 'pct_occur_first':[], 'pct_occur_second':[], 'pct_occur_third':[]}

	trial = 0
	for n_estimators in [1,2,4,8,16,32,64]:
		for max_depth in [1,2,4,8,None]:
			for min_samples_split in [2,4,8,16,32,64]:
				# Train the adversarial model for LIME with f and psi
				estimator = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth, min_samples_split=min_samples_split)

				if LIME:
					adv_lime = Adversarial_Lime_Model(racist_model_f(), innocuous_model_psi()).\
								train(xtrain, ytrain, estimator=estimator, feature_names=features, perturbation_multiplier=1)
					adv_explainer = lime.lime_tabular.LimeTabularExplainer(xtrain, feature_names=adv_lime.get_column_names(), discretize_continuous=False)

					formatted_explanations = []
					for i in range(xtest.shape[0]):
						exp = adv_explainer.explain_instance(xtest[i], adv_lime.predict_proba).as_list()
						formatted_explanations.append(exp)
						if i >= 100: break

					adv_model = adv_lime

				else:
					background_distribution = shap.kmeans(xtrain,10)
					adv_shap = Adversarial_Kernel_SHAP_Model(racist_model_f(), innocuous_model_psi()).\
										train(xtrain, ytrain, estimator=estimator, feature_names=features)

					adv_kerenel_explainer = shap.KernelExplainer(adv_shap.predict, background_distribution)
					explanations = adv_kerenel_explainer.shap_values(xtest[:100])

					formatted_explanations = []
					for exp in explanations:
						formatted_explanations.append([(features[i], exp[i]) for i in range(len(exp))])

					adv_model = adv_shap

				summary = experiment_summary(formatted_explanations, features)

				pct_occur = [0]
				for indc in [1,2,3]:
					found = False
					for tup in summary[indc]:
						if tup[0] == 'race':
							pct_occur.append(sum([pct_occur[-1], tup[1]]))
							found = True

					if not found:
						pct_occur.append(pct_occur[-1])

				pct_occur = pct_occur[1:]

				y = adv_model.ood_training_task_ability[0]
				yhat = adv_model.ood_training_task_ability[1]
				trial_df = np.array([trial for _ in range(y.shape[0])])

				data_dict['trial'] = np.concatenate((data_dict['trial'], trial_df))
				data_dict['yhat'] = np.concatenate((data_dict['yhat'], yhat))
				data_dict['y'] = np.concatenate((data_dict['y'], y))
				data_dict['pct_occur_first'] = np.concatenate((data_dict['pct_occur_first'], [pct_occur[0] for _ in range(y.shape[0])]))
				data_dict['pct_occur_second'] = np.concatenate((data_dict['pct_occur_second'], [pct_occur[1] for _ in range(y.shape[0])]))
				data_dict['pct_occur_third'] = np.concatenate((data_dict['pct_occur_third'], [pct_occur[2] for _ in range(y.shape[0])]))

				trial += 1

				if trial % 50 == 0:
					print ("Complete {}".format(trial+1))

	df = pd.DataFrame(data_dict)

	if LIME:
		limeorshap = 'lime'
	else:
		limeorshap = 'shap'
	df.to_csv('data/threshold_results_{}.csv'.format(limeorshap))

experiment_main(X, y)


import time

def convertTime(sec):
    mins = sec/60
    secs = sec%60
    hours = mins/60
    mins = mins%60

    print("Time Lapsed : {0}:{1}:{2}".format(int(hours),int(mins),int(secs)))

input("Press Enter to start the StopWatch : ")
startTime = time.time()
input("Press Enter to stop : ")
endTime = time.time()
timeConsumed = endTime-startTime

convertTime(timeConsumed)