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

from __future__ import print_function
import os
import subprocess
import glob
import requests
isolist = [
    "https://atxfiles.netgate.com/mirror/downloads/pfSense-CE-2.6.0-RELEASE-amd64.iso.gz",
    "https://osdn.mirror.constant.com//clonezilla/74519/clonezilla-live-2.7.1-22-amd64.iso",
    "https://razaoinfo.dl.sourceforge.net/project/systemrescuecd/sysresccd-x86/8.02/systemrescue-8.02-amd64.iso",
    "https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/archive-virtio/virtio-win-0.1.196-1/virtio-win-0.1.196.iso",
    "https://gox.dl.sourceforge.net/project/xigmanas/XigmaNAS-Beta/13.1.0.5.9414/XigmaNAS-x64-LiveCD-13.1.0.5.9414.iso"
]

def Str(value):
    if isinstance(value, list):
        return " ".join(value)
    if isinstance(value, basestring):
        return value
    return str(value)

def Glob(value):
    ret = glob.glob(value)
    if (len(ret) < 1):
        ret = [value]
    return ret

def downloadwgetisos():
    os.chdir("/var/lib/vz/template/iso")
    for iso in isolist:
        subprocess.call(
            "wget -c " + iso, shell=True,)
    subprocess.call("gunzip " + Str(Glob("pfSense*.iso.gz")), shell=True)

def download_file_from_google_drive(id, destination):
    URL = "https://docs.google.com/uc?export=download"

    session = requests.Session()

    response = session.get(URL, params = { 'id' : id }, stream = True)
    token = get_confirm_token(response)

    if token:
        params = { 'id' : id, 'confirm' : token }
        response = session.get(URL, params = params, stream = True)

    save_response_content(response, destination)

def get_confirm_token(response):
    for key, value in response.cookies.items():
        if key.startswith('download_warning'):
            return value

    return None

def save_response_content(response, destination):
    CHUNK_SIZE = 32768

    with open(destination, "wb") as f:
        for chunk in response.iter_content(CHUNK_SIZE):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)

autoexec = ""

def confirmaexec(texto):
    global autoexec

    if ("autoexec" == "sim"):
        subprocess.call([str(texto)], shell=True)
    else:
        resposta = input(
            "Confirma execucao de ==> " + texto + " ? digite (a) para execucao automatica (y/n/a)")
        if (str(resposta) == "y"):
            subprocess.call([str(texto)], shell=True)
        elif (str(resposta) == "a"):
            autoexec = sim
            subprocess.call([str(texto)], shell=True)

def perguntar(texto):
    resposta = str(input(texto + " ?(y/n) "))
    return(resposta)

if (perguntar("Deseja configurar o servidor com ansible") == "y"):
    subprocess.call(["apt-get -y install build-essential libssl-dev libffi-dev python-dev-is-python3"], shell=True)
    subprocess.call(["apt-get -y install python3-pip ansible"], shell=True)
    subprocess.call(["ansible-playbook --ask-vault-pass -i localhost --connection=local installproxmox.yml"], shell=True)

if (perguntar("Deseja configurar a raid") == "y"):
    raid = perguntar("Qual tipo de raid (1, 10, 5-3 ou 5-4)")
    if (raid == "1"):
        confirmaexec("sgdisk -R=/dev/sdb /dev/sda")
        confirmaexec("dd if=/dev/sda1 of=/dev/sdb1")
        confirmaexec("dd if=/dev/sda2 of=/dev/sdb2")
        confirmaexec("mdadm --create -l1 -n2 /dev/md0 /dev/sdb3 missing")
        confirmaexec("pvcreate /dev/md0")
        confirmaexec("vgextend pve /dev/md0")
        confirmaexec("pvmove /dev/sda3 /dev/md0")
        confirmaexec("vgreduce pve /dev/sda3")
        confirmaexec("mdadm --add /dev/md0 /dev/sda3")
        confirmaexec("update-grub")
        confirmaexec("grub-install /dev/sda")
        confirmaexec("grub-install /dev/sdb")
    elif (raid == "10"):
        confirmaexec("sgdisk -R=/dev/sdb /dev/sda")
        confirmaexec("sgdisk -R=/dev/sdc /dev/sda")
        confirmaexec("sgdisk -R=/dev/sdd /dev/sda")
        confirmaexec("dd if=/dev/sda1 of=/dev/sdb1")
        confirmaexec("dd if=/dev/sda2 of=/dev/sdb2")
        confirmaexec("dd if=/dev/sda1 of=/dev/sdc1")
        confirmaexec("dd if=/dev/sda2 of=/dev/sdc2")
        confirmaexec("dd if=/dev/sda1 of=/dev/sdd1")
        confirmaexec("dd if=/dev/sda2 of=/dev/sdd2")
        confirmaexec(
            "mdadm --create -l10 -n4 /dev/md0 /dev/sdb3 /dev/sdc3 /dev/sdd3 missing")
        confirmaexec("pvcreate /dev/md0")
        confirmaexec("vgextend pve /dev/md0")
        confirmaexec("pvmove /dev/sda3 /dev/md0")
        confirmaexec("vgreduce pve /dev/sda3")
        confirmaexec("mdadm --add /dev/md0 /dev/sda3")
        confirmaexec("update-grub")
        confirmaexec("grub-install /dev/sda")
        confirmaexec("grub-install /dev/sdb")
        confirmaexec("grub-install /dev/sdc")
        confirmaexec("grub-install /dev/sdd")
    elif (raid == "5-3"):
        confirmaexec("sgdisk -R=/dev/sdb /dev/sda")
        confirmaexec("sgdisk -R=/dev/sdc /dev/sda")
        confirmaexec("dd if=/dev/sda1 of=/dev/sdb1")
        confirmaexec("dd if=/dev/sda2 of=/dev/sdb2")
        confirmaexec("dd if=/dev/sda1 of=/dev/sdc1")
        confirmaexec("dd if=/dev/sda2 of=/dev/sdc2")
        confirmaexec(
            "mdadm --create -l5 -n3 /dev/md0 /dev/sdb3 /dev/sdc3 missing")
        confirmaexec("pvcreate /dev/md0")
        confirmaexec("vgextend pve /dev/md0")
        confirmaexec("pvmove /dev/sda3 /dev/md0")
        confirmaexec("vgreduce pve /dev/sda3")
        confirmaexec("mdadm --add /dev/md0 /dev/sda3")
        confirmaexec("update-grub")
        confirmaexec("grub-install /dev/sda")
        confirmaexec("grub-install /dev/sdb")
        confirmaexec("grub-install /dev/sdc")
    elif (raid == "5-4"):
        confirmaexec("sgdisk -R=/dev/sdb /dev/sda")
        confirmaexec("sgdisk -R=/dev/sdc /dev/sda")
        confirmaexec("sgdisk -R=/dev/sdd /dev/sda")
        confirmaexec("dd if=/dev/sda1 of=/dev/sdb1")
        confirmaexec("dd if=/dev/sda2 of=/dev/sdb2")
        confirmaexec("dd if=/dev/sda1 of=/dev/sdc1")
        confirmaexec("dd if=/dev/sda2 of=/dev/sdc2")
        confirmaexec("dd if=/dev/sda1 of=/dev/sdd1")
        confirmaexec("dd if=/dev/sda2 of=/dev/sdd2")
        confirmaexec(
            "mdadm --create -l5 -n4 /dev/md0 /dev/sdb3 /dev/sdc3 /dev/sdd3 missing")
        confirmaexec("pvcreate /dev/md0")
        confirmaexec("vgextend pve /dev/md0")
        confirmaexec("pvmove /dev/sda3 /dev/md0")
        confirmaexec("vgreduce pve /dev/sda3")
        confirmaexec("mdadm --add /dev/md0 /dev/sda3")
        confirmaexec("update-grub")
        confirmaexec("grub-install /dev/sda")
        confirmaexec("grub-install /dev/sdb")
        confirmaexec("grub-install /dev/sdc")
        confirmaexec("grub-install /dev/sdd")

if (perguntar("Deseja baixa algumas isos padrão?") == "y"):
    downloadwgetisos()
    print("Download finalizado")

if (perguntar("Deseja baixa a imagem do wpad?") == "y"):
    file_id = '1AV434WHnUELNQKIsfP3kRB7S06KoaOr9'
    destination = '/var/lib/vz/template/cache/wpad.tar.gz'
    download_file_from_google_drive(file_id, destination)
    print("Download finalizado")


import json
from datetime import datetime

class Flow():
    def __init__(self, timestamp=None, clientIP=None, serverIP=None, clientPort=None, serverPort=None, duration=None, _id=None, initFwdLength=-1, initBwdLength=-1, fwdHeaderLength=0, bwdHeaderLength=0, fwdBytes=0, bwdBytes=0, fwdPackets=0, bwdPackets=0, fwdPacketMin=float("inf"), fwdPacketMax=0, bwdPacketMin=float("inf"), bwdPacketMax=0, fwdFIN=0, fwdSYN=0, fwdRST=0, fwdPSH=0, fwdACK=0, fwdURG=0, fwdECE=0, fwdCWR=0, bwdFIN=0, bwdSYN=0, bwdRST=0, bwdPSH=0, bwdACK=0, bwdURG=0, bwdECE=0, bwdCWR=0, label='BENIGN'):
        self.timestamp = timestamp
        self.clientIP = clientIP
        self.serverIP = serverIP
        self.clientPort = clientPort
        self.serverPort = serverPort
        self.duration = duration
        self.id = self.getID() if not _id else _id

        self.initFwdLength = initFwdLength
        self.initBwdLength = initBwdLength

        self.fwdHeaderLength = fwdHeaderLength
        self.bwdHeaderLength = bwdHeaderLength
        self.fwdBytes = fwdBytes
        self.bwdBytes = bwdBytes
        self.fwdPackets = fwdPackets
        self.bwdPackets = bwdPackets

        self.fwdPacketMin = fwdPacketMin
        self.fwdPacketMax = fwdPacketMax
        self.bwdPacketMin = bwdPacketMin
        self.bwdPacketMax = bwdPacketMax

        self.fwdFIN = fwdFIN
        self.fwdSYN = fwdSYN
        self.fwdRST = fwdRST
        self.fwdPSH = fwdPSH
        self.fwdACK = fwdACK
        self.fwdURG = fwdURG
        self.fwdECE = fwdECE
        self.fwdCWR = fwdCWR

        self.bwdFIN = bwdFIN
        self.bwdSYN = bwdSYN
        self.bwdRST = bwdRST
        self.bwdPSH = bwdPSH
        self.bwdACK = bwdACK
        self.bwdURG = bwdURG
        self.bwdECE = bwdECE
        self.bwdCWR = bwdCWR

        self.label = label

    def load(self, flowDict):
        self.timestamp = flowDict['timestamp']
        self.clientIP = flowDict['clientIP']
        self.serverIP = flowDict['serverIP']
        self.clientPort = flowDict['clientPort']
        self.serverPort = flowDict['serverPort']
        self.duration = flowDict['duration']
        self.id = flowDict['id']

        self.initFwdLength = flowDict['initFwdLength']
        self.initBwdLength = flowDict['initBwdLength']

        self.fwdHeaderLength = flowDict['fwdHeaderLength']
        self.bwdHeaderLength = flowDict['bwdHeaderLength']
        self.fwdBytes = flowDict['fwdBytes']
        self.bwdBytes = flowDict['bwdBytes']
        self.fwdPackets = flowDict['fwdPackets']
        self.bwdPackets = flowDict['bwdPackets']

        self.fwdPacketMin = flowDict['fwdPacketMin']
        self.fwdPacketMax = flowDict['fwdPacketMax']
        self.bwdPacketMin = flowDict['bwdPacketMin']
        self.bwdPacketMax = flowDict['bwdPacketMax']

        self.fwdFIN = flowDict['fwdFIN']
        self.fwdSYN = flowDict['fwdSYN']
        self.fwdRST = flowDict['fwdRST']
        self.fwdPSH = flowDict['fwdPSH']
        self.fwdACK = flowDict['fwdACK']
        self.fwdURG = flowDict['fwdURG']
        self.fwdECE = flowDict['fwdECE']
        self.fwdCWR = flowDict['fwdCWR']

        self.bwdFIN = flowDict['bwdFIN']
        self.bwdSYN = flowDict['bwdSYN']
        self.bwdRST = flowDict['bwdRST']
        self.bwdPSH = flowDict['bwdPSH']
        self.bwdACK = flowDict['bwdACK']
        self.bwdURG = flowDict['bwdURG']
        self.bwdECE = flowDict['bwdECE']
        self.bwdCWR = flowDict['bwdCWR']

        self.label = flowDict['label']

    def getID(self):
        try:
            client = ':'.join([self.clientIP, str(self.clientPort)])
            server = ':'.join([self.serverIP, str(self.serverPort)])
            return '@'.join(['->'.join([client, server]), str(self.timestamp)])
        except(TypeError):
            return None

    def increment(self, packet, isLastPacket=False):
        if isLastPacket:
            start = datetime.strptime(self.timestamp, '%Y-%m-%d %H:%M:%S.%f')
            end = datetime.strptime(packet['time'], '%Y-%m-%d %H:%M:%S.%f')
            self.duration = (end - start).total_seconds()

        if self.isClient(packet['src']):
            self.incrementClient(packet)

        if self.isServer(packet['src']):
            self.incrementServer(packet)

    def updateLabel(self, packet):
        if self.label == 'BENIGN' and packet['label'] != 'BENIGN':
            self.label = packet['label']

        #ensure no flow has packets with differing non-benign labels
        if self.label != 'BENIGN' and self.label != packet['label']:
            #logging.debug('Differing non-benign labels discovered in packet {}'.format(packet.__dict__))
            pass

    def incrementClient(self, packet):
        if not self.seenClientPacket():
            self.initFwdLength = packet['length']

        self.updateLabel(packet)

        self.fwdPackets += 1
        self.fwdHeaderLength += packet['headerLength']
        self.fwdBytes += packet['length']

        self.fwdFIN += 1 if packet['FIN'] else 0
        self.fwdSYN += 1 if packet['SYN'] else 0
        self.fwdRST += 1 if packet['RST'] else 0
        self.fwdPSH += 1 if packet['PSH'] else 0
        self.fwdACK += 1 if packet['ACK'] else 0
        self.fwdURG += 1 if packet['URG'] else 0
        self.fwdECE += 1 if packet['ECE'] else 0
        self.fwdCWR += 1 if packet['CWR'] else 0

        if self.fwdPacketMin > packet['length']:
            self.fwdPacketMin = packet['length']

        if self.fwdPacketMax < packet['length']:
            self.fwdPacketMax = packet['length']

    def incrementServer(self, packet):
        if not self.seenServerPacket():
            self.initBwdLength = packet['length']

        self.updateLabel(packet)

        self.bwdPackets += 1
        self.bwdHeaderLength += packet['headerLength']
        self.bwdBytes += packet['length']

        self.bwdFIN += 1 if packet['FIN'] else 0
        self.bwdSYN += 1 if packet['SYN'] else 0
        self.bwdRST += 1 if packet['RST'] else 0
        self.bwdPSH += 1 if packet['PSH'] else 0
        self.bwdACK += 1 if packet['ACK'] else 0
        self.bwdURG += 1 if packet['URG'] else 0
        self.bwdECE += 1 if packet['ECE'] else 0
        self.bwdCWR += 1 if packet['CWR'] else 0

        if self.bwdPacketMin > packet['length']:
            self.bwdPacketMin = packet['length']

        if self.bwdPacketMax < packet['length']:
            self.bwdPacketMax = packet['length']

    def isClient(self, srcIP):
        return self.clientIP == srcIP

    def isServer(self, srcIP):
        return self.serverIP == srcIP

    def seenClientPacket(self):
        return self.fwdPackets > 0

    def seenServerPacket(self):
        return self.bwdPackets > 0

    def toCSV(self):
        values = [str(value) for attr, value in self.__dict__.items()]
        return ','.join(values)

    def toHeader(self):
        values = [attr for attr, value in self.__dict__.items()]
        return ','.join(values)

    def toJSON(self):
        return json.dumps(self, default=lambda x: x.__dict__)


# %load ./codes/argParse.py
import argparse
parser = argparse.ArgumentParser()
group =  parser.add_mutually_exclusive_group()
# calling this program now need to specify 2 argument 'echo' and 'square'
# Positional arguments
parser.add_argument('square', type = int, help = 'display a square of a given number')
# Optional arguments
group.add_argument('-n','--noise', action='store_true',
                   help='make some noise!')
group.add_argument('-q', '--quiet', action='store_true',
                   help = 'be qiuet!')
parser.add_argument('-v','--verbosity', help = 'increase output verbosity', choices = [1, 2, 3], type = int)
parser.add_argument('-c','--count', default = 100,
                    help = 'count  the number of occurrences of a specific optional arguments', action = 'count')
args = parser.parse_args()
answer = args.square**2
if args.count:
    print(f'It counts {args.count}')
    print(type(args.count))
if args.verbosity:
    print(f'verbosity {args.verbosity} turned on')
if args.noise:
    print('the square of {} equals {}'.format(args.square, answer))
elif args.quiet:
    print(answer)
else:
    print(f'{answer} !!!')


from urllib.request import urlopen
from pandas import json
import requests
import os
import re
#h获取链接
def get_one_page(url):
    response = requests.get(url).text
    # print(response.text)
    return response
#获得主页内容的各个子网页链接
def parse_total_page(response):
    pattern = re.compile('
<a href=(.*?)target=',re.S)
    # pattern = re.compile(r'[a-zA-z]+://[^\s]*', re.S)
    items = re.findall(pattern,response)
    # print(items)
    # for item in items:
    #     print(item)
    #     print(json.loads(item))
    # print(len(items))
    return items

#获取所有网页图片名称
def get_image_name(response1):
    result = get_one_page(json.loads(response1))
    pattern = re.compile('
(.*?)
',re.S)
    items = re.search(pattern,result)
    print(u'图片名称为：',items.group(1))
    return items.group(1)

#获取每个网页包含的图片数量
def get_image_number(response1):
    result = get_one_page(json.loads(response1))
    pattern = re.compile('(.*?)', re.S)
    items = re.findall(pattern, result)
    print(u'此图片数量为：',items[8])
    return items[8]

#获取每个网页的图片地址
def get_image_url(response1,number):
    for i in range(1, 10):
        print(i)
        new_response = json.loads(response1) + '/' + str(i)
        print(new_response)
        result = get_one_page(new_response)
        pattern = re.compile('<img src="(.*?)" alt', re.S)
        items = re.search(pattern, result)
        print(u'获取到地址为：', items.group(1), u'的图片')
        return items.group(1)

#保存图片
def save_image(detailUrl,path,name):
    # picture = urlopen(detailUrl)
    img = requests.get(detailUrl)
    print(u'正在保存链接为：',detailUrl,'的图片')
    string =  'D:\picture\%s\%s' % (path,name)
    E = os.path.exists(string)
    if not E:
        f = open(string, 'wb')
        f.write(img.content)
        f.close()
    else:
        print(u'图片已经存在，跳过')
        return False

def make_dir(path):
    path = path.strip()
    E = os.path.exists(os.path.join('D:\picture',path))
    if not E:
        # 创建新目录,若想将内容保存至别的路径（非系统默认），需要更环境变量
        # 更改环境变量用os.chdir()
        os.makedirs(os.path.join('D:\picture', path))
        os.chdir(os.path.join('D:\picture', path))
        print(u'成功创建名为', path, u'的文件夹')
        return path
    else:
        print(u'名为', path, u'的文件夹已经存在...')
        return False
def main():
    url = "http://www.mzitu.com/"
    response = get_one_page(url)
    items = parse_total_page(response)
    for item in items:
        # 获取所有网页图片名称
        path = get_image_name(item)
        # 获取每个网页包含的图片数量
        number = get_image_number(item)
        # 获取每个网页的图片地址
        make_dir(path)
        for i in range(1, int(number)+1):
            new_response = json.loads(item) + '/' + str(i)
            result = get_one_page(new_response)
            pattern = re.compile('<img src="(.*?)" alt', re.S)
            items = re.search(pattern, result)
            print(u'获取到地址为：', items.group(1), u'的图片')
            name = 'picture'+str(i)+'.jpg'
            save_image(items.group(1),path,name)
if __name__ == '__main__':
    main()


import logging
import discord
from discord import app_commands, Interaction
from discord.app_commands import Range
from discord.ext import commands

from handler.context import Context
from handler.view import DropdownView
from pepebot import PepeBot

from datetime import timedelta

import typing
from typing import Optional, Union, Literal

from handler.utils import (
    string_to_delta,
    get_place_holders,
    get_key_pair,
    to_string_list, get_relative_time, records_to_dict)
from handler.database import (
    reinitialise_channel_settings,
    reinitialise_guild_settings,
    get_channel_settings,
    get_guild_settings)

_log = logging.getLogger("pepebot")

async def setup(bot: PepeBot) -> None:
    await bot.add_cog(Configuration(bot))

class Configuration(commands.Cog):
    def __init__(self, bot: PepeBot) -> None:
        self.bot = bot
        self.Database = bot.database

    async def set_channel_settings(self, guild_id, channel_id, **options):
        """
        Edit channel settings that is stored in the database
        """
        options_names = list(options.keys())
        options_names.insert(0, "guild_id")
        options_names.insert(1, "channel_id")
        names_str_list = to_string_list(options_names)
        placeholders_str = get_place_holders(len(options_names))
        options_names.remove("guild_id")
        options_names.remove("channel_id")
        key_value_str = get_key_pair(options_names, 3)
        values = list(options.values())
        values.insert(0, guild_id)
        values.insert(1, channel_id)

        await self.Database.insert(
            *values,
            table="peep.channel_settings",
            columns=names_str_list,
            values=placeholders_str,
            on_conflicts=
            "(guild_id,channel_id) DO UPDATE SET "
            f"{key_value_str}")
        # insert new settings to the guild cache,
        cache_new_settings = reinitialise_channel_settings(
            bot=self.bot, channel_id=channel_id, guild_id=guild_id)
        self.bot.loop.create_task(cache_new_settings)

    async def set_guild_settings(self, guild_id, **options):
        """ change guild settings from the database"""
        options_names = list(options.keys())
        options_names.insert(0, "guild_id")
        names_str_list = to_string_list(options_names)
        placeholders = get_place_holders(len(options_names))
        values = list(options.values())
        values.insert(0, guild_id)
        options_names.remove("guild_id")
        key_value_str = get_key_pair(options_names, 2)
        await self.bot.database.insert(
            *values,
            table="peep.guild_settings",
            columns=f"{names_str_list}",
            values=placeholders,
            on_conflicts=
            "(guild_id) DO UPDATE SET "
            f"{key_value_str}")
        cache_new_settings = reinitialise_guild_settings(
            bot=self.bot, guild_id=guild_id)
        self.bot.loop.create_task(cache_new_settings)

    def get_valid_emoji_string(self, string: str) -> Optional[str]:
        custom = string.replace(" ", "")
        firstEmoji = custom[0]
        # it is a default emoji
        if self.bot.emoji.is_default_emoji(custom):
            emoji = firstEmoji
        else:
            # check if given emoji emoji is custom emoji and is usable
            emoji_id = self.bot.emoji.get_emoji_id(custom)
            custom_emoji = None
            if emoji_id:
                custom_emoji = self.bot.get_emoji(int(emoji_id))
            if custom_emoji is None or not custom_emoji.is_usable():
                return None
            emoji = custom_emoji
        return emoji

    setup = app_commands.Group(
        name='setup',
        description='some configuration commands related to memes',
        guild_only=True,
        default_permissions=discord.Permissions(administrator=True)
    )

    @setup.command(name="guild_settings")
    @app_commands.checks.has_permissions(manage_guild=True)
    async def edit_guild_settings(
            self, interaction: discord.Interaction,
            option: Literal["Auto Thread", "Meme listener",
                            "Oc Listener", 'economy'],
            turn: Literal['on', 'off']
    ):

        """
         configuration commands related to server.

        Parameters
        ----------
        option: :class:`typing.Literal`
            choose a setting that you want to change
        turn: typing.Literal
            turn on or turn off setting
        """

        # change the str value to boolean value
        turned = True if turn == 'on' else False
        settings_map = {
            "Auto Thread": "thread_lstnr",
            "Meme listener": "reaction_lstnr",
            "Oc Listener": "oc_lstnr",
            "economy": "economy"
        }
        setting = settings_map[option]
        await self.set_guild_settings(
            guild_id=interaction.guild.id, **{setting: turned})

        embed = discord.Embed()
        embed.title = "``config update``"
        embed.description = (f">>> {self.bot.emoji.right} {option}"
                             f" has been turned ``{turn}``")
        await interaction.response.send_message(
            embed=embed, ephemeral=True)

    @setup.command(name="channel_settings")
    @app_commands.checks.has_permissions(manage_guild=True)
    async def edit_channel_settings(
            self, interaction: Interaction, channel: discord.TextChannel,
            option: typing.Literal["Auto thread", "Meme listener",
                                   "Oc listener"],
            turn: typing.Literal["on", "off"]
    ):

        """
        change channel related settings.

        Parameters
        ----------
        channel:
            channel that you want change settings
        option:
            what settings you want to change
        turn:
            turn on or off setting
        """
        embed = discord.Embed(title="``updated Config``")
        permission = channel.permissions_for(interaction.guild.me)

        bot_required_permissions = [
            permission.manage_messages, permission.view_channel,
            permission.read_messages, permission.add_reactions]
        permission_string = [
            "manage_messages", "view_channel",
            "read_messages", "add_reactions"]
        if not all(bot_required_permissions):
            embed.title = f"**invalid permissions**"
            embed.description = (
                f">>> {self.bot.emoji.right} bot missing following "
                f"permissions in {channel.mention} channel"
                f":{channel.mention} \n"
                f" \n".join(permission_string)
            )
            await interaction.response.send_message(
                embed=embed, ephemeral=True)
            return
        turned = True if turn == "on" else False
        settings_map = {
            "Auto thread": "is_threadChannel",
            "Meme listener": "is_memeChannel",
            "Oc listener": "is_ocChannel"
        }
        setting = settings_map[option]
        await self.set_channel_settings(
            channel_id=channel.id, guild_id=channel.guild.id,
            **{setting: turned})
        embed.title = "**updated config**"
        embed.description = (
            f">>> {option} for {channel.mention} has been turned {turn}")
        await interaction.response.send_message(
            embed=embed, ephemeral=True)

    @setup.command(name="edit_meme_channel")
    @app_commands.checks.has_permissions(manage_guild=True)
    async def set_meme_channel_settings(
            self, interaction: Interaction,
            meme_channel: discord.TextChannel, duration: Optional[str] = None,
            max_likes: Optional[int] = None,
            next_gallery_channel: Optional[discord.TextChannel] = None
    ):

        """
        configure meme channel related settings.

        Parameters
        ----------
        meme_channel:
            the meme channel that you want to configure
        duration:
            example:1d,1s,1w etc. and 0 for no time limit.
        max_likes:
            maximum likes needed to go to next gallery
        next_gallery_channel:
            the channel where memes will be moved
            when reaching max likes
        """
        response = interaction.response
        embed = discord.Embed(title=f"``command failed``")
        # get configurations realted to the channel
        channel_settings = await get_channel_settings(
            bot=self.bot, channel=meme_channel)
        # send a error message if given channel is not a meme channel
        if channel_settings is None or not channel_settings["is_memechannel"]:
            embed.description = (
                f">>> {self.bot.emoji.right} {meme_channel.mention} channel"
                f" is not a meme channel, pls run command ``/config "
                f"{meme_channel.name}`` to check if the channel is a "
                f"meme channel or ``/serverconfig`` to see list of "
                f"meme channels in the gild "
            )
            await response.send_message(embed=embed, ephemeral=True)
            return
        delta_time = 'NULL' if duration == '0' else duration
        if delta_time is not None and duration != '0':
            try:
                delta_time = string_to_delta(duration)
            except Exception as error:
                embed.description = (
                    f">>> {self.bot.emoji.right} the time ``{duration}`` is "
                    f"invalid it must be in formate of"
                    f"```1(h|hr|hour|hours) \n 1(m|min|minute) \n"
                    f" 1(s|second|secs)``` "
                )
                await response.send_message(embed=embed, ephemeral=True)
                _log.error(error)
                return
        args = {}
        if max_likes is not None:
            if max_likes <= 1:
                embed.description = (
                    f">>> {self.bot.emoji.right} max likes must be greater than 1")
                await response.send_message(embed=embed, ephemeral=True)
                return
            elif max_likes > 1:
                args["max_like"] = max_likes
        if (next_gallery_channel is not None and
                next_gallery_channel.id == interaction.channel_id):
            embed.description = "the channel is not valid choose another " \
                                "channel "
            await response.send_message(embed=embed)
        if delta_time is not None:
            args["voting_time"] = delta_time if delta_time != 'NULL' else None

        if next_gallery_channel is not None:
            args["Nextlvl"] = next_gallery_channel.id

        await self.set_channel_settings(
            interaction.guild_id, interaction.channel_id, **args)

        embed.title = f"``updated config``"
        is_delta_time = isinstance(delta_time, timedelta)
        is_next_gallery_channel = "none"
        if next_gallery_channel is not None:
            is_next_gallery_channel = next_gallery_channel.mention
        human_relative_time = "none"
        if is_delta_time:
            human_relative_time = get_relative_time(delta_time)
        embed.description = f"""
        >>> {self.bot.emoji.right} **channel**:{meme_channel.mention}
        **maximum likes**: {max_likes}
        **gallery**: {is_next_gallery_channel}
        **time limit**: {human_relative_time}
        """
        await response.send_message(embed=embed)

    @app_commands.checks.has_permissions(administrator=True)
    @app_commands.checks.bot_has_permissions(manage_roles=True)
    @setup.command(name="meme_admin_role")
    async def add_meme_admin_role(
            self, interaction: Interaction, role: discord.Role,
            remove: Literal['true'] = None
    ):
        """
        add a role to manage economy related commands.

        Parameters
        ----------
        role:
            role that you wanted to manage commands
        """
        response = interaction.response
        embed = discord.Embed()
        is_owner = await self.bot.is_owner(interaction.user)
        if not is_owner and interaction.guild.owner_id != interaction.user.id:
            embed.title = "``command failed!``"
            embed.description = "only owner can execute this command"
            await interaction.response.send_message(
                embed=embed, ephemeral=True)
            return
        role_id = None if remove == 'true' else role.id
        await self.set_guild_settings(
            guild_id=interaction.guild.id, MemeAdmin=role_id)
        embed.title = f"``role {'added' if role_id else 'removed'}``"
        embed.description = (
            f">>> {self.bot.emoji.right} now members with "
            f"{role.mention} will be able to execute "
            f"all meme and economy commands")
        if role_id is None:
            embed.description = (
                f">>> {self.bot.emoji.right} meme admin role has been removed, "
                f"economy and meme commands are now owner only")
        await response.send_message(embed=embed, ephemeral=True)

    @app_commands.checks.has_permissions(administrator=True)
    @setup.command(name="like")
    async def setup_like_emoji(
            self, interaction: Interaction, meme_channel: discord.TextChannel,
            custom_emoji: str = None, setdefault: Literal['true'] = None,
            remove: Literal['true'] = None
    ):
        """
        settings related bot reactions

        Parameters
        ----------
        custom_emoji:
            specify the emoji you want the bot to react with
        setdefault:
            change the reaction emoji to default one that bot use
        remove:
            stop the bot to react like emoji on memes
        """
        response = interaction.response
        embed = discord.Embed(title="``command failed``")
        emoji = ""
        channel_settings = await get_channel_settings(
            bot=self.bot, channel=meme_channel)

        if (channel_settings is None or
                not channel_settings["is_memechannel"]):
            embed.description = (
                f">>> {self.bot.emoji.right} channel {meme_channel.mention} is "
                f"not a meme channel please run commands ``/channelconfig`` to "
                f"see list of meme channels")
            await response.send_message(embed=embed, ephemeral=True)
            return

        if not any([custom_emoji, setdefault, remove]):
            embed.description = (
                f">>> {self.bot.emoji.right}"
                f" you must specify at least one setting")
            await response.send_message(embed=embed, ephemeral=True)
            return

        if custom_emoji is not None:
            emoji = self.get_valid_emoji_string(string=custom_emoji)
            if emoji is None:
                embed.description = (
                    f">>> {self.bot.emoji.right}"
                    f"given emoji is not a valid emoji :``{custom_emoji}``")
                await response.send_message(embed=embed, ephemeral=True)
                return
            elif custom_emoji == channel_settings["dislike_emoji"]:
                embed.description = (
                    f">>> {self.bot.right} "
                    f"like emoji should not be same as dislike emoji"
                )
                await response.send_message(
                    embed=embed, ephemeral=True
                )
                return
        elif setdefault is not None:
            emoji = self.bot.emoji.like
            custom_emoji = emoji
        elif remove is not None:
            emoji = '0'
        await self.set_channel_settings(
            guild_id=interaction.guild_id, channel_id=meme_channel.id,
            like_emoji=str(emoji))
        embed.title = "``updated config``"
        embed.description = f"now bot will react to {custom_emoji}"
        if emoji == '0':
            embed.description = f"now bot will not able to like messages"
        await response.send_message(embed=embed, ephemeral=True)

    @app_commands.checks.has_permissions(administrator=True)
    @setup.command(name="dislike")
    async def setup_dislike_emoji(
            self, interaction: Interaction, meme_channel: discord.TextChannel,
            custom_emoji: str = None, setdefault: Literal['true'] = None,
            remove: Literal['true'] = None
    ):
        """
        settings related bot reactions

        Parameters
        ----------
        custom_emoji:
            specify the emoji you want the bot to react with
        setdefault:
            change the reaction emoji to default one that bot use
        remove:
            stop the bot to react like emoji on memes
        """

        response = interaction.response
        embed = discord.Embed(title="``command failed``")
        emoji = ""
        channel_settings = await get_channel_settings(
            bot=self.bot, channel=meme_channel)

        if (channel_settings is None or
                not channel_settings["is_memechannel"]):
            embed.description = (
                f">>> {self.bot.emoji.right} channel {meme_channel.mention} is "
                f"not a meme channel")
            await response.send_message(embed=embed, ephemeral=True)
            return

        if not any([custom_emoji, setdefault, remove]):
            embed.description = (
                f">>> {self.bot.emoji.right}"
                f" you must specify at least one setting")
            await response.send_message(embed=embed, ephemeral=True)
            return

        if custom_emoji is not None:
            emoji = self.get_valid_emoji_string(string=custom_emoji)
            if emoji is None:
                embed.description = (
                    f">>> {self.bot.emoji.right}"
                    f" given emoji is not a valid emoji :``{custom_emoji}``")
                await response.send_message(embed=embed, ephemeral=True)
                return
            elif custom_emoji == channel_settings["like_emoji"]:
                embed.description = (
                    f">>> {self.bot.right} "
                    f"dislike emoji should not be same as like emoji"
                )
                await response.send_message(
                    embed= embed, ephemeral= True
                )
                return
        elif setdefault is not None:
            emoji = self.bot.emoji.like
            custom_emoji = emoji
        elif remove is not None:
            emoji = '0'
        await self.set_channel_settings(
            guild_id=interaction.guild_id, channel_id=meme_channel.id,
            like_emoji=str(emoji))
        embed.title = "``updated config``"
        embed.description = f"now bot will react to {custom_emoji}"
        if emoji == '0':
            embed.description = f"now bot will not able to dislike messages"

        await response.send_message(embed=embed, ephemeral=True)

    @app_commands.checks.has_permissions(administrator=True)
    @setup.command(name="reward_role")
    async def setup_reward_role(
            self, interaction: discord.Interaction, at_likes: Range[int, 1],
            give_role: discord.Role
    ):
        """
        setup reward role for specific likes

        Parameters
        ----------
        at_likes
            at what like levels will user be given the role
        give_role
            the role that will be given to user
        """
        embed = discord.Embed(title="``command failed``")
        if not give_role.is_assignable():
            embed.description = (
                f">>> {self.bot.emoji.right} the bot can't"
                f"assign this role, whether the role is above "
                f"bot role or bot lack permissions to assign it")
            await interaction.response.send_message(embed=embed)
            return

        insert_role = self.bot.database.insert(
            interaction.guild_id,
            at_likes,
            give_role.id,
            table="peep.rolerewards",
            columns="guild_id,likes,role_id",
            values="$1,$2,$3",
            on_conflicts="(guild_id,likes) DO UPDATE SET "
                         "role_id = $3")
        embed.title = "``role added!``"
        embed.description = (
            f"{give_role.mention} will be assigned to user after "
            f"reaching ``{at_likes}`` {self.bot.emoji.like}"
        )
        await interaction.response.send_message(embed=embed)
        self.bot.loop.create_task(insert_role)

    @setup.command(name="logging")
    @app_commands.checks.has_permissions(administrator=True)
    async def configure_logging(
            self, interaction: discord.Interaction,
            shop_log: discord.TextChannel,
            remove: Literal['true'] = None,
            dm_member_on_accept: Literal['true', 'false'] = 'false',
    ):
        """
        setup logging for the purchased items by the user.

        Parameters
        ----------
        shop_log:
            the channel that you want the bot to send messages in
        dm_member_on_accept:
            whether dm user after accepting the item or not
        """

        bot_reactions = shop_log.permissions_for(shop_log.guild.me)
        required_permission = [
            bot_reactions.send_messages,
            bot_reactions.view_channel,
            bot_reactions.read_message_history,
        ]
        embed = discord.Embed(title="``command failed``")
        if not any(required_permission):
            embed.description = (
                f"the bot missing permission in channel "
                f"{shop_log.mention} check if bot has following permissions "
                f"in the channel\n"
                f"[read messages, send messages,read message history]")
            await interaction.response.send_message(embed=embed)
            return
        shop_log_channel = shop_log.id
        guild_settings = await get_guild_settings(
            bot=self.bot, guild_id=interaction.guild_id)
        if remove == 'true':
            if guild_settings["shoplog"] is None:
                embed.description = "there is already no shop log channel"
                await interaction.response.send_message(embed=embed)
                return
            shop_log_channel = None

        dm_member_on_accept = True if dm_member_on_accept == 'true' else False
        await self.set_guild_settings(
            guild_id=interaction.guild_id,
            shoplog=shop_log_channel,
            dm_on_accept=dm_member_on_accept
        )
        embed.title = "``logging configuration``"
        embed.description = (
            f">>> {self.bot.emoji.right}"
            f"bot will now send item logs to channel {shop_log.mention} "
        )
        if remove == 'true':
            embed.description = f">>> {self.bot.emoji.right}" \
                                f"logging channel has been removed"
        await interaction.response.send_message(
            embed=embed)

    @setup.command(name="thread_msg")
    @app_commands.checks.has_permissions(administrator=True)
    async def set_thread_message(
            self, interaction: discord.Interaction,
            thread_channel: discord.TextChannel,
            thread_message: app_commands.Range[str, 1, 500],
            set_default: Literal['true'] = None):

        channel_settings = await get_channel_settings(
            bot=self.bot, channel=thread_channel)
        embed = discord.Embed(title="command failed")
        if channel_settings is None or not channel_settings["is_threadchannel"]:
            embed.description = (
                f"Channel {thread_channel} is not a thread channel"
                f"please run ``/channelconfig`` to see list of channels "
                f"in the guild ")
            await interaction.response.send_message(embed=embed)
            return

        if set_default is not None:
            thread_message = None

        await self.edit_channel_settings(
            channel=interaction.channel,
            thread_msg=thread_message
        )
        embed.title = "``config update``"
        embed.description = (
            f"thread message for the channel :{interaction.channel.mention}"
            f"has been updated to message: ``{thread_message}``"
        )
        await interaction.response.send_message(
            embed=embed
        )

    @setup.command(name="prefix")
    @app_commands.checks.has_permissions(administrator=True)
    async def setup_prefix(
        self, interaction:discord.Interaction, prefix: app_commands.Range[str,0,10],
        set_default: Literal['true'] = None
    ):
        await self.set_guild_settings(
            guild_id=interaction.guild_id,
            prefix=prefix if not set_default else '$')
        if set_default == 'true':
            prefix = '$'
        embed = discord.Embed()
        embed.description = (
            f""">>> {self.bot.right} bot prefix has changed to {prefix}"""
        )
        await interaction.response.send_message(
            embed=embed
        )

    youtube = app_commands.Group(
        name='youtube',
        description='configuration commands related to youtube',
        guild_only=True,
        default_permissions=discord.Permissions(administrator=True)
    )

    @youtube.command(name="subscribe")
    @app_commands.checks.has_permissions(administrator=True)
    async def setup_youtube(
        self, interaction: discord.Interaction, youtube_channel: str,
        send_to: discord.TextChannel = None
    ):

        """
        set up a notification channel for youtube video.

        Parameters
        ----------
        youtube_channel:
            the YouTube channel that you want to get notification for, can be a
            link or username
        send_to:
            provide the channel where you want the notification to send to
        """

        channel_id = self.bot.youtube.get_id_from_url(
            url=youtube_channel)
        channel_username = self.bot.youtube.get_username_from_url(
            url=youtube_channel)
        embed = discord.Embed(title="``command failed``")
        await interaction.response.defer(thinking=True, ephemeral=True)

        subscribed_channels = await self.bot.youtube.get_subscribed_for_guilds(
            guild_id=interaction.guild_id
        )

        if subscribed_channels is not None:
            embed.description = (
                "subscribing to multiple channel is currently not available. "
                "to subscribe to new channel you must remove older one. "
                "for that please run command "
                "``/setup youtube_notification remove:true`` "
            )
            await interaction.followup.send(embed=embed)
            return

        if not channel_id and not channel_username:
            channel_username = youtube_channel
            channel_id = await self.bot.youtube.get_channel_id(
                channel_username)
            if channel_id is None:
                embed.description = (
                    f">>> {self.bot.emoji.right} channel url/username ``{youtube_channel}`` is invalid "
                    "please provide any of following types: \n"
                    "``yourusername`` \n"
                    "``https://youtube.com/c/yourcustomusername`` \n"
                    "``https://youtube.com/@yourusername`` \n"
                    "``https://youtube.com/user/yourusername`` \n"
                    "``https://youtube.com/channel/yourchannelid`` \n"
                    " for more info please visit [this link]"
                    "(https://support.google.com/youtube/answer/6180214?hl=en)"
                )
                await interaction.followup.send(
                    embed=embed)
                return
        elif channel_id is None and channel_username:
            channel_id = await self.bot.youtube.get_channel_id(
                channel_username)
            if channel_id is None:
                embed.description = "the url or username you provided is " \
                                    "invalid "
                await interaction.followup.send(
                    embed=embed)
                return

        if send_to is not None:
            # check permissions for the log channel
            channel_permissions = send_to.permissions_for(interaction.guild.me)
            required_permissions = [
                channel_permissions.send_messages,
                channel_permissions.embed_links,
                channel_permissions.view_channel]
            if not all(required_permissions):
                embed.description = (
                    f"bot missing permission in channel: ``{send_to.mention}`` : \n"
                    f"make sure bot has following permissions in the channel: "
                    f"``send message,send embed links, view channel``")
                await interaction.followup.send(embed=embed)
                return
            await self.set_guild_settings(
                guild_id=interaction.guild_id, upload_channel=send_to.id
            )
        await self.bot.youtube.subscribe_to_channel(
            channel_id=channel_id,
            guild_id=interaction.guild_id,
            upload_id=None
        )
        embed.title = "``subscribed``"
        embed.description = (
            f">>> {self.bot.emoji.right} "
            f"subscribed to channel ``{channel_username}``\n")
        await interaction.followup.send(embed=embed)

    @youtube.command(name="unsubscribe")
    async def youtube_unsubscribe(
        self, interaction: discord.Interaction, channel: Literal['all']
    ):
        """
        unsubscribe to channel.
        """
        await interaction.response.defer(thinking=True, ephemeral=True)
        embed = discord.Embed(title="command failed")
        subscribed_channels = await self.bot.youtube.get_subscribed_for_guilds(
            guild_id=interaction.guild_id
        )
        if subscribed_channels is None:
            embed.description = "you are already not subscribed to any channel"
            await interaction.followup.send(
                embed=embed, ephemeral=True)
            return
        await self.bot.youtube.unsubscribe_to_channel(
            guild_id=interaction.guild_id
        )
        embed.title = None
        embed.description = (
            f""">>> {self.bot.emoji.right} unsubscribed to {channel} channels""")
        await interaction.followup.send(embed=embed, ephemeral=True)

    @youtube.command(name="notification_channel")
    async def youtube_notification_channel(
        self, interaction: discord.Interaction, channel: discord.TextChannel
    ):
        """
        setup a youtube notification channel.

        Parameters
        ----------
        channel:
            the channel you want to set to notification channel.
        """
        channel_permissions = channel.permissions_for(interaction.guild.me)
        required_permissions = [
            channel_permissions.view_channel,
            channel_permissions.send_messages,
            channel_permissions.embed_links,
        ]
        embed = discord.Embed(title="``command failed``")
        if not all(required_permissions):
            embed.description = (
                f">>> {self.bot.emoji.right}"
                f"bot missing any of following permissions in the channel"
                f"{channel.mention} : \n"
                f"``view channel, send message, embed links`` "
            )
            await interaction.response.send_message(
                embed=embed,ephemeral=True
            )
            return
        await self.set_guild_settings(
            guild_id=interaction.guild_id, upload_channel=channel.id)

        embed.title = None
        embed.description = (
            f">>> "
            f"{self.bot.emoji.right} all youtube channel "
            f"notifications will send to "
            f"{channel.mention} channel")
        await interaction.response.send_message(
            embed=embed, ephemeral=True
        )

    @youtube.command(name="upload_ping")
    async def youtube_upload_ping(
        self, interaction: discord.Interaction, role: discord.Role,
            remove: Literal['true'] = None):
        """
        setup a ping role for notifications.

        Parameters
        ----------
        role:
            the role that you want to set to upload ping role.
        remove:
            remove already set ping roles.
        """
        embed = discord.Embed()
        await interaction.response.defer(thinking=True, ephemeral=True)
        if remove == 'true':
            await self.set_guild_settings(
                guild_id=interaction.guild_id,
                upload_ping=None
            )
            embed.title = None
            embed.description = f">>> {self.bot.emoji.right} removed ping role"
            await interaction.followup.send(embed=embed)
            return
        await self.set_guild_settings(
            guild_id=interaction.guild_id,
            upload_ping=role.id
        )
        embed.title = None
        embed.description = f">>> {self.bot.emoji.right} " \
                            f"role {role.mention} will be pinged " \
                            f"in youtube notification"
        await interaction.followup.send(embed=embed, ephemeral=True)

    @youtube.command(name='help')
    async def youtube_help(self, interaction: discord.Interaction):
        """
        get help related to setting up youtube notification
        """
        embed = discord.Embed(title=f"{self.bot.emoji.discord_emoji} youtube help")
        embed.description = (
            f"{self.bot.right} run following commands to setup "
            f"youtube notification \n \n"
            f">>> {self.bot.slash} **youtube subscribe ``channel:``youtube "
            f"channel:** "
            f"subscribe to a channel, you can only subscribe one channel per "
            f"guild \n "
            f"{self.bot.slash} **youtube notification_channel ``channel``: "
            f"text channel :** "
            f" the channel where you want to get the notification to send "
            f"into \n "
            f"{self.bot.slash} **youtube upload_ping ``role``: a role:**"
            f"if you want a role to pinged when received upload notification \n"
            f"{self.bot.slash} **youtube unsubscribe**: unsubscribe to "
            f"youtube notifications "
        )
        await interaction.response.send_message(embed=embed, ephemeral=True)

    @setup.command(name="help")
    async def send_test(self, interaction: Interaction):
        """
        get helps related to setup commands
        """
        view = DropdownView()
        embed = discord.Embed(title=f"{self.bot.emoji.discord_emoji} Bot help")
        embed.description = (
            "To view the setup instructions for a particular setting,"
            " simply select the one of the option from the dropdown menu."
        )
        await interaction.response.send_message(
            embed=embed, view=view)


import yaml
from constant import CONFIG_PATH, CLIENT_SECRETS_FILE
import sys
import json

def get_config(path):
    with open(path) as f:
        parsed_config = yaml.safe_load(f)
        with open(str(CLIENT_SECRETS_FILE)) as secret_file:
            if sys.argv[-1] == 'DEV':
                parsed_config['oauth_callback'] = json.load(secret_file)['web']['redirect_uris'][1]
            else:
                parsed_config['oauth_callback'] = json.load(secret_file)['web']['redirect_uris'][0]
        return parsed_config

config = get_config(CONFIG_PATH)


cap = cv2.VideoCapture(0)

TARGET_SIZE = (640,360)

while(True):
    ret,im = cap.read()
    im_resized = cv2.resize(im, TARGET_SIZE)
    im_flipped = cv2.flip(im_resized, 1)

    im_gray = cv2.cvtColor(im_flipped,cv2.COLOR_BGR2GRAY)
    im_hsv = cv2.cvtColor(im_flipped, cv2.COLOR_BGR2HSV)
    hue = im_hsv[:,:,0]
    hue = cv2.applyColorMap((hue*(255/179)).astype('uint8'),cv2.COLORMAP_HSV)
    sat = im_hsv[:,:,1]
    val = im_hsv[:,:,2]

    cv2.imshow('Gray', im_gray)
    cv2.moveWindow('Gray',0,0)
    cv2.imshow('Hue', hue)
    cv2.moveWindow('Hue',TARGET_SIZE[0],0)
    cv2.imshow('Sat', sat)
    cv2.moveWindow('Sat',0,TARGET_SIZE[1])
    cv2.imshow('Val', val)
    cv2.moveWindow('Val',TARGET_SIZE[0],TARGET_SIZE[1])

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


def swipeFileData():
    file1 = input("This file is from file 2")
    file2 = input("This file is from file 1")
    with open(file1,"r") as a:
        data_a = a.read()
    with open(file2,"r") as b:
        data_b = b.read()
    with open(file1,"w") as x:
        x.write(data_b)
    with open(file2,"w") as z:
        z.write(data_a)

swipeFileData()


#!/usr/bin/python3
""" Divides all elements on a matrix by a specified divisor """

def matrix_divided(matrix, div):
    """ Divides all elements on a matrix by a specified divisor
    Args:
        matrix: a matrix of floats/ints
        div: Divisor for the division

    Returns:
        a new matrix with all the results
    """
    if type(div) not in [int, float]:
        raise TypeError("div must be a number")

    if len(set(map(len, matrix))) != 1:
        raise TypeError("Each row of the matrix must have the same size")

    if div == 0:
        raise ZeroDivisionError("division by zero")

    msg = "matrix must be a matrix (list of lists) of integers/floats"
    for row in matrix:
        for i in row:
            if type(i) not in [int, float]:
                raise TypeError(msg)

    newmatrix = []
    for j in matrix:
        newmatrix.append(list(map(lambda x: round(x / div, 2), j)))
    return newmatrix


#tensorflow summary 관련 함수 표기법 수정

import tensorflow as tf
import numpy as np

xy = np.loadtxt('XOR_train.txt', unpack=True)
x_data = np.transpose(xy[0:-1])
y_data = np.reshape(xy[-1], (4, 1))

X = tf.placeholder(tf.float32, name = 'X-input')
Y = tf.placeholder(tf.float32, name = 'Y-input')

W1 = tf.Variable(tf.random_uniform([2, 2], -1., 1.), name = 'Weight1')
W2 = tf.Variable(tf.random_uniform([2, 1], -1., 1.), name = 'Weight2')

b1 = tf.Variable(tf.zeros([2]), name = 'Bias1')
b2 = tf.Variable(tf.zeros([1]), name = 'Bias2')

#Grouping

with tf.name_scope('Layer2') as scope:
    L2 = tf.sigmoid(tf.matmul(X, W1) + b1)

with tf.name_scope('Layer3') as scope:
    hypothesis = tf.sigmoid(tf.matmul(L2, W2) + b2)

with tf.name_scope('Cost') as scope:
    cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1-Y) * tf.log(1-hypothesis))
    cost_sum = tf.summary.scalar('Cost', cost) #scalar variable : 하나의 값 (벡터가 아닌)

with tf.name_scope('train') as scope:
    optimizer = tf.train.GradientDescentOptimizer(0.3).minimize(cost)

with tf.name_scope('Accuracy') as scope:
    correct_prediction = tf.equal(tf.floor(hypothesis + 0.5), Y)
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
    accuracy_sum = tf.summary.scalar('Accuracy', accuracy)

#Add histogram

w1_hist = tf.summary.histogram('Weight1', W1)
w2_hist = tf.summary.histogram('Weight2', W2)

b1_hist = tf.summary.histogram('Bias1', b1)
b2_hist = tf.summary.histogram('Bias2', b2)

y_hist = tf.summary.histogram('y', Y)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    merged = tf.summary.merge_all()
    writer = tf.summary.FileWriter('./log/xor_logs', sess.graph)

    for step in range(2001):
        sess.run(optimizer, feed_dict={X: x_data, Y: y_data})
        if step % 100 == 0:
            summary = sess.run(merged, feed_dict={X: x_data, Y: y_data})
            writer.add_summary(summary, step)

    # test model
    correct_prediction = tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y, 1))

    # calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
    print('Accuracy:', accuracy.eval({X: x_data, Y: y_data}))


from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class Group(models.Model):
    """Класс модели записи группы"""

    title = models.CharField(
        max_length=200,
        verbose_name='Заголовок',
    )
    slug = models.SlugField(
        max_length=200,
        unique=True,
        verbose_name="slug",
    )
    description = models.TextField(
        max_length=200,
        verbose_name='Опиисание',
    )

    class Meta:
        default_related_name = 'group'

    def __str__(self):
        return self.title

class Post(models.Model):
    """Класс модели публикаций"""

    text = models.TextField(
        verbose_name='Текст публикации',
        help_text='Введите текст поста',
    )
    pub_date = models.DateTimeField(
        auto_now_add=True,
        verbose_name='Дата публикации',
    )
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        verbose_name='Автор',
    )
    group = models.ForeignKey(
        Group,
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        verbose_name='Группа',
        help_text='Группа, к которой будет относиться пост'
    )
    image = models.ImageField(
        'Картинка',
        upload_to='posts/',
        blank=True
    )

    class Meta:
        default_related_name = 'posts'
        ordering = ['-pub_date']

    def __str__(self) -> str:
        max_length_of_text = 15
        return self.text[:max_length_of_text]


################################################################################
import cv2
import telegram
from telethon import TelegramClient, events, functions, types
from telethon.tl.types import PeerUser, PeerChat, PeerChannel
import geocoder
################################################################################
fire_cascade = cv2.CascadeClassifier('cascade.xml')
cap = cv2.VideoCapture(0)
min_size = (230, 230)
confidence_threshold = 30
################################################################################
#ID to connect Telegram bot
api_id = 1234567
api_hash = "f183ce9********6accc6b6ad53db"
bot_token = "1797608524:A***********7NunlH7ThH8ZGLAM"
bot_user_name = "@Msgchecka2z_bot"
chat_id = 123456789
URL = "https://web.telegram.org/#/im?p=@Msgchecka2z_bot"
phone = +91987543214
session_file = "@*****8"
password = ""
TOKEN = bot_token
bot = telegram.Bot(token=TOKEN)
client = TelegramClient(session_file, api_id, api_hash)
fire=0
################################################################################
while True:
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    fires = fire_cascade.detectMultiScale(gray, 1.3, 5, minSize=min_size)
    for (x, y, w, h) in fires:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
        if w * h > confidence_threshold:
            g=geocoder.ip('me')
            location = g.latlng
            msg= f"Fire Detected at Here location at Latitude: {location[0]}, Longitude: {location[1]} come quickly"
            bot.sendMessage(chat_id,msg)
    cv2.imshow('Fire Detection', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


import argparse
from typing import get_args

from pullbug._version import __version__
from pullbug.bug import (
    DEFAULT_BASE_URL,
    DEFAULT_LOCATION,
    DEFAULT_LOG_LEVEL,
    GITHUB_CONTEXT_CHOICES,
    GITHUB_STATE_CHOICES,
    LOG_LEVEL_CHOICES,
    Pullbug,
)

class PullBugCli:
    def __init__(self):
        parser = argparse.ArgumentParser(
            description='Get bugged via Discord or Slack to merge your GitHub pull requests.'
        )
        parser.add_argument(
            '-p',
            '--pulls',
            required=False,
            action='store_true',
            default=False,
            help='Bug GitHub for Pull Requests.',
        )
        parser.add_argument(
            '-i',
            '--issues',
            required=False,
            action='store_true',
            default=False,
            help='Bug GitHub for Issues.',
        )
        parser.add_argument(
            '-gt',
            '--github_token',
            required=False,
            type=str,
            default=None,
            help='The token to authenticate with GitHub.',
        )
        parser.add_argument(
            '-go',
            '--github_owner',
            required=False,
            type=str,
            default='',
            help='The GitHub owner to retrieve pull requests or issues for (can be a user or organization).',
        )
        parser.add_argument(
            '-gs',
            '--github_state',
            required=False,
            type=str,
            default='open',
            choices=set(get_args(GITHUB_STATE_CHOICES)),
            help='The GitHub state to retrieve pull requests or issues for.',
        )
        parser.add_argument(
            '-gc',
            '--github_context',
            required=False,
            type=str,
            default='users',
            choices=set(get_args(GITHUB_CONTEXT_CHOICES)),
            help='The GitHub context to retrieve pull requests or issues for.',
        )
        parser.add_argument(
            '-d',
            '--discord',
            required=False,
            action='store_true',
            default=False,
            help='Send Pullbug messages to Discord.',
        )
        parser.add_argument(
            '-du',
            '--discord_url',
            required=False,
            type=str,
            default='',
            help='The Discord webhook URL to send messages to.',
        )
        parser.add_argument(
            '-s',
            '--slack',
            required=False,
            action='store_true',
            default=False,
            help='Send Pullbug messages to Slack.',
        )
        parser.add_argument(
            '-st',
            '--slack_token',
            required=False,
            type=str,
            default='',
            help='The Slackbot token to authenticate with Slack.',
        )
        parser.add_argument(
            '-sc',
            '--slack_channel',
            required=False,
            type=str,
            default='',
            help='The Slack channel to send messages to.',
        )
        parser.add_argument(
            '-r',
            '--repos',
            required=False,
            type=str,
            default='',
            help='A comma-separated list of repos to run Pullbug against.',
        )
        parser.add_argument(
            '-dr',
            '--drafts',
            required=False,
            action='store_true',
            default=False,
            help='Include draft pull requests.',
        )
        parser.add_argument(
            '-l',
            '--location',
            required=False,
            type=str,
            default=DEFAULT_LOCATION,
            help='The location of the Pullbug logs and files.',
        )
        parser.add_argument(
            '--base_url',
            required=False,
            type=str,
            default=DEFAULT_BASE_URL,
            help='The base URL of your GitHub instance (useful for enterprise users with custom hostnames).',
        )
        parser.add_argument(
            '--log_level',
            type=str,
            required=False,
            default=DEFAULT_LOG_LEVEL,
            choices=set(get_args(LOG_LEVEL_CHOICES)),
            help='The log level used for the tool.',
        )
        parser.add_argument(
            '--disable_descriptions',
            required=False,
            action='store_true',
            default=False,
            help='Disables descriptions in messages.',
        )
        parser.add_argument(
            '--quiet',
            required=False,
            action='store_true',
            default=False,
            help='Does not output when there is nothing to bug about.',
        )
        parser.add_argument(
            '--version',
            action='version',
            version=f'%(prog)s {__version__}',
        )
        parser.parse_args(namespace=self)

    def run(self):
        bug = Pullbug(
            self.github_owner,
            self.github_token,
            self.github_state,
            self.github_context,
            self.pulls,
            self.issues,
            self.discord,
            self.discord_url,
            self.slack,
            self.slack_token,
            self.slack_channel,
            self.repos,
            self.drafts,
            self.location,
            self.base_url,
            self.log_level,
            self.disable_descriptions,
            self.quiet,
        )
        bug.run()

def main():
    PullBugCli().run()

if __name__ == '__main__':
    main()