from sys import path
import pyautogui as p
import time

path.append(r'..\..\_comum')
from comum_comum import _indice, _escreve_relatorio_csv, _time_execution, _open_lista_dados, _where_to_start

def esperar(imagen):
    while not p.locateOnScreen(imagen, confidence=0.9):
        time.sleep(1)

def clicar(imagen, tempo=0.1):
    try:
        p.click(p.locateCenterOnScreen(imagen, confidence=0.9))
        time.sleep(tempo)
        return True
    except:
        return False

def verificacoes(empresa):
    cod, cnpj, nome, arquivo = empresa
    if p.locateOnScreen(r'imagens\JaExiste.png'):
        p.press('enter')
        time.sleep(1)
        p.press(['esc', 'esc'])
        _escreve_relatorio_csv(';'.join([cod, cnpj, nome, 'Arquivo já importado']), 'Importação DIRF')
        print('>>> Arquivo já importado <<<')
        return False
    if p.locateOnScreen(r'imagens\JaConsta.png'):
        p.hotkey('ctrl', 'n')
        time.sleep(1)
        p.press(['esc', 'esc'])
        _escreve_relatorio_csv(';'.join([cod, cnpj, nome, 'Arquivo já consta na base de dados']), 'Importação DIRF')
        print('>>> Arquivo já consta na base de dados <<<')
        return False
    if p.locateOnScreen(r'imagens\Erros.png'):
        p.hotkey('alt', 'n')
        time.sleep(2)
        if p.locateOnScreen(r'imagens\Relatorio.png'):
            clicar(r'imagens\SalvarRelatorio.png')
            esperar(r'imagens\Salvar.png')
            time.sleep(0.2)
            p.write(cnpj + ' - ' + cod + '.pdf')
            time.sleep(0.2)
            p.press('enter')
            time.sleep(1)
            if p.locateOnScreen(r'imagens\Sobrescrever.png'):
                p.press('enter')
            clicar(r'imagens\FecharRelatorio.png')
        _escreve_relatorio_csv(';'.join([cod, cnpj, nome, 'Erros ou avisos']), 'Importação DIRF')
        print('** Erros ou avisos **')
        return False
    return True

@_time_execution
def importar_dirf():
    # abrir a planilha de dados
    empresas = _open_lista_dados()
    if not empresas:
        return False

    # configurar um indice para a planilha de dados
    index = _where_to_start(tuple(i[0] for i in empresas))
    if index is None:
        return False

    p.hotkey('win', 'm')
    time.sleep(0.5)
    p.getWindowsWithTitle('Dirf')[0].maximize()

    total_empresas = empresas[index:]
    for count, empresa in enumerate(empresas[index:], start=1):
        cod, cnpj, nome, arquivo = empresa

        _indice(count, total_empresas, empresa)

        clicar(r'imagens\TelaInicial.png')

        # Abrir tela para selecionar o arquvio
        while p.locateOnScreen(r'imagens\TelaInicial.png'):
            p.hotkey('ctrl', 'i')
            time.sleep(3)
        while not p.locateOnScreen(r'imagens\AbrirDeclaracao.png'):
            time.sleep(1)
            p.click(p.locateCenterOnScreen(r'imagens\Lupa.png'))
        p.write(arquivo)
        time.sleep(0.5)
        p.press('enter')
        time.sleep(1)

        if not verificacoes(empresa):
            continue

        # Esperar importar o arquivo
        esperar(r'imagens\Avancar.png')
        p.hotkey('alt', 'a')
        esperar(r'imagens\Resumo.png')

        if not verificacoes(empresa):
            continue

        if not p.locateOnScreen(r'imagens\Concluir.png'):
            ''
        p.hotkey('alt', 'n')
        _escreve_relatorio_csv(';'.join([cod, cnpj, nome, 'Arquivo importado']), 'Importação DIRF')
        print('>>> Arquivo importado <<<')

if __name__ == '__main__':
    try:
        importar_dirf()
    except:
        p.alert(title='Script incrível', text='ERRO')


#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Handler file to run pycasso when using pijuice

import logging
import os
import sys
import time

from pijuice import PiJuice

from piblo.pycasso import Pycasso
from piblo.constants import PiJuiceConst, BatteryConst

class PiJuiceHandler:
    """
    A class used to provide image operations for pycasso.

    Attributes
    ----------

    Methods
    -------
    safe_pijuice_shutdown(pijuice)
        Uses PiJuice to attempt to shut down safely and completely using pijuice object 'pijuice'.

    system_shutdown()
        Uses linux system command to shut down.

    pijuice_led_disable(pijuice)
        Uses PiJuice to disable LEDs on board with pijuice object 'pijuice'.

    get_charge_status(power_status, charge_level)
        Returns valid charge level or constant to be passed to pycasso for battery display. Uses valid pijuice
        power_status and charge_level

    def run(self):
        Attempts to run pycasso based on configuration and pijuice settings.
    """
    def __init__(self):

        return

    @staticmethod
    def safe_pijuice_shutdown(pijuice):
        # Remove power to PiJuice MCU IO pins
        pijuice.power.SetSystemPowerSwitch(0)

        # In 5 seconds we are not so nice - Remove 5V power to RPi
        pijuice.power.SetPowerOff(5)

        # Enable wakeup alarm
        pijuice.rtcAlarm.SetWakeupEnabled(True)

        # But try to shut down nicely first
        os.system("sudo shutdown -h 0")
        sys.exit()

    @staticmethod
    def system_shutdown():
        os.system("shutdown /s /t 1")
        sys.exit()

    @staticmethod
    def pijuice_led_disable(pijuice):
        led_config = {'function': 'NOT_USED', 'parameter': {'r': 0, 'g': 0, 'b': 0}}
        pijuice.config.SetLedConfiguration('D1', led_config)
        pijuice.config.SetLedConfiguration('D2', led_config)
        return

    @staticmethod
    def get_charge_status(power_status, charge_level):
        if power_status == PiJuiceConst.NOT_PRESENT.value:
            charge_level = charge_level
        elif power_status == PiJuiceConst.PRESENT.value:
            charge_level = BatteryConst.CHARGING.value
        elif power_status == PiJuiceConst.WEAK.value:
            charge_level = BatteryConst.WEAK.value
        elif power_status == PiJuiceConst.BAD.value:
            charge_level = BatteryConst.BAD.value
        else:
            charge_level = BatteryConst.ERROR.value

        return charge_level

    def run(self):
        try:
            instance = Pycasso()
        except Exception as e:
            logging.error(e)
            logging.error("Cannot create Pycasso object. Exiting process.")
            sys.exit()

        # Set config variables based on config that pycasso loaded
        sleep_time = instance.config.wait_to_run
        shutdown = instance.config.shutdown_on_battery
        shutdown_ex = instance.config.shutdown_on_exception

        power_status = None
        charge_level = BatteryConst.ERROR.value

        # sleep for a bit as I can't figure out a better solution to stop pijuice from failing to start
        time.sleep(sleep_time)
        try:
            pijuice = PiJuice(1, 0x14)
            power_status = pijuice.status.GetStatus()[PiJuiceConst.STATUS_ROOT.value][PiJuiceConst.STATUS_POWER.value]
            charge_level = pijuice.status.GetChargeLevel()['data']
            instance.charge_level = PiJuiceHandler.get_charge_status(power_status, charge_level)

        except Exception as e:
            logging.error(e)
            logging.error("Cannot create pijuice object. Running pycasso once with error display and exiting process.")
            # run pycasso with error symbol, then exit
            instance.add_exception_icon()
            instance.run()

            if shutdown_ex:
                logging.info(f"Shutting down if possible. Waiting {sleep_time} seconds before sending signal")
                time.sleep(sleep_time)
                self.system_shutdown()
                sys.exit()

        logging.info(f"Power status is \'{power_status}\'")
        logging.info(f"Battery level is \'{charge_level}\'")

        try:
            instance.run()

            if power_status == PiJuiceConst.NOT_PRESENT.value:
                # shutdown if we've configured pycasso to do so
                if shutdown:
                    self.safe_pijuice_shutdown(pijuice)

        except Exception as e:
            logging.error(e)

            # shutdown if we've configured pycasso to do so
            if shutdown_ex:
                logging.info(f"Shutting down if possible. Waiting {sleep_time} seconds before sending signal")
                time.sleep(sleep_time)
                self.safe_pijuice_shutdown(pijuice)
            sys.exit()

        return


import os
import sys
from PyQt5.QtWidgets import (
    QWidget, QToolTip, QDesktopWidget, QPushButton, QApplication)
from PyQt5.QtWidgets import (
    QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout, QFileDialog)
from PyQt5.QtWidgets import (QCheckBox, QComboBox, QLabel)
from PyQt5 import QtCore
from PyQt5.QtGui import QFont
import subprocess

# get the location of this file!
__location__ = os.path.realpath(os.path.join(
    os.getcwd(), os.path.dirname(__file__)))

# --------------------------------------------
# run-command utils

def run_command(command, debug=False):
    """ runs command and returns the output."""
    if debug:
        print("$ {}".format(command))
    #p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, executable='/bin/bash')
    p = subprocess.Popen(command, shell=True, executable='/bin/bash')
    # return iter(p.stdout.readline, b'')

def executeCommand(command, stderr=None, stdout=None, debug=False):
    """ Raises an error when a command fails. """
    if debug:
        print("$ {}".format(command))
    subprocess.check_call(command, stderr=stderr,
                          stdout=stdout, env=dict(os.environ), shell=True)

def executeCommands(commands, stderr=None, stdout=None, debug=False):
    for command in commands:
        executeCommand(command, stderr=stderr, stdout=stdout, debug=debug)

def executeCommandNoCheck(command, stderr=None, stdout=None, debug=False):
    """ Does not raise an error when a command fails. """
    if debug:
        print("$ {}".format(command))
    subprocess.call(command, stderr=stderr, stdout=stdout,
                    env=dict(os.environ), shell=True)

def executeCommandsNoCheck(commands, stderr=None, stdout=None, debug=False):
    for command in commands:
        executeCommandNoCheck(command, stderr=stderr,
                              stdout=stdout, debug=debug)

# --------------------------------------------
# Utils

def getBaseFileNameNoExt(filename):
    base = os.path.basename(filename)
    os.path.splitext(base)
    return os.path.splitext(base)[0]

# --------------------------------------------
# Main Widget

class MainWidget(QWidget):

    def __init__(self):
        super().__init__()

        self.cmdDebug = False

        self.mainWidgetWidth = 400
        self.mainWidgetHeight = 350

        self.exploration_pioneer_WorldName = ''
        self.exploration_pioneer_WorldsFolder = __location__ + \
            '/pioneer_ws/src/pioneer_nav/vrep_pioneer_simulation/data'

        self.exploration_pioneer_enable = True
        self.exploration_auto_launch = True

        self.teb_enable = 0
        self.voxblox_enable = 0

        self.sourceCmd = 'source source_all.bash; '

        self.initUI()
        self.center()

    def initUI(self):

        QToolTip.setFont(QFont('SansSerif', 10))

        self.setGeometry(0, 0, self.mainWidgetWidth, self.mainWidgetHeight)
        self.setWindowTitle('3DMR - PIONEER')

        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        #           PIONEER
        self.btn_exploration_pioneer = QPushButton('Launch exploration', self)
        self.btn_exploration_pioneer.setToolTip('Launch the exploration system')
        #self.btn_rviz_pioneer = QPushButton('Open RVIZ', self)
        #self.btn_rviz_pioneer.setToolTip('Launch RVIZ')

        self.checkbtn_expl_pioneer_enable = QCheckBox('Enable exploration', self)
        self.checkbtn_expl_pioneer_enable.setToolTip('Enable/disable exploration')
        self.checkbtn_expl_pioneer_enable.toggled.connect(self.slot_exploration_pioneer_enable)
        self.checkbtn_expl_pioneer_enable.setChecked(self.exploration_pioneer_enable)

        self.checkbtn_exploration_auto_launch = QCheckBox(
            'Auto launch exploration', self)
        self.checkbtn_exploration_auto_launch.setToolTip(
            'Auto launch exploration.')
        self.checkbtn_exploration_auto_launch.toggled.connect(
            self.slot_exploration_auto_launch)
        self.checkbtn_exploration_auto_launch.setChecked(
            self.exploration_auto_launch)

        self.btn_exploration_pioneer_world = QPushButton('Select exploration world', self)
        self.btn_exploration_pioneer_world.setToolTip('Select an exploration world in one of the subfolder of maps. A default world is already set in the script sim_launcher_exploration.')

        self.btn_path_planner = QPushButton('Launch navigation', self)
        self.btn_path_planner.setToolTip('Launch vrep_pioneer_simulation system')

        #
        self.checkbtn_voxblox_enable = QCheckBox(
            'Use voxblox mapping', self)
        self.checkbtn_voxblox_enable.setToolTip(
            'Enable/disable voxblox for mapping instead of using octomap.')
        self.checkbtn_voxblox_enable.toggled.connect(
            self.slot_voxblox_enable)
        self.checkbtn_voxblox_enable.setChecked(self.voxblox_enable)

        #
        self.checkbtn_teb_enable = QCheckBox(
            'Use TEB local planner', self)
        self.checkbtn_teb_enable.setToolTip(
            'Enable/disable TEB as local planner and trajectory control.')
        self.checkbtn_teb_enable.toggled.connect(
            self.slot_teb_enable)
        self.checkbtn_teb_enable.setChecked(self.teb_enable)

        # common commands
        self.btn_save_map = QPushButton('Save map', self)
        self.btn_save_map.setToolTip('Save the built map')

        self.btn_load_map = QPushButton('Load map', self)
        self.btn_load_map.setToolTip('Load the built map')

        self.btn_kill = QPushButton('Kill all', self)
        self.btn_kill.setToolTip('Kill all nodes of the system')

        # set layouts

        self.create_exploration_layout()
        self.create_nav_layout()
        self.mainLayout.addWidget(self.btn_save_map)
        self.mainLayout.addWidget(self.btn_load_map)
        self.mainLayout.addWidget(self.btn_kill)

        # connections
        self.btn_exploration_pioneer.clicked.connect(self.slot_exploration_pioneer)
        self.btn_exploration_pioneer_world.clicked.connect(self.slot_expl_pioneer_world)
        #self.btn_rviz_pioneer.clicked.connect(self.slot_rviz_pioneer)

        self.btn_path_planner.clicked.connect(self.slot_path_planner)

        self.btn_save_map.clicked.connect(self.slot_save_map)
        self.btn_load_map.clicked.connect(self.slot_load_map)
        self.btn_kill.clicked.connect(self.slot_kill)

        # show the widget
        self.show()

    def create_exploration_layout(self):
        self.horizontalGroupBox_expl_pioneer = QGroupBox(
            "Exploration - Pioneer")
        self.gridLayout_expl_pioneer = QGridLayout()
        #self.gridLayout_expl.setColumnStretch(1, 3)
        #self.gridLayout_expl.setColumnStretch(2, 3)

        self.gridLayout_expl_pioneer.addWidget(self.btn_exploration_pioneer, 0, 0)
        self.gridLayout_expl_pioneer.addWidget(self.btn_exploration_pioneer_world, 0, 1)
        #self.gridLayout_expl_pioneer.addWidget(self.btn_rviz_pioneer, 1, 0)
        self.gridLayout_expl_pioneer.addWidget(self.checkbtn_expl_pioneer_enable, 1, 1)
        self.gridLayout_expl_pioneer.addWidget(self.checkbtn_exploration_auto_launch, 2, 1)

        self.horizontalGroupBox_expl_pioneer.setLayout(
            self.gridLayout_expl_pioneer)
        self.mainLayout.addWidget(self.horizontalGroupBox_expl_pioneer)

    def create_nav_layout(self):
        self.horizontalGroupBox_pp = QGroupBox("Navigation")
        self.gridLayout_pp = QGridLayout()
        #self.gridLayout_pp.setColumnStretch(1, 3)
        #self.gridLayout_pp.setColumnStretch(2, 3)

        self.gridLayout_pp.addWidget(self.btn_path_planner, 1, 0)

        self.gridLayout_pp.addWidget(self.checkbtn_voxblox_enable, 2, 0)
        self.gridLayout_pp.addWidget(self.checkbtn_teb_enable, 3, 0)

        self.horizontalGroupBox_pp.setLayout(self.gridLayout_pp)
        self.mainLayout.addWidget(self.horizontalGroupBox_pp)

# slots

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def slot_exploration_pioneer(self):
        print('launch exploration')
        cmd_env = ''
        if not self.exploration_pioneer_enable:
            cmd_envs += 'export ENABLE_EXPLORATION_ENV=0; '   # must be integer
        if not self.exploration_auto_launch:
            cmd_envs += 'export EXPL_AUTO_LAUNCH_ENV=0; '     # must be integer
        cmd = self.sourceCmd + cmd_env + \
            'rosrun pioneer_3dexplorer sim_launcher_exploration ' + self.exploration_pioneer_WorldName
        print(cmd)
        run_command(cmd)

    def slot_expl_pioneer_world(self):
        print('select expl. world')
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self, "Select exploration world", self.exploration_pioneer_WorldsFolder, "V-REP scenes (*.ttt)", options=options)
        if fileName:
            self.exploration_pioneer_WorldName = getBaseFileNameNoExt(fileName)
            print('world: ', self.exploration_pioneer_WorldName)
        self.slot_exploration_pioneer()

    def slot_exploration_pioneer_enable(self):
        self.exploration_pioneer_enable = self.checkbtn_expl_pioneer_enable.isChecked()
        print('exploration_pioneer_enable: ', self.exploration_pioneer_enable)

    def slot_exploration_auto_launch(self):
        self.exploration_auto_launch = self.checkbtn_exploration_auto_launch.isChecked()
        print('exploration_auto_launch: ', self.exploration_auto_launch)

    def slot_path_planner(self):
        print('launch path planner system')
        cmd_envs = ''
        #cmd_envs += 'export LAUNCH_VREP_MODE_ENV=' + str(self.vrep_mode) + '; '
        if self.teb_enable:
            cmd_envs += 'export ENABLE_TEB_LOCAL_PLANNER=1; '
        if self.voxblox_enable:
            cmd_envs += 'export ENABLE_VOXBLOX=1; '
        cmd = self.sourceCmd + cmd_envs + 'rosrun pioneer_3dnav sim_launcher_navigation'
        print(cmd)
        run_command(cmd)

    def slot_rviz_pioneer(self):
        print('Launching RVIZ')
        cmd = self.sourceCmd + 'roslaunch pioneer_3dnav rviz_sim_path_planning.launch'
        print(cmd)
        run_command(cmd)

    def slot_voxblox_enable(self):
        self.voxblox_enable = self.checkbtn_voxblox_enable.isChecked()
        print('voxblox_enable: ', self.voxblox_enable)

    def slot_teb_enable(self):
        self.teb_enable = self.checkbtn_teb_enable.isChecked()
        print('teb_enable: ', self.teb_enable)

    def slot_save_map(self):
        print('save_map')
        cmd = self.sourceCmd + 'rosrun patrolling3d_sim save_map'
        print(cmd)
        run_command(cmd)

    def slot_load_map(self):
        print('load_map')
        cmd = self.sourceCmd + 'rosrun patrolling3d_sim load_map'
        print(cmd)
        run_command(cmd)

    def slot_kill(self):
        print('kill all nodes')
        cmd = self.sourceCmd + 'rosrun patrolling3d_sim kill_vrep_sim'
        print(cmd)
        run_command(cmd)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MainWidget()
    sys.exit(app.exec_())


import pygame
import sys

FPS = 60
WIN_WIDTH = 300
WIN_HEIGHT = 300
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BR_GREY = (200, 200, 200)
pygame.init()
pygame.font.init()
clock = pygame.time.Clock()
sc = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
pygame.display.set_caption('Tic-Tac')
f1 = pygame.font.SysFont('sans-serif', 35)
circle_diameter = 45
cross_width = 6
a = 1
c = False
pos = [None, None, None,
       None, None, None,
       None, None, None]

def draw_scene():
    pygame.draw.line(sc, BLACK, (100, 0), (100, 300), 5)
    pygame.draw.line(sc, BLACK, (200, 0), (200, 300), 5)
    pygame.draw.line(sc, BLACK, (0, 100), (300, 100), 5)
    pygame.draw.line(sc, BLACK, (0, 200), (300, 200), 5)

def win():
    if c == 1:
        pygame.draw.rect(sc, BLACK, (23, 131, 255, 34))
        sc.blit(f1.render("Player number 1 won", True, WHITE), (28, 135))
    if c == 0:
        pygame.draw.rect(sc, BLACK, (23, 131, 255, 34))
        sc.blit(f1.render("Player number 2 won", True, WHITE), (28, 135))

def draw():
    pygame.draw.rect(sc, BLACK, (82, 131, 140, 34))
    sc.blit(f1.render("It is a draw", True, WHITE), (87, 135))

run = True
isEnd = False
while run:
    sc.fill(WHITE)
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if i.type == pygame.MOUSEBUTTONDOWN and a != 0 and pos[a - 1] == None and isEnd == False:
            c = not c
            pos[a - 1] = int(c)

    # print(a)
    print(f"{pos[0], pos[1], pos[2]}\n{pos[3], pos[4], pos[5]}\n{pos[6], pos[7], pos[8]}\n")

    draw_scene()
    mouse = pygame.mouse.get_pos()
    if isEnd == False:
        if 5 < mouse[0] < 95:
            if 5 < mouse[1] < 95 and pos[0] == None:
                pygame.draw.rect(sc, BR_GREY, (5, 5, 90, 90))
                a = 1
            if 105 < mouse[1] < 195 and pos[3] == None:
                pygame.draw.rect(sc, BR_GREY, (5, 105, 90, 90))
                a = 4
            if 205 < mouse[1] < 295 and pos[6] == None:
                pygame.draw.rect(sc, BR_GREY, (5, 205, 90, 90))
                a = 7
        elif 105 < mouse[0] < 195:
            if 5 < mouse[1] < 95 and pos[1] == None:
                pygame.draw.rect(sc, BR_GREY, (105, 5, 90, 90))
                a = 2
            if 105 < mouse[1] < 195 and pos[4] == None:
                pygame.draw.rect(sc, BR_GREY, (105, 105, 90, 90))
                a = 5
            if 205 < mouse[1] < 295 and pos[7] == None:
                pygame.draw.rect(sc, BR_GREY, (105, 205, 90, 90))
                a = 8
        elif 205 < mouse[0] < 295:
            if 5 < mouse[1] < 95 and pos[2] == None:
                pygame.draw.rect(sc, BR_GREY, (205, 5, 90, 90))
                a = 3
            if 105 < mouse[1] < 195 and pos[5] == None:
                pygame.draw.rect(sc, BR_GREY, (205, 105, 90, 90))
                a = 6
            if 205 < mouse[1] < 295 and pos[8] == None:
                pygame.draw.rect(sc, BR_GREY, (205, 205, 90, 90))
                a = 9
        else:
            a = 0

    if pos[0] == 1:
        pygame.draw.line(sc, BLACK, (5, 5), (95, 95), cross_width)
        pygame.draw.line(sc, BLACK, (95, 5), (5, 95), cross_width)
    elif pos[0] == 0:
        pygame.draw.circle(sc, BLACK, (50, 50), circle_diameter, 5)
    if pos[1] == 1:
        pygame.draw.line(sc, BLACK, (105, 5), (195, 95), cross_width)
        pygame.draw.line(sc, BLACK, (195, 5), (105, 95), cross_width)
    elif pos[1] == 0:
        pygame.draw.circle(sc, BLACK, (150, 50), circle_diameter, 5)
    if pos[2] == 1:
        pygame.draw.line(sc, BLACK, (205, 5), (295, 95), cross_width)
        pygame.draw.line(sc, BLACK, (205, 95), (295, 5), cross_width)
    elif pos[2] == 0:
        pygame.draw.circle(sc, BLACK, (250, 50), circle_diameter, 5)
    if pos[3] == 1:
        pygame.draw.line(sc, BLACK, (5, 105), (95, 195), cross_width)
        pygame.draw.line(sc, BLACK, (95, 105), (5, 195), cross_width)
    elif pos[3] == 0:
        pygame.draw.circle(sc, BLACK, (50, 150), circle_diameter, 5)
    if pos[4] == 1:
        pygame.draw.line(sc, BLACK, (105, 105), (195, 195), cross_width)
        pygame.draw.line(sc, BLACK, (195, 105), (105, 195), cross_width)
    elif pos[4] == 0:
        pygame.draw.circle(sc, BLACK, (150, 150), circle_diameter, 5)
    if pos[5] == 1:
        pygame.draw.line(sc, BLACK, (205, 105), (295, 195), cross_width)
        pygame.draw.line(sc, BLACK, (205, 195), (295, 105), cross_width)
    elif pos[5] == 0:
        pygame.draw.circle(sc, BLACK, (250, 150), circle_diameter, 5)
    if pos[6] == 1:
        pygame.draw.line(sc, BLACK, (5, 205), (95, 295), cross_width)
        pygame.draw.line(sc, BLACK, (95, 205), (5, 295), cross_width)
    elif pos[6] == 0:
        pygame.draw.circle(sc, BLACK, (50, 250), circle_diameter, 5)
    if pos[7] == 1:
        pygame.draw.line(sc, BLACK, (105, 205), (195, 295), cross_width)
        pygame.draw.line(sc, BLACK, (195, 205), (105, 295), cross_width)
    elif pos[7] == 0:
        pygame.draw.circle(sc, BLACK, (150, 250), circle_diameter, 5)
    if pos[8] == 1:
        pygame.draw.line(sc, BLACK, (205, 205), (295, 295), cross_width)
        pygame.draw.line(sc, BLACK, (205, 295), (295, 205), cross_width)
    elif pos[8] == 0:
        pygame.draw.circle(sc, BLACK, (250, 250), circle_diameter, 5)

    if ((pos[0] == pos[1] == pos[2] != None) or (pos[3] == pos[4] == pos[5] != None) or (
            pos[6] == pos[7] == pos[8] != None) or (pos[0] == pos[3] == pos[6] != None) or (
            pos[1] == pos[4] == pos[7] != None) or (pos[2] == pos[5] == pos[8] != None) or (
            pos[6] == pos[4] == pos[2] != None) or (pos[0] == pos[4] == pos[8] != None)):
        win()
        isEnd = True
    if not None in pos:
        draw()
        isEnd = True

    pygame.display.update()
    clock.tick(FPS)


import numpy as np
import pandas as pd

#load data
df = pd.read_csv("C:/Users/Student/Desktop/SemesterProject/sneakers_Reviews_Dataset.csv", delimiter = ';')
df.head()

import subprocess

# Install NLTK using pip
subprocess.check_call(['pip', 'install', 'nltk'])

import nltk

nltk.download('punkt')

##pre processing

import re
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
from sklearn.feature_extraction.text import CountVectorizer

#convert to lowercase

df.head()

# remove special characters, numbers, and punctuation
df['review_text'] = df['review_text'].apply(lambda text: re.sub(r'[^a-zA-Z\s]', '', text))

df.head()

#tokenization

df['review_text'] = [word_tokenize(text) for text in df['review_text']]

#remove stopwords
stop_words = set(stopwords.words('english'))

df['review_text'] = [[word for word in words if word not in stop_words] for words in df['review_text']]

#stemming (reducing words to their root form)
stemmer = PorterStemmer()
df['review_text'] = [[stemmer.stem(word) for word in words] for words in df['review_text']]

#convert back text
df['review_text'] = [''.join(words) for words in df['review_text']]

#####

#feature extraction

#vectorization (convert text to numerical representation)
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(df['review_text'])

df

#deriving the sentiment frm the rating and text column

def label_sentiment(rating):
    if rating >= 4:
        return 'positive'
    elif rating == 3:
        return 'neutral'
    else:
        return 'negative'

# applying the function
df['sentiment'] = df['rating'].apply(label_sentiment)

#text length

# Install matplotlib using pip
subprocess.check_call(['pip', 'install', 'matplotlib'])

import matplotlib.pyplot as plt

#distribution of sentiment labels
sentiment_counts = df['sentiment'].value_counts()

plt.bar(sentiment_counts.index, sentiment_counts)
plt.title('Distribution of sentiment labels')
plt.xlabel('Sentiment')
plt.ylabel('Count')
plt.show()

df['text_length'] = df['review_text'].apply(len)

plt.figure(figsize = (10, 6))

for sentiment in df['sentiment'].unique():
    subset = df[df['sentiment'] == sentiment]
    plt.hist(subset['text_length'], bins = 30, alpha = 0.5, label = sentiment)

plt.title('Histogram of Text length in sentiment analysis')
plt.xlabel('Text length')
plt.ylabel('Frequency')
plt.legend()
plt.show()

#analyzing the frequency of words
from wordcloud import WordCloud

text = df['review_text'].str.cat(sep=' ')

# generate a word cloud
wordcloud = WordCloud(width = 800, height = 400, background_color = 'white').generate(text)

#plot the word cloud
plt.figure(figsize = (10, 5))
plt.imshow(wordcloud, interpolation = 'bilinear')
plt.axis('off')
plt.show()

########

# model

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, roc_curve

# split the data into test/train

del df['review_text']
train = df[df['sentiment', 'timestamp'].notnull().all(axis=1)]
test = df[df['sentiment'].isnull()]
del test['sentiment']

train['sentiment'].value_counts()

train_df = train
test_df = test

X_train, X_test, y_train, y_test = train_test_split(
    train_df.drop(labels=['sentiment', 'timestamp'], axis=1),
    train_df['sentiment'].values,
    test_size=0.2,
    random_state=42
)

# Initialize base models
model = RandomForestClassifier(random_state=42)
model.fit(X_train, y_train)

# Make predictions
predictions = model.predict(X_test)

#evaluate performance
report = classification_report(y_test, predictions)
print("Classification Report:")
print(report)

print(f"Accuracy: {accuracy:.4f}")

# Save the vectorizer and model
with open('vectorizer_model.pkl', 'wb') as file:
    pickle.dump({'vectorizer': vectorizer, 'model': model}, file)
with open('sneakerscript.pkl', 'wb') as file:
    pickle.dump(model, file)


import habitat_sim
import cv2
import numpy as np
import pandas as pd

STEP_SIZE = 0.25

# 初始化position
position = np.array([-2.4452953 ,  0.17515154,  2.349534  ], dtype='float32')

# 初始化rotation
rotation = np.quaternion(-0.150860279798508, 0, 0.988555133342743, 0)

# 初始化sensor_states
sensor_states = {
    'rgb': habitat_sim.agent.SixDOFPose(
        position=np.array([-2.306779, 1.6751516, -0.6472672], dtype='float32'),
        rotation=np.quaternion(-0.150860279798508, 0, 0.988555133342743, 0)
    )
}
zero_state = habitat_sim.AgentState(position=position,rotation=rotation,sensor_states=sensor_states)

def make_configuration():
    # 模拟器配置
    backend_cfg = habitat_sim.SimulatorConfiguration()
    backend_cfg.scene_id = "data/scene_datasets/gibson/Beach.glb"
    backend_cfg.enable_physics = True
    # backend_cfg.allow_sliding = True

    # agent 配置
    CAMsensor_cfg = habitat_sim.CameraSensorSpec()
    CAMsensor_cfg.sensor_type = habitat_sim.sensor.SensorType.COLOR
    CAMsensor_cfg.uuid = "rgb"
    CAMsensor_cfg.resolution = [256,256]
    # DepSensor_cfg = habitat_sim.CameraSensorSpec()
    # DepSensor_cfg.uuid = "depth"
    # DepSensor_cfg.resolution = [256,256]
    # DepSensor_cfg.sensor_type = habitat_sim.sensor.SensorType.DEPTH # 深度
    agent_cfg = habitat_sim.agent.AgentConfiguration()
    agent_cfg.sensor_specifications = [CAMsensor_cfg]

    return habitat_sim.Configuration(backend_cfg,[agent_cfg])

cfg = make_configuration()
sim = habitat_sim.Simulator(cfg)
agent = sim.initialize_agent(0)
agent_state = agent.get_state()
follower = sim.make_greedy_follower(agent_id=0, goal_radius=STEP_SIZE,stop_key="Stop")
observations = sim.reset()

MAX_EPISODE = 5000
MAX_EPOCH = 1000

listpd = pd.DataFrame(columns=['location'])

for episode in range(MAX_EPISODE):
    print("EPISODE:",episode,"/5000")
    nav_point = sim.pathfinder.get_random_navigable_point()
    observations = sim.reset()
    agent.set_state(zero_state)
    cv2.imshow("rgb",observations['rgb'])
    for epoch in range(MAX_EPOCH):
        try:
            action = follower.next_action_along(goal_pos=nav_point)
        except habitat_sim.errors.GreedyFollowerError:
            break
        # print(action)
        if action !=  "Stop":
           observations = sim.step(action)
           # cv2.imshow("rgb",observations['rgb'])
           # cv2.waitKey(1)
        else:
            imname ="/home/yuanzhao/PycharmProjects/Newnav/train_data/img/Beach/" +"_" + str(episode) + "_" +str(epoch) + "_" +".png"
            cv2.imwrite(imname,observations['rgb'])
            listpd.loc[len(listpd)] = str(nav_point.ravel().tolist())
            break

listpd.to_csv("/home/yuanzhao/PycharmProjects/Newnav/train_data/img/Beach/listpd.csv")


from pipeline import PipelineStep
import cv2
import numpy as np

class ThresholdHSV(PipelineStep):
	def __init__(self, lower, upper):
		self.lower = lower
		self.upper = upper

	def process(self, inputs, visualize=False):
		img = inputs['img']
		img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
		mask = cv2.inRange(img_hsv, self.lower, self.upper)
		result = cv2.bitwise_and(img, img, mask=mask)

		outputs = {'img': result, 'debug_img': result}

		return outputs


""".. module:: SPTPol

:Synopsis: Definition of python-native CMB likelihood for SPT likelihood (SPTpol+SZ l=2000-11000
power spectrum). Adapted from Fortran likelihood code
https://lambda.gsfc.nasa.gov/product/spt/spt_ps_2020_get.cfm

:Author: Matthieu Tristram

"""
import os
from typing import Optional, Sequence

import numpy as np
from cobaya.likelihoods.base_classes import InstallableLikelihood
from cobaya.log import LoggedError

from . import spt_foregrounds as sptfg

class SPTHiellLikelihood(InstallableLikelihood):
    install_options = {
        "download_url": "https://lambda.gsfc.nasa.gov/data/suborbital/SPT/reichardt_2020/likelihood.tar.gz",
        "data_path": "spt_hiell_2020",
    }

    cal_cov = [
        [1.1105131e-05, 3.5551351e-06, 1.1602891e-06],
        [3.5551351e-06, 3.4153547e-06, 2.1348018e-06],
        [1.1602891e-06, 2.1348018e-06, 1.7536000e-05],
    ]

    frequencies: Sequence[int] = [95, 150, 220]

    data_folder: Optional[str] = "spt_hiell_2020/likelihood"
    desc_file: Optional[str]
    bp_file: Optional[str]
    cov_file: Optional[str]
    beamerr_file: Optional[str]
    window_file: Optional[str]

    normalizeSZ_143GHz: Optional[bool] = True
    callFGprior: Optional[bool] = True
    applyFTSprior: Optional[bool] = True

    def initialize(self):
        # Set path to data
        if (not getattr(self, "path", None)) and (not getattr(self, "packages_path", None)):
            raise LoggedError(
                self.log,
                "No path given to CIB_Likelihood data. Set the likelihood property 'path' or the common property '%s'.",
                _packages_path,
            )

        # If no path specified, use the modules path
        data_file_path = os.path.normpath(
            getattr(self, "path", None) or os.path.join(self.packages_path, "data")
        )

        # check data_folder
        self.data_folder = os.path.join(data_file_path, self.data_folder)
        if not os.path.exists(self.data_folder):
            raise LoggedError(
                self.log,
                "The 'data_folder' directory does not exist. Check the given path [%s].",
                self.data_folder,
            )

        # Init foreground model
        self.fg = sptfg.SPTforegounds(data_folder=self.data_folder, **self.foregrounds)

        # Update data_folder location
        self.data_folder = os.path.join(self.data_folder, "data/spt_hiell_2020")

        # get info from the desc_file
        self._update_with_desc_file()

        self.log.debug(f"nall: {self.nall}")
        self.log.debug(f"nfreq: {self.nfreq}")
        self.log.debug(f"spt_windows_lmin: {self.spt_windows_lmin}")
        self.log.debug(f"spt_windows_lmax: {self.spt_windows_lmax}")

        self.lmin = self.spt_windows_lmin
        self.lmax = self.spt_windows_lmax + 1  # to match fortran convention

        if self.spt_windows_lmax > self.fg.ReportFGLmax():
            raise LoggedError(self.log, "Hard-wired lmax in foregrounds is too low for SPT_hiell")

        if self.spt_windows_lmin < 2 or self.spt_windows_lmin >= self.spt_windows_lmax:
            raise LoggedError(self.log, "Invalid lranges for sptpol")

        # read bandpowers (90x90, 90x150, 90x220, 150x150, 150x220, 220x220)
        # check file before
        bla, self.spec = np.loadtxt(os.path.join(self.data_folder, self.bp_file), unpack=True)

        # read covariance
        # check file before
        self.cov = np.fromfile(
            os.path.join(self.data_folder, self.cov_file), dtype=np.float64
        ).reshape(self.nall, self.nall)

        # read beam_err
        # check file before
        self.beam_err = np.fromfile(
            os.path.join(self.data_folder, self.beamerr_file), dtype=np.float64
        ).reshape(self.nall, self.nall)

        # Read windows
        # check file before
        self.windows = self._read_windows(os.path.join(self.data_folder, self.window_file))

        # define indicies
        self.indices = []
        for j in range(self.nfreq):
            for k in range(j, self.nfreq):
                self.indices.append((j, k))

        # define offsets for xfreq in Cl vector
        self.offsets = [0]
        for i in range(1, self.nband):
            self.offsets.append(self.offsets[i - 1] + self.nbins[i - 1])

        self.log.info("Init SPTlik done")

    def _read_windows(self, filename):
        import struct

        with open(filename, "rb") as f:
            efflmin, efflmax = struct.unpack("@II", f.read(2 * np.dtype(np.int32).itemsize))

        if efflmax < self.spt_windows_lmin or efflmin > self.spt_windows_lmax:
            raise LoggedError(self.log, "unallowed l-ranges for binary window functions")

        #        j0 = self.spt_windows_lmin if self.spt_windows_lmin > efflmin else efflmin
        #        j1 = self.spt_windows_lmax if self.spt_windows_lmax < efflmax else efflmax
        #        if j1 < j0:
        #            raise ValueError( "unallowed l-ranges for binary window functions - no allowed ells")

        offset = 2 * (np.dtype(np.int32).itemsize)
        #        windows = np.zeros( (self.nall, self.spt_windows_lmax+1) )
        #        windows[:,j0:j1+1] = np.fromfile( filename, dtype=np.float64, offset=offset).reshape(self.nall,-1)
        # windows = np.zeros((self.nall, efflmax + 1))
        windows = np.fromfile(filename, dtype=np.float64, offset=offset).reshape(self.nall, -1)

        return windows

    def _update_with_desc_file(self):
        filename = os.path.join(self.data_folder, self.desc_file)

        with open(filename) as f:
            self.nall, self.nfreq = [int(float(x)) for x in next(f).split()]
            self.nband = int(self.nfreq * (self.nfreq + 1) / 2)

            self.nbins = [int(next(f)) for i in range(self.nband)]
            if self.nall != sum(self.nbins):
                raise LoggedError(self.log, "Mismatched number of bandpowers")

            self.spt_norm_fr = [float(next(f)) for i in range(5)]

            if self.normalizeSZ_143GHz:
                self.log.debug("Using 143 as tSZ center freq")
                self.spt_norm_fr[4] = 143.0

            self.spt_windows_lmin, self.spt_windows_lmax = [int(x) for x in next(f).split()]

            eff_fr = []
            for _ in range(self.nfreq):
                eff_fr.append([float(next(f)) for i in range(5)])
            self.spt_eff_fr = np.array(eff_fr)

            self.spt_prefactor = np.array([float(next(f)) for i in range(self.nfreq)])

    def _gaussian_loglike(self, dlcov, res):
        """
        Returns -Log Likelihood for Gaussian: (d^T Cov^{-1} d + log|Cov|)/2
        """
        from scipy.linalg import cho_factor, cho_solve

        L, low = cho_factor(dlcov)

        # compute det
        detcov = 2.0 * np.sum(np.log(np.diag(L)))

        # Compute C-1.d
        invCd = cho_solve((L, low), res)

        # Compute chi2
        chi2 = res @ invCd

        return chi2 / 2.0, detcov / 2.0

    def loglike(self, dl_cmb, **params):
        """
        dl_cmb: Dl TT
        """
        CalFactors = [params[f"mapCal{nu}"] for nu in self.frequencies]
        FTSfactor = params["FTS_calibration_error"]

        # scaling theory
        # tszfac = sptfg.cosmo_scale_tsz(theory.H0,theory.sigma_8,theory.omb)
        # params["czero_tsz"] = params["czero_tsz"] * tszfac
        # kszfac = sptfg.cosmo_scale_ksz(theory.H0,theory.sigma_8,theory.omb,theory.omc+theory.omb+theory.omnu,theory.InitPower(ns_index),theory.tau)
        # params["czero_ksz"] = params["czero_ksz"] * kszfac

        # Loop on nband
        cbs = np.zeros(self.nall)
        for i in range(self.nband):
            j, k = self.indices[i]
            thisoffset = self.offsets[i]
            thisbin = self.nbins[i]

            # get theory spectra
            dl_fg = self.fg.dl_foregrounds(
                params,
                j,
                k,
                self.nfreq,
                self.spt_eff_fr + FTSfactor,
                self.spt_norm_fr,
                self.spt_windows_lmin,
                self.spt_windows_lmax
            )
            dl_th = dl_cmb[self.lmin : self.lmax] + dl_fg[self.lmin : self.lmax]

            # bin theory with window functions
            tmpcb = self.windows[thisoffset:thisoffset+thisbin] @ dl_th

            # apply prefactors
            tmpcb = tmpcb * self.spt_prefactor[k] * self.spt_prefactor[j] * CalFactors[j] * CalFactors[k]

            cbs[thisoffset : thisoffset + thisbin] = tmpcb

        # Residuals
        delta_cb = cbs - self.spec

        # Dl covariance (with beams)
        cov_w_beam = self.cov + self.beam_err * np.outer(cbs, cbs)

        # compute LogLike
        LnL, detcov = self._gaussian_loglike(cov_w_beam, delta_cb)
        SPTHiEllLnLike = LnL + detcov

        # Add FG priors
        if self.callFGprior:
            FGPriorLnLike = self.fg.getForegroundPriorLnL(params)
            SPTHiEllLnLike += FGPriorLnLike

        # Add calib LogLike
        delta_calib = np.log(CalFactors)
        CalibLnLike, _ = self._gaussian_loglike(self.cal_cov, delta_calib)
        SPTHiEllLnLike += CalibLnLike

        # Add FTS prior
        # Prior is 0.3 GHz for 1 sigma around 0.
        if self.applyFTSprior:
            FTSLnLike = 0.5 * (FTSfactor / 0.3) ** 2
            SPTHiEllLnLike += FTSLnLike

        self.log.debug(f"SPTHiEllLnLike lnlike = {SPTHiEllLnLike} (with priors)")
        self.log.debug(f"Calibration chisq = {2 * CalibLnLike}")
        self.log.debug(f"lnLcov term = {detcov}")
        self.log.debug(f"chisq for cov only: {2 * LnL}")
        self.log.debug(f"chisq for FG prior: {2 * FGPriorLnLike}")
        self.log.debug(f"SPTHiEllLnLike chisq (after prior) = {2 * (SPTHiEllLnLike - detcov)}")

        return -SPTHiEllLnLike

    def get_requirements(self):
        requirements = dict(Cl={mode: self.lmax for mode in ["tt"]})
        return requirements

    def logp(self, **params_values):
        dl = self.theory.get_Cl(units="muK2", ell_factor=True)["tt"]
        return self.loglike(dl, **params_values)


from setuptools import setup, find_packages
from setuptools.extension import Extension
from distutils.command.build_ext import build_ext as du_build_ext

class build_ext(du_build_ext):
    def run(self):
        from Cython.Build.Dependencies import cythonize
        self.distribution.ext_modules[:] = cythonize(
            self.distribution.ext_modules,
            language_level=3)
        du_build_ext.run(self)

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

extensions = [
    Extension("kpkc.kpkc", sources=["kpkc/kpkc.pyx"]),
]

setup(
    name='kpkc',
    version='0.1.2a0',
    description='A python interface to KPartiteKClique',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='https://github.com/kliem/PyKPartiteKClique',
    author='Jonathan Kliem',
    author_email='jonathan.kliem@gmail.com',
    license='GPLv3',
    packages=find_packages(),
    ext_modules=extensions,
    zip_safe=False,
    python_requires='>=3.6',
    package_dir={'kpkc': 'kpkc'},
    install_requires=["Cython"],
    package_data={"kpkc": ["*.pxd", "*.h", "cppkpkc/*.h"]},
    cmdclass={'build_ext': build_ext},
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
        'Programming Language :: Python :: 3',
        "Programming Language :: Cython",
        "Programming Language :: C++",
        'Topic :: Scientific/Engineering :: Mathematics']
    )


from PIL import *
import cv2, numpy as np
import matplotlib.pylab as plt
import glob
import requests
import json
import time
import os

print("===== start ===== ")

# 평균 해시로 변환 method
def tohash(img):

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    gray = cv2.resize(gray, (64,64))

    avg = gray.mean()

    bins = 1 * (gray > avg)

    return bins

# 해밍 거리 측정 method
def hamming(a,b):

    a = a.reshape(1, -1)

    b = b.reshape(1, -1)

    distance = (a != b).sum()

    return distance

while True:

    # take a picture first
    #os.system('wget http://192.168.0.96:8091/?action=snapshot -O 0204_image_first.jpg')
    #print("take a picture first  //  file list : ")
    #print(os.listdir(os.getcwd()))

    #60second delay
    #time.sleep(10)

    print("")

    print("===== while start ===== ")

    print("5 second later take a picture")
    time.sleep(1)

    print("4 second later take a picture")
    time.sleep(1)

    print("3 second later take a picture")
    time.sleep(1)

    print("2 second later take a picture")
    time.sleep(1)

    print("1 second later take a picture")
    time.sleep(1)

    # take a picture second
    os.system('wget http://192.168.0.2:8091/?action=snapshot -O 0204_image_second.jpg')
    print("take a picture first  //  file list : ")
    print(os.listdir(os.getcwd()))

    #comparing fist and second
    img1 = cv2.imread('/home/pi/fdCam/0204_image_first.jpg')
    img2 = cv2.imread('/home/pi/fdCam/0204_image_second.jpg')

    imgs = [img1, img2]

    white = np.arange(2)

    # 이미지의 해밍거리 계산

    img1_hash = tohash(img1)

    img2_hash = tohash(img2)

    dst = hamming(img1_hash, img2_hash)

    if dst/256 > 0.3 :
        #smilarity higer than 10% and white(green) pixels increase !!
        #in case of a litle change, : 0.10546875
        print("== 1. image changed ")
        print("no same picture : ","해밍거리 값 : ",dst/256) # 해밍 거리 출력

        # hand or plant
        if dst/256 > 0.9 :
            print("== 1(1). hand in")

        else :
            print("== 1(2). plant in")

            white = np.arange(2)

            for i, img in enumerate(imgs) :

                #---① 각 이미지를 HSV로 변환
                hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
                mask = cv2.inRange(hsv, (36,0,0), (86,255,255))

                ## slice the green
                imask = mask>0
                green = np.zeros_like(img, np.uint8)
                green[imask] = img[imask]

                # 마스크 색을 흰색으로 바꾸기
                coloured = green.copy()

                coloured[mask == 255] = (255, 255, 255)

                #흰 색인 픽셀의 개수를 세기
                white[i] = np.sum(coloured == 255)

            if(white[1]-white[0]>6000) :

                print("1(2)-1 잡초가 나타났습니다.")
                print("no same picture : ","해밍거리 값 : ",dst/256) # 해밍 거리 출력
                print("how many white pixels : ",white)
                print("white[1] - white[0] :", white[1] - white[0] )

                #FCM
                serverToken = 'AAAArVqyUkk:APA91bHhS90vKQZ09y70Cm3FSDhCezwEdCI-I8ZhS-joS01clMUI22wCet0JeaH4hcOJfK281QRarz4INArpkZmkiEUbPSUK-8gFDcEZLKcyNsyNYSrgXu-NlLHI3n-m_G3C_caIdiI3'

                deviceToken = 'fe6DJH9UQO2mM27WtIxeoG:APA91bFpCAzxzlViwgvYxac0rVjTbYdpadpsat6RIV9wu2G0gzXCots6vsZLdIpwr1AxqMfsuXvcjZQdG3YqWcybr1LHMblDQXgYk4OnsWx6bYWTXj--bcrVmD13UMW6hSE8tRmP_4Bp'

                headers = {'Content-Type': 'application/json','Authorization': 'key=' + serverToken}

                body = {'notification': {'title': 'SmartFarm','body': '잡초가 있습니다.'},'to': deviceToken, 'data': {'title': 'SmartFarm','body': '잡초가 있습니다.'}}

                response = requests.post("https://fcm.googleapis.com/fcm/send",headers = headers, data=json.dumps(body))

                print(response.status_code)

            else :
                print("1(2)-1 잡초 X")
                print("no same picture : ","해밍거리 값 : ",dst/256) # 해밍 거리 출력
                print("how many white pixels : ",white)
                print("white[1] - white[0] :", white[1] - white[0] )

                # change file name second -> first

    else :

        print("== 2. image unchanged ")

        print("해밍거리 값 : ",dst/256)
        print("해밍거리 값 bigger 10%: ",dst/256 > 0.06)

    os.rename('/home/pi/fdCam/0204_image_second.jpg', '/home/pi/fdCam/0204_image_first.jpg')
    print("file name second -> first  //  file list : ")
    print(os.listdir(os.getcwd()))

    print("===== while end ===== ")

print("===== end ===== ")


import pandas as pd
from astropy.cosmology import default_cosmology
from tsfresh.feature_extraction import extract_features
from tqdm import tqdm

import common
import config
import gc
from .common import *

cosmo = default_cosmology.get()

@feature('f1000')
def f1000_salt2_normalized_chisq(input: Input, **kw):
    salt2 = common.load_feature("f500")
    meta_ = pd.merge(input.meta, salt2, on='object_id', how='left')

    count = input.lc.groupby('object_id')['mjd'].count().reset_index()
    count.columns = ['object_id', 'n_observed']

    meta_ = pd.merge(meta_, count, on='object_id', how='left')
    meta_['sn_salt2_chisq_norm'] = meta_['sn_salt2_chisq'] / meta_['n_observed']

    return meta_[['object_id', 'sn_salt2_chisq_norm']]

@feature('f1001')
def f1001_detected_to_risetime_ratio(input: Input, **kw):
    delta = common.load_feature("f050")
    risetime = common.load_feature("f053")

    meta_ = pd.merge(input.meta, delta, on='object_id', how='left')
    meta_ = pd.merge(meta_, risetime, on='object_id', how='left')

    features = []
    for i in range(6):
        f = 'delta(first(detected), max(flux))_ch{}_to_delta_ratio'.format(i)
        meta_[f] = meta_['delta(first(detected), max(flux))_ch{}'.format(i)] / meta_['delta']
        features.append(f)

    return meta_[['object_id']+features]

@feature('f1002')
def f1002_detected_to_falltime_ratio(input: Input, **kw):
    delta = common.load_feature("f050")
    falltime = common.load_feature("f053")

    meta_ = pd.merge(input.meta, delta, on='object_id', how='left')
    meta_ = pd.merge(meta_, falltime, on='object_id', how='left')

    features = []
    for i in range(6):
        f = 'delta(max(flux), last(detected))_ch{}_to_delta_ratio'.format(i)
        meta_[f] = meta_['delta(max(flux), last(detected))_ch{}'.format(i)] / meta_['delta']
        features.append(f)

    return meta_[['object_id']+features]

def z2pc(z):
    return cosmo.luminosity_distance(z).value

@feature('f1003')
def f1003_luminosity_by_estimated_redshift(input: Input, **kw):
    aggregate = common.load_feature("f000")
    redshift = common.load_feature("f600")
    meta_ = pd.merge(input.meta, redshift, on='object_id', how='left')
    meta_ = pd.merge(meta_, aggregate, on='object_id', how='left')

    meta_['Mpc'] = meta_['hostgal_z_predicted'].apply(z2pc)
    meta_['Gpc'] = meta_['Mpc'] / 1000.0

    features = []
    for i in range(6):
        ch = i
        meta_['flux_diff_ch{}'.format(ch)] = meta_['max(flux)_ch{}'.format(ch)] - meta_['min(flux)_ch{}'.format(ch)]
        meta_['luminosity_diff_ch{}_estimated'.format(ch)] = meta_['flux_diff_ch{}'.format(ch)] * meta_['Gpc'] * meta_['Gpc']
        features.append('luminosity_diff_ch{}_estimated'.format(ch))

    features_renamed = ['luminosity_est_diff_ch{}'.format(i) for i in range(6)]

    rename = {features[i]: features_renamed[i] for i in range(6)}

    meta_.rename(columns=rename, inplace=True)

    return meta_[['object_id']+features_renamed]

def extract_features_postproc(df: pd.DataFrame):
    df.sort_values(by='id', inplace=True)
    df.rename(columns={'id': 'object_id'}, inplace=True)
    df.reset_index(drop=True, inplace=True)
    return df

@feature('f1004')
def f1004_tsfresh_flux(input: Input, **kw):
    fcp = {
        'longest_strike_above_mean': None,
        'longest_strike_below_mean': None,
        'mean_change': None,
        'mean_abs_change': None,
        'length': None,
    }

    dfs = []
    for i in tqdm(range(30)):
        lc = common.load_partial_lightcurve(i)
        partial = extract_features(lc,
                                   column_id='object_id',
                                   column_value='flux',
                                   default_fc_parameters=fcp, n_jobs=config.TSFRESH_N_JOBS)
        dfs.append(partial.reset_index())
        gc.collect()

    return extract_features_postproc(pd.concat(dfs))

@feature('f1005')
def f1005_tsfresh_flux_per_passband(input: Input, **kw):
    fcp = {
        'fft_coefficient': [
                {'coeff': 0, 'attr': 'abs'},
                {'coeff': 1, 'attr': 'abs'}
            ],
        'kurtosis': None,
        'skewness': None,
    }

    dfs = []
    for i in tqdm(range(30)):
        lc = common.load_partial_lightcurve(i)
        partial = extract_features(lc,
                                   column_id='object_id',
                                   column_sort='mjd',
                                   column_kind='passband',
                                   column_value='flux',
                                   default_fc_parameters=fcp, n_jobs=config.TSFRESH_N_JOBS)
        dfs.append(partial.reset_index())
        gc.collect()

    return extract_features_postproc(pd.concat(dfs))

@feature('f1006')
def f1006_tsfresh_mjd(input: Input, **kw):
    fcp = {
        'mean_change': None,
        'mean_abs_change': None,
    }
    lc = input.lc
    df_det = lc[lc['detected'] == 1].copy()

    dfs = []
    for i in tqdm(range(30)):
        lc = common.load_partial_lightcurve(i)
        partial = extract_features(df_det,
                                   column_id='object_id',
                                   column_value='mjd',
                                   default_fc_parameters=fcp, n_jobs=config.TSFRESH_N_JOBS)
        dfs.append(partial.reset_index())
        gc.collect()

    return extract_features_postproc(pd.concat(dfs))

def filter_lc_by_snr(lc: pd.DataFrame, snr: int):
    lc['SNR'] = lc['flux'] / lc['flux_err']
    lc['absSNR'] = np.abs(lc['SNR'])
    lc['flag'] = (lc['absSNR'] > snr).astype(np.uint8)
    return lc[lc['flag'] == 1]

@feature('f1080')
def f1080_snr3_minmax_diff(input: Input, **kw):
    lc_detected = filter_lc_by_snr(input.lc, snr=3)
    mjddelta = lc_detected.groupby('object_id').agg({'mjd': ['min', 'max']})
    mjddelta['delta'] = mjddelta[mjddelta.columns[1]] - mjddelta[mjddelta.columns[0]]
    mjddelta = mjddelta['delta'].reset_index(drop=False)

    return mjddelta

@feature('f1081')
def f1081_first_is_detected(input: Input, **kw):
    first = input.lc[['object_id', 'mjd', 'detected']].groupby('object_id').first()
    first.columns = ['mjd', 'detected_on_first_observation']

    return first.drop('mjd', axis=1).reset_index()

@feature('f1082')
def f1082_last_is_detected(input: Input, **kw):
    last = input.lc[['object_id', 'mjd', 'detected']].groupby('object_id').last()
    last.columns = ['mjd', 'detected_on_last_observation']

    return last.drop('mjd', axis=1).reset_index()

@feature('f1083')
def f1083_max_flux_within_snr3(input: Input, **kw):
    lc_detected = filter_lc_by_snr(input.lc, snr=3)
    return aggregate_by_id_passbands(lc_detected, 'flux', ['max'], prefix='snr3_')

@feature('f1084')
def f1084_min_flux_within_snr3(input: Input, **kw):
    lc_detected = filter_lc_by_snr(input.lc, snr=3)
    return aggregate_by_id_passbands(lc_detected, 'flux', ['min'], prefix='snr3_')

@feature('f1085')
def f1085_luminosity_diff_within_snr3(input: Input, **kw):
    redshift = common.load_feature('f600')
    max_flux = common.load_feature('f1083')
    min_flux = common.load_feature('f1084')

    meta = pd.merge(input.meta, redshift, on='object_id', how='left')
    meta = pd.merge(meta, max_flux, on='object_id', how='left')
    meta = pd.merge(meta, min_flux, on='object_id', how='left')

    meta['Mpc'] = meta['hostgal_z_predicted'].apply(z2pc)
    meta['Gpc'] = meta['Mpc'] / 1000.0

    features = []
    for i in range(6):
        ch = i
        meta['snr3_flux_diff_ch{}'.format(ch)] = meta['snr3_max(flux)_ch{}'.format(ch)] - meta['snr3_min(flux)_ch{}'.format(ch)]
        meta['snr3_luminosity_diff_ch{}'.format(ch)] = meta['snr3_flux_diff_ch{}'.format(ch)] * meta['Gpc'] * meta['Gpc']
        features.append('snr3_luminosity_diff_ch{}'.format(ch))

    return meta[['object_id']+features]

@feature('f1086')
def f1086_first_detected_to_prev_mjd_diff(input: Input, **kw):
    lc = input.lc
    lc['mjd_prev'] = lc[['object_id', 'mjd']].groupby('object_id').shift(1)
    lc_detected = lc[lc.detected == 1]

    first_obs = lc_detected.groupby('object_id').first()
    first_obs['first_detected_to_prev_mjd_diff'] = first_obs['mjd'] - first_obs['mjd_prev']

    return first_obs[['first_detected_to_prev_mjd_diff']].reset_index()

@feature('f1087')
def f1087_last_detected_to_next_mjd_diff(input: Input, **kw):
    lc = input.lc
    lc['mjd_next'] = lc[['object_id', 'mjd']].groupby('object_id').shift(-1)
    lc_detected = lc[lc.detected == 1]

    last_obs = lc_detected.groupby('object_id').last()
    last_obs['last_detected_to_next_mjd_diff'] = last_obs['mjd_next'] - last_obs['mjd']

    return last_obs[['last_detected_to_next_mjd_diff']].reset_index()

@feature('f1088')
def f1088_first_detected_to_prev_mjd_diff_perch(input: Input, **kw):
    lc = input.lc
    lc['mjd_prev'] = lc[['object_id', 'mjd']].groupby('object_id').shift(1)
    lc_detected = lc[lc.detected == 1]

    first_obs_pb = lc_detected.groupby(['object_id', 'passband']).first()
    first_obs_pb['first_detected_to_prev_mjd_diff_perch'] = first_obs_pb['mjd'] - first_obs_pb['mjd_prev']

    return unstack(first_obs_pb[['first_detected_to_prev_mjd_diff_perch']])

@feature('f1089')
def f1089_last_detected_to_next_mjd_diff_perch(input: Input, **kw):
    lc = input.lc
    lc['mjd_next'] = lc[['object_id', 'mjd']].groupby('object_id').shift(-1)
    lc_detected = lc[lc.detected == 1]

    last_obs_pb = lc_detected.groupby(['object_id', 'passband']).last()
    last_obs_pb['last_detected_to_next_mjd_diff_perch'] = last_obs_pb['mjd_next'] - last_obs_pb['mjd']

    return unstack(last_obs_pb[['last_detected_to_next_mjd_diff_perch']])


import argparse
import os
from tqdm import tqdm
import numpy as np
import re
import shutil

def process_GT_label(args):
   annotations_path = args.annotations_path
   annotations= os.listdir(annotations_path)
   save_path = args.save_path
   if os.path.exists(save_path):
      shutil.rmtree(save_path)
   os.makedirs(save_path, exist_ok=True)
   # print(annotations_path, save_path)
   # return
   str_XY = "(Xmax, Ymax)"
   str_size = 'Image size (X x Y x C)'

   os.makedirs(save_path, exist_ok=True)

   for file in tqdm(annotations):
      with open(os.path.join(annotations_path, file), encoding = "ISO-8859-1") as f:
         bboxes = []
         iter_f = f.readlines()
         for line in iter_f:
            if str_size in line:
               size = [int(i) for i in re.findall(r"\d+", line)]
               w, h = size[:2]
            if str_XY in line:
               strlist = line.split(str_XY)
               strlist1 = "".join(strlist[1:])    # 把list转为str
               strlist1 = strlist1.replace(':', '')
               strlist1 = strlist1.replace('-', '')
               strlist1 = strlist1.replace('(', '')
               strlist1 = strlist1.replace(')', '')
               strlist1 = strlist1.replace(',', '')
               b = strlist1.split()
               bnd = np.array([float(b[0]), float(b[1]), float(b[2]), float(b[3])])
               bnd[[0, 2]] = bnd[[0, 2]] / w
               bnd[[1, 3]] = bnd[[1, 3]] / h
               bnd *= args.rescale_factor
               bnd = [str(i) for i in bnd]
               bnd.insert(0, 'person')
               bboxes.append(' '.join(list(bnd)))
         with open(os.path.join(save_path, file), 'w') as f:
            f.write('\n'.join(bboxes))
      # break

if __name__ == "__main__":
   from pathlib import Path
   FILE = Path(__file__).resolve()
   PROJECT_DIR = FILE.parents[2]
   print(PROJECT_DIR)

   parser = argparse.ArgumentParser()
   parser.add_argument('-s', '--save_path', type=str, default=os.path.join(PROJECT_DIR, 'data/INRIAPerson/Test/labels/ground-truth-rescale-labels'),
                       help="Path of the parsed labels to save.")
   parser.add_argument('-a', '--annotations_path', type=str, default=os.path.join(PROJECT_DIR, 'data/INRIAPerson/Test/annotations'),
                       help="Path of the annotation files.")
   parser.add_argument('-r', '--rescale_factor', type=int, default=416,
                       help="Rescale factor for an input size [41, 416]. Decide this based on your input image size.")
   args = parser.parse_args()

   process_GT_label(args)


#*************************************************************************
# Copyright (C) 2018 Kaan Kara - Systems Group, ETH Zurich

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#*************************************************************************

import socket
import cv2
import threading
import struct
import numpy as np
import sys

sys.path.append("/home/xilinx/jupyter_notebooks/dac_2019_contest/common")
#################### import all libraries and initializations ############
from pynq import Xlnk
from pynq import Overlay
from pynq.mmio import MMIO
from PIL import Image

class FPGA_Connect_Object:
    def __init__(self, addr_port_client=("192.168.1.100", 3000)):
        print('FPGA_Connect_Object init')
        self.resolution = [640, 360]
        self.client_port = addr_port_client

        team_name = 'SystemsETHZ'
        # agent = Agent(team_name)

        interval_time = 0
        xlnk = Xlnk()
        xlnk.xlnk_reset()

        ###########################variable initializing######################
        OVERLAY_PATH = '/home/xilinx/jupyter_notebooks/dac_2019_contest/common/' + team_name + '/ultra96_v04.bit'
        WEIGHTS_FILE_NAME = '/home/xilinx/jupyter_notebooks/dac_2019_contest/common/' + team_name + '/weights_file_v04_demo.txt'

        ###########################change board settings######################

        ###########################download      overlay######################
        overlay = Overlay(OVERLAY_PATH)
        self.dma = overlay.axi_dma_0
        self.nn_ctrl = MMIO(0xA0010000, length=1024)
        ###########################download      weights######################
        self.MINIBATCH_SIZE = 1
        self.height = 176
        self.width = 320
        pixel_bits = 24
        pixels_per_line = 384/pixel_bits
        self.num_lines = int((self.height*self.width)/pixels_per_line)

        self.in_buffer = xlnk.cma_array(shape=(self.MINIBATCH_SIZE*self.num_lines, 64), dtype=np.uint8)
        fire1_num_out_lines = (self.height/4)*(self.width/4)*self.MINIBATCH_SIZE
        self.fire1_out_buffer = xlnk.cma_array(shape=(int(16*fire1_num_out_lines),), dtype=np.uint32)
        fire2_num_out_lines = (self.height/8)*(self.width/8)*self.MINIBATCH_SIZE
        self.fire2_out_buffer = xlnk.cma_array(shape=(int(16*fire2_num_out_lines),), dtype=np.uint32)
        fire3_num_out_lines = (self.height/16)*(self.width/16)*self.MINIBATCH_SIZE
        self.fire3_out_buffer = xlnk.cma_array(shape=(int(16*fire3_num_out_lines),), dtype=np.uint32)
        self.fire4_out_buffer = xlnk.cma_array(shape=(int(16*fire3_num_out_lines),), dtype=np.uint32)
        self.fire5_out_buffer = xlnk.cma_array(shape=(int(16*fire3_num_out_lines),), dtype=np.uint32)
        final_num_lines = int((self.height/16)*(self.width/16))
        self.bndboxes = [xlnk.cma_array(shape=(self.MINIBATCH_SIZE,final_num_lines,16), dtype=np.int32),
                        xlnk.cma_array(shape=(self.MINIBATCH_SIZE,final_num_lines,16), dtype=np.int32),
                        xlnk.cma_array(shape=(self.MINIBATCH_SIZE,final_num_lines,16), dtype=np.int32),
                        xlnk.cma_array(shape=(self.MINIBATCH_SIZE,final_num_lines,16), dtype=np.int32)]
        self.obj_array = np.zeros((self.MINIBATCH_SIZE,final_num_lines))

        NUM_LAYERS = 3+4*4
        weights_file = open(WEIGHTS_FILE_NAME, "r")
        layer = 0
        total_iterations = np.zeros(NUM_LAYERS)
        for line in weights_file:
            if "layer" in line:
                temp = line.split(": ")
                layer = int(temp[1])
            if "total_iterations" in line:
                temp = line.split(": ")
                total_iterations[layer] = int(temp[1])
        weights_file.close()

        weightfactors_length = np.zeros(NUM_LAYERS)
        self.weightsfactors = []
        for i in range(0, NUM_LAYERS):
            weightfactors_length[i] = int(total_iterations[i])
            self.weightsfactors.append( xlnk.cma_array(shape=(int(16*weightfactors_length[i]),), dtype=np.uint32) )
        self.obj_factors = np.zeros(4)
        self.box_factors = np.zeros(4)

        index = 0
        weights_file = open(WEIGHTS_FILE_NAME, "r")
        for line in weights_file:
            if "layer" in line:
                temp = line.split(": ")
                layer = int(temp[1])
                index = 0
            elif "total_iterations" not in line:
                if "obj_factor" in line:
                    temp = line.split(' ')
                    self.obj_factors[int(temp[1])] = int(temp[2])
                elif "box_factor" in line:
                    temp = line.split(' ')
                    self.box_factors[int(temp[1])] = int(temp[2])
                else:
                    no0x = line.split('0x')[-1]
                    base = 1
                    while base < len(no0x):
                        part = no0x[-1*(base+8):-1*base]
                        self.weightsfactors[layer][index*16 + int(base/8)] = int(part, 16)
                        base += 8
                    index += 1

    ## Define transfer functions
    def weightsfactors_transfer(self, weightsfactors):
        self.nn_ctrl.write(0x40, 13)
        self.nn_ctrl.write(0x48, 0)
        self.nn_ctrl.write(0x0, 0) # Reset
        self.nn_ctrl.write(0x0, 1) # Deassert reset
        self.dma.sendchannel.transfer(weightsfactors)
        self.dma.sendchannel.wait()

    def fire(self, inbuffer, outbuffer,
             squeeze_din_w, squeeze_din_h,
             expand_din_w, expand_din_h,
             expand_din_w_afterpool, expand_din_h_afterpool,
             whichfire):
        self.nn_ctrl.write(0x0, 0) # Reset
        self.nn_ctrl.write(0x10, int(squeeze_din_w))
        self.nn_ctrl.write(0x18, int(squeeze_din_h))
        self.nn_ctrl.write(0x20, int(expand_din_w))
        self.nn_ctrl.write(0x28, int(expand_din_h))
        self.nn_ctrl.write(0x30, int(expand_din_w_afterpool))
        self.nn_ctrl.write(0x38, int(expand_din_h_afterpool))
        self.nn_ctrl.write(0x40, whichfire)
        self.nn_ctrl.write(0x48, self.MINIBATCH_SIZE) # set numReps
        self.nn_ctrl.write(0x0, 1) # Deassert reset
        self.dma.recvchannel.transfer(outbuffer)
        self.dma.sendchannel.transfer(inbuffer)

        ###########################end      initializing######################
    def Socket_Connect_Client(self):
        print('FPGA_Connect_Object Socket_Connect')
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.client.connect(self.client_port)
        print("As a client, FPGA receives imgs from %s:%d" % (self.client_port[0], self.client_port[1]))

    def ProcessImg(self):
        print('FPGA_Connect_Object begins process imgs')
        self.client.send(struct.pack("hh", self.resolution[0], self.resolution[1]))

        print("debug_FPGA 1")

        while (1):
            recv_data = self.client.recv(16)
            # print("size ", len(recv_data))
            info = struct.unpack("qq", recv_data)

            buf_size = info[0]
            ## receive imgs
            if buf_size:
                try:
                    self.buf = b""
                    temp_buf = self.buf
                    while (buf_size):
                        temp_buf = self.client.recv(buf_size)
                        buf_size -= len(temp_buf)
                        self.buf += temp_buf
                except:
                    pass;

            data = np.fromstring(self.buf, dtype='uint8')

            ## get the imgs and process it
            image = cv2.imdecode(data, 1)

            ###########################call PL to do inference######################
            #detected bounding box coordinates in x1, y1, x2, y2
            result = np.zeros((1, 17))

            image = cv2.resize(image, (self.width, self.height), interpolation=cv2.INTER_NEAREST)
            self.in_buffer[0:self.num_lines,0:48] = np.reshape(image, (self.num_lines, 48))

            self.weightsfactors_transfer(self.weightsfactors[0])
            self.fire(self.in_buffer, self.fire1_out_buffer,\
                self.width/2, self.height/2, self.width/2, self.height/2, self.width/4, self.height/4, 1)
            self.dma.recvchannel.wait()

            self.weightsfactors_transfer(self.weightsfactors[1])
            self.fire(self.fire1_out_buffer, self.fire2_out_buffer,\
                self.width/4, self.height/4, self.width/4, self.height/4, self.width/8, self.height/8, 2)
            self.dma.recvchannel.wait()

            self.weightsfactors_transfer(self.weightsfactors[2])
            self.fire(self.fire2_out_buffer, self.fire3_out_buffer,\
                self.width/8, self.height/8, self.width/8, self.height/8, self.width/16, self.height/16, 3)
            self.dma.recvchannel.wait()

            for t in range(0, 4):
                self.weightsfactors_transfer(self.weightsfactors[3 + t*4])
                self.fire(self.fire3_out_buffer, self.fire4_out_buffer,\
                    self.width/16, self.height/16, self.width/16, self.height/16, self.width/16, self.height/16, 4)
                self.dma.recvchannel.wait()

                self.weightsfactors_transfer(self.weightsfactors[4 + t*4])
                self.fire(self.fire4_out_buffer, self.fire5_out_buffer,
                    self.width/16, self.height/16, self.width/16, self.height/16, self.width/16, self.height/16, 5)
                self.dma.recvchannel.wait()

                self.weightsfactors_transfer(self.weightsfactors[5 + t*4])
                self.fire(self.fire5_out_buffer, self.fire4_out_buffer,\
                    self.width/16, self.height/16, self.width/16, self.height/16, self.width/16, self.height/16, 6)
                self.dma.recvchannel.wait()

                self.weightsfactors_transfer(self.weightsfactors[6 + t*4])
                self.fire(self.fire4_out_buffer, self.bndboxes[t],\
                    self.width/16, self.height/16, self.width/16, self.height/16, self.width/16, self.height/16, 7)
                self.dma.recvchannel.wait()

                temp_obj = np.multiply(np.divide(self.bndboxes[t][:,:,4],float((1<<16))), float(self.obj_factors[t]))
                if t == 0:
                    self.obj_array = temp_obj
                else:
                    self.obj_array = np.add(self.obj_array, temp_obj)

            grid_cell = np.argmax(self.obj_array, axis=1)
            result[0,16] = grid_cell[0]
            for t in range(0,4):
                result[0, t*4:(t+1)*4] = self.bndboxes[t][0,grid_cell[0],0:4]

            float_objdetect = result[0,16].astype('float')
            float_bndboxes1 = np.multiply(np.divide(result[0,0:4].astype('float'), float((1<<16))), float(self.box_factors[0]))
            float_bndboxes2 = np.multiply(np.divide(result[0,4:8].astype('float'), float((1<<16))), float(self.box_factors[1]))
            float_bndboxes3 = np.multiply(np.divide(result[0,8:12].astype('float'), float((1<<16))), float(self.box_factors[2]))
            float_bndboxes4 = np.multiply(np.divide(result[0,12:16].astype('float'), float((1<<16))), float(self.box_factors[3]))
            float_bndboxes = float_bndboxes1+float_bndboxes2+float_bndboxes3+float_bndboxes4
            float_bndboxes = np.divide( float_bndboxes, 4.0*float((1 << 22)) )

            obj_h = int(float_objdetect/(self.width/16))
            obj_w = int(float_objdetect%(self.width/16))

            x1 = int((float_bndboxes[0] + obj_w*16) *(640/self.width))
            y1 = int((float_bndboxes[1] + obj_h*16) *(360/self.height))
            x2 = int((float_bndboxes[2] + obj_w*16) *(640/self.width))
            y2 = int((float_bndboxes[3] + obj_h*16) *(360/self.height))
            ###########################end        PL       call######################

            self.client.send(struct.pack("hhhh", abs(x1), abs(y1), abs(x2), abs(y2)))

    def ProcessInThread(self):
        print('FPGA_Connect_Object   Get_Data')
        showThread = threading.Thread(target=self.ProcessImg)
        showThread.start()

if __name__ == '__main__':
    FPGA = FPGA_Connect_Object(("192.168.3.109", 3000))
    print("connect object created")
    FPGA.Socket_Connect_Client()
    FPGA.ProcessInThread()


# rocket
import pygame

ROCKET_SIZE = (90, 90)

class Rocket:
    def __init__(self):
        rocket = pygame.image.load('resources/rocket.png').convert()
        self.rocket = pygame.transform.scale(rocket, ROCKET_SIZE)

    def draw(self, x, y, surface):
        surface.blit(self.rocket, (x, y))

if __name__ == '__main__':
    rrrr = Rocket()
    rrrr.draw(1, 2, 4)


"""Tests for GerryDB's local caching layer."""
import uuid
from datetime import datetime, timedelta, timezone

import pytest

from gerrydb.cache import CacheInitError, CacheObjectError, CachePolicyError, GerryCache
from gerrydb.schemas import BaseModel, ObjectCachePolicy, ObjectMeta

@pytest.fixture
def cache():
    """An in-memory instance of `GerryCache`."""
    return GerryCache(":memory:")

def test_gerry_cache_init__no_schema_version(cache):
    cache._conn.execute("DELETE FROM cache_meta")
    cache._conn.commit()
    with pytest.raises(CacheInitError, match="no schema version"):
        GerryCache(cache._conn)

def test_gerry_cache_init__bad_schema_version(cache):
    cache._conn.execute("UPDATE cache_meta SET value='bad' WHERE key='schema_version'")
    cache._conn.commit()
    with pytest.raises(CacheInitError, match="expected schema version"):
        GerryCache(cache._conn)

def test_gerry_cache_init__missing_table(cache):
    cache._conn.execute("DROP TABLE object")
    cache._conn.commit()
    with pytest.raises(CacheInitError, match="missing tables"):
        GerryCache(cache._conn)


from turtle import Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong Game")
screen.tracer(0)

r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
ball = Ball()
scoreboard = Scoreboard()

screen.update()

screen.listen()
screen.onkeypress(r_paddle.move_paddle_up, "Up")
screen.onkeypress(r_paddle.move_paddle_down, "Down")

screen.onkeypress(l_paddle.move_paddle_up, "w")
screen.onkeypress(l_paddle.move_paddle_down, "s")

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(ball.moving_speed)
    ball.move()

    # Detect collision with up and down wall
    if ball.ycor() >= 290 or ball.ycor() < -290:
        # need to bounce
        ball.wall_bounce()

    # Detect collision with paddle
    if (ball.distance(r_paddle) < 50 and ball.xcor() > 320) or (ball.distance(l_paddle) < 50 and ball.xcor() < -320):
        ball.paddle_bounce()

    # Detect ball passing by the right paddle
    if ball.xcor() > 400:
        ball.ball_reset()
        scoreboard.score_1 += 1
        scoreboard.update_scoreboard()

    # Detect ball passing by the left paddle
    if ball.xcor() < -400:
        ball.ball_reset()
        scoreboard.score_2 += 1
        scoreboard.update_scoreboard()

screen.exitonclick()


import logging

from netort.resource import manager as resource

from . import info
from . import instance_plan as ip
from . import load_plan as lp
from . import missile
from .mark import get_marker
from .module_exceptions import StepperConfigurationError, AmmoFileError

class ComponentFactory():
    def __init__(
            self,
            rps_schedule=None,
            http_ver='1.1',
            ammo_file=None,
            instances_schedule=None,
            instances=1000,
            loop_limit=-1,
            ammo_limit=-1,
            uris=None,
            headers=None,
            autocases=0,
            enum_ammo=False,
            ammo_type='phantom',
            chosen_cases=None,
            use_cache=True):
        self.log = logging.getLogger(__name__)
        self.ammo_file = ammo_file
        self.ammo_type = ammo_type
        self.rps_schedule = rps_schedule
        self.http_ver = http_ver
        self.instances_schedule = instances_schedule
        loop_limit = int(loop_limit)
        if loop_limit == -1:  # -1 means infinite
            loop_limit = None
        ammo_limit = int(ammo_limit)
        if ammo_limit == -1:  # -1 means infinite
            ammo_limit = None
        if loop_limit is None and ammo_limit is None and not rps_schedule:
            # we should have only one loop if we have instance_schedule
            loop_limit = 1
        info.status.loop_limit = loop_limit
        info.status.ammo_limit = ammo_limit
        info.status.publish("instances", instances)
        self.uris = uris
        if self.uris and loop_limit:
            info.status.ammo_limit = len(self.uris) * loop_limit
        self.headers = headers if headers is not None else []
        self.marker = get_marker(autocases, enum_ammo)
        self.chosen_cases = chosen_cases or []
        self.use_cache = use_cache

    def get_load_plan(self):
        """
        return load plan (timestamps generator)
        """
        if self.rps_schedule and self.instances_schedule:
            raise StepperConfigurationError(
                'Both rps and instances schedules specified. You must specify only one of them'
            )
        elif self.rps_schedule:
            info.status.publish('loadscheme', self.rps_schedule)
            return lp.create(self.rps_schedule)
        elif self.instances_schedule:
            info.status.publish('loadscheme', self.instances_schedule)
            return ip.create(self.instances_schedule)
        else:
            self.instances_schedule = []
            info.status.publish('loadscheme', self.instances_schedule)
            return ip.create(self.instances_schedule)

    def get_ammo_generator(self):
        """
        return ammo generator
        """
        af_readers = {
            'phantom': missile.AmmoFileReader,
            'slowlog': missile.SlowLogReader,
            'line': missile.LineReader,
            'uri': missile.UriReader,
            'uripost': missile.UriPostReader,
            'access': missile.AccessLogReader,
            'caseline': missile.CaseLineReader,
        }
        if self.uris and self.ammo_file:
            raise StepperConfigurationError(
                'Both uris and ammo file specified. You must specify only one of them'
            )
        elif self.uris:
            ammo_gen = missile.UriStyleGenerator(
                self.uris, self.headers, http_ver=self.http_ver)
        elif self.ammo_file:
            if self.ammo_type in af_readers:
                if self.ammo_type == 'phantom':
                    opener = resource.get_opener(self.ammo_file)
                    with opener(self.use_cache) as ammo:
                        try:
                            ammo_str = next(ammo).decode('utf-8')
                            if not ammo_str[0].isdigit():
                                self.ammo_type = 'uri'
                                self.log.info(
                                    "Setting ammo_type 'uri' because ammo is not started with digit and you did not specify ammo format"
                                )
                            else:
                                self.log.info(
                                    "Default ammo type ('phantom') used, use 'phantom.ammo_type' option to override it"
                                )
                        except StopIteration:
                            self.log.exception(
                                "Couldn't read first line of ammo file")
                            raise AmmoFileError(
                                "Couldn't read first line of ammo file")
            else:
                raise NotImplementedError(
                    'No such ammo type implemented: "%s"' % self.ammo_type)
            ammo_gen = af_readers[self.ammo_type](
                self.ammo_file, headers=self.headers, http_ver=self.http_ver, use_cache=self.use_cache)
        else:
            raise StepperConfigurationError(
                'Ammo not found. Specify uris or ammo file')
        self.log.info("Using %s ammo reader" % type(ammo_gen).__name__)
        return ammo_gen

    def get_marker(self):
        return self.marker

    def get_filter(self):
        if len(self.chosen_cases):

            def is_chosen_case(ammo_tuple):
                return ammo_tuple[1] in self.chosen_cases

            return is_chosen_case
        else:
            return lambda ammo_tuple: True


####################################################################
## Run 'opencv_test\env\Scripts\Activate.ps1' befor run this file ##
####################################################################

import cv2 as cv
import numpy as np
import random
import copy

#cap = cv.VideoCapture(0)   ##pcカメラから画像取得の場合この二行を使う
#ret, img = cap.read()
img = cv.imread("test\sample9_0m.jpg")

#画像のサイズを小さくする（前処理）
height = img.shape[0]
width = img.shape[1]
#resized_img = cv.resize(img,(round(width), round(height)))
print("image size is", height ,width)

# HSVに変換
resized_img_HSV = cv.cvtColor(img, cv.COLOR_BGR2HSV)
#cv.imshow("HSV", resized_img_HSV)

#赤を抽出
low_hsv_min = np.array([0, 108, 30]) #108
low_hsv_max = np.array([4, 256, 256]) #4

#画像の2値化（Hueが0近辺）
maskHSV_low = cv.inRange(resized_img_HSV,low_hsv_min,low_hsv_max)

high_hsv_min = np.array([168, 108, 30]) #177
high_hsv_max = np.array([180, 256, 256])

#画像の2値化（Hueが179近辺）
maskHSV_high = cv.inRange(resized_img_HSV,high_hsv_min,high_hsv_max)

#２つの領域を統合
hsv_mask = maskHSV_low | maskHSV_high

#画像のマスク（合成）
resultHSV = cv.bitwise_and(img, img, mask = hsv_mask)

# ラベリング処理
label = cv.connectedComponentsWithStats(hsv_mask)

# オブジェクト情報を項目別に抽出
n = label[0] - 1
data = np.delete(label[2], 0, 0)
center = np.delete(label[3], 0, 0)
size = []

# オブジェクト情報を利用してラベリング結果を画面に表示
for i in range(n):

    # 各オブジェクトの外接矩形を赤枠で表示
    x0 = data[i][0]
    y0 = data[i][1]
    x1 = data[i][0] + data[i][2]
    y1 = data[i][1] + data[i][3]

    cv.rectangle(resultHSV, (x0, y0), (x1, y1), (0, 0, 255))

    size.append(data[i][4])

max_size = max(size)
num = size.index(max_size)
center_x = center[num][0]
center_y = center[num][1]

print("centerX : " + str(center_x))
print("centerY : " + str(center_y))
print(max_size)

cv.putText(resultHSV, "X: " + str(int(center_x)), (x1 - 30, y1 + 15), cv.FONT_HERSHEY_PLAIN, 1, (0, 255, 255))
cv.putText(resultHSV, "Y: " + str(int(center_y)), (x1 - 30, y1 + 30), cv.FONT_HERSHEY_PLAIN, 1, (0, 255, 255))

cv.imshow("Result mask", hsv_mask)
cv.imshow("Result HSV", resultHSV)
cv.imshow("raw img", img)

cv.waitKey(0)
cv.destroyAllWindows()


from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import ChatBannedRights

from Cosmic import cosmo
from Cosmic.functions.handler import cosmic
from Cosmic.functions.misc import eor, get_user

BANNED_RIGHTS = ChatBannedRights(
    until_date=None,
    view_messages=True,
    send_messages=True,
    send_media=True,
    send_stickers=True,
    send_gifs=True,
    send_games=True,
    send_inline=True,
    embed_links=True,
)

UNBAN_RIGHTS = ChatBannedRights(
    until_date=None,
    send_messages=None,
    send_media=None,
    send_stickers=None,
    send_gifs=None,
    send_games=None,
    send_inline=None,
    embed_links=None,
)

KICK_RIGHTS = ChatBannedRights(until_date=None, view_messages=True)

MUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=True)

UNMUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=False)

@cosmic(pattern="kick ?(.*)")
async def kick(event):
    if event.is_private:
        return await eor(event, "Please use this in groups.")
    try:
        user, extra = await get_user(event)
        await cosmo(EditBannedRequest(event.chat_id, user, KICK_RIGHTS))
        await event.delete()
    except:
        pass

@cosmic(pattern="pin$")
async def pin(event):
    if event.is_private:
        return
    r = await event.get_reply_message()
    await r.pin()

@cosmic(pattern="kickme")
async def lmao(event):
    await event.client.delete_dialog(event.chat_id)

@cosmic(pattern="del")
async def bruh(event):
    x = await event.get_reply_message()
    await x.delete()
    await event.delete()

@cosmic(pattern="ban  ?(.*)")
async def ban(event):
    if event.is_private:
        return await eor(event, "Please use this in groups.")
    try:
        user, extra = await get_user(event)
        await cosmo(EditBannedRequest(event.chat_id, user, BANNED_RIGHTS))
        await event.delete()
    except:
        pass

@cosmic(pattern="dban ?(.*)")
async def dban(event):
    if event.is_private:
        return await event.edit("Please use this in groups.")
    try:
        user, _ = await get_user(event)
        await cosmo(EditBannedRequest(event.chat_id, user, BANNED_RIGHTS))
        await event.delete()
        await (
            await event.get_reply_message()
        ).delete() if event.reply_to_msg_id else await event.delete()
    except:
        pass

@cosmic(pattern="unban ?(.*)")
async def unban(event):
    if event.is_private:
        return await eor(event, "Please use this in groups.")
    try:
        user, extra = await get_user(event)
        await cosmo(EditBannedRequest(event.chat_id, user, UNBAN_RIGHTS))
        await event.delete()
    except:
        pass


from flask.views import MethodView
from flask import request, jsonify, abort
from datetime import datetime
from jsonschema import Draft4Validator
from jsonschema.exceptions import best_match
import uuid

from gift_card.models import GiftCard
from gift_card.schema import create_gift_cart_schema
from gift_card.templates import gift_card_obj, gift_card_objs
from store.models import Store
from store.decorators import token_required
from customer.models import Customer
from utils import paginated_results

CUSTOMER_NOT_FOUND = "CUSTOMER_NOT_FOUND"
MISSING_PARAMETERS = "MISSING_PARAMETERS"
GIFT_CARD_NOT_FOUND = "GIFT_CARD_NOT_FOUND"

class GiftCardAPI(MethodView):

    def __init__(self):
        self.PER_PAGE = 10
        if (request.method != 'GET' and request.method != 'DELETE') and not request.json:
            abort(400)

    @token_required
    def get(self, gift_card_id=None):
        """
        returns a gift_card object of list of gift_card objects
        """
        store = Store.objects.filter(app_id=request.headers.get('APP-ID'), deleted_at=None).first()

        if gift_card_id:
            gift_card = GiftCard.objects.filter(gift_card_id=gift_card_id).first()

            if gift_card is None:
                return jsonify({}), 404

            if gift_card.recipient_customer.store_id != store:
                return jsonify({}), 404

            response = {
                "result": "ok",
                "gift_card": gift_card_obj(gift_card)
            }
            return jsonify(response), 200
        else:
            gift_cards = GiftCard.objects()

            if "giftercustomerid" not in request.args and "recipientcustomerid" not in request.args:
                return jsonify({"error": MISSING_PARAMETERS}), 400

            if "giftercustomerid" in request.args:
                gifter_customer = Customer.objects.filter(customer_id=request.args['giftercustomerid'], store_id=store
                                                          , deleted_at=None).first()
                if gifter_customer is None:
                    return jsonify({"error": CUSTOMER_NOT_FOUND}), 404
                gift_cards = gift_cards.filter(gifter_customer=gifter_customer)

            if "recipientcustomerid" in request.args:
                recipient_customer = Customer.objects.filter(customer_id=request.args['recipientcustomerid']
                                                             , store_id=store, deleted_at=None).first()

                if recipient_customer is None:
                    return jsonify({"error": CUSTOMER_NOT_FOUND}), 404
                gift_cards = gift_cards.filter(recipient_customer=recipient_customer)

            if "active" in request.args:
                if request.args['active'].lower() == 'true':
                    gift_cards = gift_cards.filter(current_balance_in_cents__gt=0)

            return paginated_results(objects=gift_cards, collection_name='gift_card', request=request
                                     , per_page=self.PER_PAGE, serialization_func=gift_card_objs), 200

    @token_required
    def post(self):
        """
        creates a new gift card.
        """
        error = best_match(Draft4Validator(create_gift_cart_schema).iter_errors(request.json))
        if error:
            return jsonify({"error": error.message}), 400

        store = Store.objects.filter(app_id=request.headers.get('APP-ID'), deleted_at=None).first()

        gifter_customer = Customer.objects.filter(customer_id=request.json.get("gifter_customer_id")
                                           , store_id=store, deleted_at=None).first()
        if gifter_customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        recipient_customer = Customer.objects.filter(customer_id=request.json.get("recipient_customer_id")
                                                     , store_id=store, deleted_at=None).first()
        if recipient_customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        gift_card = GiftCard(
            gift_card_id=str(uuid.uuid4().int),
            gifter_customer=gifter_customer,
            recipient_customer=recipient_customer,
            original_balance_in_cents=request.json.get("original_amount"),
            current_balance_in_cents=request.json.get("original_amount")
        ).save()

        response = {
            "result": "ok",
            "gift_card": gift_card_obj(gift_card)
        }
        return jsonify(response), 201

    @token_required
    def delete(self, gift_card_id):
        """
        voids a gift_card
        """
        store = Store.objects.filter(app_id=request.headers.get('APP-ID'), deleted_at=None).first()
        gift_card = GiftCard.objects.filter(gift_card_id=gift_card_id).first()

        if gift_card is None:
            return jsonify({"error": GIFT_CARD_NOT_FOUND}), 404

        if gift_card.recipient_customer.store_id != store:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        gift_card.void()

        return jsonify({}), 204

class CustomerGiftCardAPI(MethodView):

    def __init__(self):
        self.PER_PAGE = 10
        if (request.method != 'GET' and request.method != 'DELETE') and not request.json:
            abort(400)

    @token_required
    def get(self, customer_id):
        """
        returns a list of customer gift cards
        """
        store = Store.objects.filter(app_id=request.headers.get('APP-ID'), deleted_at=None).first()

        customer = Customer.objects.filter(customer_id=customer_id, store_id=store, deleted_at=None).first()

        if customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        gift_cards = GiftCard.objects.filter(recipient_customer=customer)

        if "active" in request.args:
            if request.args['active'].lower() == 'true':
                gift_cards = gift_cards.filter(current_balance_in_cents__gt=0)

        return paginated_results(objects=gift_cards, collection_name='gift_card', request=request
                                 , per_page=self.PER_PAGE, serialization_func=gift_card_objs), 200


import json
import logging
import random
import string

import feedparser
import mf2py
import requests
from flask import jsonify, request

def notify_subscribers(feed_item_url, hub_url, cursor, feed_item):
    fetch_last_item = cursor.execute(
        "SELECT last_url_fetched FROM feeds WHERE feed_url = ?", (hub_url,)
    ).fetchall()

    if len(fetch_last_item) > 0 and fetch_last_item[0][0] != feed_item_url:
        subscribers = cursor.execute(
            "SELECT * FROM subscriptions WHERE hub_topic = ?",
            (request.form.get("hub.url"),),
        ).fetchall()

        if len(fetch_last_item) > 0:
            cursor.execute(
                "UPDATE feeds SET last_url_fetched = ? WHERE feed_url = ?",
                (feed_item_url, hub_url),
            )
        else:
            cursor.execute(
                "INSERT INTO feeds (feed_url, last_url_fetched) VALUES (?, ?)",
                (hub_url, feed_item_url),
            )

        # send subscriber notification that content has changed
        for subscriber in subscribers:
            r = requests.post(
                subscriber[0],
                data=feed_item.text.encode("utf-8"),
                headers={
                    "Content-Type": feed_item.headers.get("content-type"),
                    "Link": feed_item.headers.get("link"),
                },
            )

def publish(cursor):
    # if hub.url form is a list
    if request.form.getlist("hub.url"):
        urls = request.form.getlist("hub.url")
    else:
        urls = [request.form.get("hub.url")]

    for url in urls:
        hub_url = url

        r = requests.get(hub_url)

        if r.status_code != 200:
            return jsonify({"message": "Invalid publish url."})

        if (
            "application/atom+xml" in r.headers["Content-Type"]
            or "application/rss+xml" in r.headers["Content-Type"]
        ):
            feed = feedparser.parse(r.text)

            # get most recent entry
            most_recent_entry = feed.entries[0]

            notify_subscribers(most_recent_entry["url"], hub_url, cursor, r)

        elif "text/html" in r.headers["Content-Type"]:
            feed_item = requests.get(hub_url)
            read_feed = mf2py.Parser(r.text)

            # most recent item in feed
            most_recent_item_json = read_feed.to_dict()

            # get first h-feed

            for item in most_recent_item_json["items"]:
                if type(item["type"]) == list and "h-feed" in item["type"]:
                    most_recent_item = item.get("children")
                elif type(item["type"]) == str and "h-feed" in item["type"]:
                    most_recent_item = item.get("children")

            if most_recent_item is not None:
                notify_subscribers(
                    most_recent_item[0]["properties"]["url"][0],
                    hub_url,
                    cursor,
                    feed_item,
                )

        elif "application/json" in r.headers["Content-Type"]:
            feed_item = requests.get(hub_url)
            feed_item_json = json.loads(feed_item.text)

            notify_subscribers(feed_item_json[0]["url"], hub_url, cursor, feed_item)

        elif "text/plain" in r.headers["Content-Type"]:
            feed_item = requests.get(hub_url)

            notify_subscribers(feed_item.url, hub_url, cursor, feed_item)

        logging.info("Received notification from hub: " + hub_url)

        return jsonify({"message": "Accepted"}), 202

def unsubscribe(subscription_exists, hub_callback, hub_topic, hub_mode, cursor):
    if len(subscription_exists) == 0:
        return jsonify({"message": "Subscription does not exist."})

    challenge = "".join(
        random.choice(string.ascii_uppercase + string.digits) for _ in range(30)
    )

    r = requests.get(
        hub_callback
        + "?mode=unsubscribe&hub.topic="
        + hub_topic
        + "&hub.challenge="
        + challenge
        + "&hub.mode="
        + hub_mode
    )

    if r.status_code != 200:
        return jsonify({"message": "Bad request."}), 400

    cursor.execute(
        "DELETE FROM subscriptions WHERE hub_callback = ? AND hub_topic = ?",
        (hub_callback, hub_topic),
    )

    logging.info("Unsubscribed from " + hub_topic)
    return jsonify({"message": "Accepted"}), 202

def subscribe(
    subscription_exists,
    hub_callback,
    hub_mode,
    hub_topic,
    hub_lease_seconds,
    hub_secret,
    cursor,
):
    if len(subscription_exists) > 0:
        cursor.execute(
            "DELETE FROM subscriptions WHERE hub_callback = ? AND hub_topic = ?",
            (hub_callback, hub_topic),
        )

    challenge = "".join(
        random.choice(string.ascii_uppercase + string.digits) for _ in range(30)
    )

    verify_request = requests.get(
        hub_callback
        + "?hub.mode=subscribe&hub.topic="
        + hub_topic
        + "&hub.challenge="
        + challenge
        + "&hub.lease_seconds="
        + str(hub_lease_seconds)
        + "&hub.mode"
        + hub_mode
    )

    if verify_request.status_code == 200:
        if verify_request.text and verify_request.text != challenge:
            return jsonify({"message": "Bad request."}), 400

        cursor.execute(
            """INSERT INTO subscriptions (
                hub_callback,
                hub_mode,
                hub_topic,
                hub_lease_seconds,
                hub_secret
            ) VALUES (?, ?, ?, ?, ?)""",
            (hub_callback, hub_mode, hub_topic, hub_lease_seconds, hub_secret),
        )

        logging.info("Subscribed to " + hub_topic)
        return jsonify({"message": "Accepted"}), 202
    else:
        return jsonify({"message": "Bad request."}), 400