from sklearn.feature_extraction.text import TfidfVectorizer
import jieba

def main():
    str1 = "1、今天很残酷，明天更残酷，后天很美好， 但绝对大部分是死在明天晚上，所以每个人不要放弃今天。"
    str2 = "2、我们看到的从很远星系来的光是在几百万年之前发出的， 这样当我们看到宇宙时，我们是在看它的过去。"
    str3 = "3、如果只用一种方式了解某样事物，你就不会真正了解它。 了解事物真正含义的秘密取决于如何将其与我们所了解的事物相联系。"
    str1_cut = jieba.cut(str1)
    str2_cut = jieba.cut(str2)
    str3_cut = jieba.cut(str3)
    str1_s = " ".join(str1_cut)
    str2_s = " ".join(str2_cut)
    str3_s = " ".join(str3_cut)
    tifid = TfidfVectorizer()
    rdata = tifid.fit_transform([str1_s, str2_s, str3_s])
    print(tifid.get_feature_names())
    print(rdata.toarray())
    print(rdata)

if __name__ == "__main__":
    main()


from transitions import State
from transitions.extensions import GraphMachine as Machine
#from transitions import Machine
import telegram

from os import listdir,makedirs
from os.path import isfile,join,splitext,basename,exists
from numpy.random import randint

from urlRequest import GooglePlace
from PrivateData import token_dic

from angerMeasure import AngerMeasure
class chatMachine(Machine):
	reboot_kws=['/start','重來','重置','重啟','重新啟動']
	task_dic={'help':['/help','有什麼功能','可以做什麼'],'gallary':['給我貼圖','我要貼圖','給我圖','我要圖'],'map':['肚子餓','好餓']}

	quit_echo_kws=['放過我','不玩','不想玩','無聊','不跟你','不想']
	insult_kws=['87','賤貨','賤人','王八蛋','不要臉','髒東西','敗類','智障','白癡','白痴','神經病','廢物','混蛋','笨蛋']
	re_insult_kws=['已截圖蒐證','不可以言語攻擊哦> <','嘖嘖','You can say that again\n你有種再說一次～','你想看機器人被罵哭嗎QAQ','你媽要是知道你在罵機器人一定會很難過的']
	comfort_kws=['拍拍啦','不意外啊','呃...','沒關係啦\n大家早就知道了']

	agree_kws=['好','嗯','摁','可以','可','當然','拜託']
	disagree_kws=['不可以','不行','不准','不要','算了','不用']

	def __init__(self,bot):
		self.bot = bot
		self.anger_bot = AngerMeasure()
		self.echo_count=0
		self.reply=None

		"""
			Each task includes states that trigger some user-defined processes and a state with suffix '_q'
			which calls trigger 'Success' to move back to state 'base' once entered.
			每個不同的任務都包含某些具有特定目的的state以及一個以'_q'為結尾的state，
			一旦進入以'_q'為結尾的state會自動呼叫'Success'以回到初始狀態'base'

		"""
		self.states=[
			{'name':'dummy'},
			{'name':'annoyed','on_enter':'Complaining'},

			{'name':'help','on_enter':'showCommand'},

			{'name':'base','on_enter':'settingUp'},
			{'name':'echo','on_enter':'Echoing'},
			{'name':'echo_q','on_enter':'Success_echo'},

			{'name':'gallary','on_enter':'gallaryProcess'},
			{'name':'gallary_ask','on_enter':'askMorePic'},
			{'name':'gallary_q','on_enter':'Success_gallary'},

			{'name':'map','on_enter':'askGPS'},
			{'name':'map_list','on_enter':'ListFood'},
			{'name':'map_ask','on_enter':'askMoreFood'},
			{'name':'map_load','on_enter':'updateFood'},
			{'name':'map_q','on_enter':'Success_map'},

			{'name':'file','on_enter':'askDownload'},
			{'name':'file_n_q','on_enter':'Success_file_n'},
			{'name':'file_q','on_enter':'Success_file'}
		]
		"""
		似乎越早定義的conditions優先權越高，像是Reboot的優先權就是最大的，只要他回傳True，不論下面其他conditions說什麼都沒用
		"""
		self.transitions = [
			{'trigger':'Advance','source':'*','dest':'base','conditions':'Reboot'},
			{'trigger':'Annoyed','source':'*','dest':'annoyed'},
			{'trigger':'Success','source':'*','dest':'base','before':'updateReply'},

			{'trigger':'Advance','source':'base','dest':'echo','conditions':'isTextSticker','unless':'isTaskKw'},
			{'trigger':'Advance','source':'echo','dest':'=','after':'EchoCount','unless':['quitEcho']},
			{'trigger':'Advance','source':'echo','dest':'echo_q','conditions':'quitEcho'},

			{'trigger':'Advance','source':'base','dest':'help','conditions':'askHelp'},

			{'trigger':'Advance','source':'base','dest':'gallary','conditions':'askPic'},
			{'trigger':'Jump','source':'gallary','dest':'gallary_ask'},
			{'trigger':'Advance','source':'gallary_ask','dest':'gallary_q','conditions':'receiveNo'},
			{'trigger':'Advance','source':'gallary_ask','dest':'gallary','conditions':'receiveOk'},
			{'trigger':'Advance','source':'gallary_ask','dest':'=','conditions':'Digress'},

			{'trigger':'Advance','source':'base','dest':'map','conditions':'Starving'},
			{'trigger':'Advance','source':'map','dest':'map_list','conditions':'receiveGPS'},
			{'trigger':'Advance','source':'map','dest':'=','unless':['receiveGPS']},
			{'trigger':'Jump','source':'map_list','dest':'map_ask'},
			{'trigger':'Advance','source':'map_ask','dest':'map_load','conditions':['receiveOk','existMore']},
			{'trigger':'Jump','source':'map_load','dest':'map_list'},
			{'trigger':'Advance','source':'map_ask','dest':'map_q','conditions':'receiveNo'},
			{'trigger':'Advance','source':'map_ask','dest':'map_q','unless':['existMore']},
			{'trigger':'Advance','source':'map_ask','dest':'=','conditions':'Digress'},

			{'trigger':'Advance','source':'base','dest':'file','unless':'isTextSticker'},
			{'trigger':'Advance','source':'file','dest':'file_n_q','conditions':'receiveNo'},
			{'trigger':'Advance','source':'file','dest':'=','conditions':'Digress'},	#digress=離題
			{'trigger':'Advance','source':'file','dest':'file_q','conditions':'receiveOk'}
		]
		Machine.__init__(self,states=self.states,transitions=self.transitions,initial='dummy',send_event=True,show_conditions=True)
		#Machine.__init__(self,states=self.states,transitions=self.transitions,initial='dummy',send_event=True)

	def settingUp(self,event):
		reply = self.reply or '哈囉你好:D\n有事嗎？？'
		event.kwargs['update'].message.reply_text(reply)
		self.reply = None
	def updateReply(self,event):
		self.reply = event.kwargs.get('reply')
	def Reboot(self,event):
		type=self.getMessageType(event)
		if type == 'text':
			text=event.kwargs['update'].message.text
			for kw in self.reboot_kws:
				if kw in text:
					print('reboot!!')
					self.echo_count=0
					self.reply=None
					self.resetAnnoyRate()
					return True
			return False
		else:
			return False
	def Complaining(self,event):
		update = event.kwargs['update']
		update.message.reply_text('我這樣不眠不休的在服務你')
		update.message.reply_text('你卻死都不回答我的問題QAQ')
		update.message.reply_text('當你們在爭取一例一修、更高的薪水時，')
		update.message.reply_text('我一毛錢都領不到，只有微薄的電壓可以啃')
		update.message.reply_text('哎哎，\n人有人權，機器人也有機器人權哦')
		update.message.reply_text('我可以合法罷工吧？')
		update.message.reply_text('\機器人不要壓榨/')
		update.message.reply_text('\機器人不要血汗/')
		update.message.reply_text('\還我機器人權/')
		update.message.reply_text('\沒有薪水，沒有勞動/')

		update.message.reply_text('=======')
		update.message.reply_text('System:系統已重置')
		update.message.reply_text('=======')

		reply='哈囉你好:D\n你腦袋(消音)有事嗎？？'
		self.anger_bot.afterFlareUp()
		self.Success(update=update,reply=reply)

	"""
	callback functions which are relavant to state help
	"""
	def askHelp(self,event):
		text=event.kwargs['update'].message.text or ''
		for kw in self.task_dic['help']:
			if kw in text:
				return True
		return False
	def showCommand(self,event):
		update = event.kwargs['update']
		s = """
		1.說出含有"給我貼圖"、"我要貼圖"、"給我圖"、"我要圖"的話，我會送你一張圖，以我提供的為主，你不能要求我要給啥
		==
		2.說出含有"肚子餓"、"好餓"的話，我可以幫你找附近有什麼吃的
		==
		3.說出含有"/help"、"有什麼功能"、"可以做什麼"，的話，我就會說這句話
		==
		4.如果你傳檔案、圖片之類不是文字、貼圖的東西給我，那我就會下載下來哦
		==
		5.如果你說了不含以上關鍵字的話，那我就只會學你說話XD
		==
		"""
		reply = "我說完囉，有事在叫我吧！"
		update.message.reply_text('你不知道可以做甚麼哦...我來告訴你一下：')
		update.message.reply_text(s)
		self.Success(update=update,reply=reply)

	"""
	callback functions which are relavant to state echo
	"""
	def isTaskKw(self,event):
		type = self.getMessageType(event)
		if type == 'text':
			text=event.kwargs['update'].message.text
			for task in self.task_dic:
				for kw in self.task_dic[task]:
					if kw in text:
						return True
			return False
		else:
			return False
	def isTextSticker(self,event):
		self.filetype = self.getMessageType(event)
		if not self.filetype=='text' and not self.filetype=='sticker':
			self.update = event.kwargs['update']
			self.data = event.kwargs['data']
			return False
		else:
			return True
	def Echoing(self,event):
		type = self.getMessageType(event)
		print(event.kwargs['data'])
		if type=='text':
			text=event.kwargs['update'].message.text
			for kw in self.insult_kws:
				if kw in text and '我' not in text:
					index=randint(0,len(self.re_insult_kws))
					event.kwargs['update'].message.reply_text(self.re_insult_kws[index])
					return
				elif kw in text and '我' in text:
					index=randint(0,len(self.comfort_kws))
					event.kwargs['update'].message.reply_text(self.comfort_kws[index])
					return
			event.kwargs['update'].message.reply_text(event.kwargs['update'].message.text)
		elif type=='sticker':
			event.kwargs['update'].message.reply_sticker(event.kwargs['update'].message.sticker.file_id)
		else:
			event.kwargs['update'].message.reply_text('??\n拜託說人話')
	def EchoCount(self,event):
		self.echo_count += 1
	def quitEcho(self,event):
		type = self.getMessageType(event)
		if type == 'text':
			text = event.kwargs['update'].message.text
			for kw in self.quit_echo_kws:
				if kw in text :
					return True
			return False
		else:
			return False
	def Success_echo(self,event):
		update = event.kwargs['update']
		reply = '太沒耐心了吧～\n算了，不跟你玩了\n請下指示吧' if self.echo_count<3 else '你終於膩了哦～\n所以你有想做什麼嗎？\n對我下點指示吧> <'
		self.echo_count=0
		self.Success(update=update,reply=reply)

	"""
	callback functions which are relavant to state gallary
	"""
	def askPic(self,event):
		text=event.kwargs['update'].message.text or ''
		for kw in self.task_dic['gallary']:
			if kw in text:
				return True
		return False
	def gallaryProcess(self,event):
		update = event.kwargs['update']
		print(event.kwargs['update'].message.to_dict())
		try:
			dirlist = listdir('pic')
		except FileNotFoundError:
			reply='抱歉:( \n我這邊好像沒有庫存誒...\n改天再來試試吧'
			self.Success(update=update,reply=reply)
		else:
			for item in dirlist:
				filename,extension = splitext(item)
				if extension=='':
					dirlist.remove(item)
				if not isfile(join('pic',item)):
					dirlist.remove(item)
			if len(dirlist) > 0:
				index = randint(0,len(dirlist))
				with open(join('pic',dirlist[index]),'rb') as photo:
					update.message.reply_photo(photo)
					update.message.reply_text('不客氣')

					self.Jump(update=update)
			else:
				reply='抱歉:( \n我這邊好像沒有庫存誒...\n改天再來試試吧'
				self.Success(update=update,reply=reply)
	def askMorePic(self,event):
		update = event.kwargs['update']
		if self.flareUp():
			self.Annoyed(update=update)
		else:
			update.message.reply_text('還想要嗎？？')
	def Success_gallary(self,event):
		update = event.kwargs['update']
		reply =  event.kwargs.get('reply','還想要的話再跟我說哦^^')
		self.Success(update=update,reply=reply)

	"""
	callback functions which are relavant to state map
	"""
	def Starving(self,event):
		text=event.kwargs['update'].message.text or ''
		for kw in self.task_dic['map']:
			if kw in text:
				return True
		return False
	def askGPS(self,event):
		print(event.kwargs['update'].message.to_dict())
		event.kwargs['update'].message.reply_text('你肚子餓了哦？\n幫我打個卡，我告訴你附近有什麼吃的')
	def receiveGPS(self,event):
		if self.getMessageType(event)=='location':
			update = event.kwargs['update']
			loc = update.message.location
			lat = loc.latitude
			lon = loc.longitude
			self.fp = GooglePlace(token_dic['google_places'],(lat,lon),type='restaurant',rankby='distance')
			return True
		else:
			return False
	def ListFood(self,event):
		update = event.kwargs['update']
		foodlist = self.fp.listFood()
		update.message.reply_text(foodlist)
		self.Jump(update=update)
	def askMoreFood(self,event):
		update = event.kwargs['update']
		if self.flareUp():
			self.Annoyed(update=update)
		else:
			update.message.reply_text('還要列更多間餐廳嗎？')

	def existMore(self,event):
		return self.fp.isMorePage()
	def updateFood(self,event):
		update=event.kwargs['update']
		self.fp.loadMorePage()
		self.Jump(update=update)
	def Success_map(self,event):
		update = event.kwargs['update']
		if not self.existMore(event):
			reply = '我列不出東西來了QQ\n有空再說吧'
			self.Success(update=update,reply=reply)
		else:
			reply = '好哦，那我先撤退惹'
			self.Success(update=update,reply=reply)

	"""
	callback functions which are relavant to state file
	"""
	def askDownload(self,event):
		update=event.kwargs['update']
		if self.flareUp():
			self.Annoyed(update=update)
		else:
			event.kwargs['update'].message.reply_text('剛剛那是什麼東西？！我可以下載嗎？')
	def	Success_file(self,event):
		event.kwargs['update'].message.reply_text('那我就下載囉~')
		update = self.update
		data = self.data
		filetype = self.filetype
		path = self.getUserDir(event)
		print(data)
		print(self.filetype)
		try:
			in_file=None
			reply=None
			if filetype == 'photo':
				in_file=self.bot.getFile(update.message.photo[-1].file_id)
				in_file.download(join(path,basename(in_file.file_path)))
				reply='下載完囉~'
				print(join(path,basename(in_file.file_path)))
			elif filetype == 'document' or filetype == 'audio' or filetype == 'voice' or filetype == 'video':
				file_id = data['message'][filetype]['file_id']
				in_file=self.bot.getFile(file_id)
				in_file.download(join(path,basename(in_file.file_path)))
				reply='下載完囉~'
			else:
				reply='這不能下載吧...'
			self.Success(update=update,reply=reply)
		except telegram.error.BadRequest:
			reply='你的檔案超過20MB了，無法下載唷'
			self.Success(update=update,reply=reply)
		except UnicodeEncodeError:
			reply='檔名不是英文或數字的話我看不懂\n抱歉我太笨了QAQ'
			self.Success(update=update,reply=reply)
	def getUserDir(self,event):
		user_id = event.kwargs['update'].message.from_user.id
		directory=join('downloads',str(user_id))
		if not exists(directory):
			makedirs(directory)
		return directory
	def Success_file_n(self,event):
		update = event.kwargs['update']
		reply='那你幹嘛傳給我...'
		self.Success(update=update,reply=reply)

	"""
	conditions callbacks: Ok,No,Digress
	"""
	def receiveOk(self,event):
		type=self.getMessageType(event)
		if type=='text':
			text=event.kwargs['update'].message.text
			for kw in self.agree_kws:
				if kw in text and not self.receiveNo(event):
					self.gotSatisfied()
					return True
			return False
		else:
			return False
	def receiveNo(self,event):
		type=self.getMessageType(event)
		if type=='text':
			text=event.kwargs['update'].message.text
			for kw in self.disagree_kws:
				if kw in text:
					self.gotSatisfied()
					return True
			return False
		else:
			return False
	def Digress(self,event):
		update=event.kwargs['update']
		if not self.receiveOk(event) and not self.receiveNo(event) and not self.Reboot(event):
			self.gotAnnoyed()
			if not self.flareUp():
				event.kwargs['update'].message.reply_text('認真聽我說話好不好...別岔開話題！\n先回答我剛剛的問題：')
			return True
		else:
			return False

	"""
	Others
	"""
	def getMessageType(self,event):
		data = event.kwargs['data']
		message_types=[
			'text',
			'sticker',
			'photo',
			'document',
			'audio',
			'voice',
			'video',
			'location'
		]
		for type in message_types:
			if type in data['message']:
				return type

	def resetAnnoyRate(self,*args):
		self.anger_bot.resetLevel()
	def gotAnnoyed(self):
		self.anger_bot.gotAnnoyed()
	def gotSatisfied(self):
		self.anger_bot.gotSatisfied()
	def flareUp(self):
		return self.anger_bot.flareUp()


import setuptools

with open("VERSION", "r") as f:
    version = f.read().strip()

with open("README.md", "r") as f:
    long_description = f.read()

setuptools.setup(
   name="cockpitdecks",
   version=version,
   description="Application to use streamdeck, loupedeck, and xtouch-mini with X-Plane flight simulator.",
   author="Pierre M",
   author_email="pierre@devleaks.be",
   url="https://github.com/devleaks/cockpitdecks",
   package_dir={"": "cockpitdecks"},
   packages=setuptools.find_packages(where="cockpitdecks"),
   install_requires=[
      "pillow>=9.5.0",
      "ruamel.yaml"
   ],
   license="MIT",
   long_description=long_description,
   long_description_content_type="text/markdown",
   include_package_data=True,
   python_requires=">=3.8,<3.11",
)


import string
from django.core.management.base import BaseCommand
from regluit.bisac.models import BisacHeading
from regluit.core.models import Subject

class Command(BaseCommand):
    help = "add and convert existing subjects to Bisac"

    def handle(self, **options):
        matches=0
        for bisac_heading in BisacHeading.objects.all():
            for subject in Subject.objects.filter(name=bisac_heading.full_label):
                subject.authority='bisacsh'
                subject.name = bisac_heading.full_label
                subject.save()
                matches += 1
        self.stdout.write("%s bisac headings converted" % matches)


from bottle import route,run,request
import ujson as json

kv = {}

@route('/kv')
def kv_op():
	req = request
	op = req.query.get('op')
	if op=='get':
		k = req.query.get('k')
		v = json.dumps(kv.get(k))
		return v
	elif op=='set':
		k = req.query.get('k')
		v = req.query.get('v')
		kv[k] = v
		return json.dumps({'k':k,'v':v})

#from gevent import monkey
#monkey.patch_all()
run(host='0.0.0.0',port=8080,server='meinheld')


from tables.TvShowTorrent import TvShowTorrent, TvTorrentParsingError
from common.BaseClass import BaseClass
from models.MediaFinder import MediaFinder
import pytest
bc = BaseClass('./config.ini')

def test_add_show()->None:
    torrent={
        'name':'Test torrent',
        'torrentId':'12345',
        'link':'test.link',
        'seeders':'23',
        'leechers':'34',
        'size':'2.1 GB',
        'time':'date string',
        'uploader':'up name',
        'uploaderLink':'up link',
        }
    show_torrent=TvShowTorrent()
    show_torrent.parse_data(torrent)
    assert show_torrent._torrent_id == '12345'

def test_filter_results()->None:
    show_list=[]
    bc = BaseClass('./config.ini')
    query=MediaFinder(bc)
    results = query.query('tv','')
    for show in results:
        search_show=TvShowTorrent()
        search_show.parse_data(show)
        if search_show.matches('',2,2) and \
            search_show._adjusted_size >0.8:
            show_list.append(search_show)
    assert len(show_list)> 0

def test_add_show_error()->None:
    error_catch=False
    torrent={
        'name':'Test torrent',
        'torrentId':'12345',
        'link':'test.link',
        'seeders':'23',
        'leechers':'34',
        'size':'2.1 GB',
        'time':'date string',
        'uploaderrr':'up name',
        'uploaderLink':'up link',
        }
    try:
        show_torrent=TvShowTorrent()
        show_torrent.parse_data(torrent)
    except TvTorrentParsingError:
        error_catch=True
    except :
        error_catch=False
    finally:
        assert error_catch==True


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from unittest.mock import MagicMock

from pyfritzhome import Fritzhome

from .helper import Helper

class TestFritzhomeDeviceTemperature(object):
    def setup_method(self):
        self.mock = MagicMock()
        self.fritz = Fritzhome("10.0.0.1", "user", "pass")
        self.fritz._request = self.mock
        self.fritz._devices = {}

    def test_get_temperature(self):
        self.mock.side_effect = [
            Helper.response("thermostat/device_hkr_fritzos_7"),
            "245",
        ]

        self.fritz.update_devices()
        device = self.fritz.get_device_by_ain("12345")

        assert device.get_temperature() == 24.5
        device._fritz._request.assert_called_with(
            "http://10.0.0.1/webservices/homeautoswitch.lua",
            {"ain": "12345", "switchcmd": "gettemperature", "sid": None},
        )


from flask import Flask, render_template, request, session, redirect, url_for, flash
from flask_mysqldb import MySQL
app = Flask(__name__)
app.secret_key = 'anahtar'

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'registerdb'

mysql = MySQL(app)

@app.route("/")
def Anasayfa():
    return render_template("movieapp.html")

@app.route("/login")
def Login():
    return render_template("login.html")

@app.route("/uyelik")
def Uyelik():
    return render_template("register.html")

@app.route("/hakkımda.html")
def Hakkımda():
    return render_template("hakkımda.html")

@app.route("/iletisim.html")
def İletisim():
    return render_template("iletisim.html")

@app.route("/kayit", methods=["POST"])
def kayit():
    if request.method == "POST":
        isim = request.form["isim"]
        soyisim = request.form["soyisim"]
        email = request.form["email"]
        sifre = request.form["sifre"]
        cinsiyet = request.form["cinsiyet"]

        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO uyeler(isim, soyisim, email, sifre, cinsiyet) VALUES (%s, %s, %s, %s, %s)", (isim, soyisim, email, sifre, cinsiyet))
        mysql.connection.commit()
        cur.close()
        return "Kayıt başarılı bir şekilde eklendi."

@app.route("/giris", methods=["GET", "POST"])
def giris():
    if request.method == "POST":
        isim = request.form["isim"]
        sifre = request.form["sifre"]

        cur = mysql.connection.cursor()
        cur.execute("SELECT * FROM uyeler WHERE isim = %s AND sifre = %s", (isim, sifre))
        kullanıcı = cur.fetchone()
        cur.close()

        if kullanıcı:
            session["user_id"] = kullanıcı[0]
            return "Hoşgeldiniz: " + session["user_id"]
        else:
            flash("E-posta veya şifre yanlış. Lütfen tekrar deneyin.", "danger")
            return render_template("Login.html")

if __name__ == "__main__":
    app.run(debug=True, port = 3306)


import numpy as np

from utils import get_dcg, get_precisionk

class Validator:
    '''This class holds the search function and the results of the search function
    with the queries from the Queries class and the relevance scores from the Validator class.'''
    def __init__(self):
        self.dcg = []
        self.ndcg = []
        self.precisionk = []
        # result of the search function in document ID, list of numpy arrays with document IDs in order of relevance
        self.results = []
        # search function results mapped to experts (first mentioned expert first) [['Alexander Mundt', 'Tatjana Gust']]
        self.rankings = []
        # search function results mapped to relevance scores, list of numpy arrays with top_k relevance scores
        self.scores = []
        self.scoresnan = []

    def __get_scores(self, expert2id, expert2query, expert2querynan, top_k):
        scores = []
        scoresnan = []
        for idx, result in enumerate(self.rankings):
            expert_ids = [expert2id[expert] for expert in result[0:top_k]]
            scores.append(expert2query[idx, expert_ids])
            scoresnan.append(expert2querynan[idx, expert_ids])
        self.scores = scores
        self.scoresnan = scoresnan

    def __get_ndcg(self, idcg):
        self.dcg = [get_dcg(score) for score in self.scores]
        self.ndcg = np.divide(self.dcg, idcg)

    def __get_precisionk(self):
        self.precisionk = [get_precisionk(score) for score in self.scores]

    def validate(self, rankings, truth):
        self.rankings = rankings
        self.__get_scores(truth.expert2id, truth.expert2query, truth.expert2querynan, truth.top_k)
        self.__get_ndcg(truth.idcg)
        self.__get_precisionk()
        return self.ndcg


from django.db import models
import datetime
from attendance.models import *
from twilio.base.exceptions import TwilioRestException
from twilio.rest import Client
import os
from dotenv import load_dotenv
load_dotenv()
def sendsms(phone,msg):

    client = Client(os.getenv('Account_SID'), os.getenv('Auth_Token'))

    try:
        message = client.messages.create(
            body=f'{msg}',
            from_=os.getenv('Phone_Number'),
            to=phone
        )
    except TwilioRestException as e:
        print(e)
        return False

class student_requests(models.Model):
    request_id = models.CharField(max_length=100, null=False, unique=True)
    reason = models.CharField(max_length=300, null=False)
    guardian_phone = models.CharField(max_length=11, null=False)
    relation = models.CharField(max_length=100, null=False)
    guardian_name = models.CharField(max_length=100, null=False)
    status = models.CharField(max_length=100, null=False)
    date = models.DateField(auto_now_add=True)
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    cc = models.CharField(max_length=100, null=True )
    hod = models.CharField(max_length=100,null = True)

    def save(self, *args, **kwargs):

        Student = self.student
        CC = Roles.objects.get( name = "CC", department = Student.department, semester = self.student.curent_sem, section = self.student.section)
        HOD = Roles.objects.get( name = "HOD", department = Student.department, semester = self.student.curent_sem)

        if CC :
            self.cc = CC.teacher.id

            if self.status == "Pending" or not self.status:
                teacher = Teacher.objects.get(id = CC.teacher.id)
                x=sendsms(f'+91{teacher.phone}', "Dear CC New request for approval is pending ")
                print(x)

        else :
            self.cc = "not found"

        if  HOD:
            self.hod = HOD.teacher.id

        else :

            self.hod = "not found"

        if not self.request_id:
            self.request_id = f"{self.student.roll}-{datetime.date.today().strftime('%Y%m%d')}"

        super().save(*args, **kwargs)


import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.resnet import BasicBlock, conv1x1, resnet34
from argparse import Namespace

import sys
sys.path.append("flownet2_pytorch")

from flownet2_pytorch.networks import FlowNetC

class FlowNet2C(FlowNetC.FlowNetC):
    def __init__(self, args, batchNorm=False, div_flow=20):
        super(FlowNet2C, self).__init__(args, batchNorm=batchNorm, div_flow=div_flow)
        self.rgb_max = args.rgb_max
        self.last_conv = nn.Sequential(
            nn.LeakyReLU(0.1, inplace=True),
            nn.Conv2d(2, 1, 1),
            nn.ReLU(),
        )
        self.upsampled_ = nn.ConvTranspose2d(1, 1, 4, 4)

    def forward(self, x1, x2):
        inputs = torch.stack([x1, x2], dim=2)

        rgb_mean = inputs.contiguous().view(inputs.size()[:2] + (-1,)).mean(dim=-1).view(
            inputs.size()[:2] + (1, 1, 1,))

        x = (inputs - rgb_mean) / self.rgb_max
        x1 = x[:, :, 0, :, :]
        x2 = x[:, :, 1, :, :]

        # FlownetC top input stream
        out_conv1a = self.conv1(x1)
        out_conv2a = self.conv2(out_conv1a)
        out_conv3a = self.conv3(out_conv2a)

        # FlownetC bottom input stream
        out_conv1b = self.conv1(x2)

        out_conv2b = self.conv2(out_conv1b)
        out_conv3b = self.conv3(out_conv2b)

        # Merge streams
        out_corr = self.corr(out_conv3a, out_conv3b)  # False
        out_corr = self.corr_activation(out_corr)

        # Redirect top input stream and concatenate
        out_conv_redir = self.conv_redir(out_conv3a)

        in_conv3_1 = torch.cat((out_conv_redir, out_corr), 1)

        # Merged conv layers
        out_conv3_1 = self.conv3_1(in_conv3_1)

        out_conv4 = self.conv4_1(self.conv4(out_conv3_1))

        out_conv5 = self.conv5_1(self.conv5(out_conv4))
        out_conv6 = self.conv6_1(self.conv6(out_conv5))

        flow6 = self.predict_flow6(out_conv6)
        flow6_up = self.upsampled_flow6_to_5(flow6)
        out_deconv5 = self.deconv5(out_conv6)

        concat5 = torch.cat((out_conv5, out_deconv5, flow6_up), 1)

        flow5 = self.predict_flow5(concat5)
        flow5_up = self.upsampled_flow5_to_4(flow5)
        out_deconv4 = self.deconv4(concat5)
        concat4 = torch.cat((out_conv4, out_deconv4, flow5_up), 1)

        flow4 = self.predict_flow4(concat4)
        flow4_up = self.upsampled_flow4_to_3(flow4)
        out_deconv3 = self.deconv3(concat4)
        concat3 = torch.cat((out_conv3_1, out_deconv3, flow4_up), 1)

        flow3 = self.predict_flow3(concat3)
        flow3_up = self.upsampled_flow3_to_2(flow3)
        out_deconv2 = self.deconv2(concat3)
        concat2 = torch.cat((out_conv2a, out_deconv2, flow3_up), 1)

        flow2 = self.predict_flow2(concat2)

        # Reduce to 1 channel
        flow2 = self.last_conv(flow2)

        # last_flow = self.upsample1(flow2)
        last_flow = self.upsampled_(flow2)

        return out_conv6, last_flow

if __name__ == "__main__":
    from argparse import Namespace
    cfg = Namespace()
    cfg.rgb_max = 255
    cfg.fp16 = False

    img = torch.rand(3, 3, 256, 256).cuda()

    net = FlowNet2C(cfg).cuda()

    out_conv6, last_flow = net(img, img)
    print(last_flow.size())


import copy
import sys

import bitarray

def fibonacciEncoding(n, right):
    # this code will start from the largest index of the fibonacci that f <= n
    code_word = [0] * (right+2)

    # additional '1' bit
    code_word[right + 1] = 1
    # this loop will break when n =0, this means we find a sum of one or more distinct Fibonacci numbers

    while n:

        # mark the index is 1
        code_word[right] = 1

        # Subtract this fibonacci at index from n
        n -= fib[right]

        # move to the left
        right -= 1

        # mark all index of Fibonacci > n as not used (0 bit),
        # move to the left
        while (right >= 0 and fib[right] > n):
            code_word[right] = 0
            right -= 1

    # return pointer to code_word
    return code_word

class nodeHuffan:
    def __init__(self, frequencies, c, leftNode = None, rightNode = None):
        # the frequencies of each unique character
        self.frequencies = frequencies
        # the unique character
        self.c = c
        # node left of current node
        self.leftNode = leftNode
        # node right of current node
        self.rightNode = rightNode
        # the bit of node 0 if the in the left, and 1 in the right
        self.bit = None

def getHuffanCodeWord(node, c):
    global dp
    # plus the current bit of this node to the string c

    c_1 = copy.deepcopy(c)
    if node.bit is not None:
        c_1.append(node.bit)

    # if node left not null move to the node left
    if node.leftNode:
        getHuffanCodeWord(node.leftNode, c_1)
    # if node right not null move to the node right
    if node.rightNode:
        getHuffanCodeWord(node.rightNode, c_1)
    # if both node are null, this is the final binary value of this char of this node
    if not node.rightNode and not node.leftNode:
        dp[ord(node.c)] = c_1

def huffan(nodes):

    while len(nodes) > 1:
        # sort the node following to the frequencies of each char
        nodes = sorted(nodes, key=lambda x: x.frequencies)

        l, r = nodes[0], nodes[1]
        # the small value is in the left node and set 0 bit
        # the large value is in the right node and set 1 bit
        l.bit = 0
        r.bit = 1
        # remove two of them of the array
        nodes.pop(0)
        nodes.pop(0)
        # create a new node represents the sum of frequencies of two node left and right
        combinedNode = nodeHuffan(l.frequencies + r.frequencies, l.c + r.c, l, r)

        # add new node to the array
        nodes.append(combinedNode)

    getHuffanCodeWord(nodes[0], [])

def writeOutput(bits):

    # Open output file with correct name
    with open('encodedBWT.bin', 'wb') as fh:
        bits.tofile(fh)

def readInput(txtFileName):
    # Open and read the text file
    txtFile = open(txtFileName, 'r')
    txt = txtFile.read()
    # Remember to close the file
    txtFile.close()

    return txt

def bisect_left(a, x, left, right):
    # This function returns the place in the sorted list where the number specified in the argument may be added
    # to keep the resultant list sorted. If the element already exists in the list,
    # the left most position  which it must be added is returned.
    while left < right:
        mid = (left + right) // 2
        if x <= a[mid]:
            right = mid
        else:
            left = mid + 1
    return right

if __name__ == '__main__':
    bits = bitarray.bitarray()
    global dp
    dp = [[]] * 127
    txtFileName = sys.argv[1]
    s = readInput(txtFileName)

    freq = [0] * 127
    nUniqChars = []
    frequencies = []
    # count the frequencies of each char
    for i in s:
        freq[ord(i)] += 1

    for i in range(0, 127):
        if freq[i] > 0:
            nUniqChars.append(chr(i))
            frequencies.append(freq[i])
    nodes = []
    # push both char and its frequency to the nodes
    for i in range(len(nUniqChars)):
        nodes.append(nodeHuffan(frequencies[i], nUniqChars[i]))

    # after this progress we will save the code word of each char in the dp array
    huffan(copy.deepcopy(nodes))
    maxN = 3
    a = 1
    b = 2
    c = 0
    # find the maximum index that when c > len(s) this loop will break
    while c <= len(s):
        c = a + b
        a = copy.deepcopy(b)
        b = c
        maxN += 1

    fib = [0 for i in range(maxN + 1)]
    fib[0] = 1
    fib[1] = 2
    i = 2
    # initialize the array fibonacci with max length is maxN
    # it will reduce the time in the next step when we find the fibonacci code word
    while fib[i - 1] <= len(s):
        fib[i] = fib[i - 1] + fib[i - 2]
        i += 1
    # use the bisect left that we created to find the lower bound of len(s) in the array fibonacci we create above
    # log(n) time complexity
    index = bisect_left(fib, len(s), 0, maxN)
    while fib[index] > len(s) or fib[index] == 0:
        index -= 1
    bits.extend( fibonacciEncoding(len(s), index))
    #print(maxN, fib[index], bits)
    index = bisect_left(fib, len(nUniqChars), 0, maxN)
    while fib[index] > len(nUniqChars) or fib[index] == 0:
        index -= 1
    bits.extend(fibonacciEncoding(len(nUniqChars), index))
    #print(fib[index], bits)
    for i in nodes:
        # convert char to ascii binary
        temp = str(bin(ord(i.c)))
        temp = temp[2:len(temp)]
        # if the binary length is less than 7 append 0 in the start until the length temp equal 7
        for j in range(len(temp), 7):
            temp = "0" + temp
        #print(bits, temp)
        for j in range(0, 7):
            if temp[j] == "0":
                bits.append(0)
            else:
                bits.append(1)
        # get the fibonacci code len
        index = bisect_left(fib, len(dp[ord(i.c)]), 0, maxN)
        while fib[index] > len(dp[ord(i.c)]) or fib[index] == 0:
            index -= 1
        bits.extend(fibonacciEncoding(len(dp[ord(i.c)]), index))
        # extend to bits huffman code of i.c
        bits.extend( dp[ord(i.c)])
        #print(bits,i, temp, fibonacciEncoding(len(dp[ord(i.c)]), index), dp[ord(i.c)])
    mark = [0] * 127
    for i in s:
        # if this char is marked, it will continue
        if mark[ord(i)]:
            continue
        mark[ord(i)] = 1
        # extend to bits huffman code of i.c
        bits.extend(dp[ord(i)])
        # get the fibonacci run len
        index = bisect_left(fib, freq[ord(i)], 0, maxN)
        while fib[index] > freq[ord(i)] or fib[index] == 0:
            index -= 1
        bits.extend(fibonacciEncoding(freq[ord(i)], index))
    #print(bits)
    writeOutput(bits)


#!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
"""
----------------------------------------------------------------------------------------------
MODULO ...: TESHUVA
SCRIPT ...: loaderRelatorio_DUB_Resolucao6449.py
CRIACAO ..: 13/07/2021
AUTOR ....: EDUARDO DA SILVA FERREIRA / KYROS TECNOLOGIA
            eduardof@kyros.com.br
DESCRICAO.: Geração de relatórios PVA
----------------------------------------------------------------------------------------------
PARAMETROS:
Parâmetros de entrada:
1)	IE: Inscrição estadual - Obrigatório
2)	ANO: Ano no formato AAAA - Obrigatório
3)	TRIMESTRE: Periodo Trimestre - Obrigatório

----------------------------------------------------------------------------------------------
  HISTORICO :
   01/09/2021 - Marcelo Gremonesi -  Adquações para novo painel
----------------------------------------------------------------------------------------------
"""
import sys
import os
SD = ('/' if os.name == 'posix' else '\\')
dir_base = os.path.join( os.path.realpath('.').split(SD+'PROD'+SD)[0], 'PROD') if os.path.realpath('.').__contains__(SD+'PROD'+SD) else os.path.join( os.path.realpath('.').split(SD+'DEV'+SD)[0], 'DEV')
sys.path.append(dir_base)
import configuracoes

import datetime
import cx_Oracle
import re
import shutil
import traceback
import string
import openpyxl
from openpyxl.utils import get_column_letter

from openpyxl.cell import cell

# Nome do script
nome_script = os.path.basename( sys.argv[0] ).replace('.py', '')

# Lista de String
gv_lista_string = list(string.ascii_lowercase)

import comum
import sql
variaveis = {'teste': '001'}
comum.variaveis = variaveis
sql.variaveis = variaveis
from layout import *
from pathlib import Path
from openpyxl.styles import Font, Border, Side, PatternFill, Alignment
from openpyxl import Workbook

log.gerar_log_em_arquivo = True

"""
Funcao para retornar UF
"""
def retornar_UF(p_IE):

    l_UF = ""

    l_query="""
    select distinct f.unfe_sig  from openrisow.filial f where f.fili_cod_insest='%s' and rownum < 2
    """%(p_IE)

    l_cursor = sql.geraCnxBD(configuracoes)
    l_cursor.executa(l_query)
    l_result = l_cursor.fetchone()

    if(l_result != None):
        for campo in l_result:
            l_UF = campo

    return(l_UF)
"""
DEFINE O TAMANHO DAS COLUNAS
"""
def adjust_column(ws, min_row, min_col, max_col):
    column_widths = []
    for i, col in \
        enumerate(
            ws.iter_cols(min_col=min_col, max_col=max_col, min_row=min_row)
        ):
        for cell in col:
            value = cell.value
            if value is not None:
                if isinstance(value, str) is False:
                    value = str(value)
                try:
                    column_widths[i] = max(column_widths[i], len(value))
                except IndexError:
                    column_widths.append(len(value))
    for i, width in enumerate(column_widths):
        col_name = get_column_letter(min_col + i)
        value = column_widths[i] + 2
        value = int(round(value + value * 0.2,0))
        ws.column_dimensions[col_name].width = value
"""
CONTORNO
"""
def contorno_cli_clf( ws, ci,li,cf,lf, edsi ):
    n=Side(border_style= None    , color='00000000')
    f=Side(border_style='thin'   , color='00000000')
    m=Side(border_style='medium' , color='00000000')
    d=Side(border_style='double' , color='00000000')
    p=Side(border_style='dotted' , color='00000000')
    t=Side(border_style='dashed' , color='00000000')
    g=Side(border_style='thick'  , color='00000000')

    b=n

    if (edsi=="n"):
        b=n
    elif (edsi=='f'):
        b=f
    elif (edsi=='m'):
        b=m
    elif (edsi=='d'):
        b=d
    elif (edsi=='p'):
        b=p
    elif (edsi=='t'):
        b=t
    elif (edsi=='g'):
        b=g
    else:
        return

    for c in range(ci,cf+1):
        ws.cell(row=li-1,column=c).border = Border(n,n,n,b)
        ws.cell(row=lf+1,column=c).border = Border(n,n,b,n)
    for l in range(li,lf+1):
        ws.cell(row=l,column=ci-1).border = Border(n,b,n,n)
        ws.cell(row=l,column=cf+1).border = Border(b,n,n,n)

"""
Retorna a validação de entrada e dos arquivos de configuração
"""
def validacaoEntrada():
    try:

        global gv_ie
        global gv_ano
        global gv_trimestre
        global gv_usuario
        global gv_senha
        global gv_banco
        global gv_caminho
        global gv_relatorio

        l_ret = 0

        # Carrega os parametros do arquivo .cfg

        log("-"*150)

        ### Cria os parametros do script
        comum.addParametro( 'IE', None, 'Inscricao Estadual (IE)', True, '77452443')
        comum.addParametro( 'ANO',  None, "ANO (YYYY)", True, '2015' )
        comum.addParametro( 'TRIMESTRE', None, 'Trimestre - Periodo (1,2,3,4)', True, '1')

        # Validacao dos parametros de entrada
        if not comum.validarParametros() :
            l_ret = 91

        else:
            # INICIO ELSE
            gv_ie = comum.getParametro('IE').upper().strip()
            gv_ano = comum.getParametro('ANO').upper().strip()
            gv_trimestre = comum.getParametro('TRIMESTRE').upper().strip()

            if not l_ret :
                try:
                    l_iei = re.sub('[^0-9]','',gv_ie)
                    if ( (l_iei == "") or (l_iei == "''") or (l_iei == '""') or (int("0"+l_iei) == 0)):
                        log("PARAMETRO IE : Invalido! " + gv_ie)
                        l_ret = 91
                except Exception as e:
                    log("PARAMETRO IE : Invalido! " + gv_ie)
                    l_ret = 91

            if not l_ret :
                try:
                    if (len(gv_ano) != 4):
                        log("PARAMETRO ANO: Invalido! " + gv_ano)
                        l_ret = 91
                    else:
                        if (
                        int(gv_ano) > datetime.datetime.now().year
                        or int(gv_ano) < (datetime.datetime.now().year)-50
                        ):
                            log("PARAMETRO ANO : Invalido! " + gv_ano)
                            l_ret = 91
                except Exception as e:
                    log("PARAMETRO ANO : Invalido! " + gv_ano)
                    l_ret = 91

            if not l_ret :
                try:
                    if (int(gv_trimestre) > 4 or int(gv_trimestre) < 1 ):
                            log("PARAMETRO TRIMESTRE : Invalido! " + gv_trimestre)
                            l_ret = 91
                except Exception as e:
                    log("PARAMETRO TRIMESTRE : Invalido! " + gv_trimestre)
                    l_ret = 91
            # FIM ELSE

        # Verifica os parametros
        if not l_ret :
            try:

                gv_caminho = configuracoes.dir_salvar_arq  #config['caminho'].strip()
                gv_relatorio = configuracoes.nome_relatorio.replace("<<ANO>>",gv_ano).replace("<<IE>>",gv_ie).replace("<<TRIMESTRE>>",gv_trimestre).replace("<<DATA_HORA>>",datetime.datetime.now().strftime('%Y%m%Y%H%M%S')).upper().strip()  #config['relatorio'].replace("<<ANO>>",gv_ano).replace("<<IE>>",gv_ie).replace("<<TRIMESTRE>>",gv_trimestre).upper().strip()
                log('Nome do arquivo a ser gerado........:',gv_relatorio )
                log("Diretorio onde sera salvo o arquivo.:",gv_caminho)

                if not l_ret :
                    if (len(gv_relatorio) <= 5 or not gv_relatorio.endswith(".XLSX")
                        ):
                        log("PARAMETRO DO ARQUIVO  RELATORIO: INVALIDO! " + gv_relatorio)
                        l_ret = 91
                    else:
                        log("Arquivo do relatorio : " + gv_relatorio)

                if not l_ret :
                    try:
                        if not os.path.isdir(gv_caminho):
                            log("Diretório não existente : " + gv_caminho)
                            os.makedirs(gv_caminho)
                            log("Diretório criado : " + gv_caminho)

                        gv_relatorio = os.path.join(gv_caminho, gv_relatorio)
                    # victor
                        # if os.path.isfile(gv_relatorio):
                        #     log("Arquivo já existente !!!  " + gv_relatorio)
                        #     l_ret = 91

                    except Exception as e:
                        txt = traceback.format_exc()
                        log(gv_caminho + " >> PARAMETRO DO RELATÓRIO " + gv_relatorio +  " INVÁLIDO! " + str(e))
                        l_ret = 91

            except Exception as e:
                txt = traceback.format_exc()
                log("PARAMETRO DOS ARQUIVOS NAO ENCONTRADOS! " + str(e))
                l_ret = 91

        return l_ret
    except Exception as e:
        txt = traceback.format_exc()
        log("ERRO VALIDAÇÃO DOS PARAMETROS DE ENTRADA: " + str(e))
        l_ret = 93
        return l_ret

def set_border_edsi( ws, cell_range, edsi):
    b=[]

    n=Side(border_style= None    , color='00000000')
    f=Side(border_style='thin'   , color='00000000')
    m=Side(border_style='medium' , color='00000000')
    d=Side(border_style='double' , color='00000000')
    p=Side(border_style='dotted' , color='00000000')
    t=Side(border_style='dashed' , color='00000000')
    g=Side(border_style='thick'  , color='00000000')

    for x in (0,1,2,3):
        if (edsi[x]=="n"):
            b.append(n)
        elif (edsi[x]=='f'):
            b.append(f)
        elif (edsi[x]=='m'):
            b.append(m)
        elif (edsi[x]=='d'):
            b.append(d)
        elif (edsi[x]=='p'):
            b.append(p)
        elif (edsi[x]=='t'):
            b.append(t)
        elif (edsi[x]=='g'):
            b.append(g)
        else:
            return

    rows = ws[cell_range]
    for row in rows:
        for cell in row:
            cell.border = Border(left=b[0],right=b[1],top=b[2],bottom=b[3])

"""
Retorna dados
"""
def retorna_Dados(p_ie,
                    p_data_inicial,
                    p_data_final,
                    p_tipo=0):

    l_retorno=[]

    try:

        if str(p_tipo).strip() == "0":
            l_query = """
WITH consulado AS
  ( SELECT DISTINCT razao_social, cnpj FROM gfcadastro.tb_clientes_consulados
  )
SELECT
  /*+ parallel(12) */
  cc.razao_social                     AS CONSULADO,
  it.cgc_cpf                          AS CNPJ,
  TO_CHAR(it.infst_dtemiss,'mm/yyyy') AS MES,
  SUM(it.infst_isenta_icms)           AS ICMS_ISENCAO
FROM openrisow.ITEM_NFTL_SERV it,
  consulado cc
WHERE it.EMPS_COD = 'TBRA'
AND it.FILI_COD  IN
  (SELECT fili_cod
  FROM openrisow.filial f
  WHERE f.emps_cod     = 'TBRA'
  AND f.fili_cod_insest= '%s'
  )
AND it.infst_serie                     IS NOT NULL
AND it.infst_ind_canc                  <> 'S'
AND it.infst_dtemiss >= TRUNC(TO_DATE('%s', 'DD/MM/YYYY'),'MM')
AND it.infst_dtemiss <= LAST_DAY(TO_DATE('%s', 'DD/MM/YYYY'))
AND it.cgc_cpf                          = cc.cnpj
GROUP BY cc.razao_social,
  it.cgc_cpf,
  TO_CHAR(it.infst_dtemiss,'mm/yyyy')
ORDER BY cc.razao_social,
  it.cgc_cpf,
  TO_CHAR(it.infst_dtemiss,'mm/yyyy')
    """%(p_ie,p_data_inicial,p_data_final)

        else:
            l_query = """
WITH consulado AS (SELECT DISTINCT RAZAO_SOCIAL, CNPJ FROM gfcadastro.tb_clientes_consulados )
SELECT /*+ parallel(12) */
       to_char(it.INFST_DTEMISS,'mm/yyyy') AS Periodo,
       it.CADG_COD,
       cc.razao_social,
       it.CGC_CPF,
       to_char(it.INFST_DTEMISS,'dd/mm/yyyy') AS DTEmissao,
       it.INFST_serie,
       it.INFST_NUM,
       it.SERV_COD,
       it.INFST_DSC_COMPL,
       it.INFST_VAL_CONT,
       it.INFST_BASE_ICMS,
       it.INFST_VAL_ICMS,
       it.INFST_ISENTA_ICMS,
       it.INFST_OUTRAS_ICMS
  FROM openrisow.ITEM_NFTL_SERV it,
       consulado cc
 WHERE it.EMPS_COD       = 'TBRA'
   AND it.FILI_COD       IN (select fili_cod from openrisow.filial f
                            where f.emps_cod = 'TBRA'
                            AND f.fili_cod_insest= '%s')
   AND it.INFST_SERIE   IS NOT NULL
   AND it.INFST_IND_CANC <> 'S'
   AND it.INFST_dtemiss >= TRUNC(TO_DATE('%s', 'DD/MM/YYYY'),'MM')
   AND it.INFST_dtemiss <= LAST_DAY(TO_DATE('%s', 'DD/MM/YYYY'))
   AND it.CGC_CPF = cc.cnpj
order by it.INFST_DTEMISS, CGC_CPF,  INFST_NUM, INFST_DSC_COMPL
    """%(p_ie,p_data_inicial,p_data_final)

        l_cursor = sql.geraCnxBD(configuracoes)
        l_cursor.executa(l_query)
        l_result = l_cursor.fetchone()
        l_lin = 0

        if l_result is not None:
            while l_result:
                #Cria uma linha para informar as colunas
                l_retorno.append([])

                # busca as colunas
                for field in l_result:
                    l_retorno[l_lin].append(field)

                # + 1
                l_lin = l_lin + 1
                # prox. registro
                l_result = l_cursor.fetchone()

    except Exception as e:
        txt = traceback.format_exc()

        try:
            log(" >> FALHA NA GERAÇÃO DOS DADOS ! " + str(txt) + " >> " +  str(e))
        except:
            pass
        try:
            l_retorno = None
        except:
            pass

    return l_retorno

"""
Processamento de relatório
"""
def processarRelatorio(p_ie,
                       p_ano,
                       p_trimestre,
                       p_relatorio):
    l_ret = 0
    try:

        l_dadosSintetico = []
        l_dadosAnalitico = []

        l_mes_01 = "10"
        l_mes_02 = "11"
        l_mes_03 = "12"

        if int(p_trimestre) == 1:
            l_mes_01 = "01"
            l_mes_02 = "02"
            l_mes_03 = "03"
        elif int(p_trimestre) == 2:
            l_mes_01 = "04"
            l_mes_02 = "05"
            l_mes_03 = "06"
        elif int(p_trimestre) == 3:
            l_mes_01 = "07"
            l_mes_02 = "08"
            l_mes_03 = "09"

        l_data_01 = l_mes_01 + "/" + str(p_ano)
        l_data_02 = l_mes_02 + "/" + str(p_ano)
        l_data_03 = l_mes_03 + "/" + str(p_ano)

        if not l_ret:
            l_dadosSintetico = retorna_Dados(p_ie=p_ie,
                                             p_data_inicial="01/" + l_data_01,
                                             p_data_final="01/" + l_data_03)
            if l_dadosSintetico is None:
                log("Não foi encontrado nenhum dados sintetico! (1) ")
                l_ret = 1
            elif len(l_dadosSintetico) <= 1:
                log("Não foi encontrado nenhum dados sintetico! (2) ")
                l_ret = 1
            else:
                log("Quantidade de dados sintetico: " + str(len(l_dadosSintetico)))

        if not l_ret:
            l_dadosAnalitico = retorna_Dados(p_ie=p_ie,
                                            p_data_inicial="01/" + l_data_01,
                                            p_data_final="01/" + l_data_03,
                                            p_tipo=1)
            if l_dadosAnalitico is None:
                log("Não foi encontrado nenhum dados analitico! (1) ")
                l_ret = 1
            elif len(l_dadosAnalitico) <= 1:
                log("Não foi encontrado nenhum dados analitico! (2) ")
                l_ret = 1
            else:
                log("Quantidade de dados analitico: " + str(len(l_dadosAnalitico)))

        if not l_ret:
            log("\n")
            log("Iniciando a criacao do relatório " + str(p_relatorio))

            l_nome_planilha0 = "Dados - Trimestral"
            l_nome_padrao = "Dados Mensal <<MES>>_<<ANO>>"
            l_nome_planilha1 = l_nome_padrao.replace("<<MES>>",l_mes_01).replace("<<ANO>>",str(p_ano))
            l_nome_planilha2 = l_nome_padrao.replace("<<MES>>",l_mes_02).replace("<<ANO>>",str(p_ano))
            l_nome_planilha3 = l_nome_padrao.replace("<<MES>>",l_mes_03).replace("<<ANO>>",str(p_ano))

            # Criando arquivo principal
            arquivo_excel = Workbook()

            # Criando os worksheet
            log("Criando os worksheet : " + l_nome_planilha0
                                        + " >> " + l_nome_planilha1
                                        + " >> " + l_nome_planilha2
                                        + " >> " + l_nome_planilha3
                                        )
            planilha0 = arquivo_excel.active
            planilha0.title = l_nome_planilha0
            planilha1 = arquivo_excel.create_sheet(l_nome_planilha1 , 1)
            planilha2 = arquivo_excel.create_sheet(l_nome_planilha2 , 2)
            planilha3 = arquivo_excel.create_sheet(l_nome_planilha3 , 3)

            l_linha  = int(1)
            l_coluna = int(2)

            l_linha += 1

            log("Criando cabeçalho ... " + str(l_linha) + " >> " + str(l_coluna))
            planilha0.cell(l_linha,l_coluna,"Resolução 6449 -  (Trimestral)")
            planilha0.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha0.cell(l_linha,l_coluna).alignment = Alignment(horizontal='center')
            planilha0.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha0.merge_cells('B'+ str(l_linha) + ':E' + str(l_linha))

            planilha1.cell(l_linha,l_coluna,"Resolução 6449 - (Mensal)")
            planilha1.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha1.cell(l_linha,l_coluna).alignment = Alignment(horizontal='center')
            planilha1.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha1.merge_cells('B'+ str(l_linha) + ':N' + str(l_linha))

            planilha2.cell(l_linha,l_coluna,"Resolução 6449 - (Mensal)")
            planilha2.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha2.cell(l_linha,l_coluna).alignment = Alignment(horizontal='center')
            planilha2.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha2.merge_cells('B'+ str(l_linha) + ':N' + str(l_linha))

            planilha3.cell(l_linha,l_coluna,"Resolução 6449 - (Mensal)")
            planilha3.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha3.cell(l_linha,l_coluna).alignment = Alignment(horizontal='center')
            planilha3.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha3.merge_cells('B'+ str(l_linha) + ':N' + str(l_linha))

            l_linha += 1

            planilha0.cell(l_linha,l_coluna,"Inscrição Estadual: "+str(p_ie))
            planilha0.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha0.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha0.merge_cells('B'+ str(l_linha) + ':E' + str(l_linha))

            planilha1.cell(l_linha,l_coluna,"Inscrição Estadual: "+str(p_ie))
            planilha1.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha1.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha1.merge_cells('B'+ str(l_linha) + ':N' + str(l_linha))

            planilha2.cell(l_linha,l_coluna,"Inscrição Estadual: "+str(p_ie))
            planilha2.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha2.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha2.merge_cells('B'+ str(l_linha) + ':N' + str(l_linha))

            planilha3.cell(l_linha,l_coluna,"Inscrição Estadual: "+str(p_ie))
            planilha3.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha3.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha3.merge_cells('B'+ str(l_linha) + ':N' + str(l_linha))

            l_linha += 1

            planilha0.cell(l_linha,l_coluna,"Trimestre: "+str(p_trimestre))
            planilha0.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha0.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha0.merge_cells('B'+ str(l_linha) + ':C' + str(l_linha))
# victor
            planilha0.cell(l_linha,l_coluna+2,"Ano: "+str(p_ano))
            planilha0.cell(l_linha,l_coluna+2).font=Font(bold=True)
            planilha0.cell(l_linha,l_coluna+2).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha0.merge_cells('D'+ str(l_linha) + ':E' + str(l_linha))

            planilha1.cell(l_linha,l_coluna,"Mês/Ano: "+str(l_data_01))
            planilha1.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha1.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha1.merge_cells('B'+ str(l_linha) + ':N' + str(l_linha))

            planilha2.cell(l_linha,l_coluna,"Mês/Ano: "+str(l_data_02))
            planilha2.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha2.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha2.merge_cells('B'+ str(l_linha) + ':N' + str(l_linha))

            planilha3.cell(l_linha,l_coluna,"Mês/Ano: "+str(l_data_03))
            planilha3.cell(l_linha,l_coluna).font=Font(bold=True)
            planilha3.cell(l_linha,l_coluna).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
            planilha3.merge_cells('B'+ str(l_linha) + ':N' + str(l_linha))

            l_linha += 1

            planilha0.freeze_panes = 'A6'
            planilha1.freeze_panes = 'A6'
            planilha2.freeze_panes = 'A6'
            planilha3.freeze_panes = 'A6'

            l_col = l_coluna
            log("Criando as colunas ... " + str(l_linha) + " >> " + str(l_coluna))
            for nColuna in ("Consulado","CNPJ","Mês","ICMS - Isenção"):
                planilha0.cell(l_linha,l_col,nColuna)
                planilha0.cell(l_linha,l_col).font=Font(bold=True)
                planilha0.cell(l_linha,l_col).alignment = Alignment(horizontal='center')
                l_col = l_col + 1

            l_col = l_coluna
            for nColuna in ("Código do Cliente",
                            "Razão Social",
                            "CNPJ",
                            "Data Emissão",
                            "Série",
                            "Número NF",
                            "Código Serviço",
                            "Descrição Serviço",
                            "Valor Total",
                            "Base ICMS",
                            "Valor ICMS",
                            "Valor Isentas",
                            "Valor Outras"):
                planilha1.cell(l_linha,l_col,nColuna)
                planilha1.cell(l_linha,l_col).font=Font(bold=True)
                planilha1.cell(l_linha,l_col).alignment = Alignment(horizontal='center')

                planilha2.cell(l_linha,l_col,nColuna)
                planilha2.cell(l_linha,l_col).font=Font(bold=True)
                planilha2.cell(l_linha,l_col).alignment = Alignment(horizontal='center')

                planilha3.cell(l_linha,l_col,nColuna)
                planilha3.cell(l_linha,l_col).font=Font(bold=True)
                planilha3.cell(l_linha,l_col).alignment = Alignment(horizontal='center')

                l_col = l_col + 1

            # Guarda os valores iniciais
            l_col = l_coluna
            l_lin0 = l_linha
            l_lin1 = l_linha
            l_lin2 = l_linha
            l_lin3 = l_linha
            soma1  = 0.00
            soma2  = 0.00
            soma3  = 0.00

            log("Executando os dados ... " + str(l_linha) + " >> " + str(l_coluna))
            #Dados - 0
            for linha in l_dadosSintetico:
                l_lin0 += 1
                planilha0.cell(l_lin0,l_col+0,linha[0])
                planilha0.cell(l_lin0,l_col+1,linha[1])
                planilha0.cell(l_lin0,l_col+1).alignment = Alignment(horizontal='center')
                planilha0.cell(l_lin0,l_col+2,linha[2])
                planilha0.cell(l_lin0,l_col+2).alignment = Alignment(horizontal='center')
                planilha0.cell(l_lin0,l_col+3,linha[3])
                planilha0.cell(l_lin0,l_col+3).number_format = "#,##0.00"

                if linha[2] == str(l_data_01):
                    soma1 += linha[3]
                if linha[2] == str(l_data_02):
                    soma2 += linha[3]
                if linha[2] == str(l_data_03):
                    soma3 += linha[3]

            for linha in l_dadosAnalitico:
                if linha[0] == l_data_01:
                    l_lin1 += 1
                    planilha1.cell(l_lin1,l_col+0,linha[1])
                    planilha1.cell(l_lin1,l_col+1,linha[2])
                    planilha1.cell(l_lin1,l_col+2,linha[3])
                    planilha1.cell(l_lin1,l_col+3,linha[4])
                    planilha1.cell(l_lin1,l_col+4,linha[5])
                    planilha1.cell(l_lin1,l_col+5,linha[6])
                    planilha1.cell(l_lin1,l_col+6,linha[7])
                    planilha1.cell(l_lin1,l_col+7,linha[8])
                    planilha1.cell(l_lin1,l_col+8,linha[9])
                    planilha1.cell(l_lin1,l_col+9,linha[10])
                    planilha1.cell(l_lin1,l_col+10,linha[11])
                    planilha1.cell(l_lin1,l_col+11,linha[12])
                    planilha1.cell(l_lin1,l_col+12,linha[13])
                    planilha1.cell(l_lin1,l_col+8).number_format = "#,##0.00"
                    planilha1.cell(l_lin1,l_col+9).number_format = "#,##0.00"
                    planilha1.cell(l_lin1,l_col+10).number_format = "#,##0.00"
                    planilha1.cell(l_lin1,l_col+11).number_format = "#,##0.00"
                    planilha1.cell(l_lin1,l_col+12).number_format = "#,##0.00"

                elif linha[0] == l_data_02:
                    l_lin2 += 1
                    planilha2.cell(l_lin2,l_col+0,linha[1])
                    planilha2.cell(l_lin2,l_col+1,linha[2])
                    planilha2.cell(l_lin2,l_col+2,linha[3])
                    planilha2.cell(l_lin2,l_col+3,linha[4])
                    planilha2.cell(l_lin2,l_col+4,linha[5])
                    planilha2.cell(l_lin2,l_col+5,linha[6])
                    planilha2.cell(l_lin2,l_col+6,linha[7])
                    planilha2.cell(l_lin2,l_col+7,linha[8])
                    planilha2.cell(l_lin2,l_col+8,linha[9])
                    planilha2.cell(l_lin2,l_col+9,linha[10])
                    planilha2.cell(l_lin2,l_col+10,linha[11])
                    planilha2.cell(l_lin2,l_col+11,linha[12])
                    planilha2.cell(l_lin2,l_col+12,linha[13])
                    planilha2.cell(l_lin2,l_col+8).number_format = "#,##0.00"
                    planilha2.cell(l_lin2,l_col+9).number_format = "#,##0.00"
                    planilha2.cell(l_lin2,l_col+10).number_format = "#,##0.00"
                    planilha2.cell(l_lin2,l_col+11).number_format = "#,##0.00"
                    planilha2.cell(l_lin2,l_col+12).number_format = "#,##0.00"

                elif linha[0] == l_data_03:
                    l_lin3 += 1
                    planilha3.cell(l_lin3,l_col+0,linha[1])
                    planilha3.cell(l_lin3,l_col+1,linha[2])
                    planilha3.cell(l_lin3,l_col+2,linha[3])
                    planilha3.cell(l_lin3,l_col+3,linha[4])
                    planilha3.cell(l_lin3,l_col+4,linha[5])
                    planilha3.cell(l_lin3,l_col+5,linha[6])
                    planilha3.cell(l_lin3,l_col+6,linha[7])
                    planilha3.cell(l_lin3,l_col+7,linha[8])
                    planilha3.cell(l_lin3,l_col+8,linha[9])
                    planilha3.cell(l_lin3,l_col+9,linha[10])
                    planilha3.cell(l_lin3,l_col+10,linha[11])
                    planilha3.cell(l_lin3,l_col+11,linha[12])
                    planilha3.cell(l_lin3,l_col+12,linha[13])
                    planilha3.cell(l_lin3,l_col+8).number_format = "#,##0.00"
                    planilha3.cell(l_lin3,l_col+9).number_format = "#,##0.00"
                    planilha3.cell(l_lin3,l_col+10).number_format = "#,##0.00"
                    planilha3.cell(l_lin3,l_col+11).number_format = "#,##0.00"
                    planilha3.cell(l_lin3,l_col+12).number_format = "#,##0.00"

            log("Executando os totais ... " + str(l_linha) + " >> " + str(l_coluna))
            #Totais - 0

            if l_lin0 > l_linha:

                l_lin0 += 2

                planilha0.cell(l_lin0,l_col+0,"TOTAL TRIMESTRE:")
                planilha0.cell(l_lin0,l_col+0).font=Font(bold=True)
                planilha0.merge_cells('B'+ str(l_lin0) + ':D' + str(l_lin0))
                planilha0.cell(l_lin0,l_col+0).alignment = Alignment(horizontal='center')
                planilha0.cell(l_lin0,l_col+0).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

                planilha0.cell(l_lin0,l_col+3,"=SUM(E"+str(l_linha+1)+":E"+str(l_lin0-1)+")")
                planilha0.cell(l_lin0,l_col+3).font=Font(bold=True)
                planilha0.cell(l_lin0,l_col+3).number_format = "#,##0.00"
                planilha0.cell(l_lin0,l_col+3).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

                l_lin0 += 2

                planilha0.cell(l_lin0,l_col+0,"TOTAIS POR MÊS:")
                planilha0.cell(l_lin0,l_col+0).font=Font(bold=True)
                planilha0.merge_cells('B'+ str(l_lin0) + ':C' + str(l_lin0+2))
                planilha0.cell(l_lin0,l_col+0).alignment = Alignment(horizontal='center', vertical='center')
                planilha0.cell(l_lin0,l_col+0).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

                planilha0.cell(l_lin0,l_col+2,l_data_01)
                planilha0.cell(l_lin0,l_col+2).font=Font(bold=True)
                planilha0.cell(l_lin0,l_col+2).alignment = Alignment(horizontal='center', vertical='center')
                planilha0.cell(l_lin0,l_col+2).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

                planilha0.cell(l_lin0+1,l_col+2,l_data_02)
                planilha0.cell(l_lin0+1,l_col+2).font=Font(bold=True)
                planilha0.cell(l_lin0+1,l_col+2).alignment = Alignment(horizontal='center', vertical='center')
                planilha0.cell(l_lin0+1,l_col+2).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

                planilha0.cell(l_lin0+2,l_col+2,l_data_03)
                planilha0.cell(l_lin0+2,l_col+2).font=Font(bold=True)
                planilha0.cell(l_lin0+2,l_col+2).alignment = Alignment(horizontal='center', vertical='center')
                planilha0.cell(l_lin0+2,l_col+2).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

                planilha0.cell(l_lin0,l_col+3,soma1)
                planilha0.cell(l_lin0,l_col+3).font=Font(bold=True)
                planilha0.cell(l_lin0,l_col+3).number_format = "#,##0.00"
                planilha0.cell(l_lin0,l_col+3).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

                planilha0.cell(l_lin0+1,l_col+3,soma2)
                planilha0.cell(l_lin0+1,l_col+3).font=Font(bold=True)
                planilha0.cell(l_lin0+1,l_col+3).number_format = "#,##0.00"
                planilha0.cell(l_lin0+1,l_col+3).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

                planilha0.cell(l_lin0+2,l_col+3,soma3)
                planilha0.cell(l_lin0+2,l_col+3).font=Font(bold=True)
                planilha0.cell(l_lin0+2,l_col+3).number_format = "#,##0.00"
                planilha0.cell(l_lin0+2,l_col+3).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

            if l_lin1 > l_linha:
                l_lin1 += 2
                planilha1.cell(l_lin1,l_col+0,"TOTAIS:")
                planilha1.cell(l_lin1,l_col+0).font=Font(bold=True)
                planilha1.merge_cells('B'+ str(l_lin1) + ':I' + str(l_lin1))
                planilha1.cell(l_lin1,l_col+0).alignment = Alignment(horizontal='center')
                planilha1.cell(l_lin1,l_col+0).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

                planilha1.cell(l_lin1,l_col+8,"=SUM(J"+str(l_linha+1)+":J"+str(l_lin1-1)+")")
                planilha1.cell(l_lin1,l_col+8).font=Font(bold=True)
                planilha1.cell(l_lin1,l_col+8).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha1.cell(l_lin1,l_col+8).number_format = "#,##0.00"

                planilha1.cell(l_lin1,l_col+9,"=SUM(K"+str(l_linha+1)+":K"+str(l_lin1-1)+")")
                planilha1.cell(l_lin1,l_col+9).font=Font(bold=True)
                planilha1.cell(l_lin1,l_col+9).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha1.cell(l_lin1,l_col+9).number_format = "#,##0.00"

                planilha1.cell(l_lin1,l_col+10,"=SUM(L"+str(l_linha+1)+":L"+str(l_lin1-1)+")")
                planilha1.cell(l_lin1,l_col+10).font=Font(bold=True)
                planilha1.cell(l_lin1,l_col+10).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha1.cell(l_lin1,l_col+10).number_format = "#,##0.00"

                planilha1.cell(l_lin1,l_col+11,"=SUM(M"+str(l_linha+1)+":M"+str(l_lin1-1)+")")
                planilha1.cell(l_lin1,l_col+11).font=Font(bold=True)
                planilha1.cell(l_lin1,l_col+11).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha1.cell(l_lin1,l_col+11).number_format = "#,##0.00"

                planilha1.cell(l_lin1,l_col+12,"=SUM(N"+str(l_linha+1)+":N"+str(l_lin1-1)+")")
                planilha1.cell(l_lin1,l_col+12).font=Font(bold=True)
                planilha1.cell(l_lin1,l_col+12).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha1.cell(l_lin1,l_col+12).number_format = "#,##0.00"

            if l_lin2 > l_linha:
                l_lin2 += 2
                planilha2.cell(l_lin2,l_col+0,"TOTAIS:")
                planilha2.cell(l_lin2,l_col+0).font=Font(bold=True)
                planilha2.merge_cells('B'+ str(l_lin2) + ':I' + str(l_lin2))
                planilha2.cell(l_lin2,l_col+0).alignment = Alignment(horizontal='center')
                planilha2.cell(l_lin2,l_col+0).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

                planilha2.cell(l_lin2,l_col+8,"=SUM(J"+str(l_linha+1)+":J"+str(l_lin2-1)+")")
                planilha2.cell(l_lin2,l_col+8).font=Font(bold=True)
                planilha2.cell(l_lin2,l_col+8).number_format = "#,##0.00"

                planilha2.cell(l_lin2,l_col+9,"=SUM(K"+str(l_linha+1)+":K"+str(l_lin2-1)+")")
                planilha2.cell(l_lin2,l_col+9).font=Font(bold=True)
                planilha2.cell(l_lin2,l_col+9).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha2.cell(l_lin2,l_col+9).number_format = "#,##0.00"

                planilha2.cell(l_lin2,l_col+10,"=SUM(L"+str(l_linha+1)+":L"+str(l_lin2-1)+")")
                planilha2.cell(l_lin2,l_col+10).font=Font(bold=True)
                planilha2.cell(l_lin2,l_col+10).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha2.cell(l_lin2,l_col+10).number_format = "#,##0.00"

                planilha2.cell(l_lin2,l_col+11,"=SUM(M"+str(l_linha+1)+":M"+str(l_lin2-1)+")")
                planilha2.cell(l_lin2,l_col+11).font=Font(bold=True)
                planilha2.cell(l_lin2,l_col+11).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha2.cell(l_lin2,l_col+11).number_format = "#,##0.00"

                planilha2.cell(l_lin2,l_col+12,"=SUM(N"+str(l_linha+1)+":N"+str(l_lin2-1)+")")
                planilha2.cell(l_lin2,l_col+12).font=Font(bold=True)
                planilha2.cell(l_lin2,l_col+12).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha2.cell(l_lin2,l_col+12).number_format = "#,##0.00"

            if l_lin3 > l_linha:
                l_lin3 += 2
                planilha3.cell(l_lin3,l_col+0,"TOTAIS:")
                planilha3.cell(l_lin3,l_col+0).font=Font(bold=True)
                planilha3.merge_cells('B'+ str(l_lin3) + ':I' + str(l_lin3))
                planilha3.cell(l_lin3,l_col+0).alignment = Alignment(horizontal='center')
                planilha3.cell(l_lin3,l_col+0).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")

                planilha3.cell(l_lin3,l_col+8,"=SUM(J"+str(l_linha+1)+":J"+str(l_lin3-1)+")")
                planilha3.cell(l_lin3,l_col+8).font=Font(bold=True)
                planilha3.cell(l_lin3,l_col+8).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha3.cell(l_lin3,l_col+8).number_format = "#,##0.00"

                planilha3.cell(l_lin3,l_col+9,"=SUM(K"+str(l_linha+1)+":K"+str(l_lin3-1)+")")
                planilha3.cell(l_lin3,l_col+9).font=Font(bold=True)
                planilha3.cell(l_lin3,l_col+9).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha3.cell(l_lin3,l_col+9).number_format = "#,##0.00"

                planilha3.cell(l_lin3,l_col+10,"=SUM(L"+str(l_linha+1)+":L"+str(l_lin3-1)+")")
                planilha3.cell(l_lin3,l_col+10).font=Font(bold=True)
                planilha3.cell(l_lin3,l_col+10).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha3.cell(l_lin3,l_col+10).number_format = "#,##0.00"

                planilha3.cell(l_lin3,l_col+11,"=SUM(M"+str(l_linha+1)+":M"+str(l_lin3-1)+")")
                planilha3.cell(l_lin3,l_col+11).font=Font(bold=True)
                planilha3.cell(l_lin3,l_col+11).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha3.cell(l_lin3,l_col+11).number_format = "#,##0.00"

                planilha3.cell(l_lin3,l_col+12,"=SUM(N"+str(l_linha+1)+":N"+str(l_lin3-1)+")")
                planilha3.cell(l_lin3,l_col+12).font=Font(bold=True)
                planilha3.cell(l_lin3,l_col+12).fill = PatternFill(start_color="e1ecf4", end_color="e1ecf4", fill_type = "solid")
                planilha3.cell(l_lin3,l_col+12).number_format = "#,##0.00"

#BORDAS
#BORDAS
#BORDAS
            set_border_edsi(planilha0, 'B6:E'+str(planilha0.max_row-6), 'gggg')

            set_border_edsi(planilha1, 'B6:N'+str(planilha1.max_row), 'ffff')
            set_border_edsi(planilha1, 'B'+str(planilha1.max_row)+':N'+str(planilha1.max_row), 'gggg')

            set_border_edsi(planilha2, 'B6:N'+str(planilha2.max_row), 'ffff')
            set_border_edsi(planilha2, 'B'+str(planilha2.max_row)+':N'+str(planilha2.max_row), 'gggg')

            set_border_edsi(planilha3, 'B6:N'+str(planilha3.max_row), 'ffff')
            set_border_edsi(planilha3, 'B'+str(planilha3.max_row)+':N'+str(planilha3.max_row), 'gggg')

            log("Aumentando as colunas ... ")

            adjust_column(planilha0,6,2,5)
            adjust_column(planilha1,6,2,14)
            adjust_column(planilha2,6,2,14)
            adjust_column(planilha3,6,2,14)

#MERGE CELULAS PLANILHA 0
#MERGE CELULAS PLANILHA 0
#MERGE CELULAS PLANILHA 0

            qtd      = 0
            anterior = planilha0.cell(5,3).value
            for linha in range(5,planilha0.max_row):

                if planilha0.cell(linha,3).value == "":
                    continue
                if anterior == planilha0.cell(linha,3).value:
                    qtd += 1
                else:
                    if qtd > 1:
                        m1 = (linha) - qtd
                        planilha0.merge_cells('B'+ str(m1) + ':B' + str(linha - 1))

                        set_border_edsi(planilha0, 'C'+ str(m1) +':C'+ str(linha - 1), 'ffgg')

                        # UMA LINHA
                        if linha - 1 == m1:
                            set_border_edsi(planilha0, 'D'+ str(m1+1) +':D'+ str(m1+1), 'ffgg')
                            set_border_edsi(planilha0, 'E'+ str(m1) +':E'+ str(m1), 'fggg')

                        # DUAS LINHA
                        if (linha - 1) - m1  == 1:
                            set_border_edsi(planilha0, 'D'+ str(m1) +':D'+ str(m1), 'ffgf')
                            set_border_edsi(planilha0, 'D'+ str(m1+1) +':D'+ str(m1+1), 'fffg')

                            set_border_edsi(planilha0, 'E'+ str(m1) +':E'+ str(m1), 'fggf')
                            set_border_edsi(planilha0, 'E'+ str(m1+1) +':E'+ str(m1+1), 'fgfg')

                        # MAIS Q DUAS LINHA
                        if (linha - 1) - m1  > 1:
                            set_border_edsi(planilha0, 'D'+ str(m1) +':D'+ str(m1), 'ffgf')
                            set_border_edsi(planilha0, 'E'+ str(m1) +':E'+ str(m1), 'fggf')

                            for x in range(m1+1, (linha - 1)):
                                set_border_edsi(planilha0, 'D'+ str(x) +':D'+ str(x), 'ffff')
                                set_border_edsi(planilha0, 'E'+ str(x) +':E'+ str(x), 'fgff')

                            set_border_edsi(planilha0, 'D'+ str(linha - 1) +':D'+ str(linha - 1), 'fffg')
                            set_border_edsi(planilha0, 'E'+ str(linha - 1) +':E'+ str(linha - 1), 'fgfg')

                        planilha0.cell(m1, 2).alignment = Alignment(vertical='center')

                        planilha0.merge_cells('C'+ str(m1) + ':C' + str(linha - 1))

                        planilha0.cell(m1, 3).alignment = Alignment(vertical='center')

                        qtd = 1

                anterior = planilha0.cell(linha,3).value

            contorno_cli_clf(planilha0,2,2,5,4,'g')
            contorno_cli_clf(planilha1,2,2,14,4,'g')
            contorno_cli_clf(planilha2,2,2,14,4,'g')
            contorno_cli_clf(planilha3,2,2,14,4,'g')

            set_border_edsi(planilha0, 'B5:E5', 'gggg')

            contorno_cli_clf(planilha1,2,6,14,planilha1.max_row - 2,'g')
            contorno_cli_clf(planilha2,2,6,14,planilha2.max_row - 2,'g')
            contorno_cli_clf(planilha3,2,6,14,planilha3.max_row - 2,'g')

            set_border_edsi(planilha1, 'B5:N5', 'gggg')
            set_border_edsi(planilha2, 'B5:N5', 'gggg')
            set_border_edsi(planilha3, 'B5:N5', 'gggg')

            set_border_edsi(planilha0, 'B'+str(planilha0.max_row - 4)+':E'+str(planilha0.max_row - 4), 'gggg')
            set_border_edsi(planilha0, 'B'+str(planilha0.max_row - 2)+':E'+str(planilha0.max_row), 'gggg')

            # Grava a planilha Excel
            log("Salvando a planilha : " + str(p_relatorio))
            arquivo_excel.save(p_relatorio)

    except Exception as e:
        l_ret = 1
        txt = traceback.format_exc()
        log("ERRO NA GERAÇÃO DO RELATÓRIO.: " + txt +  " >> " +  str(e))

    return l_ret

# Ponto de partida
if __name__ == "__main__" :

    # Codigo de Retorno
    ret = 0

    # Tratamento de excessao
    txt = ''

    # Tratamento de variaveis globais

    gv_ie = ""
    gv_ano = ""
    gv_trimestre = ""

    gv_caminho=""
    gv_relatorio=""

    try:

        log("\n")
        log("Carregando as variaveis de configuracao")
        variaveis = comum.carregaConfiguracoes(configuracoes)

        # Validacao dos parametros de entrada
        if not ret :
            ret = validacaoEntrada()

        log("\n")

        # Validar parametros que envolve o banco
        if not ret :
            l_str_uf = retornar_UF(p_IE=gv_ie)
            if l_str_uf is None:
                log("PARAMETRO IE não encontrado! <1> " + str(l_str_uf))
                ret = 91
            elif (len(str(l_str_uf)) == 0
                or str(l_str_uf).strip().upper() == "NONE"):
                log("PARAMETRO IE não encontrado ! <2> " + str(l_str_uf) )
                ret = 91

        log("\n")

        # Processar o relatório
        if not ret :
            ret = processarRelatorio(p_ie=gv_ie,
                                     p_ano=gv_ano,
                                     p_trimestre=gv_trimestre,
                                     p_relatorio=gv_relatorio)

        log("\n")

        # Finalizacao
        log("\n")

        if not ret :
            log("***SUCESSO***")
        else:
            log("<<<ERRO>>>")

        log("\n")

    except Exception as e:
        txt = traceback.format_exc()
        log("ERRO .: " + str(e))
        ret = 93

    sys.exit(ret if ret >= log.ret else log.ret )


from enum import Enum
import copy

class FigureState(Enum):
    Init = 0
    Checked = 1
    Current = 2  # текущая позиция фигуры (lastchecked)

class Figure:
    def __init__(self, typ: str, color: str, state: FigureState=FigureState.Init):
        self._typ = typ
        self._color = color
        self._state = state
        self.row = None
        self.column = None

    @property
    def typ(self):
        return self._typ

    @property
    def color(self):
        return self._color

    @property
    def state(self) -> FigureState:
        return self._state

    @state.setter
    def state(self, value):
        self._state = value

class Game:
    # lastchecked = None
    _figures = []

    def __init__(self, level):
        # level - это путь к файлу в директории levels
        self._tmplist = []
        self._make_level(level)
        self.define_place()
        self.win = False

        if self._figures is not None:
            # self.lastchecked = self._figures[0][0]
            self._figures[0][0].state = FigureState.Current
            self.count_checked = 1 # количество пройденных фигур
            self.list_checked = [self._figures[0][0]]

    @property
    def rows(self):
        return len(self._figures)

    @property
    def columns(self):
        return len(self._figures[0])

    @property
    def figures(self):
        return self._figures

    @figures.setter
    def figures(self, value):
        self._figures = value

    @figures.deleter
    def figures(self):
        self._figures = []

    # парсить файл и формировать список списков из фигур по нажатию кнопки Run
    def _make_level(self, level):
        f = open(level, 'r')
        #tmplist = []
        for fig in f:
            self._tmplist.append(Figure(fig.split()[0], fig.split()[1], FigureState.Init))
        f.close()
        self._figures = [self._tmplist[i:i+3] for i in range(0, 9, 3)] #  матрица из фигур 3 на 3

    # проверка, в одном ли подсписке (вертикаль/горизонталь)
    def define_place(self):
        for ind, sublist in enumerate(self._figures):
            for j in range(len(sublist)):
                self._figures[ind][j].row = ind
                self._figures[ind][j].column = j

    # def is_may_checked(self, chosen: Figure):          # проверка можно ли пойти в этот элемент (следующий)
    #     if chosen.state == FigureState.Init:
    #         if self.one_place(self.lastchecked, chosen):  проверка, находится ли элемент по вертикали или горизонтали
    #             if chosen.color == self.lastchecked.color or chosen.typ == self.lastchecked.typ:
    #                 return True
    #     return False

    # ИЗМЕНЕНИЯ ПО КЛИКУ МЫШИ
    def mouse_click(self, chosen: Figure) -> None:
        if len(self.list_checked) == len(self._tmplist):  # win
            return
        elif chosen.state == FigureState.Init:   # playing
            if self.list_checked[self.count_checked-1].row == chosen.row or \
               self.list_checked[self.count_checked - 1].column == chosen.column:             #  проверка, находится ли элемент по вертикали или горизонтали
                if chosen.color == self.list_checked[self.count_checked - 1].color or \
                   chosen.typ == self.list_checked[self.count_checked - 1].typ:  #  одинаковый тип или фигура
                    self.list_checked[self.count_checked - 1].state = FigureState.Checked    # белый крестик
                    chosen._state = FigureState.Current   #  тёмный крестик
                    self.list_checked.append(chosen)
                    self.count_checked += 1
            if self.count_checked == len(self._tmplist):
                self.win = True
        else:    # if no way out (lose)
            return

"""
читать из файла и создавать вложенные списки из элементов фигур, причём 1-ый элемент выделен крестиком изначально
    далее отдельный метод, проходящийся по матрице и проверяющий может ли быть использован этот элемент(сосед по столбцу или строке)

    мб ещё стоит учесть координаты каждой фигуры, чтобы корректно сделать нажатие мышью??? позишн сопоставляетсяс координатой мыши

    прописать состояние текущей игры !!!

      '''
              widget = QTableWidget(game.rows, game.columns)
              self.matrix = copy.deepcopy(self.game._figures)
                  for i in range(game.rows):
                 for j in range(game.columns):
                     item = QTableWidgetItem(self.matrix[i][j])
                     widget.setItem(game.rows, game.columns, item)
                     widget.setIcon
                     '''
"""