#!/usr/bin/env python

from player import Player
from squad import Squad
from manager import Manager

import api as fpl_api

old_diff = False
overall_diff = False

from PyQt5 import QtWidgets, QtCore, QtGui

'''

	To-Do's

		+ blank GW fixture should be black
		+ highlight GW number for specials: DGW, blank, etc.
		+ add selected %
		+ add injury/flag to player name
		- Chip availability

		+ Differentiate between did not play, too early and no fixture
		- Current game score in tooltip
		+ difficulty in future gw tooltip
		- Future fixture tooltips
		+ deal with double game week support

		+ Add total squad value and buying power (sum[selling prices])
		+ checkbox to select transfers in watchlist

'''

# from gui import FPL_Window

# import plot

def main():

	print("main()")

	api = fpl_api.FPL_API()

	watchlist = [
				# "Callum Wilson",
				# "Dasilva",
				# "Malacia",
				# "Botman",
				# "Barnes",
				# "Darwin",
				"Trippier",
				"Zinchenko",
				"Reece",
				"Kyle Walker",
				"Luis D",
				"Haaland",
				"Kane",
				"Mount",
				"Ederson",
				"Lloris",
				"Alisson",
				"Pedro Neto",
				"Rashford",
				]

	manager = Manager("Max",780664,api,authenticate=True)

	manager.get_current_squad()

	window = NewFPL_Window(manager,api,watchlist=watchlist)
	window.show()

	# squad = Squad()

	# for player in players:
	# 	player = Player(player,api)
	# 	# print(player)
	# 	squad.add_player(player)

	# league = []

	# for manager in managers:
	# 	league.append(Manager(manager['name'],manager['id'],api))

class NewFPL_Window():

	def __init__(self,manager,api,watchlist=None):

		## prefs

		self._prevGWcount = 5
		self._nextGWcount = 10
		self._winWidth = 800
		self._winHeight = 600
		self._textSizeGlobal = 15
		self._textSizeScores = 13
		self._textSizeFixs = 13
		self._rowHeightGlobal = 17

		##

		self._api = api
		self._current_gw = api.current_gw

		self._manager = manager

		self._watchlist = watchlist
		if self._watchlist:
			squad = Squad()
			for name in self._watchlist:
				squad.add_player(Player(name,api))
			self._watchlist = squad

		self.app = QtWidgets.QApplication([])
		self.window = QtWidgets.QWidget()
		self.layout = QtWidgets.QVBoxLayout()

		self.window.setWindowTitle("Max's FPL Planner")
		self.app.setFont(QtGui.QFont('Courier', self._textSizeGlobal))

		self.layout.addLayout(self.current_squad_layout())

		# self.create_connections()

		self.window.setLayout(self.layout)

	def current_squad_layout(self):

		layout = QtWidgets.QGridLayout()

		if self._current_gw < self._prevGWcount:
			self._prevGWcount = self._current_gw

		# create the header widgets
		self.create_headers(layout,row_index=0)

		for i,player in enumerate(self._manager.squad.sorted_players):
			self.add_player_row(layout,i+1,player)

		layout.addWidget(QtWidgets.QLabel(""),16,1,alignment=QtCore.Qt.AlignHCenter)

		layout.addWidget(QtWidgets.QLabel("Squad"),17,1,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Bank"),17,2,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Liquid"),17,3,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("#T Free"),17,5,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("#T Made"),17,7,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Chips"),17,9,alignment=QtCore.Qt.AlignHCenter)

		layout.addWidget(QtWidgets.QLabel(str(self._manager._squad_value[-1])),18,1,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel(str(self._manager._bank_balance[-1])),18,2,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel(str(self._manager.purchase_power)),18,3,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel(str(self._manager._transfers_available)),18,5,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel(str(self._manager._transfers_made)),18,7,alignment=QtCore.Qt.AlignHCenter)

		layout.addWidget(QtWidgets.QLabel(""),19,1,alignment=QtCore.Qt.AlignHCenter)

		if self._watchlist:

			self.create_headers(layout,row_index=20)

			for i,player in enumerate(self._watchlist.sorted_players):
				self.add_player_row(layout,i+21,player)

		return layout

	def add_player_row(self,layout,row_index,player):

		layout.addWidget(QtWidgets.QLabel(["GK","DEF","MID","FWD"][player.position_id-1]),row_index,0,alignment=QtCore.Qt.AlignHCenter)

		widget = QtWidgets.QLabel(" "+player.shortteam.ljust(14))
		self.recolor_by_team(widget,player.team_obj)
		layout.addWidget(widget,row_index,1,alignment=QtCore.Qt.AlignHCenter)

		layout.addWidget(QtWidgets.QLabel(player.name),row_index,2,alignment=QtCore.Qt.AlignLeft)

		pp = player.purchase_price
		sp = player.selling_price

		widget = QtWidgets.QLabel(str(pp))
		layout.addWidget(widget,row_index,3,alignment=QtCore.Qt.AlignHCenter)

		widget = QtWidgets.QLabel(str(sp))
		if isinstance(sp,float):
			if sp > pp:
				widget.setStyleSheet("color: green")
			elif sp < pp:
				widget.setStyleSheet("color: red")
		layout.addWidget(widget,row_index,4,alignment=QtCore.Qt.AlignHCenter)

		widget = QtWidgets.QLabel(str(player.price))
		if isinstance(sp,float):
			if pp < player.price:
				widget.setStyleSheet("color: green")
			elif pp > player.price:
				widget.setStyleSheet("color: red")
		layout.addWidget(widget,row_index,5,alignment=QtCore.Qt.AlignHCenter)

		layout.addWidget(QtWidgets.QLabel(str(player.total_points)),row_index,6,alignment=QtCore.Qt.AlignHCenter)

		widget = QtWidgets.QLabel(str(player.net_transfers))
		widget.setFixedHeight(self._rowHeightGlobal)
		if widget.text().startswith("-"):
			widget.setStyleSheet("color: red")
		else:
			widget.setStyleSheet("color: green")
		layout.addWidget(widget,row_index,7,alignment=QtCore.Qt.AlignHCenter)

		# previous and current weeks
		for i in range(self._prevGWcount):
			last = self._prevGWcount == i+1

			gw = self._current_gw-self._prevGWcount+i+1

			if player.num_gwfix(gw) > 1:
				print("XXX")
				print(f'{player} has {player.num_gwfix(gw)} fixtures in GW{gw}')

			score, summary = player.get_event_score(gw,summary=True)

			if score is None:
				widget = QtWidgets.QLabel(" -- ")
			else:
				widget = QtWidgets.QLabel(" "+str(score).rjust(2)+" ")

				if score < 1:
					widget.setStyleSheet("background-color: darkred;""color: white")
				elif score == 2:
					widget.setStyleSheet("background-color: orange")
				elif score > 9:
					widget.setStyleSheet("background-color: darkgreen;""color: white")
				elif score > 5:
					widget.setStyleSheet("background-color: lightgreen")
				elif score > 2:
					widget.setStyleSheet("background-color: yellow")
				elif score > 0:
					widget.setStyleSheet("background-color: red")

			widget.setToolTip(summary)

			widget.setFont(QtGui.QFont('Courier', self._textSizeScores))

			layout.addWidget(widget,row_index,8+i,alignment=QtCore.Qt.AlignHCenter)

		# form
		score = float(player.form)
		widget = QtWidgets.QLabel(" "+str(score).rjust(4)+" ")

		if score < 1:
			widget.setStyleSheet("background-color: darkred;""color: white")
		elif score == 2:
			widget.setStyleSheet("background-color: orange")
		elif score > 9:
			widget.setStyleSheet("background-color: darkgreen;""color: white")
		elif score > 5:
			widget.setStyleSheet("background-color: lightgreen")
		elif score > 2:
			widget.setStyleSheet("background-color: yellow")
		elif score > 0:
			widget.setStyleSheet("background-color: red")

		widget.setFont(QtGui.QFont('Courier', self._textSizeScores))

		layout.addWidget(widget,row_index,9+self._prevGWcount,alignment=QtCore.Qt.AlignHCenter)

		# future weeks
		for i in range(self._nextGWcount):

			gw = self._current_gw+i+1

			if player.num_gwfix(gw) > 1:
				print(f'{player} has {player.num_gwfix(gw)} fixtures in GW{gw}')

				if player.num_gwfix(gw) == 2:

					fix_strs = player.get_fixture_str(gw,short=True)
					diffs = player.get_fixture_diff(gw,old=old_diff,overall=overall_diff)

					widget1 = QtWidgets.QLabel(fix_strs[0])
					widget2 = QtWidgets.QLabel(fix_strs[1])

					widget1.setFont(QtGui.QFont('Courier', self._textSizeFixs))
					widget2.setFont(QtGui.QFont('Courier', self._textSizeFixs))

					self.adjust_colour_by_diff(widget1,diffs[0],old=old_diff)
					self.adjust_colour_by_diff(widget2,diffs[1],old=old_diff)

					sublayout = QtWidgets.QHBoxLayout()
					sublayout.addWidget(widget1)
					sublayout.addWidget(widget2)

					layout.addLayout(sublayout,row_index,10+self._prevGWcount+i,alignment=QtCore.Qt.AlignHCenter)

			else:
				widget = QtWidgets.QLabel(" "+player.get_fixture_str(gw,short=True)+" ")

				difficulty = player.get_fixture_diff(gw,old=old_diff,overall=overall_diff)
				self.adjust_colour_by_diff(widget,difficulty,old=old_diff)

				widget.setFont(QtGui.QFont('Courier', self._textSizeFixs))

				layout.addWidget(widget,row_index,10+self._prevGWcount+i,alignment=QtCore.Qt.AlignHCenter)

		diff = sum([player.get_fixture_diff(self._current_gw+i+1,old=old_diff,overall=overall_diff) for i in range(self._nextGWcount)
				if isinstance(player.get_fixture_diff(self._current_gw+i+1,old=old_diff,overall=overall_diff),float)])/self._nextGWcount
		widget = QtWidgets.QLabel(' '+f'{diff:4.1f} ')
		self.adjust_colour_by_diff(widget,diff,old=old_diff)
		layout.addWidget(widget,row_index,11+self._prevGWcount+self._nextGWcount,alignment=QtCore.Qt.AlignHCenter)

	def create_headers(self,layout,row_index=0):

		layout.addWidget(QtWidgets.QLabel("Pos."),row_index,0,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Team"),row_index,1,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Player"),row_index,2,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Purc. £"),row_index,3,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Sell. £"),row_index,4,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Curr. £"),row_index,5,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Tot. Pts."),row_index,6,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Trans."),row_index,7,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Form"),row_index,9+self._prevGWcount,alignment=QtCore.Qt.AlignHCenter)
		layout.addWidget(QtWidgets.QLabel("Diff."),row_index,11+self._prevGWcount+self._nextGWcount,alignment=QtCore.Qt.AlignHCenter)

		for i in range(self._prevGWcount):
			layout.addWidget(QtWidgets.QLabel("GW"+str(self._current_gw-self._prevGWcount+i+1)),row_index,8+i,alignment=QtCore.Qt.AlignHCenter)

		for i in range(self._nextGWcount):
			layout.addWidget(QtWidgets.QLabel("GW"+str(self._current_gw+i+1)),row_index,10+self._prevGWcount+i,alignment=QtCore.Qt.AlignHCenter)

	def show(self):
		self.window.show()
		self.app.exec()

	def adjust_colour_by_diff(self,widget,difficulty,old=False):

		if old:
			if difficulty == 5:
				widget.setStyleSheet("background-color: darkred;""color: white")
			elif difficulty == 4:
				widget.setStyleSheet("background-color: red")
			elif difficulty == 2:
				widget.setStyleSheet("background-color: lightgreen")
			elif difficulty == 1:
				widget.setStyleSheet("background-color: darkgreen;""color: white")
			return

		else:

			# ranges from -4 to +4

			if not isinstance(difficulty,float):
				widget.setStyleSheet("background-color: black;""color: white")
				return

			if abs(difficulty) < 1.0:
				return
			elif difficulty > 0.0:
				if difficulty < 2.0:
					widget.setStyleSheet("background-color: lightgreen")
				else:
					widget.setStyleSheet("background-color: darkgreen;""color: white")
			elif difficulty < 0.0:
				if difficulty > -2.0:
					widget.setStyleSheet("background-color: red")
				else:
					widget.setStyleSheet("background-color: darkred;""color: white")

	def recolor_by_team(self,widget,team):

		style = team._style

		if style is None:
			return

		widget.setStyleSheet(f"background-color: {style['background-color']}; color: {style['color']}")

if __name__ == '__main__':
	main()


#color-finder

import numpy
import cv

capture = cv.CaptureFromCAM(0)
imageSize = 1280, 720

h = 0
s = 0
v = 0

channels3 = cv.CreateImage(imageSize, 8, 3)
channels1 = cv.CreateImage(imageSize, 8, 1)

while True:
        frame = cv.QueryFrame(capture)
        clone = cv.CloneImage(frame)
        hsv = cv.CloneImage(channels3)
        threshold = cv.CloneImage(channels1)
        threshold2 = cv.CloneImage(channels1)

        cv.CvtColor(clone, hsv, cv.CV_BGR2HSV)
        cv.InRangeS(hsv, (110, 120, 75),
                    (140, 255, 255),
                   threshold)
        cv.InRangeS(hsv, (110, 120, 75),
                    (140, 255, 255),
                    threshold2)
        cv.Add(threshold, threshold2, threshold)
        cv.Erode(threshold, threshold, iterations = 5)
        cv.Dilate(threshold, threshold, iterations = 5)

        cv.ShowImage("normal", frame)

        cv.ShowImage("color", threshold)

 #       h += 1
        s += 1
        s %= 255
 #       v += 1


import sys
import numpy as np
import gdal
import os
import math
import re
import csv
import subprocess

class TerrainFinder:
    def __init__(self):
        self.pathRoot=''
        self.pathHome=''
        self.pathGrid=''
        self.pathCentroids=''
        self.pathDEM=''
        self.pathLow=self.pathHome+'/cubesUp.txt'
        self.pathUp=self.pathHome+'/cubesLow.txt'
        self.pathcsvfile1step='/solution1step.txt'
        self.pathcsvfile2step='/solution2step.txt'
        self.variables={}
        self.variables['v1step']=1
        self.variables['v2step']=5
        test.pathGPS0=''
        test.pathGPS1=''
        test.pathInclinometer=''
        self.stringsG=[]
        self.stringsI=[]

    def grid_construction(self):
        self.grid = np.array(list(csv.reader(open(self.pathGrid, "rb"), delimiter=" "))).astype("float")
        self.centroids = np.array(list(csv.reader(open(self.pathCentroids, "rb"), delimiter=" "))).astype("float")
        landslide=self.centroids
        landslide=np.delete(landslide, 1, axis=1)
        cubesLow=np.zeros((len(landslide),2,2),dtype=int)
        cubesUp=np.zeros((len(landslide),2,2),dtype=int)
        count=0
        for row in landslide:
            low=np.zeros((2,2),dtype=int)
            up=np.zeros((2,2),dtype=int)
            eucledian=np.array([])
            cube=np.array([])
            cubeUp=np.array([])
            cubeLow=np.array([])
            cubeUpNorth=np.array([])
            cubeUpSouth=np.array([])
            cubeLowNorth=np.array([])
            cubeLowSouth=np.array([])
            cubeUpNorthWest=np.array([])
            cubeUpNorthEast=np.array([])
            cubeUpSouthWest=np.array([])
            cubeUpSouthEast=np.array([])
            cubeLowNorthWest=np.array([])
            cubeLowNorthEast=np.array([])
            cubeLowSouthWest=np.array([])
            cubeLowSouthEast=np.array([])
            for rows in self.grid:
                dist=np.float(math.sqrt(np.sum((row[1:]-rows[1:])**2)))
                eucledian=np.append(eucledian,dist)
            a=np.vstack((eucledian,self.grid.T)).T
            a=a[np.argsort(a[:,0])]
            cube=a[:8,1:]
            cube=cube[np.argsort(cube[:,3])]
            ####
            cubeLow=cube[:4,:]
            cubeUp=cube[4:,:]
            cubeLow=cubeLow[np.argsort(cubeLow[:,2])]
            cubeUp=cubeUp[np.argsort(cubeUp[:,2])]
            ####
            cubeLowSouth=cubeLow[:2,:]
            cubeLowNorth=cubeLow[2:,:]
            cubeUpSouth=cubeUp[:2,:]
            cubeUpNorth=cubeUp[2:,:]
            cubeLowSouth=cubeLowSouth[np.argsort(cubeLowSouth[:,1])]
            cubeLowNorth=cubeLowNorth[np.argsort(cubeLowNorth[:,1])]
            cubeUpSouth=cubeUpSouth[np.argsort(cubeUpSouth[:,1])]
            cubeUpNorth=cubeUpNorth[np.argsort(cubeUpNorth[:,1])]
            ####
            cubeLowSouthWest=cubeLowSouth[0,:]
            cubeLowSouthEast=cubeLowSouth[1,:]
            cubeLowNorthWest=cubeLowNorth[0,:]
            cubeLowNorthEast=cubeLowNorth[1,:]
            cubeUpSouthWest=cubeUpSouth[0,:]
            cubeUpSouthEast=cubeUpSouth[1,:]
            cubeUpNorthWest=cubeUpNorth[0,:]
            cubeUpNorthEast=cubeUpNorth[1,:]
            ####
            low=np.array([[cubeLowNorthWest[0],cubeLowNorthEast[0]],[cubeLowSouthWest[0],cubeLowSouthEast[0]]]).astype(int)
            up=np.array([[cubeUpNorthWest[0],cubeUpNorthEast[0]],[cubeUpSouthWest[0],cubeUpSouthEast[0]]]).astype(int)
            cubesLow[count,:,:]=low
            cubesUp[count,:,:]=up
            count=count+1
        with open(self.pathLow,'wb') as f:
            for a in cubesLow:
               np.savetxt(f, a, fmt='%10d')
               f.write('\n')
        with open(self.pathUp,'wb') as f:
            for a in cubesUp:
               np.savetxt(f, a, fmt='%10d')
               f.write('\n')

    def input_data(self):
        self.PM1=len(self.stringsG)
        self.PM2=len(self.stringsI)
        self.dem=self.pathDEM
        self.grid = np.array(list(csv.reader(open(self.pathGrid, "rb"), delimiter=" "))).astype("float")
        self.centroids = np.array(list(csv.reader(open(self.pathCentroids, "rb"), delimiter=" "))).astype("float")
        f=np.loadtxt(self.pathUp).astype(int)
        self.cubesL=np.zeros((len(f)/2,2,2),dtype=int)
        countf=0
        for i in range(0,len(f),2):
            self.cubesL[countf,:,:]=f[i:i+2,:]
            countf=countf+1
        ff=np.loadtxt(self.pathLow).astype(int)
        self.cubesU=np.zeros((len(ff)/2,2,2),dtype=int)
        countff=0
        for i in range(0,len(ff),2):
            self.cubesU[countff,:,:]=ff[i:i+2,:]
            countff=countff+1

    def CentroidPixel(self):
        src_ds=gdal.Open(self.dem)
        gt=src_ds.GetGeoTransform()
        rb=src_ds.GetRasterBand(1)
        arr = np.float16(rb.ReadAsArray())
        [rows, columns]=np.shape(arr)#dem dimensions
        gdal.UseExceptions()#it doesn't print to screen everytime point is outside grid
        mx=None
        my=None
        self.q=None
        mx=self.first[0]
        my=self.first[1]
        self.q=self.first[2]
        self.LowerLeft=np.array([gt[0],gt[3]-(rows*gt[1])])
        self.LowerLeft[0]=self.LowerLeft[0]
        self.LowerLeft[1]=self.LowerLeft[1]
        self.cx=None
        self.cy=None
        self.cx=mx-self.LowerLeft[0]
        self.cy=my-self.LowerLeft[1]
        src_ds=None

    def NearestCentroidFlug3d(self):
        self.ref=None
        self.ref=10000
        id=None
        id=1
        count=0
        for row in self.centroids:
            if row[1]==1 or row[1]==2:
                diff=None
                vect=None
                vect=math.sqrt((self.cx-row[2])**2+(self.cy-row[3])**2+(self.q-row[4])**2)
                if vect < self.ref:
                    self.ref=None
                    self.ref=vect
                    self.id_ref=None
                    self.id_ref=row[0]
                    row_ref=np.array([])
                    row_ref=row
                    diff_ref=None
                    diff_ref=diff
                    self.xyz=np.array([])
                    self.xyz=np.array([row[2], row[3], row[4]])
                rows=np.array([row[0],row[2], row[3], row[4]])
                count=count+1
            id=id+1
        if row_ref[1]==0:
            print('wrong point of reference!!!!')
        elif row_ref[1]==1:
            print('landslide n°1')
        else:
            print('landslide n°2')

    def PolarCoordinatesflac(self):
        #print(lineflac)
        if self.lineflac[1]==0 or self.lineflac[2]==0:
            b=0
        else:
            b=abs(math.atan(float(self.lineflac[2])/float(self.lineflac[1])))
        #print(lineflac,b)
        if self.lineflac[1]>0 and self.lineflac[2]>0:
            self.gamma=math.pi/2.-b
        elif self.lineflac[1]>0 and self.lineflac[2]<0:
            self.gamma=math.pi-(math.pi/2.-b)
        elif self.lineflac[1]<0 and self.lineflac[2]<0:
            self.gamma=(3./2.)*math.pi-b
        elif self.lineflac[1]<0 and self.lineflac[2]>0:
            self.gamma=2.*math.pi-((math.pi/2.)-b)
        elif self.lineflac[1]>0 and self.lineflac[2]==0:
            self.gamma=math.pi/2.
        elif self.lineflac[1]==0 and self.lineflac[2]<0:
            self.gamma=math.pi
        elif self.lineflac[1]<0 and self.lineflac[2]==0:
            self.gamma=(3./2.)*math.pi
        elif self.lineflac[1]==0 and self.lineflac[2]>0:
            self.gamma=0
        elif self.lineflac[1]==0 and self.lineflac[2]==0:
            self.gamma=None
        xy=math.sqrt((math.pow(self.lineflac[1], 2))+(math.pow(self.lineflac[2], 2)))
        if xy==0 or self.lineflac[3]==0:
            z=0
        else:
            z=abs(math.atan(float(self.lineflac[3])/float(xy)))
        ####
        if xy>0 and self.lineflac[3]>0:
            self.omega=math.pi/2.-z
        elif xy>0 and self.lineflac[3]<0:
            self.omega=math.pi-(math.pi/2.-z)
        elif xy<0 and self.lineflac[3]<0:
            self.omega=(3./2.)*math.pi-z
        elif xy<0 and self.lineflac[3]>0:
            self.omega=2.*math.pi-(math.pi/2.-z)
        elif xy>0 and self.lineflac[3]==0:
            self.omega=math.pi/2.
        elif xy==0 and self.lineflac[3]<0:
            self.omega=math.pi
        elif xy<0 and self.lineflac[3]==0:
            self.omega=(3./2.)*math.pi
        elif xy==0 and self.lineflac[3]>0:
            self.omega=0
        elif xy==0 and self.lineflac[3]==0:
            self.omega=None

    def PolarCoordinates(self):
        if self.line[0]==0 or self.line[1]==0:
            b=0
        else:
            b=abs(math.atan(float(self.line[1])/float(self.line[0])))
        if self.line[0]>0 and self.line[1]>0:
            self.alfa=math.pi/2.-b
        elif self.line[0]>0 and self.line[1]<0:
            self.alfa=math.pi-(math.pi/2.-b)
        elif self.line[0]<0 and self.line[1]<0:
            self.alfa=(3./2.*np.pi)-b
        elif self.line[0]<0 and self.line[1]>0:
            self.alfa=2.*math.pi-(math.pi/2.-b)
        elif self.line[0]>0 and self.line[1]==0:
            self.alfa=math.pi/2.
        elif self.line[0]==0 and self.line[1]<0:
            self.alfa=math.pi
        elif self.line[0]<0 and self.line[1]==0:
            self.alfa=(3./2.)*math.pi
        elif self.line[0]==0 and self.line[1]>0:
            self.alfa=0
        elif self.line[0]==0 and self.line[1]==0:
            self.alfa=None
        ####
        if len(self.line)==3:
            xy=math.sqrt((math.pow(self.line[0], 2))+(math.pow(self.line[1], 2)))
            if xy==0 or self.line[2]==0:
                z=0
            else:
                z=abs(math.atan(float(self.line[2])/float(xy)))
            if xy>0 and self.line[2]>0:
                self.beta=math.pi/2.-z
            elif xy>0 and self.line[2]<0:
                self.beta=math.pi-(math.pi/2.-z)
            elif xy<0 and self.line[2]<0:
                self.beta=(3./2.)*math.pi-z
            elif xy<0 and self.line[2]>0:
                self.beta=2.*math.pi-(math.pi/2.-z)
            elif xy>0 and self.line[2]==0:
                self.beta=math.pi/2.
            elif xy==0 and self.line[2]<0:
                self.beta=math.pi
            elif xy<0 and self.line[2]==0:
                self.beta=(3./2.)*math.pi
            elif xy==0 and self.line[2]>0:
                self.beta=0
            elif xy==0 and self.line[2]==0:
                self.beta=None
        else:
            self.beta=0
    def ReadPerm(self):
        path=os.path.join(self.pathData)
        perm=np.zeros(3,dtype=float)
        perm.fill(100000)
        ListPerm=np.array([(0.,0.,0.,0.,0.,'txt')],dtype='float,float,float,float,float,object')#id,ratio,pl,ver,path
        List2step=np.array([(0.,0.,0.,0.,0.,0.,'txt')],dtype='float,float,float,float,float,float,object')
        AngleErrors=np.zeros((6,2),dtype=float)
        RatioErrors=np.zeros((3,3),dtype=float)
        cc=0
        for filename in os.listdir(path):
            c=0
            if filename.endswith(".log"):
                filenameL=np.array([filename])
                filenamelist=filenameL
                if np.any(self.name==filenamelist):
                    print('next perm')
                else:
                    f = open((os.path.join(path, filename)),"r")
                    lines = f.readlines()
                    CheckAngles=np.zeros((len(self.id), 2), dtype=float)
                    CheckDisp=np.zeros(len(self.id), dtype=float)
                    dispGPS=np.array([])
                    for ii in range(len(self.id)):
                        idL=np.reshape(self.cubesL[self.id[ii]-1,:,:], (1,4)).astype(int)
                        idU=np.reshape(self.cubesU[self.id[ii]-1,:,:], (1,4)).astype(int)
                        gammaV=np.array([])
                        omegaV=np.array([])
                        displacement=np.array([])
                        displaceI=np.array([])
                        for iiii in range(4):
                            #lower quadrant options
                            x=lines[idL[0,iiii]+10-1]
                            List=re.findall("[-+]?\d+[\.]?\d*[eE]?[-+]?\d*", x)
                            self.lineflac=np.array([])
                            self.lineflac=(np.array([float(i) for i in List]))
                            displace=float(math.sqrt((self.lineflac[1])**2+(self.lineflac[2])**2+(self.lineflac[3])**2))
                            displacement=np.append(displacement,displace)
                            self.PolarCoordinatesflac()
                            gammaV=np.append(gammaV,self.gamma)
                            omegaV=np.append(omegaV,self.omega)
                            #upper quadrant options
                            y=lines[idU[0,iiii]+10-1]
                            List=re.findall("[-+]?\d+[\.]?\d*[eE]?[-+]?\d*", y)
                            self.lineflac=np.array([])
                            self.lineflac=(np.array([float(i) for i in List]))
                            displace=float(math.sqrt((self.lineflac[1])**2+(self.lineflac[2])**2+(self.lineflac[3])**2))
                            displacement=np.append(displacement,displace)
                            self.PolarCoordinatesflac()
                            gammaV=np.append(gammaV,self.gamma)
                            omegaV=np.append(omegaV,self.omega)
                            ####
                        sumPlane=float((np.sum(gammaV*displacement))/(np.sum(displacement)))#weighted average
                        sumVert=float((np.sum(omegaV*displacement))/(np.sum(displacement)))#weighted average
                        dispT=float((np.sum(displacement))/(len(displacement)))#weighted average
                        CheckDisp[ii]=dispT
                        CheckAngles[ii, 0]=sumPlane
                        CheckAngles[ii, 1]=sumVert
                        if ii<=len(self.idGPS)-1:
                            modeledDisp=np.sum(displacement)/len(displacement)
                            dispGPS=np.append(dispGPS,modeledDisp)
                    div=np.zeros((len(self.idGPS),len(self.idGPS)),dtype=float)
                    divMeasured=np.zeros((len(self.idGPS),len(self.idGPS)),dtype=float)
                    for s in range(len(self.idGPS)):
                        for ss in range(len(self.idGPS)):
                            div[ss,s]=float(dispGPS[s]/dispGPS[ss])
                            divMeasured[ss,s]=float(self.dispGPSmeasured[s]/self.dispGPSmeasured[ss])
                    fitDiv=(abs(divMeasured-div))
                    ##########removing None value where the points are not moving
                    fit=np.array([])
                    fit1=np.array([])
                    fitt=np.zeros(4)
                    idx=None
                    idx=np.argwhere(np.isnan(CheckAngles))
                    fit=abs(self.mAngle-CheckAngles)
                    if len(idx)>0:
                        print('some points are not valid!!!!!!!!',stop)
                    fitPlaneGps=fit[:self.PM1,0]#planar errors of GPS
                    fitPlaneInc=fit[self.PM1:,0]#planar errors of Invlinometers
                    fitVertGps=fit[:self.PM1,1]#vertical errors of GPS
                    [row,col]=np.shape(fitDiv)
                    dim=row*col
                    ##########################################################
                    #based on average errors
                    #fitPlaneGps=np.array([0])#if we are not considering xy plane of GPS
                    #fitPlaneInc=np.array([0])#if we are not considering xy plane of Inclinometers
                    fitVertGps=np.array([0])#if we are not considering vertical plane GPS
                    #fitDiv=np.array([0])###if we are not considering ratio
                    ##################################################average of the parameters
                    fitt[0]=np.sum((fitPlaneGps/float(np.pi*2))/float(len(fitPlaneGps)))
                    fitt[1]=np.sum((fitPlaneInc/float(np.pi*2))/float(len(fitPlaneInc)))
                    fitt[2]=np.sum((fitVertGps/float(np.pi*2))/float(len(fitVertGps)))
                    fitt[3]=float(np.sum(fitDiv)/dim)
                    ###########################################################
                    #collection of permutations
                    rowPerm=np.array([(cc,fitt[0],fitt[1],fitt[2],fitt[3],filename)], dtype='float,float,float,float,float,object')
                    row2step=np.array([(cc,float((fitt[0]+fitt[1])/2.),fitt[0],fitt[1],fitt[2],fitt[3],filename)], dtype='float,float,float,float,float,float,object')
                    ListPerm=np.append(ListPerm,rowPerm)
                    List2step=np.append(List2step,row2step)
                    AngleErrors=np.dstack((AngleErrors,fit))
                    RatioErrors=np.dstack((RatioErrors,fitDiv))
                    cc=cc+1
        #########################
        ListPerm=ListPerm[1:]#the first is zeros()
        List2step=List2step[1:]#the first is zeros()
        AngleErrors=AngleErrors[:,:,1:]#the first is zeros()
        RatioErrors=RatioErrors[:,:,1:]#the first is zeros()
        ######################
        self.Perm10=[]
        self.Perm1=[]
        ee=np.zeros((1,2),dtype=int)
        eee=np.array([])
        for n in range(len(List2step)):
            aa=List2step[n][0]#count
            ff=List2step[n][1]#h
            dd=List2step[n][5]#r
            eee=np.array([aa,int(ff*1000000)])
            ee=np.vstack((ee,eee))
        ee=ee[1:,:]
        ee=sorted(ee, key=lambda a_entry: a_entry[1])
        ee=np.asarray(ee)
        col=ee[:,1]
        p=int(np.percentile(col, 25))
        idx=np.where(col>=p)
        idx2=int(ee[idx[0][0],0])
        ListPermSorted=sorted(List2step, key=lambda b_entry: b_entry[self.variables['v1step']])
        [item for item in ListPermSorted if item[0] == idx2]
        idx3=[x for x, y in enumerate(ListPermSorted) if y[0] == idx2]
        self.Perm10=ListPermSorted[:idx3[0]]
        ListPerm10=sorted(self.Perm10, key=lambda c_entry: c_entry[self.variables['v2step']])
        self.Perm1=ListPerm10[:self.v2step]#best
        #########################

        #################core functions###########################################
    def GPS(self):
        print('GPS')
        #################################GPS
        self.idGPS=np.zeros((self.PM1), dtype=np.int)
        self.dispGPSmeasured=np.zeros((self.PM1), dtype=float)
        self.mAngleGPS=np.zeros((self.PM1, 2))
        coord=np.array([])
        positionXYZ=np.array([])
        for i in range(self.PM1):
            #open txt file of GPS coordinates
            #fr=['fr1', 'fr2', 'fr2']
            GPS0=os.path.join(self.pathGPS0+'/xxx.txt')
            GPS2=GPS0.replace('xxx', self.stringsG[i])
            #GPS2=GPS1.replace('nnn', fr[i])
            self.first=None
            self.first=np.loadtxt(GPS2)
            positionXYZ=np.append(positionXYZ, self.first)
            GPSfirst0=os.path.join(self.pathGPS0+'/xxx.txt')
            GPSfirst2=GPSfirst0.replace('xxx', self.stringsG[i])
            #GPSfirst2=GPSfirst1.replace('nnn', fr[i])
            self.GPSfirst=np.loadtxt(GPSfirst2)
            GPSsecond0=os.path.join(self.pathGPS1+'/xxx.txt')
            GPSsecond2=GPSsecond0.replace('xxx', self.stringsG[i])
            #GPSsecond2=GPSsecond1.replace('nnn', fr[i])
            self.GPSsecond=np.loadtxt(GPSsecond2)
            self.CentroidPixel()
            self.NearestCentroidFlug3d()
            coord=np.append(coord, self.xyz)
            print('Distance from centroid of reference: %s' %self.ref, 'id centroid of reference: %s' %self.id_ref.astype(int))
            self.line=np.array([])
            self.line=self.GPSsecond-self.GPSfirst
            self.PolarCoordinates()#GPS polar coordinates
            self.mAngleGPS[i, :]=np.array([self.alfa, self.beta])
            self.idGPS[i]=self.id_ref
            self.dispGPSmeasured[i]=float(math.sqrt((self.line[0])**2+(self.line[1])**2+(self.line[2])**2))
        position0=np.reshape(positionXYZ, (self.PM1, 3))
        points=np.reshape(coord, (self.PM1, 3))

    def inclinometers(self):
        print('inclinometers')
        #################################inclinometers
        self.idInc=np.zeros((self.PM2), dtype=np.int)
        self.mAngleInc=np.zeros((self.PM2, 2))
        coord=np.array([])
        positionXYZ=np.array([])
        for i in range(self.PM2):
            self.first=None
            #open txt file of inclinometers coordinates
            #fr=['fr1', 'fr2', 'fr2']
            first0=os.path.join(self.pathInclinometer+'/xxx.txt')
            first2=first0.replace('xxx', self.stringsI[i])
            #first2=first1.replace('nnn', fr[i])
            self.first=np.loadtxt(first2)
            positionXYZ=np.append(positionXYZ, self.first)
            #depth0=os.path.join(self.pathRoot+'/depth_slip_surf_per_inclinometer')
            #depth2=depth0.replace('xxx', self.stringsI[i])
            #depth2=depth1.replace('nnn', fr[i])
            depth=self.first[3]
            self.first[2]=self.first[2]-depth
            self.CentroidPixel()
            self.q=self.q#reference system altitude
            self.NearestCentroidFlug3d()
            coord=np.append(coord, self.xyz)
            print('Distance from centroid of reference: %s' %self.ref, 'id centroid of reference: %s' %self.id_ref.astype(int))
            #disp0=os.path.join(self.pathRoot+'/input_inclinometers')
            #disp2=disp0.replace('xxx', self.stringsI[i])
            #disp2=disp1.replace('nnn', fr[i])
            disp=np.loadtxt(disp2)
            self.line=np.array([self.first[4],self.first[5]])
            #self.line=self.first[3]
            self.PolarCoordinates()
            self.mAngleInc[i, :]=np.array([self.alfa, self.beta])
            self.idInc[i]=self.id_ref
        position0=np.reshape(positionXYZ, (self.PM2, 3))
        points=np.reshape(coord, (self.PM2, 3))######only plane xy

    def GPS_inclinometers(self):
        self.input_data()
        PMs=self.PM1+self.PM2
        self.GPS()
        self.inclinometers()
        self.id=np.append(self.idGPS,self.idInc)
        self.mAngle=np.vstack((self.mAngleGPS,self.mAngleInc))
        #self.name='perm'
        self.name=np.array([])
        self.ReadPerm()
        ########################top first quartile, first step
        self.csvfile1 =os.path.join(self.pathHome+self.pathcsvfile2step)
        with open(self.csvfile1, "w") as output:
            writer = csv.writer(output, lineterminator='\n')
            for val in self.Perm1:
                writer.writerow([val])
        subprocess.check_call([self.pathHome+'/myscript.sh',os.path.join(self.pathHome+self.pathcsvfile2step)])
        ###########################top 10, second step
        self.csvfile10 =os.path.join(self.pathHome+self.pathcsvfile1step)
        with open(self.csvfile10, "w") as output:
            writer = csv.writer(output, lineterminator='\n')
            for val in self.Perm10:
                writer.writerow([val])
        subprocess.check_call([self.pathHome+'/myscript.sh',os.path.join(self.pathHome+self.pathcsvfile1step)])


import pyttsx3
import pytube
import wikipedia
import os
import random
import pyaudio
import datetime
import webbrowser
import speech_recognition as sr

usern=os.environ['USERNAME']
engine= pyttsx3.init('sapi5')
voices=engine.getProperty('voices')
engine.setProperty('voice',voices[0].id)

def speak(text):
    engine.say(text)
    engine.runAndWait()

def recognition():
    s=sr.Recognizer()
    s.energy_threshold=800
    with sr.Microphone() as source:
        print("Listening...")
        audio = s.listen(source)

    try:
        print("Recognizing.....")
        print("Please wait....")
        query=s.recognize_google(audio, language='en-in')
        print(query)
        return query
    except Exception as e:
        print("Something went wrong while recognizing say that again please.")
        print("Check your internet connection")
        speak("Check your internet connection")
        return "None"

def copycatgame():
    speak("Speak any thing")
    while True:
        repeat=recognition().lower()
        if "exit" in repeat:
            speak("Exiting game mode")
            break
        else:
            speak(repeat)
            print(repeat)
def tossgame():
    while True:
        speak("coin is in the air so what you choose heads or tails")
        choose=recognition().lower()
        r=random.randint(1,2)
        if "heads" in choose or "head" in choose:
            if(r==1):
                print("Heads it is")
                speak("Head it is, you won")
            else:
                print("Tails it is")
                speak("tail it is, you loose")
        elif "tails" in choose or "tail" in choose or "tales" in choose or "tale" in choose:
            if(r==1):
                print("Heads it is")
                speak("head it is, you loose")
            else:
                print("Tails it is")
                speak("tail it is, you won")
        elif "exit" in choose:
            speak("exiting game mode")
            break
        else:
            speak("don't cheat, choose either head or tail")
            print("You said "+choose)

def petalsgame():
    randno=int(random.randint(4,9))
    for i in range(randno):
        if i%2==0:
            print("She Loves You")
            speak("she loves you")
        else:
            print("She Loves you not")
            speak("she loves you not")
    print('\a')
    if randno%2==0:
        print("Oh ohh... I Sorry but the petals ended")
        speak("sorry to say but the petals ended")
    else:
        print("Congratulation.... She Loves you")
        speak("congratulation, she loves you")

def remove_char(list1, list2):
	for i in range(len(list1)) :
		for j in range(len(list2)) :
			if list1[i] == list2[j] :
				c = list1[i]
				list1.remove(c)
				list2.remove(c)
				list3 = list1 + ["*"] + list2
				return [list3, True]
	list3 = list1 + ["*"] + list2
	return [list3, False]

def flamesgame():
    print("Enter your name:")
    speak("Enter your name")
    p1=input()
    p1=p1.lower()
    p1_list=list(p1)
    p1.replace(" ","")
    print("Enter your Crush name:")
    speak("enter your crush name")
    p2=input()
    p2=p2.lower()
    p2.replace(" ","")
    p2_list=list(p2)
    proceed=True
    while proceed:
        ret_list=remove_char(p1_list,p2_list)
        con_list=ret_list[0]
        proceed=ret_list[1]
        star=con_list.index("*")
        p1_list=con_list[:star]
        p2_list=con_list[star+1:]
    count=len(p1_list)+len(p2_list)
    reslt=["Friends","Lovers","Arrange marriage","Marriage","Enemies","Siblings"]
    while len(reslt)>1:
        sp=(count%len(reslt)-1)
        if sp>=0:
            right=reslt[sp+1:]
            left=reslt[:sp]
            reslt=right+left
        else:
            reslt=reslt[:len(reslt)-1]
    print(p1+" and "+p2+"'s relationship status is "+reslt[0])
    speak(p1+" and "+p2+"'s relationship status is "+reslt[0])

def lovecalc():
    speak("enter your lover name")
    nme=input()
    speak("enter your name")
    nme1=input()
    r=random.randint(1,100)
    print(nme+" loves "+nme1)
    print("And love percentage is "+str(r)+"%")
    speak("your love percentage is "+str(r)+" percent")
    speak("press any key to exit")
    r=input()
def dicegame():
    r=random.randint(1,6)
    print("Dice shows"+str(r))
    speak("dice shows"+str(r))
    print("Press any key to exit")
    k=input()
def wishing():
    hour=int(datetime.datetime.now().hour)
    if hour >= 0 and hour < 12:
        print("Good Morning "+usern+".. i am Kaushiki... What can i do for you")
        speak("good morning "+usern+", i am kaushiki what can i do for you")
    elif hour >=12 and hour < 13:
        print("Good Noon "+usern+" i am Kaushiki.... What can i do for you")
        speak("good noon "+usern+", i am kaushiki what can i do for you")
    elif hour >=13 and hour < 16:
        print("Good Afternoon "+usern+" Sir... I am Kaushiki your Assistant.. Tell me how can i help you")
        speak("good afternoon "+usern+", sir i am kaushiki your assistant, tell me how can i help you")
    elif hour >=16 and hour < 21:
        print("Good Evening "+usern+" My Friend... I am Kaushiki your virtual helper.. Tell me how can i help you")
        speak("good eveniong "+usern+", my friend, i am kaushiki your virtual helper, tell me how can i help you")
    else:
        print("Good Night Dear "+usern+"... Kaushiki is here for you... Tell me what can i do for you")
        speak("good night dear "+usern+", kaushiki is here for you, tell me what can i do for you")

if __name__ == "__main__":
    wishing()
    while True:
        querry=None
        querry=recognition().lower()
        r=random.randint(1,4)
        if "alexa" in querry or "google assistant" in querry or "siri" in querry or "cortana" in querry:
            print("Please don't compare me with big names, i am your little friend developed by Kaustubh")
            speak("oh! come on dear")
            speak("Please don't compare me with big names, i am your little friend developed by Kaustubh")
        elif "i love you" in querry or "marry me" in querry:
            if(r==1):
                print("awwww.... I am feeling shy")
                speak("I am feeling shy")
            elif(r==2):
                print("but i am a machine... (HUMAN)")
                speak("but i am a machine, human")
            elif(r==3):
                print("but our marriage is not possile")
                speak("bitter truth is that our marriage is not possible")
            else:
                print("can we continue as a friend")
                speak("can we continue as a friend only")
        elif "your developer" in querry or "who developed you" in querry:
            print("My developer is Kaustubh vats")
            speak("my developer is kaustubh vats")
        elif "what can you do" in querry or "features" in querry or "help" in querry:
            print("Ask me to open your Favourite website, Talk to me, Play games, Play videos, Download Youtube Videos, Wikipedia")
            speak("ask me to open your favourite website, talk to me, play games, play videos, download youtube videos, wikipedia")
        elif "how are you" in querry or "how are you doing" in querry:
            print("I am good tell me what can i do for you")
            speak("i am good tell me what can i do for you")
        elif "you are beautiful" in querry or "you are good" in querry:
            print("Thank you for the compliment")
            speak("thank you for the compliment")
        elif "roll a die" in querry:
            dicegame()
        elif "did you know me" in querry or "my name" in querry:
            print("Yes your name is "+usern)
            speak("yes your name is "+usern)
        elif "how do you know me" in querry:
            print("I use your system username as your name")
            speak("I use your system username as your name")
        elif "thanks" in querry or "thank you" in querry:
            print("It's nothing, you are my friend dear")
            speak("It's nothing, you are my friend dear and it is my duty to make you happy")
        elif "time" in querry:
            print(datetime.datetime.now())
            nh=str(datetime.datetime.now().hour)
            nm=str(datetime.datetime.now().minute)
            ns=str(datetime.datetime.now().second)
            speak("currently it is "+nh+" hours "+nm+" minutes and "+ns+" seconds")
        elif "youtube" in querry:
            if "download" in querry:
                print("Paste your Youtube URL here")
                speak("paste your youtube video U R L here")
                video_url = input()
                speak("downloading your video")
                print("Downloading your video")
                try:
                    youtube = pytube.YouTube(video_url)
                    video = youtube.streams.first()
                    video.download('Kaushiki/Download')
                    print("Video Downloaded succesfully")
                    speak("Video Downloaded succesfully press any key")
                    print("Press any key")
                    input()
                except:
                    print("Some error occured")
                    speak("Some error occured")
            else:
                print("Opening youtube..")
                speak("opening youtube")
                webbrowser.open("https://www.youtube.com/")
                speak("welcome to youtube")
                break
        elif "facebook" in querry or "fb" in querry:
            print("Opening Facebook...")
            speak("Opening facebook")
            webbrowser.open("https://www.facebook.com/")
            speak("here is your f b requested page")
            break
        elif "instagram" in querry or "insta" in querry:
            print("opening Instagram...")
            speak("Opening insta gram")
            webbrowser.open("https://instagram.com/")
            speak("Instagram is here")
            break
        elif "whatsapp" in querry:
            print("Opening Whatsapp...")
            speak("opening whatsapp")
            webbrowser.open("https://web.whatsapp.com/")
            speak("welcome to whatsapp")
            break
        elif "cricket" in querry or "live score" in querry:
            print("Live cricket score is here")
            speak("live cricket score is here")
            webbrowser.open("https://www.google.com/search?q=cricket live score")
            speak("these thrilling cricket match is going on check them out")
            break
        elif "videos" in querry or "video" in querry:
            speak("which type of video you want to play")
            vid=recognition()
            speak("sure")
            webbrowser.open("https://www.youtube.com/results?search_query="+vid+"videos")
            break
        elif "google" in querry:
            if "open google" in querry:
                speak("opening google")
                webbrowser.open("https://www.google.co.in/")
                speak("search anything here")
            else:
                querry=querry.replace("google","")
                webbrowser.open("https://www.google.com/search?q="+querry)
                speak("search results from google are here")
            break
        elif "wikipedia" in querry:
            querry=querry.replace("wikipedia","")
            results=wikipedia.summary(querry, sentences=2)
            print("According to wikipedia")
            speak("according to wikipedia")
            print(results)
            speak(results)
            print("Press any key to continue")
            inp=input()
        elif "games" in querry or "game" in querry:
            print("which game you want to play")
            print("1. Toss a coin")
            print("2. Count the petals")
            print("3. roll a dice")
            print("4. copy cat")
            print("5. Love calculator")
            print("6. Flames")
            print("Input the number using keyboard: ")
            speak("input the number using keyboard")
            h=input()
            os.system("cls")
            print("Say exit to exit game mode during playing a game.")
            speak("say exit to exit game mode during playing a game")
            if(h=="1"):
                speak("opening toss a coin game")
                tossgame()
            elif(h=="2"):
                speak("opening count the petals")
                petalsgame()
            elif(h=="3"):
                speak("roll a dice")
                dicegame()
            elif(h=="4"):
                speak("opening copy cat")
                copycatgame()
            elif(h=="5"):
                speak("opening love calculator")
                lovecalc()
            elif(h=="6"):
                speak("opening Flames")
                flamesgame()
            else:
                print("Exiting game mode")
                speak("exiting game mode")

        elif "hello" in querry or "hey" in querry or "hay" in querry:
            if(r==1):
                print("Hello my friend")
                speak("hello my friend")
            elif(r==2):
                print("Hola....            (Hola is Hello in Spanish)")
                speak("hola, hola is Hello in Spanish")
            elif(r==3):
                print("Namaskaar...          (Namaskaar is hello in hindi)")
                speak("namaskaar, namaskaar is hello in hindi")
            else:
                print("Hello dear how can i help you")
                speak("hello dear how can i help you")
        elif "open" in querry:
            querry=querry.replace("open ","")
            querry=querry.replace(" ","")
            print("opening "+querry)
            speak("opening "+querry)
            webbrowser.open("https://www."+querry)
            speak("here is what i found")
            break
        elif "exit" in querry or "bye" in querry:
            print("Bye Bye see you later")
            speak("bye bye see you later")
            break
        elif "none" in querry:
            continue
        else:
            print("Sorry i did not understand")
            speak("sorry i did not understand")
            webbrowser.open("www.google.com/search?q="+querry)
            speak("but here is what i found")
            break


import logging
import os
import random

import numpy as np
import torch
from omegaconf import DictConfig
from torch import Tensor
from torch.utils.data import Dataset

from openspeech.data import AUDIO_FEATURE_TRANSFORM_REGISTRY
from openspeech.data.audio.augment import JoiningAugment, NoiseInjector, SpecAugment, TimeStretchAugment
from openspeech.data.audio.load import load_audio

logger = logging.getLogger(__name__)

class SpeechToTextDataset(Dataset):
    r"""
    Dataset for audio & transcript matching

    Note:
        Do not use this class directly, use one of the sub classes.

    Args:
        dataset_path (str): path of librispeech dataset
        audio_paths (list): list of audio path
        transcripts (list): list of transript
        sos_id (int): identification of <startofsentence>
        eos_id (int): identification of <endofsentence>
        del_silence (bool): flag indication whether to apply delete silence or not
        apply_spec_augment (bool): flag indication whether to apply spec augment or not
        apply_noise_augment (bool): flag indication whether to apply noise augment or not
        apply_time_stretch_augment (bool): flag indication whether to apply time stretch augment or not
        apply_joining_augment (bool): flag indication whether to apply audio joining augment or not
    """
    NONE_AUGMENT = 0
    SPEC_AUGMENT = 1
    NOISE_AUGMENT = 2
    TIME_STRETCH = 3
    AUDIO_JOINING = 4

    def __init__(
        self,
        configs: DictConfig,
        dataset_path: str,
        audio_paths: list,
        transcripts: list,
        sos_id: int = 1,
        eos_id: int = 2,
        del_silence: bool = False,
        apply_spec_augment: bool = False,
        apply_noise_augment: bool = False,
        apply_time_stretch_augment: bool = False,
        apply_joining_augment: bool = False,
    ) -> None:
        super(SpeechToTextDataset, self).__init__()
        self.dataset_path = dataset_path
        self.audio_paths = list(audio_paths)
        self.transcripts = list(transcripts)
        self.augments = [self.NONE_AUGMENT] * len(self.audio_paths)
        self.dataset_size = len(self.audio_paths)
        self.sos_id = sos_id
        self.eos_id = eos_id
        self.sample_rate = configs.audio.sample_rate
        self.num_mels = configs.audio.num_mels
        self.del_silence = del_silence
        self.apply_spec_augment = apply_spec_augment
        self.apply_noise_augment = apply_noise_augment
        self.apply_time_stretch_augment = apply_time_stretch_augment
        self.apply_joining_augment = apply_joining_augment
        self.transforms = AUDIO_FEATURE_TRANSFORM_REGISTRY[configs.audio.name](configs)
        self._load_audio = load_audio

        if self.apply_spec_augment:
            self._spec_augment = SpecAugment(
                freq_mask_para=configs.augment.freq_mask_para,
                freq_mask_num=configs.augment.freq_mask_num,
                time_mask_num=configs.augment.time_mask_num,
            )
            for idx in range(self.dataset_size):
                self.audio_paths.append(self.audio_paths[idx])
                self.transcripts.append(self.transcripts[idx])
                self.augments.append(self.SPEC_AUGMENT)

        if self.apply_noise_augment:
            if eval(configs.augment.noise_dataset_dir) is None:
                raise ValueError("`noise_dataset_dir` should be contain audio files.")

            self._noise_injector = NoiseInjector(
                noise_dataset_dir=configs.augment.noise_dataset_dir,
                sample_rate=configs.augment.noise_sample_rate,
                noise_level=configs.augment.noise_level,
            )
            for idx in range(self.dataset_size):
                self.audio_paths.append(self.audio_paths[idx])
                self.transcripts.append(self.transcripts[idx])
                self.augments.append(self.NONE_AUGMENT)

        if self.apply_time_stretch_augment:
            self._time_stretch_augment = TimeStretchAugment(
                min_rate=configs.time_stretch_min_rate,
                max_rate=configs.time_stretch_max_rate,
            )
            for idx in range(self.dataset_size):
                self.audio_paths.append(self.audio_paths[idx])
                self.transcripts.append(self.transcripts[idx])
                self.augments.append(self.TIME_STRETCH)

        if self.apply_joining_augment:
            self._joining_augment = JoiningAugment()
            for idx in range(self.dataset_size):
                self.audio_paths.append(self.audio_paths[idx])
                self.transcripts.append(self.transcripts[idx])
                self.augments.append(self.AUDIO_JOINING)

        self.total_size = len(self.audio_paths)

        tmp = list(zip(self.audio_paths, self.transcripts, self.augments))
        random.shuffle(tmp)

        for i, x in enumerate(tmp):
            self.audio_paths[i] = x[0]
            self.transcripts[i] = x[1]
            self.augments[i] = x[2]

    def _parse_audio(self, audio_path: str, augment: int = None, joining_idx: int = 0) -> Tensor:
        """
        Parses audio.

        Args:
            audio_path (str): path of audio file
            augment (int): augmentation identification

        Returns:
            feature (np.ndarray): feature extract by sub-class
        """
        signal = self._load_audio(audio_path, sample_rate=self.sample_rate, del_silence=self.del_silence)

        if signal is None:
            logger.warning(f"{audio_path} is not Valid!!")
            return torch.zeros(1000, self.num_mels)

        if augment == self.AUDIO_JOINING:
            joining_signal = self._load_audio(self.audio_paths[joining_idx], sample_rate=self.sample_rate)
            signal = self._joining_augment((signal, joining_signal))

        if augment == self.TIME_STRETCH:
            signal = self._time_stretch_augment(signal)

        if augment == self.NOISE_AUGMENT:
            signal = self._noise_injector(signal)

        feature = self.transforms(signal)

        feature -= feature.mean()
        feature /= np.std(feature)

        feature = torch.FloatTensor(feature).transpose(0, 1)

        if augment == self.SPEC_AUGMENT:
            feature = self._spec_augment(feature)

        return feature

    def _parse_transcript(self, transcript: str) -> list:
        """
        Parses transcript
        Args:
            transcript (str): transcript of audio file
        Returns
            transcript (list): transcript that added <sos> and <eos> tokens
        """
        tokens = transcript.split(" ")
        transcript = list()

        transcript.append(int(self.sos_id))
        for token in tokens:
            transcript.append(int(token))
        transcript.append(int(self.eos_id))

        return transcript

    def __getitem__(self, idx):
        """Provides paif of audio & transcript"""
        audio_path = os.path.join(self.dataset_path, self.audio_paths[idx])

        if self.augments[idx] == self.AUDIO_JOINING:
            joining_idx = random.randint(0, self.total_size)
            feature = self._parse_audio(audio_path, self.augments[idx], joining_idx)
            transcript = self._parse_transcript(f"{self.transcripts[idx]} {self.transcripts[joining_idx]}")

        else:
            feature = self._parse_audio(audio_path, self.augments[idx])
            transcript = self._parse_transcript(self.transcripts[idx])

        return feature, transcript

    def __len__(self):
        return len(self.audio_paths)

    def count(self):
        return len(self.audio_paths)


import time
from selenium.webdriver.common.keys import Keys

from base.selenium_driver import SeleniumDriver

class GlobalCatalog1(SeleniumDriver):

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver

   # Locators :
    Catlog = "//*[@id='root']/div[1]/div[3]/div/div[2]/div[2]/div/div/div[3]/div/a/div/div"
    filter = "//*[@id='main-container']/main/div/div/div/div[1]/div/div[1]/h2"
    collection = "//h4[contains(text(),'Collection')]"
    warehouse =  "//h4[contains(text(),'Warehouse')]"
    Country = "//h4[contains(text(),'Country')]"
    type = "// h4[contains(text(), 'Type')]"
    Subtype= "// h4[contains(text(), 'Sub type')]"
    Colorfamily = "//h4[contains(text(),'Color family')]"
    manufacturer = "//h4[contains(text(),'Manufacturer')]"
    vendor = "//h4[contains(text(),'Vendor')]"
    materialtype = "//h4[contains(text(),'Material type')]"
    lightingtag = "//h4[contains(text(),'Lighting tag')]"
    lowvoltage = "//h4[contains(text(),'Low voltage')]"
    project = "//*[@id='root']/div[1]/div[3]/div/div[2]/div[2]/div/div/div[1]/div/a/div/div"

    def filterLabel(self):
        actual = 'Filters'
        self.element_click(self.Catlog)
        filter_label = self.get_text(self.filter)
        self.verify_text_contains(actual_text=filter_label, expected_text=actual)

    def collectionFilter(self):
        actual = 'Collection'
        self.element_click(self.Catlog)
        label = self.get_text(self.collection)
        self.verify_text_contains(actual_text=label, expected_text=actual)

    def WarehouseFiler(self):
        actual = 'Warehouse'
        self.element_click(self.Catlog)
        label = self.get_text(self.warehouse)
        self.verify_text_contains(actual_text=label, expected_text=actual)

    def CountryFilter(self):
        actual = 'Country'
        self.element_click(self.Catlog)
        label = self.get_text(self.Country)
        self.verify_text_contains(actual_text=label, expected_text=actual)

    def typeFilter(self):
        actual = 'Type'
        self.element_click(self.Catlog)
        label = self.get_text(self.type)
        self.verify_text_contains(actual_text=label, expected_text=actual)

    def subTypeFilter(self):
        actual = 'Sub type'
        self.element_click(self.Catlog)
        label = self.get_text(self.Subtype)
        self.verify_text_contains(actual_text=label, expected_text=actual)

    def manufactureFilter(self):
        actual = 'Manufacturer'
        self.element_click(self.Catlog)
        label = self.get_text(self.manufacturer)
        self.verify_text_contains(actual_text=label, expected_text=actual)

    def vendorFilter(self):
        actual = 'Vendor'
        self.element_click(self.Catlog)
        label = self.get_text(self.vendor)
        self.verify_text_contains(actual_text=label, expected_text=actual)

    def materialFilter(self):
        actual = 'Material type'
        self.element_click(self.Catlog)
        label = self.get_text(self.materialtype)
        self.verify_text_contains(actual_text=label, expected_text=actual)

    def colorfamilyFilter(self):
        actual = 'Color family'
        self.element_click(self.Catlog)
        label = self.get_text(self.Colorfamily)
        self.verify_text_contains(actual_text=label, expected_text=actual)

    def lightingtagFilter(self):
         actual = 'Lighting tag'
         self.element_click(self.Catlog)
         label = self.get_text(self.lightingtag)
         self.verify_text_contains(actual_text=label, expected_text=actual)

    def lowvoltageFilter(self):
        actual = 'Low voltage'
        self.element_click(self.Catlog)
        label = self.get_text(self.lowvoltage)
        self.verify_text_contains(actual_text=label, expected_text=actual)

    Collection_position = "//h4[contains(text(),'Collection')]"
    see_more = "//div[1]//span[contains(text(),'See more')]"
    #old = "//div[4]//ul[1]//li[7]//span[1]"
    see_less = "//span[contains(text(),'See Less')]"

    def checkSeeMorelink(self):
        time.sleep(4)
        self.element_click(self.Catlog)
 #      if self.is_element_present(self.Country_position) == True:
        self.element_click(self.see_more)
        time.sleep(2)
        see_less = self.get_text(self.see_less)
        text = "See Less"
        self.verify_text_contains(actual_text=see_less, expected_text=text)
        time.sleep(2)
        self.element_click(self.see_less)
        time.sleep(2)
        see_more = self.get_text(self.see_more)
        text = "See more"
        self.verify_text_contains(actual_text=see_more, expected_text=text)

    _filter_click = "//label[contains(.,'Bulk 1.0')]"
    _clear_filter = "//p[contains(text(),'Reset filters')]"

    def applyFilter(self):
        time.sleep(2)
        self.element_click(self.Catlog)
        self.web_scroll(direction="up")
        self.wait_for_element(self._filter_click)
        self.element_click(self._filter_click)
        time.sleep(2)
        self.wait_for_element(self._clear_filter)
        clear_filter = self.get_text(self._clear_filter)
        self.verify_text_contains(actual_text=clear_filter, expected_text='Reset filters')
        time.sleep(2)

 # Check filter values after applying the filters.

    # Applied filter on listing screen
    _type_select = "//*[@id='main-container']/main/div/div/div/div[1]/div/div[5]/ul/li[1]/label/div[2]/div/span[1]"
    _sub_type_click = "//*[@id='main-container']/main/div/div/div/div[1]/div/div[6]/ul/li[1]/label/div[2]/div/span[1]"
    _manufacture_click = "//*[@id='main-container']/main/div/div/div/div[1]/div/div[8]/ul/li[1]/label/div[2]/div/span[1]"

    # detail page filter value verification
    _manufacture_value = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[6]/div[2]/div/div/div/div[2]/span[2]"
    _type_value = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[6]/div[2]/div/div/div/div[7]/span[2]"
    _subtype_value = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[6]/div[2]/div/div/div/div[8]/span[2]"

    # click on first cell after applying the filter

    _first_cell = "//*[@id='main-container']/main/div/div/div/div[2]/div/div[2]/a[1]"

    def verifyAppliedFilterDetailPage(self):
        """ verify result after click on manufacturer , type and subtype"""
        time.sleep(2)
        self.element_click(self.Catlog)
        collection = self.get_text(self._filter_click)
        self.element_click(self._type_select)
        time.sleep(2)
        typefilter = self.get_text(self._type_select)
        time.sleep(3)
        self.element_click(self._sub_type_click)
        sub_type = self.get_text(self._sub_type_click)
        time.sleep(3)
        self.element_click(self._manufacture_click)
        manufacture = self.get_text(self._manufacture_click)
        time.sleep(3)
        self.element_click(self._first_cell)
        time.sleep(3)
        subtype_detail_value = self.get_text(self._subtype_value)
        type_detail_value = self.get_text(self._type_value)
        manufacture_detail_value = self.get_text(self._manufacture_value)
        self.verify_text_contains(actual_text=typefilter, expected_text=type_detail_value)
        self.verify_text_contains(actual_text=sub_type, expected_text=subtype_detail_value)
        self.verify_text_contains(actual_text=manufacture, expected_text=manufacture_detail_value)
        print("typefilter->",type_detail_value, "|| sub_type filter->",subtype_detail_value,"||manufacture",manufacture_detail_value)
        self.element_click(self.project)
        time.sleep(2)

    # Locator for search product form global catalog
    _search_box = "//input[@placeholder='Filter by product name, SKU']"
    _product_name = "//*[@id='main-container']/main/div/div/div/div[2]/div/div[2]/a[1]/div[2]/span[1]"

    """search product via search box"""
    def searchBox(self):
        time.sleep(5)
        self.element_click(self.Catlog)
        time.sleep(3)
        product_name = self.get_text(self._product_name)
        time.sleep(2)
        self.element_click(self._search_box)
        time.sleep(4)
        self.EnterProductName(str(product_name))
        time.sleep(2)
        self.pressEnter(Keys.RETURN)
        time.sleep(2)
        SearchedResult = self.get_text(self._product_name)
        self.verify_text_contains(actual_text=product_name, expected_text=SearchedResult)
        print("actual_text=", product_name, "expected_text=",SearchedResult)
        self.element_click(self.project)
        time.sleep(5)

        '''second_product = self.getText(self._second_product_name)
        time.sleep(2)
        second_product = second_product.split()
        for i in second_product:
            if i == 'Rustic':
                return True
            elif i == 'copper':
                return True
            elif i == 'wallet':
                return True
            else:
                return False'''

    def EnterProductName(self, value):
        time.sleep(2)
        self.clear_field(self._search_box)
        time.sleep(2)
        self.send_keys(value, self._search_box)

    def pressEnter(self, value):
        self.send_keys(value, self._search_box)

    _sku = "//*[@id='main-container']/main/div/div/div/div[2]/div/div[2]/a[1]/div[2]/span[2]"
    _custom_sku = "//p[contains(text(),'+ Custom SKU')]"

    def skuSearch(self):
        """Verify SKU once with exact match is match"""
        time.sleep(2)
        self.element_click(self.Catlog)
        sku_text = self.get_text(self._sku)
        time.sleep(1)
        self.element_click(self._search_box)
        time.sleep(4)
        self.EnterProductName(str(sku_text))
        time.sleep(2)
        self.pressEnter(Keys.RETURN)
        time.sleep(2)
        sku_result = self.get_text(self._sku)
        time.sleep(2)
        self.verify_text_contains(actual_text=sku_text, expected_text=sku_result)
        print("actual_text=", sku_text, "expected_text=",sku_result)
        self.clear_field(self._search_box)
        time.sleep(2)
        self.element_click(self.project)
        time.sleep(5)

    def skuSearchCharTrim(self):
        """Verify SKU once first character is trim"""
        time.sleep(5)
        self.element_click(self.Catlog)
        sku_text = self.get_text(self._sku)
        sku_textFC = sku_text[1:]
        self.EnterProductName(sku_textFC)
        time.sleep(5)
        self.pressEnter(Keys.ENTER)
        time.sleep(5)
        sku_result1 = self.get_text(self._sku)
        self.verify_text_contains(actual_text=sku_result1, expected_text=sku_text)
        print("First character trim - ", sku_textFC, "Actual result-", sku_result1, "Expected text-",sku_text)
        self.clear_field(self._search_box)
        self.element_click(self.project)
        time.sleep(5)

    def skuSearch_LowerChar(self):
        """Verify SKU with lower text"""
        time.sleep(5)
        self.element_click(self.Catlog)
        sku_result2 = self.get_text(self._sku)
        sku_textlower = sku_result2.lower()
        self.EnterProductName(sku_textlower)
        time.sleep(5)
        self.pressEnter(Keys.ENTER)
        time.sleep(5)
        sku_result1 = self.get_text(self._sku)
        self.verify_text_contains(actual_text=sku_textlower, expected_text=sku_result1)
        print("actual_text=",sku_textlower, "expected_text=",sku_result1)
        self.clear_field(self._search_box)
        self.element_click(self.project)
        time.sleep(5)

    def skuSearch_FirstLastChTrim(self):
        """Verify SKU with frist and last character trim"""
        time.sleep(5)
        self.element_click(self.Catlog)
        removed_Actual_sku = self.get_text(self._sku)
        removed_FirstCharcterTrim_sku = removed_Actual_sku[1:]
        removed_LastCharcterTrim_sku = removed_FirstCharcterTrim_sku[:-1]
        time.sleep(5)
        self.EnterProductName(removed_LastCharcterTrim_sku)
        time.sleep(5)
        self.pressEnter(Keys.ENTER)
        time.sleep(5)
        sku_result3 = self.get_text(self._sku)
        self.verify_text_contains(actual_text=sku_result3, expected_text=removed_Actual_sku)
        print("Actual result -", sku_result3 , "Expected result-", removed_Actual_sku)
        self.clear_field(self._search_box)
        time.sleep(2)
        self.element_click(self.project)
        time.sleep(5)

    _click_most_relevant_dropdown = "//div[@id='root']//div[contains(text(),'Most relevant')]"
    _click_sort_by_lowest = "//div[@id='root']//div[contains(text(),'Sort by lowest price')]"
    _click_sort_by_highest = "//div[@id='root']//div[contains(text(),'Sort by highest price')]"
    _click_sort_by_rating = "//div[@id='root']//div[contains(text(),'Sort by highest rating')]"
    _click_sort_by_most_reviewed = "//div[@id='root']//div[contains(text(),'Sort by most reviewed')]"

    def pressDownKey(self, value):
        self.send_keys(value, self._click_most_relevant_dropdown)

    def pressEnterSortSelection(self, value):
        self.send_keys(value, self._click_most_relevant_dropdown)

    def clickSortLowestDropdown(self):

        time.sleep(4)
        self.element_click(self.Catlog)
        time.sleep(2)
        self.element_click(self._click_most_relevant_dropdown)
        time.sleep(5)
        a = self.element_click(self._click_sort_by_lowest)
        self.log.info(a)
        time.sleep(4)
        self.log.info("hi this is a print")
        a = "//body/div[@id='root']//div"
        c = '/div[1]/div[2]/div[1]//span[1]'
        list = []
        for i in range(2, 25):
            x = [i]
            price_xpath = a + str(x) + c
            time.sleep(4)
            if self.is_element_present(price_xpath) == False:
                break
            else:
                price = self.get_text(price_xpath)
                price = price.replace("$", '')
                price = price.replace(",", '')
                (list.append(float(price)))
        self.log.info("Original list : " + str(list))
        # using all() to
        # check sorted list
        flag = 0
        if (list == sorted(list)):
            flag = 1
        # printing result
        if (flag):
            self.log.info("Yes, List is sorted.")
            return True
        else:
            self.log.info("No, List is not sorted.")
            return False

    GC_link = "//*[@id='main-container']/main/div/div/div[1]/span[1]"
    Rating = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[1]/div[1]/p[1]"
    def sortRating(self):
        """test_14Verify_Sort_By__Highest_Rating"""
        time.sleep(4)
        self.element_click(self.Catlog)
        time.sleep(2)
        self.element_click(self._click_most_relevant_dropdown)
        time.sleep(5)
        self.element_click(self._click_sort_by_rating)
        time.sleep(5)
        card1 = "//*[@id='main-container']/main/div/div/div/div[2]/div/div[2]/a["
        card2 = "]/div[1]"
        list = []
        for i in range(2, 25):
            _path = card1 + str(i) + card2
            self.element_click(_path)
            time.sleep(5)
            RatingValue = self.get_text(self.Rating)
            #RatingValue = RatingValue.replace("0", '')
            #RatingValue = RatingValue.replace(".", '')
            list.append(float(RatingValue))
            self.element_click(self.GC_link)
        ExpResult = "True"
        if(list == sorted(list,reverse=True)):
            ActResult = "True"
            print("list is sorted",list)
        else:
            ActResult = "False"
            print("list is not sorted",list)
        self.verify_text_match(ActResult,ExpResult)

    # Qtywarehouse locators for xpath
    QtyWarehouse = "//h4[contains(text(),'Qty in warehouse')]"
    QtywarehouseValue = "//*[@id='main-container']/main/div/div/div/div[1]/div/div[3]/ul/ul/div/div[1]/div/div/input"
    warehouseCheckbox_xpath = "//*[@id='main-container']/main/div/div/div/div[1]/div/div[3]/ul/li[1]/label/div[2]/div/span[1]"
    Applybutton_qty ="//*[@id='main-container']/main/div/div/div/div[1]/div/div[3]/ul/ul/div/button/span"
    QtyResult_card = "//*[@id='main-container']/main/div/div/div/div[2]/div/div[2]/a[1]"
    Availibility = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[4]/div[1]/span[1]"
    warehousenameExpted = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[4]/div[2]/div/div/div/div[2]/div[2]/table/tbody/tr/td[1]/div/div/div/div/strong"
    QtyActualvaluepath = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[4]/div[2]/div/div/div/div[2]/div[2]/table/tbody/tr/td[2]/div/div/div"

    def QtyWarehouse(self):
      time.sleep(2)
      self.element_click(self.Catlog)
      time.sleep(2)
      expvalueWarehouse=self.get_text(self.warehouseCheckbox_xpath)
      self.element_click(self.warehouseCheckbox_xpath)
      time.sleep(2)
      self.element_click(self.QtywarehouseValue)
      time.sleep(2)
      self.clear_field(self.QtywarehouseValue)
      time.sleep(2)
      self.send_keys(50, self.QtywarehouseValue)
      time.sleep(2)
      self.element_click(self.Applybutton_qty)
      time.sleep(2)
      self.element_click(self.QtyResult_card)
      time.sleep(2)
      self.element_click(self.Availibility)
      time.sleep(2)
      QtyinwarehouseActualvalue=self.get_text(self.QtyActualvaluepath)
      warehouseActualValue = self.get_text(self.warehousenameExpted)
      if(int(QtyinwarehouseActualvalue)<50):
         print("condition does not match")
      else:
        self.verify_text_contains(actual_text=warehouseActualValue, expected_text=expvalueWarehouse)
        print("actual_text=", warehouseActualValue, "expected_text=",expvalueWarehouse)
      self.element_click(self.project)
      time.sleep(5)

    #loctaor for country availability
    Countrychebox = "//*[@id='main-container']/main/div/div/div/div[1]/div/div[4]/ul/li[1]/label"
    Country_Availabitly_actual = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[4]/div[2]/div/div/div/div[3]/strong"
    #Country_avl_label = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[4]/div[2]/div/div/div/strong[2]"

    def Country_availability(self):
        """Verify Quantity in warehouse"""
        time.sleep(2)
        self.element_click(self.Catlog)
        time.sleep(4)
        self.element_click(self.Countrychebox)
        CA_Expected = self.get_text(self.Countrychebox)
        CA_Expected = CA_Expected[:-5]
        time.sleep(4)
        self.element_click(self.QtyResult_card)
        time.sleep(5)
        self.element_click(self.Availibility)
        time.sleep(5)
        #CAL=self.get_text(self.Country_avl_label)
        CA_Actual=self.get_text(self.Country_Availabitly_actual)
        CA_Actual= CA_Actual.strip()
        #if self.is_element_present(CAL) == False:
        #print("Country does not exit")
        #else:
        self.verify_text_contains(actual_text=CA_Actual.strip(),expected_text=CA_Expected.strip())
        print("Country availabilty excepted value ->",CA_Expected, "||Country availabilty excepted value ->", CA_Actual)
        self.element_click(self.project)
        time.sleep(5)

    #locator for lighting tag
    ligtingCheckbox = "//*[@id='main-container']/main/div/div/div/div[1]/div/div[11]/ul/li[1]/label"
    product_card_result = "//*[@id='main-container']/main/div/div/div/div[2]/div/div[2]/a[1]"
    Ligting_information_pdp = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[6]/div[2]/div/div/div[2]/div/div[1]/span[1]"
    lighting_fixer = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[6]/div[2]/div/div/div[2]/div/div[2]/div/div/div/div[1]/span[2]"

    def Lighting_Tag(self):
        """Verify Lighting Tags in PDP"""
        time.sleep(5)
        self.element_click(self.Catlog)
        time.sleep(4)
        self.element_click(self.ligtingCheckbox)
        time.sleep(4)
        ExpValue_Lighting_Tag = self.get_text(self.ligtingCheckbox)
        ExpValue_Lighting_Tag = ExpValue_Lighting_Tag[:4]
        self.element_click(self.product_card_result)
        time.sleep(5)
        LightingTag_label = self.get_text(self.Ligting_information_pdp)
        Actual_value_lightingTag = self.get_text(self.lighting_fixer)
        if LightingTag_label in ("Lighting information"):
           self.verify_text_contains(actual_text=Actual_value_lightingTag.strip(),expected_text=ExpValue_Lighting_Tag.strip())
           print("actvalue =", Actual_value_lightingTag, "ExpValue =", ExpValue_Lighting_Tag)
        else:
           print("Lighting information label does not found")
           print(LightingTag_label)
        self.element_click(self.project)
        time.sleep(5)

 # Verify tag selected from left side should show expected list accordingly.

    _bulk_tag = "//*[@id='main-container']/main/div/div/div/div[2]/div/div[2]/a[1]/div[2]/div/div/div[1]"
    collection_see_more = "//div[@id='root']/div/div[3]/div/div/div[2]/div/div/div[3]/ul/li[7]/span"

    _bulk_2 = "//label[contains(.,'Bulk 2.0')]"
    def filterTagBulk2(self):
        time.sleep(5)
        self.element_click(self.Catlog)
        time.sleep(4)
        self.element_click(self._bulk_2)
        name = self.get_text(self._bulk_2)
        name = name[:-4]
        time.sleep(2)
        bulk_tag_text = self.get_text(self._bulk_tag)
        time.sleep(2)
        self.verify_text_contains(actual_text=bulk_tag_text.strip(), expected_text=name.strip())
        print("actual_text",bulk_tag_text, "expected_text",name)
        self.element_click(self.project)
        time.sleep(5)
        self.element_click(self.project)
        time.sleep(5)

    _custom_tag = "//label[contains(.,'Custom')]"

    def filterTagCustom(self):
        time.sleep(5)
        self.element_click(self.Catlog)
        time.sleep(4)
        self.element_click(self._custom_tag)
        name = self.get_text(self._custom_tag)
        name = name[:-5]
        time.sleep(2)
        bulk_tag_text = self.get_text(self._bulk_tag)
        bulk_tag_text1 = bulk_tag_text.lower()
        time.sleep(2)
        self.verify_text_contains(actual_text=bulk_tag_text1.strip(),expected_text=name.strip())
        print("actual_text",bulk_tag_text, "expected_text=",name)
        self.element_click(self.project)
        time.sleep(5)

    _NorthAmerica2020_tag = "//label[contains(.,'NorthAmerica2020')]"
    _pdp_tag = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[1]/div[2]/div"

    def filterTagNorthAmerica2020(self):
        time.sleep(5)
        self.element_click(self.Catlog)
        time.sleep(4)
        self.element_click(self.see_more)
        time.sleep(2)
        self.element_click(self._NorthAmerica2020_tag)
        name = self.get_text(self._NorthAmerica2020_tag)
        name = name[:-5]
        time.sleep(2)
        self.element_click(self._first_cell)
        _pdp_tag_text = self.get_text(self._pdp_tag)
        PD_Tag1 = _pdp_tag_text.lower()
        time.sleep(2)
        self.verify_text_contains(actual_text=PD_Tag1.strip(), expected_text=name.strip())
        print("actual_text", PD_Tag1, "expected_text=", name)
        self.element_click(self.project)
        time.sleep(5)

    _phoenix_tag = "//label[contains(.,'Phoenix')]"

    def filterTagPhoenix(self):
        time.sleep(5)
        self.element_click(self.Catlog)
        time.sleep(4)
        self.element_click(self.see_more)
        time.sleep(2)
        self.element_click(self._phoenix_tag)
        name = self.get_text(self._phoenix_tag)
        name = name[:-5]
        time.sleep(2)
        bulk_tag1= self.get_text(self._bulk_tag)
        bulk_tag2 = bulk_tag1.lower()
        time.sleep(2)
        self.verify_text_contains(actual_text=bulk_tag2.strip(), expected_text=name.strip())
        print("Actual_text=",bulk_tag2 ,"expected_text=",name)
        self.element_click(self.project)
        time.sleep(5)

    PD = "//*[@id='main-container']/main/div/div/div[1]/span[1]"
    def sortmostreviewed(self):
        """test_15_Verify_Sort_By__Most_Reviewed"""
        time.sleep(4)
        self.element_click(self.Catlog)
        time.sleep(2)
        self.element_click(self._click_most_relevant_dropdown)
        time.sleep(5)
        self.element_click(self._click_sort_by_most_reviewed)
        time.sleep(5)
        time.sleep(5)
        card1 = "//*[@id='main-container']/main/div/div/div/div[2]/div/div[2]/a["
        card2 = "]/div[1]"
        list = []
        for i in range(2, 25):
            _path = card1 + str(i) + card2
            self.element_click(_path)
            time.sleep(5)
            review = "//*[@id='main-container']/main/div/div/div[2]/div[3]/div[2]/div[1]/div[1]/p[2]"
            ReviewsValue = self.get_text(review)
            ReviewsValue = ReviewsValue.replace("See", '')
            ReviewsValue = ReviewsValue.replace("reviews", '')
            ReviewsValue = ReviewsValue.replace("one review", '')
            #print(ReviewsValue)
            self.element_click(self.PD)
            list.append(float(ReviewsValue))
        self.log.info(list)
        flag = 0
        if (list == sorted(list, reverse=True)):
           self.log.info("Yes, List is sorted.")
        else:
            self.log.info("No, List is not sorted.")
        self.element_click(self.project)

    #PD = "//*[@id='main-container']/main/div/div/div[1]/span[1]"
    def sorthighest1(self):
        """test_13_Verify_Sort_By__Highest_price"""
        time.sleep(4)
        self.element_click(self.Catlog)
        time.sleep(2)
        self.element_click(self._click_most_relevant_dropdown)
        time.sleep(5)
        a = self.element_click(self._click_sort_by_highest)
        time.sleep(3)
        card1 = "//*[@id='main-container']/main/div/div/div/div[2]/div/div[2]/a["
        card2 = "]/div[2]/div/span"
        list = []
        for i in range(2, 25):
            _path = card1 + str(i) + card2
            pricevalue = self.get_text(_path)
            time.sleep(5)
            pricevalue = pricevalue.replace("$", '')
            pricevalue = pricevalue.replace(",", '')
            list.append(float(pricevalue))
        ExpResult = "True"
        if (list == sorted(list, reverse=False)):
                flag = "True"
                print("Yes, List is sorted.")
        else:
                flag = "False"
                print("No, List is not sorted.")
        self.verify_text_contains(ExpResult,flag)
        self.element_click(self.project)


import sys

N = int(sys.stdin.readline())
A = list(map(int, sys.stdin.readline().split()))
dp_increase = [1] * N

reversed_A = list(reversed(A))
dp_decrease = [1] * N

for i in range(N):
    for j in range(i):
        if A[i] > A[j]:
            dp_increase[i] = max(dp_increase[i], dp_increase[j]+1)
        if reversed_A[i] > reversed_A[j]:
            dp_decrease[i] = max(dp_decrease[i], dp_decrease[j]+1)

res = []
for i in range(N):
    res.append(dp_increase[i] + dp_decrease[N-i-1]-1)

print(max(res))


import js
import pyodide
from pyodide.http import pyfetch

import asyncio
from urllib.parse import urlparse
import uuid
import json
import base64

import cloudpickle

class JupyterAPI:
    def __init__(self, notebook_url: str, api_token : str):
        self.api_url = f'{notebook_url}/api'
        self.api_token = api_token

    async def request(self, url : str, method : str = 'GET', data=None, headers=None):
        headers = headers or {}
        options = {
            'method': method,
            'headers': {
                'Authorization': f'token {self.api_token}',
                **headers
            },
        }
        if data:
            options['body'] = data
        return await pyfetch(url, **options)

    async def status(self):
        response = await self.request(self.api_url)
        return await response.json()

    async def create_kernel(self, kernel_spec=None):
        data = {"kernel_spec": kernel_spec} if kernel_spec else {}
        response = await self.request(
            f'{self.api_url}/kernels',
            method='POST',
            data=json.dumps(data),
        )
        return await response.json()

    async def list_kernel_specs(self):
        response = await self.request(f'{self.api_url}/kernelspecs')
        return await response.json()

    async def list_kernels(self):
        response = await self.request(f'{self.api_url}/kernels')
        return await response.json()

    async def get_kernel(self, kernel_id):
        response = await self.request(f'{self.api_url}/kernels/{kernel_id}')
        if response.status == 404:
            return None
        elif response.status == 200:
            return await response.json()

    async def ensure_kernel(self, kernel_spec=None):
        kernel_specs = await self.list_kernel_specs()
        if kernel_spec is None:
            kernel_spec = kernel_specs["default"]
        else:
            available_kernel_specs = list(kernel_specs["kernelspecs"].keys())
            if kernel_spec not in kernel_specs["kernelspecs"]:
                print(
                    f"kernel_spec={kernel_spec} not listed in available kernel specifications={available_kernel_specs}"
                )
                raise ValueError(
                    f"kernel_spec={kernel_spec} not listed in available kernel specifications={available_kernel_specs}"
                )

        kernel_id = (await self.create_kernel(kernel_spec=kernel_spec))["id"]
        jupyter_kernel = JupyterKernelAPI(
            f'{self.api_url}/kernels/{kernel_id}',
            self.api_token,
        )
        await jupyter_kernel.initialize()
        return kernel_id, jupyter_kernel

class JupyterKernelAPI:
    def __init__(self, kernel_url, api_token):
        self.api_url = kernel_url
        self.api_token = api_token

    async def initialize(self):
        parsed_url = urlparse(self.api_url)
        self.websocket = js.WebSocket.new(f'ws://{parsed_url.netloc}{parsed_url.path}/channels?token={self.api_token}')

        self.queue = asyncio.Queue()

        def handleMessage(event):
            self.queue.put_nowait(event.data)

        self.websocket.addEventListener(
            'message',
            pyodide.create_proxy(handleMessage))

        def handleOpen(event):
            self.queue.put_nowait('ready')

        self.websocket.addEventListener(
            'open',
            pyodide.create_proxy(handleOpen))

        # collect the 'ready' task
        await self.queue.get()

    def request_execute_code(self, msg_id, username, code):
        return {
            "header": {
                "msg_id": msg_id,
                "username": username,
                "msg_type": "execute_request",
                "version": "5.2",
            },
            "metadata": {},
            "content": {
                "code": code,
                "silent": False,
                "store_history": True,
                "user_expressions": {},
                "allow_stdin": True,
                "stop_on_error": True,
            },
            "buffers": [],
            "parent_header": {},
            "channel": "shell",
        }

    async def send_code(self, username, code, wait=True, timeout=None):
        msg_id = str(uuid.uuid4())

        self.websocket.send(
            json.dumps(self.request_execute_code(msg_id, username, code))
        )

        if not wait:
            return None

        stdout_lines = []
        stderr_lines = []
        result = None

        while True:
            message = await self.queue.get()
            msg = json.loads(message)

            if "parent_header" in msg and msg["parent_header"].get("msg_id") == msg_id:
                if msg["msg_type"] == "error":
                    raise eval(msg["content"]["ename"])(msg["content"]["evalue"])
                elif msg["channel"] == "iopub":
                    if msg["msg_type"] == "execute_result":
                        result = msg["content"]["data"]["text/plain"]
                        break
                    elif msg["msg_type"] == "stream" and msg['content']['name'] == 'stdout':
                        stdout_lines.append(msg["content"]["text"])
                    elif msg["msg_type"] == "stream" and msg['content']['name'] == 'stderr':
                        stderr_lines.append(msg["content"]["text"])
                    # cell did not produce output
                    elif msg["content"].get("execution_state") == "idle":
                        break

        return ''.join(stdout_lines), ''.join(stderr_lines), result

    def delayed(self, func):
        function_pickle = base64.b64encode(cloudpickle.dumps(func)).decode('utf-8')
        code = '''
import base64
import cloudpickle
function = cloudpickle.loads(base64.b64decode(b'{function_pickle}'))
args, kwargs = cloudpickle.loads(base64.b64decode(b'{function_args}'))
result = function(*args, **kwargs)
base64.b64encode(cloudpickle.dumps(result)).decode('utf-8')
'''

        async def wrapper(*args, **kwargs):
            function_args = base64.b64encode(cloudpickle.dumps((args, kwargs))).decode('utf-8')
            stdout, stderr, result = await self.send_code('jupyter-api', code.format(
                function_pickle=function_pickle, function_args=function_args)
            )

            result = cloudpickle.loads(base64.b64decode(result[1:-1].encode('utf-8')))
            return result

        return wrapper

# jupyter-server --ServerApp.allow_origin='*' --ServerApp.token='asdfqwerzxcvqwer'
jupyter_client = JupyterAPI('http://localhost:8888', api_token='asdfqwerzxcvqwer')


#% extends "py-script.mk" %#
#% block name %#confirm#% endblock %#
#% block script %#

import sys

###-
# this is just to trick the LSP during development
from utils import a

# -###
##- '$(utils_py)' -##

def confirm():
    """
    Ask user to enter Y or N (case-insensitive).
    :return: True if the answer is Y.
    :rtype: bool
    """
    answer = ""
    while answer not in ["y", "n"]:
        sys.stderr.write(f"""$(2) {a.b_red}[Y/n]{a.end} \n""")
        answer = input().lower()
    return answer == "y"

if confirm():
    sys.exit()
else:
    sys.exit(1)
#% endblock %#


import random

class Can_Walk:
    def __init__(self, rect, speed_walk=random.randint(1, 3), screen_width=-1280):
        self.rect = rect
        self.speed_walk = speed_walk
        self.screen_width = screen_width

    def move_left(self):
        self.rect.x -= self.speed_walk
        self.sprite.status = 'run'
        self.sprite.animation_speed = 0.15
        self.sprite.facing_right = True
        self.speed_walk = random.randint(1, 3)

    def move_right(self):
        self.sprite.facing_right = False
        self.speed_walk = random.randint(1, 3)
        self.move_npc()

    def move_npc(self):
        self.rect.x += self.speed_walk
        self.sprite.status = 'run'
        self.sprite.animation_speed = 0.23

    # def move_limit(self):
    #     if self.move_left():
    #         self.sprite <= self.screen_width
    #     else:
    #         self.move_right()


import statistics
from typing import List

from Point import Point

class PrioritySearchTree:
    def __init__(self, points: List[Point]):
        self.point = None
        self.mid_y = None
        self.left = None
        self.right = None
        if not points: return

        points.sort(key=lambda p: p.x)
        self.point, points = points[0], points[1:]
        if not points: return

        self.mid_y = statistics.median((p.y for p in points))
        left_points = [p for p in points if p.y <= self.mid_y]
        right_points = [p for p in points if p.y > self.mid_y]
        if left_points: self.left = PrioritySearchTree(left_points)
        if right_points: self.right = PrioritySearchTree(right_points)

    def __repr__(self):
        s = '(' + str(self.point)
        if self.mid_y: s += ' - ' + str(self.mid_y)
        s += '):{' + str(self.left) + ', ' + str(self.right) + '}'
        return s

    def query_by_x(self, x):
        return self.query_by_box(x, float('-Inf'), float('Inf'))

    def query_by_box(self, x, y1, y2):
        result = []
        if self.point.x <= x:
            if self.point.in_y(y1, y2): result += [self.point.id]
            if self.left and self.mid_y >= y1: result += self.left.query_by_box(x, y1, y2)
            if self.right and self.mid_y <= y2: result += self.right.query_by_box(x, y1, y2)
        return result