coins = {'2GIVE': '2GIVE',
         'AMP': 'AMP',
         'AdEx': 'ADX',
         'Ada': 'ADA',
         'Aeon': 'AEON',
         'Apx': 'APX',
         'Aragon': 'ANT',
         'Ardor': 'ARDR',
         'Ark': 'ARK',
         'ArtByte': 'ABY',
         'Augur': 'REP',
         'AuroraCoin': 'AUR',
         'BURSTCoin': 'BURST',
         'Bancor': 'BNT',
         'Basic Attention Token': 'BAT',
         'BitBay': 'BAY',
         'BitBean': 'BITB',
         'BitCrystals': 'BCY',
         'BitSend': 'BSD',
         'Bitcoin Cash': 'BCC',
         'Bitcoin Gold': 'BTG',
         'BitcoinDark': 'BTCD',
         'Bitswift': 'SWIFT',
         'BlackCoin': 'BLK',
         'Blitzcash': 'BLITZ',
         'BlockNet': 'BLOCK',
         'Blocktix': 'TIX',
         'Breakout': 'BRK',
         'Breakout Stake': 'BRX',
         'Bytecent': 'BYC',
         'Bytes': 'GBYTE',
         'CLAMs': 'CLAM',
         'CannabisCoin': 'CANN',
         'CapriCoin': 'CPC',
         'Circuits of Value': 'COVAL',
         'Civic': 'CVC',
         'CloakCoin': 'CLOAK',
         'ClubCoin': 'CLUB',
         'Cofound.it': 'CFI',
         'Counterparty': 'XCP',
         'CreditBit': 'CRB',
         'Crown': 'CRW',
         'CureCoin': 'CURE',
         'DECENT': 'DCT',
         'Dash': 'DASH',
         'Databits': 'DTB',
         'Decentraland': 'MANA',
         'Decred': 'DCR',
         'Diamond': 'DMD',
         'Digibyte': 'DGB',
         'DigitalNote': 'XDN',
         'DigixDAO': 'DGD',
         'Dogecoin': 'DOGE',
         'DopeCoin': 'DOPE',
         'Dynamic': 'DYN',
         'Edgeless': 'EDG',
         'Einsteinium': 'EMC2',
         'Elastic': 'XEL',
         'ElectronicGulden': 'EFL',
         'EmerCoin': 'EMC',
         'EnergyCoin': 'ENRG',
         'Enigma': 'ENG',
         'Ethereum': 'ETH',
         'Ethereum Classic': 'ETC',
         'EuropeCoin': 'ERC',
         'EverGreenCoin': 'EGC',
         'ExclusiveCoin': 'EXCL',
         'Expanse': 'EXP',
         'Factom': 'FCT',
         'FairCoin': 'FAIR',
         'Feathercoin': 'FTC',
         'FirstBlood': '1ST',
         'Florin': 'FLO',
         'FoldingCoin': 'FLDC',
         'FunFair': 'FUN',
         'GBG': 'GBG',
         'Gambit': 'GAM',
         'GameCredits': 'GAME',
         'GeoCoin': 'GEO',
         'GlobalCurrencyReserve': 'GCR',
         'Gnosis': 'GNO',
         'GoldCoin': 'GLD',
         'Golem': 'GNT',
         'Golos': 'GOLOS',
         'GridCoin': 'GRC',
         'Groestlcoin': 'GRS',
         'Gulden': 'NLG',
         'Guppy': 'GUP',
         'HempCoin': 'THC',
         'Humaniq': 'HMQ',
         'I/OCoin': 'IOC',
         'IDNI Agoras': 'AGRS',
         'Incent': 'INCNT',
         'InfluxCoin': 'INFX',
         'Internet Of People': 'IOP',
         'Ion': 'ION',
         'Komodo': 'KMD',
         'Kore': 'KORE',
         'LBRY Credits': 'LBC',
         'Legends': 'LGD',
         'Lisk': 'LSK',
         'Litecoin': 'LTC',
         'Lomocoin': 'LMC',
         'Lumen': 'XLM',
         'Lunyr': 'LUN',
         'Magi': 'XMG',
         'MaidSafe': 'MAID',
         'Melon': 'MLN',
         'Memetic': 'MEME',
         'Mercury': 'MER',
         'Metal': 'MTL',
         'MonaCoin': 'MONA',
         'Monaco': 'MCO',
         'Monero': 'XMR',
         'MonetaryUnit': 'MUE',
         'Musicoin': 'MUSIC',
         'Myriad': 'XMY',
         'Mysterium': 'MYST',
         'NAVCoin': 'NAV',
         'NXT': 'NXT',
         'Neo': 'NEO',
         'NeosCoin': 'NEOS',
         'NewEconomyMovement': 'XEM',
         'Nexium': 'NXC',
         'Nexus': 'NXS',
         'Nubits': 'NBT',
         'Numeraire': 'NMR',
         'OMNI': 'OMNI',
         'OkCash': 'OK',
         'OmiseGO': 'OMG',
         'ParkByte': 'PKB',
         'Particl': 'PART',
         'Patientory': 'PTOY',
         'Peercoin': 'PPC',
         'PesetaCoin ': 'PTC',
         'PinkCoin': 'PINK',
         'Pivx': 'PIVX',
         'PotCoin': 'POT',
         'PowerLedger': 'POWR',
         'Project Decorum': 'PDC',
         'Qtum': 'QTUM',
         'Quantum Resistant Ledger': 'QRL',
         'Qwark': 'QWARK',
         'Radium': 'RADS',
         'ReddCoin': 'RDD',
         'Ripio Credit Network': 'RCN',
         'Ripple': 'XRP',
         'Rise': 'RISE',
         'RubyCoin': 'RBY',
         'STEEM': 'STEEM',
         'Salt': 'SALT',
         'SaluS': 'SLS',
         'Sequence': 'SEQ',
         'Shift': 'SHIFT',
         'Siacoin': 'SC',
         'Siberian Chervonets': 'SIB',
         'SingularDTV': 'SNGLS',
         'SolarCoin': 'SLR',
         'Sphere': 'SPHR',
         'SpreadCoin': 'SPR',
         'StartCoin': 'START',
         'Status Network Token': 'SNT',
         'StealthCoin': 'XST',
         'SteemDollars': 'SBD',
         'Storj': 'STORJ',
         'Stratis': 'STRAT',
         'Swarm City Token': 'SWT',
         'Syndicate': 'SYNX',
         'Synergy': 'SNRG',
         'SysCoin': 'SYS',
         'TRIG Token': 'TRIG',
         'TenX Pay Token': 'PAY',
         'Tokes': 'TKS',
         'TransferCoin': 'TX',
         'TrustPlus': 'TRUST',
         'Trustcoin': 'TRST',
         'Ubiq': 'UBQ',
         'UnbreakableCoin': 'UNB',
         'Vcash': 'XVC',
         'Verge': 'XVG',
         'VeriCoin': 'VRC',
         'Verium': 'VRM',
         'Vertcoin': 'VTC',
         'ViaCoin ': 'VIA',
         'Viberate': 'VIB',
         'Voxels': 'VOX',
         'Waves': 'WAVES',
         'WhiteCoin': 'XWC',
         'Wings DAO': 'WINGS',
         'Xaurum': 'XAUR',
         'ZCoin': 'XZC',
         'Zcash': 'ZEC',
         'Zclassic': 'ZCL',
         'Zencash': 'ZEN',
         'adToken': 'ADT',
         'district0x': 'DNT',
         'eBoost': 'EBST',
         'iEx.ec': 'RLC',
         'vTorrent': 'VTR'
         }

coins_abbr = [
    'LTC',
    'DOGE',
    'VTC',
    'PPC',
    'FTC',
    'RDD',
    'NXT',
    'DASH',
    'POT',
    'BLK',
    'EMC2',
    'XMY',
    'AUR',
    'EFL',
    'GLD',
    'SLR',
    'PTC',
    'GRS',
    'NLG',
    'RBY',
    'XWC',
    'MONA',
    'THC',
    'ENRG',
    'ERC',
    'VRC',
    'CURE',
    'XMR',
    'CLOAK',
    'START',
    'KORE',
    'XDN',
    'TRUST',
    'NAV',
    'XST',
    'BTCD',
    'VIA',
    'PINK',
    'IOC',
    'CANN',
    'SYS',
    'NEOS',
    'DGB',
    'BURST',
    'EXCL',
    'SWIFT',
    'DOPE',
    'BLOCK',
    'ABY',
    'BYC',
    'XMG',
    'BLITZ',
    'BAY',
    'FAIR',
    'SPR',
    'VTR',
    'XRP',
    'GAME',
    'COVAL',
    'NXS',
    'XCP',
    'BITB',
    'GEO',
    'FLDC',
    'GRC',
    'FLO',
    'NBT',
    'MUE',
    'XEM',
    'CLAM',
    'DMD',
    'GAM',
    'SPHR',
    'OK',
    'SNRG',
    'PKB',
    'CPC',
    'AEON',
    'ETH',
    'GCR',
    'TX',
    'BCY',
    'EXP',
    'INFX',
    'OMNI',
    'AMP',
    'AGRS',
    'XLM',
    'CLUB',
    'VOX',
    'EMC',
    'FCT',
    'MAID',
    'EGC',
    'SLS',
    'RADS',
    'DCR',
    'BSD',
    'XVG',
    'PIVX',
    'XVC',
    'MEME',
    'STEEM',
    '2GIVE',
    'LSK',
    'PDC',
    'BRK',
    'DGD',
    'WAVES',
    'RISE',
    'LBC',
    'SBD',
    'BRX',
    'ETC',
    'STRAT',
    'UNB',
    'SYNX',
    'TRIG',
    'EBST',
    'VRM',
    'SEQ',
    'XAUR',
    'SNGLS',
    'REP',
    'SHIFT',
    'ARDR',
    'XZC',
    'NEO',
    'ZEC',
    'ZCL',
    'IOP',
    'GOLOS',
    'UBQ',
    'KMD',
    'GBG',
    'SIB',
    'LMC',
    'QWARK',
    'CRW',
    'SWT',
    'MLN',
    'ARK',
    'DYN',
    'TKS',
    'MUSIC',
    'DTB',
    'INCNT',
    'GBYTE',
    'GNT',
    'NXC',
    'EDG',
    'LGD',
    'TRST',
    'WINGS',
    'RLC',
    'GNO',
    'GUP',
    'LUN',
    'APX',
    'HMQ',
    'ANT',
    'SC',
    'BAT',
    'ZEN',
    '1ST',
    'QRL',
    'CRB',
    'PTOY',
    'MYST',
    'CFI',
    'BNT',
    'NMR',
    'SNT',
    'DCT',
    'XEL',
    'MCO',
    'ADT',
    'FUN',
    'PAY',
    'MTL',
    'STORJ',
    'ADX',
    'OMG',
    'CVC',
    'PART',
    'QTUM',
    'BCC',
    'DNT',
    'ADA',
    'MANA',
    'SALT',
    'TIX',
    'RCN',
    'VIB',
    'MER',
    'POWR',
    'BTG',
    'ENG'
]


# Import packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import uncertainties
from uncertainties import unumpy
print('')

# Load data from file
mass_data = np.loadtxt('aud16.dat',skiprows=2)

# Create empty lists to read data into
Z = []
A = []
BE = []
BE_error = []
N = []

# Assign variables of a given isotope to each list
for i in range(len(mass_data)):
	Z.append(int(mass_data[i,0]))
	A.append(int(mass_data[i,1]))
	BE.append(mass_data[i,2])
	BE_error.append(mass_data[i,3])
	N.append(int(mass_data[i,5]))

# Assign variables of a given isotope to each list
Z = np.array(Z)
A = np.array(A)
BE = np.array(BE)
BE_error = np.array(BE_error)
BE = unumpy.uarray(BE,BE_error)
N = np.array(N)

# Create array of each Z and N in arrays
Z_i = np.arange(Z.min(),Z.max()+0.1,1)
N_i = np.arange(N.min(),N.max()+0.1,1)

# Create empty lists for reordering
N_1 = []
Z_1 = []
BE_1 = []

# Reorder lists into isotones of given N number
for i in range(len(N_i)):
	for j in range(len(N)):
		if N[j] == N_i[i]:
			N_1.append(N[j])
			Z_1.append(Z[j])
			BE_1.append(BE[j])

# Create empty lists for S_2p
S_2p = []
S_1p = []
N_S_2p= []
Z_S_2p = []

# Calculate and add S_2p, S_1p (and Z,N) for isotones for which it can be computed
for i in np.arange(2,len(N_1)-1,1):
	if N_1[i] == N_1[i-2]:
		S_2p.append(BE_1[i]-BE_1[i-2])
		S_1p.append(BE_1[i]-BE_1[i-1])
		N_S_2p.append(N_1[i])
		Z_S_2p.append(Z_1[i])

# Turn them into arrays
S_2p = np.array(S_2p)
S_1p = np.array(S_1p)
N_S_2p = np.array(N_S_2p)
Z_S_2p = np.array(Z_S_2p)

# Find which isotopes are unbound to 2 proton decay
S_2p_u = S_2p[S_2p < 0]
S_1p_2p_u = S_1p[S_2p < 0]
N_S_2p_u = N_S_2p[S_2p < 0]
Z_S_2p_u = Z_S_2p[S_2p < 0]

# Find which of these isotopes are unbound to 2 proton decay but stable to 1 proton decay
print('These isotopes are unbound to two proton decay:')
print('N 	 Z 	 S2p 		 S1p')
for i in range(len(N_S_2p_u)):
	print(Z_S_2p_u[i],'	',N_S_2p_u[i]+Z_S_2p_u[i],'	',S_2p_u[i],'	',S_1p_2p_u[i])
print('')

N_1p_b_2p_u = N_S_2p_u[S_1p_2p_u > 0]
Z_1p_b_2p_u = Z_S_2p_u[S_1p_2p_u > 0]
S_2p_u = S_2p_u[S_1p_2p_u > 0]
S_1p_b_2p_u = S_1p_2p_u[S_1p_2p_u > 0]

print('These isotopes are unbound to proton decay but stable to one proton decay')
print('Z 	 N 	 S2p 		 S1p')
for i in range(len(N_1p_b_2p_u)):
	print(Z_1p_b_2p_u[i],'	',N_1p_b_2p_u[i]+Z_1p_b_2p_u[i],'	',S_2p_u[i],'	',S_1p_b_2p_u[i])

# # Create empty lists for reordering
# N_1 = []
# Z_1 = []
# BE_1 = []

# # Reorder lists into isotones of given Z number
# for i in range(len(Z_i)):
# 	for j in range(len(Z)):
# 		if Z[j] == Z_i[i]:
# 			N_1.append(N[j])
# 			Z_1.append(Z[j])
# 			BE_1.append(BE[j])

# # Create empty lists for S_2n
# S_2n = []
# S_1n = []
# N_S_2n= []
# Z_S_2n = []

# # Calculate and add S_2p, S_1p (and Z,N) for isotones for which it can be computed
# for i in np.arange(1,len(Z_1)-1,1):
# 	if Z_1[i] == Z_1[i-2]:
# 		S_2n.append(BE_1[i]-BE_1[i-2])
# 		S_1n.append(BE_1[i]-BE_1[i-1])
# 		N_S_2n.append(N_1[i])
# 		Z_S_2n.append(Z_1[i])

# S_2n = np.array(S_2n)
# N_S_2n = np.array(N_S_2n)
# Z_S_2n = np.array(Z_S_2n)

# S_2n = S_2n[Z_S_2n==8]
# N_S_2n = N_S_2n[Z_S_2n==8]
# S_2n /= 1000

# plt.errorbar(N_S_2n,unumpy.nominal_values(S_2n),yerr=unumpy.std_devs(S_2n),fmt='bo')
# plt.xlabel('Neutron number')
# plt.ylabel('$S_{2n}$ (M8V)')
# plt.xlim(5,19)
# plt.ylim(-1,50)
# plt.savefig('S_2n_even_N.pdf',bbox_inches='tight')
# plt.show()


from .king_curve import KingCurve
from ..core.king_figure import KingFigure
from ..alg.conic_alg import *
from ..alg.plane_geometry_alg import get_edge_two_point_by_line
from ..alg.basic_alg import nan
from ..alg.circle_alg import get_circle_xy_data_by_center_radius
from ..alg.ellipse_alg import get_ellipse_xy_data_by_standard_equation
from ..alg.hyperbola_alg import get_hyperbola_xy_data_by_standard_equation
from ..alg.parabola_alg import get_parabola_xy_data_by_standard_equation

class KingConic(KingCurve):
    conic_type_cls_var = None

    def __init__(self, depends=(), essential_data=None, create_type=1, infinite=True):
        self.conic_type = None
        self.conic_basic_data = None
        super(KingConic, self).__init__(depends=depends, essential_data=essential_data, create_type=create_type,
                                        infinite=infinite)

    def generate_xy_data_from_basic_data(self):
        x_min, x_max = KingFigure().get_x_lim()
        y_min, y_max = KingFigure().get_y_lim()
        t1, t2, translation_coefficient = get_simplest_conic_equation_and_transform_by_conic_equation(*self.basic_data)
        type_basic_data = get_conic_type_and_basic_data_by_simplest_equation(*translation_coefficient)
        kind = type_basic_data[0]
        self.conic_type = kind
        if kind == CONIC_TYPE_CAN_NOT_PLOT:
            self.conic_basic_data = [[], []]
            return self.conic_basic_data
        if kind == CONIC_TYPE_POINT:
            self.conic_basic_data = t1(0, 0)
            return self.conic_basic_data
        if kind == CONIC_TYPE_LINE:
            x1, y1 = t1(*type_basic_data[1][0])
            x2, y2 = t1(*type_basic_data[1][1])
            basic_data = get_edge_two_point_by_line(x1, y1, x2, y2, x_min, x_max, y_min, y_max)
            self.conic_basic_data = basic_data
            return [[basic_data[0][0], basic_data[1][0]], [basic_data[0][1], basic_data[1][1]]]
        if kind == CONIC_TYPE_PARALLEL_LINE or kind == CONIC_TYPE_INTERSECT_LINE:
            x1, y1 = type_basic_data[1][0][0]
            x2, y2 = type_basic_data[1][0][1]
            x3, y3 = type_basic_data[1][1][0]
            x4, y4 = type_basic_data[1][1][1]
            x1, y1 = t1(x1, y1)
            x2, y2 = t1(x2, y2)
            x3, y3 = t1(x3, y3)
            x4, y4 = t1(x4, y4)
            l1 = get_edge_two_point_by_line(x1, y1, x2, y2, x_min, x_max, y_min, y_max)
            l2 = get_edge_two_point_by_line(x3, y3, x4, y4, x_min, x_max, y_min, y_max)
            self.conic_basic_data = [l1, l2]
            return [[l1[0][0], l1[1][0], nan, l2[0][0], l2[1][0]], [l1[0][1], l1[1][1], nan, l2[0][1], l2[1][1]]]
        if kind == CONIC_TYPE_CIRCLE:
            o = t1(0, 0)
            r = type_basic_data[1]
            self.conic_basic_data = [o, r]

            return get_circle_xy_data_by_center_radius(*o, r)
        if kind == CONIC_TYPE_ELLIPSE:
            standard_xy = \
                get_ellipse_xy_data_by_standard_equation(-translation_coefficient[0] / translation_coefficient[5],
                                                         0,
                                                         -translation_coefficient[2] / translation_coefficient[5],
                                                         0, 0, -1)
            self.conic_basic_data = [t1(*type_basic_data[1][0]), t1(*type_basic_data[1][1]), type_basic_data[1][2]]

            return t1(*standard_xy)
        if kind == CONIC_TYPE_HYPERBOLA:
            center = t2((x_min + x_max) / 2, (y_min + y_max) / 2)
            x_lim = 0.71 * (x_max - x_min)
            y_lim = 0.71 * (y_max - y_min)

            standard_xy = \
                get_hyperbola_xy_data_by_standard_equation(translation_coefficient[0] / translation_coefficient[5],
                                                           0,
                                                           translation_coefficient[2] / translation_coefficient[5],
                                                           0, 0, 1,
                                                           center[0] - x_lim,
                                                           center[0] + x_lim,
                                                           center[1] - y_lim,
                                                           center[1] + y_lim)
            self.conic_basic_data = [t1(*type_basic_data[1][0]), t1(*type_basic_data[1][1]), type_basic_data[1][2]]

            return t1(*standard_xy)
        if kind == CONIC_TYPE_PARABOLA:
            center = t2((x_min + x_max) / 2, (y_min + y_max) / 2)
            x_lim = 0.71 * (x_max - x_min)
            y_lim = 0.71 * (y_max - y_min)

            standard_xy = get_parabola_xy_data_by_standard_equation(*translation_coefficient,
                                                                    center[0] - x_lim,
                                                                    center[0] + x_lim,
                                                                    center[1] - y_lim,
                                                                    center[1] + y_lim)
            self.conic_basic_data = [t1(*type_basic_data[1][0]), t1(*type_basic_data[1][1])]

            return t1(*standard_xy)


#!/usr/bin/python
import sys

def process(infile):
  prevs = []
  cycle = 0
  infc = 0
  cycleseen = False

  lst = slurp(infile)
  while True:
    prevs.append(lst)
    print(lst)

    newlst = level_lst(lst)
    cycle +=1

    if newlst in prevs:
      break
    lst = newlst

  print("{0:d} cycles for :{1}".format(cycle, newlst))

  targetlst = newlst
  lst = newlst
  while True:
    newlst = level_lst(lst)
    infc += 1
    if newlst == targetlst:
      break
    lst = newlst
  print("{0:d} cycles for again.".format(infc))

def slurp(fname):
  lst = []
  inf = open(fname,'r')
  for l in inf:
    for w in l.split():
      i = int(w)
      lst.append(i)

  return lst

def level_lst(inlst):
  outlst = []

  # start point
  idxm = 0
  for x in range(len(inlst)):
    if inlst[idxm] < inlst[x]:
      idxm = x

  amt = inlst[idxm]
  outlst = inlst.copy()
  outlst[idxm] = 0
  idxr = idxm + 1
  while amt > 0 and idxr != idxm:
    if idxr >= len(inlst):
      idxr = 0

    outlst[idxr] += 1
    amt -=1
    idxr +=1

  return outlst

if __name__ == "__main__":
  process(sys.argv[1])


player_health = 12

# def game():
#     def drink_portion():
#         potion_strength = 10
#         print(player_health)

#     drink_portion()

# print(player_health)

game_level = 3
def create_enemy():
    enemies = ["Aliens","Zombies","Skeleton"]
    if game_level<5:
        new_enemy = enemies[0]

    print(new_enemy)

create_enemy()

enemies = 1
def increase_enemies():
    print(f"enemies inside function:{enemies}")
    return enemies+1

enemies = increase_enemies()
print(f"enemies outside function:{enemies}")

#Global Constants
PI =3.14
URL="www.youtube.com"
TWITTER_HANDLE="ashishkumar@24"

Day-12(Scope and Number Guessing Game)/main.py


import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import base64
import glob
import os

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

server = app.server

###################################################
#####         TECH SURVEY                      ####
###################################################

data_path  = "survey.csv"
data = pd.read_csv(data_path)

oftenAll = data[data['work_interfere']=='Often']
oftenYes = oftenAll[oftenAll['treatment']=='Yes']
oftenPercent = (len(oftenYes) / len(oftenAll))
oftenAll['percentage'] = oftenAll['treatment'].astype('category').map({"Yes":"{}%".format(round(oftenPercent*100)), "No":"{}%".format(round((1-oftenPercent)*100))})

sometimesAll = data[data['work_interfere']=='Sometimes']
sometimesYes = sometimesAll[sometimesAll['treatment']=='Yes']
sometimesPercent = (len(sometimesYes) / len(sometimesAll))
sometimesAll['percentage'] = sometimesAll['treatment'].astype('category').map({"Yes":"{}%".format(round(sometimesPercent*100)), "No":"{}%".format(round((1-sometimesPercent)*100))})

rarelyAll = data[data['work_interfere']=='Rarely']
rarelyYes = rarelyAll[rarelyAll['treatment']=='Yes']
rarelyPercent = (len(rarelyYes) / len(rarelyAll))
rarelyAll['percentage'] = rarelyAll['treatment'].astype('category').map({"Yes":"{}%".format(round(rarelyPercent*100)), "No":"{}%".format(round((1-rarelyPercent)*100))})

neverAll = data[data['work_interfere']=='Never']
neverYes = neverAll[neverAll['treatment']=='Yes']
neverPercent = (len(neverYes) / len(neverAll))
neverAll['percentage'] = neverAll['treatment'].astype('category').map({"Yes":"{}%".format(round(neverPercent*100)), "No":"{}%".format(round((1-neverPercent)*100))})

frames = [neverAll, rarelyAll, sometimesAll, oftenAll]
result = pd.concat(frames)

fig = px.bar(
    result,
    x="work_interfere",
    color="treatment",
    range_y=[0, 501],
    category_orders={
        "work_interfere":["Never", "Rarely", "Sometimes", "Often"],
        "treatment":["Yes", "No"],
    },
    hover_name='percentage',
    color_discrete_sequence=["#004DA1", "#2EBBAB"],
    labels={"work_interfere": "Frequency of Negative Mental Health Condition Effects", "treatment": "Did the individual
seek treatment?"},
    hover_data=["work_interfere", "treatment", "percentage"],
)

fig.update_layout(
    plot_bgcolor='white',
    # paper_bgcolor='#a9d5fd',
    barmode='stack',
    xaxis_title="Frequency of Interference in Work",
    yaxis_title="Count",
)

fig.update_traces(
    go.Bar(
        hovertemplate =
            '%{customdata[1]}' +
            '
Frequency of Negative Mental Health Condition Effects: %{x}' +
            '
Did the individual seek treatment?: %{customdata[0]}'
    ),
    marker_line_width=0,
)

###########################################################
######            SUNBURST CHART                     ######
###########################################################

data_path2  = "Mental Health Data.csv"

dfSTI = pd.read_csv(data_path2)[:1100]

# dfSTI['Would you be willing to share with you friends and family that you have a mental illness?'] = dfSTI['How willing would you be to share with friends and family that you have a mental illness?'].astype('category').map({
#     "Somewhat open":"Probably",
#     "Very open":"Yes",
#     "Somewhat not open":"Likely not",
#     "Neutral":"Neutral",
#     "Not open at all":"No",
#     "Not applicable to me (I do not have a mental illness)":"N/A"
# })

# fig2 = px.sunburst(
#     dfSTI,
#     path=['Do you currently have a mental health disorder?', 'Would you be willing to share with you friends and family that you have a mental illness?'],
#     color='Do you currently have a mental health disorder?',
#     color_discrete_sequence=['#004DA1', '#CEE5F6', '#F5A627'],
#     maxdepth=-1,
#     hover_data=['Do you currently have a mental health disorder?', 'Would you be willing to share with you friends and family that you have a mental illness?'],
#     branchvalues="total",
# )

# sizes = [35, 18, 18, 18, 35, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 50, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18]

# fig2.update_traces(
#     go.Sunburst(
#         hovertemplate =
#             'Would you be willing to share with you friends and family that you have a mental illness? : %{customdata[1]}' +
#             '
Count: %{value}'
#     ),
#     insidetextorientation='radial',
#     insidetextfont = dict(size=sizes)
# )

sizes = [18, 18, 18, 18, 18, 18, 35, 35, 18, 18, 18, 20]

fig2 = px.sunburst(
    dfSTI,
    path=['Do you currently have a mental health disorder?', 'Has your employer ever formally discussed mental health (for example, as part of a wellness campaign or other official communication)?'],
    color='Do you currently have a mental health disorder?',
    color_discrete_sequence=['#004DA1', '#2EBBAB', '#9FC4E8'],
    maxdepth=-1,
    hover_data=['Do you currently have a mental health disorder?', 'Has your employer ever formally discussed mental health (for example, as part of a wellness campaign or other official communication)?'],
    branchvalues="total",
)

fig2.update_traces(
    go.Sunburst(
        hovertemplate =
            'Has your employer ever formally discussed mental health (for example, as part of a wellness campaign or other official communication)? : %{customdata[1]}' +
            '
Count: %{value}'
    ),
    insidetextorientation='radial',
    insidetextfont = dict(size=sizes)
)

fig2.update_layout(
    margin=dict(t=40, r=0, l=0, b=0),
    font_family="Lato",
)

###########################################################
######            MENTAL HEALTH MAP                  ######
###########################################################

data_path3  = "people-with-mental-health-disorders copy.csv"

df = pd.read_csv(data_path3)

df2 = pd.read_csv('WPP2019_TotalPopulationBySex.csv')

df2['Code'] = df2['Location'].astype('category').map({
    'Aruba': 'ABW',
    'Afghanistan': 'AFG',
    'Angola': 'AGO',
    'Anguilla': 'AIA',
    'Åland Islands': 'ALA',
    'Albania': 'ALB',
    'Andorra': 'AND',
    'Netherlands Antilles': 'ANT',
    'United Arab Emirates': 'ARE',
    'Argentina': 'ARG',
    'Armenia': 'ARM',
    'American Samoa': 'ASM',
    'Antarctica': 'ATA',
    'French Southern Territories': 'ATF',
    'Antigua and Barbuda': 'ATG',
    'Australia': 'AUS',
    'Austria': 'AUT',
    'Azerbaijan': 'AZE',
    'Burundi': 'BDI',
    'Belgium': 'BEL',
    'Benin': 'BEN',
    'Burkina Faso': 'BFA',
    'Bangladesh': 'BGD',
    'Bulgaria': 'BGR',
    'Bahrain': 'BHR',
    'Bahamas': 'BHS',
    'Bosnia and Herzegovina': 'BIH',
    'Saint Barthélemy': 'BLM',
    'Belarus': 'BLR',
    'Belize': 'BLZ',
    'Bermuda': 'BMU',
    'Bolivia (Plurinational State of)': 'BOL',
    'Brazil': 'BRA',
    'Barbados': 'BRB',
    'Brunei Darussalam': 'BRN',
    'Bhutan': 'BTN',
    'Bouvet Island': 'BVT',
    'Botswana': 'BWA',
    'Central African Republic': 'CAF',
    'Canada': 'CAN',
    'Cocos (Keeling) Islands': 'CCK',
    'Switzerland': 'CHE',
    'Chile': 'CHL',
    'China': 'CHN',
    'Côte d\'Ivoire': 'CIV',
    'Cameroon': 'CMR',
    'Democratic Republic of the Congo': 'COD',
    'Congo': 'COG',
    'Cook Islands': 'COK',
    'Colombia': 'COL',
    'Comoros': 'COM',
    'Cape Verde': 'CPV',
    'Costa Rica': 'CRI',
    'Cuba': 'CUB',
    'Christmas Island': 'CXR',
    'Cayman Islands': 'CYM',
    'Cyprus': 'CYP',
    'Czech Republic': 'CZE',
    'Czechia': 'CZE',
    'Germany': 'DEU',
    'Djibouti': 'DJI',
    'Dominica': 'DMA',
    'Denmark': 'DNK',
    'Dominican Republic': 'DOM',
    'Algeria': 'DZA',
    'Ecuador': 'ECU',
    'Egypt': 'EGY',
    'Eritrea': 'ERI',
    'Western Sahara': 'ESH',
    'Spain': 'ESP',
    'Estonia': 'EST',
    'Eswatini': 'SWZ',
    'Ethiopia': 'ETH',
    'Finland': 'FIN',
    'Fiji': 'FJI',
    'Falkland Islands (Malvinas)': 'FLK',
    'France': 'FRA',
    'Faroe Islands': 'FRO',
    'Micronesia (country)': 'FSM',
    'Gabon': 'GAB',
    'United Kingdom': 'GBR',
    'Georgia': 'GEO',
    'Guernsey': 'GGY',
    'Ghana': 'GHA',
    'Gibraltar': 'GIB',
    'Guinea': 'GIN',
    'Guadeloupe': 'GLP',
    'Gambia': 'GMB',
    'Guinea-Bissau': 'GNB',
    'Equatorial Guinea': 'GNQ',
    'Greece': 'GRC',
    'Grenada': 'GRD',
    'Greenland': 'GRL',
    'Guatemala': 'GTM',
    'French Guiana': 'GUF',
    'Guam': 'GUM',
    'Guyana': 'GUY',
    'Hong Kong': 'HKG',
    'Heard Island and McDonald Islands': 'HMD',
    'Honduras': 'HND',
    'Croatia': 'HRV',
    'Haiti': 'HTI',
    'Hungary': 'HUN',
    'Indonesia': 'IDN',
    'Isle of Man': 'IMN',
    'India': 'IND',
    'British Indian Ocean Territory': 'IOT',
    'Ireland': 'IRL',
    'Iran (Islamic Republic of)': 'IRN',
    'Iraq': 'IRQ',
    'Iceland': 'ISL',
    'Israel': 'ISR',
    'Italy': 'ITA',
    'Jamaica': 'JAM',
    'Jersey': 'JEY',
    'Jordan': 'JOR',
    'Japan': 'JPN',
    'Kazakhstan': 'KAZ',
    'Kenya': 'KEN',
    'Kyrgyzstan': 'KGZ',
    'Lao People\'s Democratic Republic': 'LAO',
    'Cambodia': 'KHM',
    'Kiribati': 'KIR',
    'Saint Kitts and Nevis': 'KNA',
    'Republic of Korea': 'KOR',
    'Kuwait': 'KWT',
    'Lebanon': 'LBN',
    'Liberia': 'LBR',
    'Libya': 'LBY',
    'Saint Lucia': 'LCA',
    'Liechtenstein': 'LIE',
    'Sri Lanka': 'LKA',
    'Lesotho': 'LSO',
    'Lithuania': 'LTU',
    'Luxembourg': 'LUX',
    'Latvia': 'LVA',
    'Macao': 'MAC',
    'Saint Martin (French part)': 'MAF',
    'Morocco': 'MAR',
    'Monaco': 'MCO',
    'Moldova': 'MDA',
    'Madagascar': 'MDG',
    'Maldives': 'MDV',
    'Mexico': 'MEX',
    'Marshall Islands': 'MHL',
    'North Macedonia': 'MKD',
    'Mali': 'MLI',
    'Malta': 'MLT',
    'Myanmar': 'MMR',
    'Montenegro': 'MNE',
    'Mongolia': 'MNG',
    'Northern Mariana Islands': 'MNP',
    'Mozambique': 'MOZ',
    'Mauritania': 'MRT',
    'Montserrat': 'MSR',
    'Martinique': 'MTQ',
    'Mauritius': 'MUS',
    'Malawi': 'MWI',
    'Malaysia': 'MYS',
    'Mayotte': 'MYT',
    'Namibia': 'NAM',
    'New Caledonia': 'NCL',
    'Niger': 'NER',
    'Norfolk Island': 'NFK',
    'Nigeria': 'NGA',
    'Nicaragua': 'NIC',
    'Niue': 'NIU',
    'Netherlands': 'NLD',
    'Norway': 'NOR',
    'Nepal': 'NPL',
    'Nauru': 'NRU',
    'New Zealand': 'NZL',
    'Oman': 'OMN',
    'Pakistan': 'PAK',
    'Panama': 'PAN',
    'Pitcairn': 'PCN',
    'Peru': 'PER',
    'Philippines': 'PHL',
    'Palau': 'PLW',
    'Papua New Guinea': 'PNG',
    'Poland': 'POL',
    'Puerto Rico': 'PRI',
    'Dem. People\'s Republic of Korea': 'PRK',
    'Portugal': 'PRT',
    'Paraguay': 'PRY',
    'Palestine': 'PSE',
    'French Polynesia': 'PYF',
    'Qatar': 'QAT',
    'Réunion': 'REU',
    'Romania': 'ROU',
    'Russian Federation': 'RUS',
    'Rwanda': 'RWA',
    'Saudi Arabia': 'SAU',
    'South Sudan': 'SSD',
    'Sudan': 'SDN',
    'Senegal': 'SEN',
    'Singapore': 'SGP',
    'South Georgia and the South Sandwich Islands': 'SGS',
    'Saint Helena, Ascension and Tristan da Cunha': 'SHN',
    'Svalbard and Jan Mayen': 'SJM',
    'Solomon Islands': 'SLB',
    'Sierra Leone': 'SLE',
    'El Salvador': 'SLV',
    'San Marino': 'SMR',
    'Somalia': 'SOM',
    'Saint Pierre and Miquelon': 'SPM',
    'Serbia': 'SRB',
    'Sao Tome and Principe': 'STP',
    'Suriname': 'SUR',
    'Slovakia': 'SVK',
    'Slovenia': 'SVN',
    'Sweden': 'SWE',
    'Swaziland': 'SWZ',
    'Seychelles': 'SYC',
    'Syria': 'SYR',
    'Turks and Caicos Islands': 'TCA',
    'Chad': 'TCD',
    'Togo': 'TGO',
    'Thailand': 'THA',
    'Tajikistan': 'TJK',
    'Tokelau': 'TKL',
    'Turkmenistan': 'TKM',
    'Timor': 'TLS',
    'Tonga': 'TON',
    'Trinidad and Tobago': 'TTO',
    'Tunisia': 'TUN',
    'Turkey': 'TUR',
    'Tuvalu': 'TUV',
    'Taiwan': 'TWN',
    'United Republic of Tanzania': 'TZA',
    'Uganda': 'UGA',
    'Ukraine': 'UKR',
    'United States Minor Outlying Islands': 'UMI',
    'Uruguay': 'URY',
    'United States of America': 'USA',
    'Uzbekistan': 'UZB',
    'Holy See (Vatican City State)': 'VAT',
    'Saint Vincent and the Grenadines': 'VCT',
    'Venezuela (Bolivarian Republic of)': 'VEN',
    'Virgin Islands, British': 'VGB',
    'United States Virgin Islands': 'VIR',
    'Vietnam': 'VNM',
    'Vanuatu': 'VUT',
    'Wallis and Futuna': 'WLF',
    'Samoa': 'WSM',
    'Yemen': 'YEM',
    'South Africa': 'ZAF',
    'Zambia': 'ZMB',
    'Zimbabwe': 'ZWE',
})

df2["population"] = df2["PopTotal"] * 1000

frames2 = []

for theYear in range(1990, 2017):
    blank = []
    yearlyDF = df[df['Year']==theYear]
    yearlyDF2 = df2[df2['Time']==theYear]
    for i in yearlyDF["Code"]:
        for index in yearlyDF2.index:
            if i == yearlyDF2['Code'][index]:
                blank.append(yearlyDF2['population'][index])
                break

    yearlyDF["totalPop"] = blank
    frames2.append(yearlyDF)

print("SUCCESS")
result2 = pd.concat(frames2)
result2["percentage"] = (result2["Prevalence - Mental health disorders: Both (Number)"] / result2["totalPop"]) * 100

##################################################
######           LAYOUT                     ######
##################################################

image_directory = '/home/antz/vscode/Web/dataviz-for-mental-health/images/'
list_of_images = [os.path.basename(x) for x in glob.glob('{}*.jpg'.format(image_directory))]
static_image_route = '/static/'

image_filename = 'images/mental-health.jpg'
encoded_image = base64.b64encode(open(image_filename, 'rb').read())

app.layout = html.Div(children=[

    html.H6(children='Data Viz for Mental Health', className="header"),

    html.Div([
        html.Div([
            html.H2(children='It\'s time to talk about', className="pre-bold-header"),
            html.H2(children='mental health.', className="post-bold-header"),

        ], className="left-side-hero"),
        html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode()), className='hero_img'),
    ], className="hero"),

    html.Div([
        html.P(children='With the pandemic looming overhead and Simone Biles\' Withdrawal from the Olympics, more attention is being drawn towards the issue of mental health in recent times.'),
    ], className="transition-p"),

    html.Hr(className='transition-hr'),

    html.Div([
        html.Div([
            html.H2(children='The problem is that mental health isn\'t being treated enough as an illness or as a serious problem.', className="section-header"),
            html.P(children='Take a second to think about the people that you see everyday, and the people you don’t see often. According to the National Alliance on Mental Illness, 20.6% of US adults experienced an illness related to mental health in 2019. This means that 1 in 5 of all US adults were experiencing mental health issues.', className="section-info"),
        ]),
        html.Hr(className='transition-mini-hr'),
        html.P(children='Here\'s a look at our first visualization. This is a graph of the percentage of population with mental health disorders for every country.', className="section-info"),

        html.Div([
            html.H5(children='Percentage of Population with Mental Health Disorders by Country'),
            dcc.Graph(id='graph-with-slider'),
            dcc.Slider(
                id='year-slider',
                min=result2['Year'].min(),
                max=result2['Year'].max(),
                value=result2['Year'].min(),
                marks={str(year): str(year) for year in result2['Year'].unique()},
                step=None
            ),
            html.Br(),
            html.Br(),
            html.Div([
                html.Span(
                    children=[
                        html.Span(children='Sources: '),
                        html.A(children='Population Prospects (Population Division UN),', href='https://population.un.org/wpp/Download/Standard/CSV/'),
                        html.Span(children=' '),
                        html.A(children='Mental Health Disorders (Our World in Data)', href='https://ourworldindata.org/grapher/people-with-mental-health-disorders'),
                    ]
                ),
            ]),
        ], className='viz-1'),

        html.P(children='It\'s getting worse every year - not enough efforts are being undertaken to fight mental health disorders and to treat mental health. Not enough awareness?', className="section-info"),
    ], className='section'),

    html.Hr(className='transition-hr'),

    html.Div([
        html.Div([
            html.H2(children='Let\'s take a closer look at mental health in the workplace.', className="section-header"),
            html.P(children='Our next visualization utilizes survey data to examine the stigma surrounding mental health. The most common response to, \'Do you currently have a mental health disorder?\' was \'Yes.\' Additionally, our visualization analyzes the responses to another question based on the response to the first question.', className="section-info"),
        ]),
        html.Hr(className='transition-mini-hr'),
        html.P(children='Click on the graph\'s responses to zoom in on a section of responses!', className="section-info"),

        html.Div([
            html.H5(children='Do you currently have a mental health disorder?'),
            html.P(children='Has your employer ever formally discussed mental health (for example, as part of a wellness campaign or other official communication)?'),
            dcc.Graph(
                id='graph2',
                figure=fig2
            ),
            html.Br(),
            html.Br(),
            html.Span(
                children=[
                    html.Span(children='Source: '),
                    html.A(children='Mental Health Data (Kaggle)', href='https://www.kaggle.com/ron2112/mental-health-data?select=Mental+Health+Data.csv'),
                ]
            )
        ], className='viz-2'),

        html.P(children='', className="section-info"),
    ], className='section'),

    html.Hr(className='transition-hr'),

    html.Div([
        html.Div([
            html.H2(children='Thankfully, some people are taking the care they need.', className="section-header"),
            html.P(children='Take a look at this bar graph of survey responses, showing people in the tech industry seeking mental health treatment. The first question they were asked was \'If you have a mental health condition, do you feel that it interferes with your work?\' The second question they were asked was \'Did you seek treatment for your mental health condition?\'', className="section-info"),
        ]),
        html.Hr(className='transition-mini-hr'),
        html.P(children='On the x axis is the response to the first question, and on the y axis is the number of responses. The labels of yes and no correspond to the responses of the second question. If you hover over the sections labeled Yes and No, you can see the percentages of respondents who answered Yes or No.', className="section-info"),

        html.Div([
            html.H5(children='Severity of Mental Health Condition Effects and Whether Treatment Was Sought'),
            dcc.Graph(
                id='graph1',
                figure=fig
            ),
            html.Br(),
            html.Br(),
            html.Span(
                children=[
                    html.Span(children='Source: '),
                    html.A(children='Mental Health in Tech Survey (Kaggle)', href='https://www.kaggle.com/osmi/mental-health-in-tech-survey'),
                ]
            )
        ], className='viz-3'),

        html.P(children='Stay safe and take care of your mental health!', className="section-info"),
    ], className='section'),
])

########################################################
######              CALLBACKS                   ########
########################################################

@app.callback(
    Output('graph-with-slider', 'figure'),
    Input('year-slider', 'value'))
def update_figure(selected_year):
    filtered_df = result2[result2['Year'] == selected_year]

    fig3 = go.Figure(data=go.Choropleth(

        locations = filtered_df['Code'],
        z = filtered_df['percentage'],
        text = ['Country: {}
Disorder Count: {}
Total Population: {}'.format(filtered_df["Entity"][i], int(filtered_df['Prevalence - Mental health disorders: Both (Number)'][i]), int(filtered_df['totalPop'][i])) for i in filtered_df.index],
        colorscale = [[0, "#004DA1"], [0.4, "#004DA1"], [0.6, "#A6FFA6"], [1, "#A6FFA6"]],
        autocolorscale=False,
        reversescale=True,
        zmax=26,
        zmin=0,
        marker_line_color='darkgray',
        marker_line_width=0.5,
        colorbar_ticksuffix = '%',
        colorbar_title = 'Percentage of Population',
        hovertemplate =
            '%{z:.2f}%' +
            '
%{text}'
    ))

    fig3.update_layout(
        geo=dict(
            showframe=False,
            showcoastlines=False,
            projection_type='equirectangular'
        ),
        transition_duration=1500,
        margin=dict(t=0, r=0, l=0, b=0)
    )

    return fig3

if __name__ == '__main__':
    app.run_server(debug=True)


from flask import Flask,render_template,redirect,request,send_file,session
import requests
from modules import scraper,analyser
import json
import glob
import os
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import pandas as pd
app = Flask(__name__,static_folder='static')
from app import app

@app.route('/')
@app.route('/index')
def index():
    return render_template('mainpage.html')

@app.route('/ekstrakcja_opinii', methods=['GET', 'POST'])

def ekstrakcja_opinii():
     if request.method == 'POST':
        kod_produktu = request.form.get('kod-produktu')

        if kod_produktu.strip() == '':

            error_message = 'Nic nie wprowadziłeś. Podaj kod produktu.'
            return render_template('ekstraction.html', error_message=error_message)
        else:
            url = f'https://www.ceneo.pl/{kod_produktu}'
            response = requests.get(url)

            if response.status_code == 200 or response.status_code==405:
                urlreview=f'https://www.ceneo.pl/{kod_produktu}#tab=reviews'
                all_opinions=scraper.get_opinions(urlreview)

                scraper.dumping_to_opinions(kod_produktu,all_opinions)
                scraper.dumping_to_products(kod_produktu)
                opinions=pd.read_json(f'./opinions/{kod_produktu}.json')
                analyser.charts(opinions,kod_produktu)
                return redirect(url)
            else:
                error_message = 'Niepoprawny kod produktu. Spróbuj jeszcze raz.'
                return render_template('ekstraction.html', error_message=error_message)
     else:
        return render_template('ekstraction.html')

@app.route('/ekstraction')
def scenariusz2():
    return render_template('ekstraction.html')
@app.route('/lista-produktow')
def lista_produktow():

    products_data = []

    json_files = glob.glob('./products/*.json')

    for file in json_files:
        with open(file, 'r', encoding='UTF-8') as jf:
            products_data += json.load(jf)

    return render_template('productslist.html', products=products_data)
@app.route('/download/<path:file_path>')
def download_file(file_path):
    try:
        full_path = os.path.join(app.root_path, file_path)
        return send_file(full_path, as_attachment=True)
    except FileNotFoundError:
        error_message = 'File not found.'
        return render_template('error.html', error_message=error_message)
@app.route('/product/<product_id>')
def product_page(product_id):
    opinions = []
    json_files = glob.glob('./opinions/*.json')

    for file in json_files:
        filename = os.path.basename(file)
        if filename.startswith(product_id):
            with open(file, 'r') as json_file:
                opinions = json.load(json_file)
                break
    return render_template('product.html', opinions=opinions,product_id=product_id)

@app.route('/charts/<product_id>')
def charts_page(product_id):
    filename_for_score_chart=f'{product_id}_score.png'
    filename_for_recommendation_chart=f'{product_id}_recommendation.png'
    return render_template('charts.html',filename_for_score_chart=filename_for_score_chart,filename_for_recommendation_chart=filename_for_recommendation_chart,product_id=product_id)


from django.shortcuts import render, get_object_or_404, redirect
from rooms.models import RoomImage, Room, Status
from rooms.forms import RoomsFilterForm, RoomImageForm
from django.contrib import auth

# Create your views here.
def home(request):
    rooms = RoomImage.objects.all();
    form = RoomsFilterForm(request.GET)
    if form.is_valid():
        if form.cleaned_data["min_square"]:
            rooms = rooms.filter(room__square__gte=form.cleaned_data["min_square"])
        if form.cleaned_data["max_square"]:
            rooms = rooms.filter(room__square__lte=form.cleaned_data["max_square"])
        if form.cleaned_data["min_price_per_m2"]:
            rooms = rooms.filter(room__price_per_m2__gte=form.cleaned_data["min_price_per_m2"])
        if form.cleaned_data["max_price_per_m2"]:
            rooms = rooms.filter(room__price_per_m2__lte=form.cleaned_data["max_price_per_m2"])
        if form.cleaned_data["min_price"]:
            rooms = rooms.filter(room__price__gte=form.cleaned_data["min_price"])
        if form.cleaned_data["max_price"]:
            rooms = rooms.filter(room__price__lte=form.cleaned_data["max_price"])
    context = {"rooms": rooms, "form": form, "username": auth.get_user(request).username}
    return render(request, 'home.html', context)
def room_detail(request, pk):
    room = get_object_or_404(RoomImage, pk=pk)
    return render(request, 'room_detail1.html', {'room_image': room, "username": auth.get_user(request).username})
def scheme(request):
    rooms = RoomImage.objects.all;
    return render(request, 'scheme.html', {"rooms": rooms, "username": auth.get_user(request).username})
def about(request):
    return render(request, 'about.html', {"username": auth.get_user(request).username})
def add_room(request):
    form = RoomImageForm()
    if request.method == "POST":
        form = RoomImageForm(request.POST)
        room = Room()
        room.name = request.POST.get('name')
        room.description = request.POST.get('description')
        room.square = request.POST.get('square')
        room.price_per_m2 = request.POST.get('price_per_m2')
        room.price = request.POST.get('price')
        room.comments = request.POST.get('comments')
        room.status = get_object_or_404(Status, pk=2)
        room.save()
        roomImage = RoomImage()
        roomImage.room = get_object_or_404(Room, pk=room.pk)
        roomImage.image = request.POST.get('image')
        roomImage.save()
        return redirect('/')
    return render(request, 'add_room.html', {"form":form,"username": auth.get_user(request).username})
def bron(request, pk):
    room_image = get_object_or_404(RoomImage, pk=pk)
    print(room_image)
    room_image.room.user = auth.get_user(request)
    room_image.room.save()
    room_image.save()
    return redirect('/')
def unbron(request, pk):
    room_image = get_object_or_404(RoomImage, pk=pk)
    print(room_image)
    room_image.room.user = None
    room_image.room.save()
    room_image.save()
    return redirect('/')


from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)

class Desevolvedor(Resource):
    def get(self):
        return 'Ola dev'
#substitui a rota

api.add_resource(Desevolvedor,'/dev')

if __name__ == '__main__':
    app.run()


from random import randint
import pyxel

class App:
    def __init__(self):
        pyxel.init(200, 120)
        pyxel.load("..\Jump Game\jump_game.pyxres")

        # スコア
        self.score = 0
        self.player_x = 72
        self.player_y = -16
        # Y方向の速度
        self.player_vy = 0
        self.player_is_alive = True
        # 遠い雲
        self.far_cloud = [(-10, 75), (40, 65), (90, 60)]
        # 近い雲
        self.near_cloud = [(10, 25), (70, 35), (200, 15)]
        # 床の配置
        self.floor = [(i * 60, randint(50, 104), True) for i in range(4)]
        # フルーツの配置
        self.fruit = [(i * 60, randint(0, 104), randint(0, 2), True) for i in range(4)]
        # BGMの再生(音がデカいのでコメントアウト)
        # pyxel.playm(0, loop=True)
        # 実行
        pyxel.run(self.update, self.draw)

    def update(self):
        if pyxel.btnp(pyxel.KEY_Q):
            pyxel.quit()

        self.update_player()

        # 床の更新
        for i, v in enumerate(self.floor):
            self.floor[i] = self.update_floor(*v)

        # フルーツの更新
        for i, v in enumerate(self.fruit):
            self.fruit[i] = self.update_fruit(*v)

    def update_player(self):
        # 左を押した場合
        if pyxel.btn(pyxel.KEY_LEFT):
            self.player_x = max(self.player_x - 2, pyxel.width - 239)

        # 右を押した場合
        if pyxel.btn(pyxel.KEY_RIGHT):
            self.player_x = min(self.player_x + 2, pyxel.width - 16)
        # 速度の分だけプレイヤーを動かす
        self.player_y += self.player_vy
        # Y方向の最大値(8)
        self.player_vy = min(self.player_vy + 1, 6)

        # プレイヤーのy座標が画面外にいったら
        if self.player_y > pyxel.height:
            if self.player_is_alive:
                self.player_is_alive = False
                pyxel.play(3, 5)

            if self.player_y > 600:
                self.score = 0
                self.player_x = 72
                self.player_y = -16
                self.player_vy = 0
                self.player_is_alive = True

    def update_floor(self, x, y, is_active):
        if is_active:
            if (
                self.player_x + 16 >= x
                and self.player_x <= x + 40
                and self.player_y + 16 >= y
                and self.player_y <= y + 8
                and self.player_vy > 0
            ):
                is_active = False
                self.score += 10
                self.player_vy = -12
                pyxel.play(3, 3)
        else:
            y += 6
        # 床を左に動かす
        x -= 4

        # 画面外に出た場合
        if x < - 40:
            # 画面右に移動
            x += 240
            y = randint(50, 104)
            is_active = True

        return x, y, is_active

    def update_fruit(self, x, y, kind, is_active):
        # フルーツとプレイヤーの当たり判定
        # absは絶対値。x,y座標ともにプレイヤーとフルーツの距離が12より小さくなったら
        if is_active and abs(x - self.player_x) < 12 and abs(y - self.player_y) < 12:
            is_active = False
            # スコア加算
            self.score += (kind + 1) * 100
            # 最小-8のスピードで上に飛ぶ
            self.player_vy = min(self.player_vy, -8)
            pyxel.play(3, 4)
        # 左に動かす
        x -= 2

        # 画面外左に出たら
        if x < -40:
            # 画面外、右に移動
            x += 240
            y = randint(0, 104)
            kind = randint(0, 2)
            is_active = True

        return (x, y, kind, is_active)

    def draw(self):
        # clear screen 画面をクリア
        pyxel.cls(12)
        # 空描画
        pyxel.blt(0, 88, 0, 0, 88, 160, 32)
        # 山描画
        pyxel.blt(0, 88, 0, 0, 64, 160, 24, 12)
        # 森描画
        offset = pyxel.frame_count % 160
        for i in range(2):
            pyxel.blt(i * 160 - offset, 104, 0, 0, 48, 160, 16, 12)
        # 雲描画
        offset = (pyxel.frame_count // 16) % 160
        for i in range(2):
            for x, y in self.far_cloud:
                pyxel.blt(x + i * 160 - offset, y, 0, 64, 32, 32, 8, 12)

        offset = (pyxel.frame_count // 8) % 160
        for i in range(2):
            for x, y in self.near_cloud:
                pyxel.blt(x + i * 160 - offset, y, 0, 0, 32, 56, 8, 12)

        # 床描画
        for x, y, is_active in self.floor:
            pyxel.blt(x, y, 0, 0, 16, 40, 8, 12)

        # フルーツ描画
        for x, y, kind, is_active in self.fruit:
            if is_active:
                pyxel.blt(x, y, 0, 32 + kind * 16, 0, 16, 16, 12)

        # プレイヤー描画
        pyxel.blt(
            self.player_x,
            self.player_y,
            0,
            16 if self.player_vy > 0 else 0,
            0,
            16,
            16,
            12,
        )

        # スコア描画
        s = "SCORE {:>4}".format(self.score)
        pyxel.text(5, 4, s, 1)
        pyxel.text(4, 4, s, 7)
App()


import json
from gensim.models import Doc2Vec
from gensim.models.doc2vec import TaggedDocument
from joblib import load, dump
import numpy as np
import os
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer

from core import tokenizer, stopwords

class NewTfidfVectorizer(TfidfVectorizer):
    def _valid_ngram(self, ngram, stop_words):
        if len(ngram) == 1 and ngram[0] in stop_words:
            return False
        for w in ngram[1:]:
            if w in stop_words:
                return False
        return True

    def _word_ngrams(self, tokens, stop_words=None):
        tokens = super(TfidfVectorizer, self)._word_ngrams(tokens, None)

        if stop_words is not None:
            new_tokens = []
            for token in tokens:
                if self._valid_ngram(token.split(' '), stop_words):
                    new_tokens.append(token)
            return new_tokens

        return tokens

common_data = pd.read_json('common.json', orient='records')
review_data = pd.concat([pd.read_json('apple.json', orient='records'),
                         pd.read_json('google.json', orient='records')])
common_corpus = list(set([('. '.join(filter(None, t))).strip('. ') for t in common_data.itertuples(index=False, name=None)]))
review_corpus = list(set([('. '.join(filter(None, t))).strip('. ') for t in review_data.itertuples(index=False, name=None)]))
print('load data', len(common_data), 'common corpus', len(review_corpus), 'review corpus')

tfidf_file = '1/tfidf.joblib'
if os.path.exists(tfidf_file):
    tfidf = load(tfidf_file)
else:
    tfidf = NewTfidfVectorizer(stop_words=stopwords, tokenizer=tokenizer, ngram_range=(1, 3))
    tfidf.fit(common_corpus + review_corpus)
    dump(tfidf, tfidf_file)
feature_names = tfidf.get_feature_names()
print('fit tdidf')

train = list([TaggedDocument(tokenizer(t, True), [i]) for i, t in enumerate(review_corpus)])

for size in [50]:
    for window in [5]:
        model_file = '1/doc2vec_s%s_w_%s.model' % (size, window)
        if os.path.exists(model_file):
            model = Doc2Vec.load(model_file)
        else:
            model = Doc2Vec(train, vector_size=size, window=window)
            model.save(model_file)
        X = model.docvecs.vectors_docs
        print('fit doc2vec', size, window)

        for n_clusters in [300]:
            clf = KMeans(n_clusters=n_clusters)
            clf.fit(X)
            dump(clf, '1/kmeans_s%s_w%s_cl%s.joblib' % (size, window, n_clusters))
            print('fit kmeans', size, window, n_clusters)

            d = {}
            for i in range(len(clf.labels_)):
                if clf.labels_[i] in d:
                    d[clf.labels_[i]].append(review_corpus[i])
                else:
                    d[clf.labels_[i]] = [review_corpus[i]]

            all_res = []
            i = 0
            for cluster, texts in sorted(d.items(), key=lambda x: -len(x[1])):
                X = tfidf.transform(texts)
                scores = zip(feature_names, np.asarray(X.sum(axis=0)).ravel())
                sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True)
                print('cluster stat %s/%s' % (i, len(d)))
                i += 1
                res = {
                    'cluster': int(cluster),
                    'size': len(texts),
                    'reviews': [],
                    'ngrams': []
                }

                for text in texts[:20]:
                    res['reviews'].append(text)
                for item in sorted_scores[:10]:
                    res['ngrams'].append({'ngram': item[0], 'score': item[1]})
                all_res.append(res)

            with open('1/kmeans_s%s_w%s_cl%s.json' % (size, window, n_clusters), 'w') as f:
                json.dump(all_res, f, ensure_ascii=False, indent=2)

            print('Done', size, window, n_clusters)


import os
import sys
import time

from tracforge.config import Config

class Tracenvadmin:

    def __init__(self):
        self.db = "sqlite:db/trac.db"
        self.template = "/usr/share/trac/templates"
        self.svn = "svn"

    def create_env(self, config, projectname = None):
        os.chdir(config.svn_dir)
        os.system("/usr/bin/svnadmin create "+projectname)
        os.chdir(config.trac_dir)
        os.system("/usr/bin/trac-admin "+projectname+" initenv "+projectname+" "+self.db+" "+self.svn+" "+config.svn_dir+"/"+projectname+" "+self.template)

    def delete_env(self, config, projectname = None):
        os.system("/bin/rm -Rf "+config.svn_dir+"/"+projectname)
        os.system("/bin/rm -Rf "+config.trac_dir+"/"+projectname)


import os
import discord
from discord.ext import commands
import openai
from datetime import datetime, timedelta
import asyncio
import random
from googletrans import Translator
import aiohttp
import webbrowser
import re
from collections import defaultdict
import wikipediaapi
import aiosqlite
import asyncio
import sqlite3
from cachetools import TTLCache
from bs4 import BeautifulSoup
import requests
import json
from urllib.parse import quote
from dotenv import load_dotenv

# Leveling system
xp_per_message = 5
reward_levels = {10: "Bronze", 20: "Silver", 30: "Gold"}

# Spam check system
recent_messages = {}  # key: user_id, value: list of message timestamps

polls = defaultdict(dict)
load_dotenv()
    # Load environment variables
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")

    # Configure the OpenAI API client
openai.api_key = OPENAI_API_KEY
RIOT_API_KEY = os.getenv('RIOT_API_KEY')
GIPHY_API_KEY = os.environ.get("GIPHY_API_KEY")
OPENWEATHER_API_KEY = os.environ.get("OPENWEATHER_API_KEY")
YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY")
GENIUS_API_KEY = os.environ.get("GENIUS_API_KEY")
OTD_API_KEY = os.environ.get("OTD_API_KEY")
NEWS_API_KEY = "your_news_api_key_here"

wiki_lang = "en"
wiki = wikipediaapi.Wikipedia(wiki_lang)
    # Set the command prefix for your bot
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.message_content = True

# Rate limiting and caching
cache = TTLCache(maxsize=100, ttl=3600)

bot = commands.Bot(command_prefix="!", intents=intents)
bot.remove_command("help")

async def fetch_random_exercise():
    url = "https://wger.de/api/v2/exercise/?format=json&language=2&limit=1&offset=" + str(random.randint(1, 300))
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

@bot.command(name="workout")
async def workout(ctx):
    exercise_data = await fetch_random_exercise()
    exercise_name = exercise_data["results"][0]["name"]
    exercise_description = exercise_data["results"][0]["description"].replace("<p>", "").replace("</p>", "")
    await ctx.send(f"Exercise: {exercise_name}\nDescription: {exercise_description}")

async def fetch_prompt():
    url = "https://www.reddit.com/r/WritingPrompts/random.json"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

async def fetch_random_fact():
    url = "https://api.chucknorris.io/jokes/random"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

@bot.command(name="random_fact")
async def random_fact(ctx):
    fact_data = await fetch_random_fact()
    fact = fact_data["value"]
    await ctx.send(fact)

async def fetch_random_cat():
    url = "https://api.thecatapi.com/v1/images/search"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

async def fetch_random_dog():
    url = "https://dog.ceo/api/breeds/image/random"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

@bot.command(name="random_pet")
async def random_pet(ctx, pet: str = "cat"):
    if pet.lower() == "cat":
        pet_data = await fetch_random_cat()
        pet_image = pet_data[0]["url"]
    elif pet.lower() == "dog":
        pet_data = await fetch_random_dog()
        pet_image = pet_data["message"]
    else:
        await ctx.send("Invalid pet type. Available types are 'cat' and 'dog'.")
        return

    await ctx.send(pet_image)

async def fetch_random_quote():
    url = "https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

async def fetch_subreddit_posts(subreddit: str):
    url = f"https://www.reddit.com/r/{subreddit}/hot.json"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

async def fetch_random_poem():
    url = "https://www.poemist.com/api/v1/randompoems"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

async def fetch_random_cocktail():
    url = "https://www.thecocktaildb.com/api/json/v1/1/random.php"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

async def fetch_random_wine():
    url = "https://api.sampleapis.com/wines/reds"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

async def fetch_news(query: str):
    url = f"https://newsapi.org/v2/everything?q={query}&apiKey={NEWS_API_KEY}"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

@bot.command(name="news")
async def news(ctx, *, query: str):
    news_data = await fetch_news(query)
    articles = news_data["articles"]
    for article in articles[:5]:
        title = article["title"]
        url = article["url"]
        await ctx.send(f"{title}\n{url}")

@bot.command(name="wine")
async def wine(ctx):
    wine_data = await fetch_random_wine()
    random_wine = random.choice(wine_data)
    wine_name = random_wine["name"]
    wine_origin = random_wine["origin"]
    await ctx.send(f"Wine recommendation: {wine_name}\nOrigin: {wine_origin}")

@bot.command(name="cocktail")
async def cocktail(ctx):
    cocktail_data = await fetch_random_cocktail()
    cocktail_name = cocktail_data["drinks"][0]["strDrink"]
    cocktail_instructions = cocktail_data["drinks"][0]["strInstructions"]
    await ctx.send(f"{cocktail_name}\nInstructions: {cocktail_instructions}")

@bot.command(name="poem")
async def poem(ctx):
    poem_data = await fetch_random_poem()
    poem_title = poem_data[0]["title"]
    poem_content = poem_data[0]["content"]
    poem_author = poem_data[0]["poet"]["name"]
    await ctx.send(f'"{poem_title}" by {poem_author}\n{poem_content}')

@bot.command(name="reddit")
async def reddit(ctx, subreddit: str):
    post_data = await fetch_subreddit_posts(subreddit)
    posts = post_data["data"]["children"]
    for post in posts[:5]:
        title = post["data"]["title"]
        url = post["data"]["url"]
        await ctx.send(f"{title}\n{url}")

@bot.command(name="rquote")
async def rquote(ctx):
    rquote_data = await fetch_random_quote()
    rquote_text = rquote_data["rquoteText"]
    rquote_author = rquote_data["rquoteAuthor"]
    await ctx.send(f'"{rquote_text}" - {rquote_author}')

@bot.command(name="prompt")
async def prompt(ctx):
    prompt_data = await fetch_prompt()
    prompt_title = prompt_data[0]["data"]["children"][0]["data"]["title"]
    await ctx.send(prompt_title)

wiki_lang = "en"
wiki = wikipediaapi.Wikipedia(wiki_lang)

@bot.command(name="wikipedia")
async def wikipedia(ctx, *, search: str):
    page = wiki.page(search)
    if page.exists():
        summary = page.summary[:1500] + ("..." if len(page.summary) > 1500 else "")
        await ctx.send(f"{page.title}\n{summary}\nLink: {page.fullurl}")
    else:
        await ctx.send("No Wikipedia page found for that search.")

async def fetch_trivia():
    url = f"https://opentdb.com/api.php?amount=1&apikey={OTD_API_KEY}"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

@bot.command(name="trivia")
async def trivia(ctx):
    trivia_data = await fetch_trivia()
    question = trivia_data["results"][0]["question"]
    answer = trivia_data["results"][0]["correct_answer"]
    await ctx.send(f"Trivia question: {question}\nAnswer: {answer}")

def parse_duration(duration_str):
    units = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
    duration = int(duration_str[:-1]) * units[duration_str[-1]]
    return duration

    # Helper function
def find_member(ctx, member_str):
    return discord.utils.find(lambda m: m.name.lower() == member_str.lower(), ctx.guild.members)

@bot.command(name='freechamps')
async def freechamps_command(ctx):
    free_champion_rotation = get_free_champion_rotation()
    if free_champion_rotation:
        response_text = f"Current Free Champion Rotation:\n{free_champion_rotation}"
        await ctx.send(response_text)
    else:
        await ctx.send("Could not find the current free champion rotation")

def get_free_champion_rotation():
    region = "na1"  # Change this based on the desired region
    free_champ_url = f"https://{region}.api.riotgames.com/lol/platform/v3/champion-rotations?api_key={RIOT_API_KEY}"
    free_champ_response = requests.get(free_champ_url)

    if free_champ_response.status_code != 200:
        return None

    free_champ_data = free_champ_response.json()
    free_champion_ids = free_champ_data["freeChampionIds"]
    free_champion_names = [champion_id_to_name(champion_id) for champion_id in free_champion_ids]

    return ", ".join(free_champion_names)

@bot.command(name='matchhistory')
async def matchhistory_command(ctx, *, summoner_name: str):
    match_history = get_match_history(summoner_name)
    if match_history:
        response_text = f"Match History for {summoner_name}:\n{match_history}"
        await ctx.send(response_text)
    else:
        await ctx.send(f"Could not find match history for '{summoner_name}'")

def get_match_history(summoner_name: str):
    account_id = get_account_id(summoner_name)
    if not account_id:
        return None

    region = "na1"  # Change this based on the desired region
    match_history_url = f"https://{region}.api.riotgames.com/lol/match/v4/matchlists/by-account/{account_id}?api_key={RIOT_API_KEY}"
    match_history_response = requests.get(match_history_url)

    if match_history_response.status_code != 200:
        return None

    match_history_data = match_history_response.json()
    matches = match_history_data["matches"]

    formatted_matches = "\n".join(
        [
            f"{index+1}. Game Mode: {match['queue']} | Champion: {champion_id_to_name(match['champion'])} | Timestamp: {match['timestamp']}"
            for index, match in enumerate(matches[:10])  # Limit to the last 10 matches
        ]
    )

    return formatted_matches

def get_account_id(summoner_name: str):
    region = "na1"  # Change this based on the desired region
    summoner_url = f"https://{region}.api.riotgames.com/lol/summoner/v4/summoners/by-name/{summoner_name}?api_key={RIOT_API_KEY}"
    summoner_response = requests.get(summoner_url)

    if summoner_response.status_code != 200:
        return None

    summoner_data = summoner_response.json()
    return summoner_data["accountId"]

@bot.command(name='tierlist')
async def tierlist_command(ctx):
    tier_list = get_tier_list()
    if tier_list:
        response_text = f"Current Tier List:\n{tier_list}"
        await ctx.send(response_text)
    else:
        await ctx.send("Could not fetch the tier list.")

def get_tier_list():
    url = "https://www.leagueofgraphs.com/champions/overview"
    response = requests.get(url)

    if response.status_code != 200:
        return None

    soup = BeautifulSoup(response.text, "html.parser")
    tier_list_sections = soup.find_all("div", {"class": "medium-6"})

    if not tier_list_sections:
        return None

    formatted_tier_list = ""
    for section in tier_list_sections:
        role_title = section.find("h3")
        if not role_title:
            continue

        role = role_title.text.strip()
        champions = section.find_all("div", {"class": "championBox"})

        tier_champions = [
            f"{index + 1}. {champion.find('div', {'class': 'name'}).text.strip()} - Win Rate: {champion.find('div', {'class': 'winRate'}).text.strip()}"
            for index, champion in enumerate(champions)
        ]

        formatted_tier_list += f"{role}:\n" + "\n".join(tier_champions) + "\n\n"

    return formatted_tier_list.strip()

@bot.command(name='counters')
async def counters_command(ctx, *, champion_name: str):
    counters = get_champion_counters(champion_name.lower())
    if counters:
        response_text = f"Counters for {champion_name.capitalize()}:\n{counters}"
        await ctx.send(response_text)
    else:
        await ctx.send(f"Could not find counters for '{champion_name}'")

def get_champion_counters(champion_name: str):
    url = f"https://www.leagueofgraphs.com/en/champions/counters/{champion_name.lower()}/all"
    response = requests.get(url)

    if response.status_code != 200:
        return None

    start_index = response.text.find("data: ") + 6
    end_index = response.text.find("\n", start_index) - 1
    json_data = response.text[start_index:end_index]
    counters_data = json.loads(json_data)

    formatted_counters = "\n".join(
        [
            f"{index + 1}. {counter['champion']} - Win Rate: {counter['winRate']}%, Matches: {counter['matchNumber']}"
            for index, counter in enumerate(counters_data)
        ]
    )

    return formatted_counters

@bot.command(name='esports')
async def esports_command(ctx):
    esports_matches = get_esports_matches()
    if esports_matches:
        response_text = f"Upcoming and Ongoing eSports Matches:\n{esports_matches}"
        await ctx.send(response_text)
    else:
        await ctx.send("No upcoming or ongoing eSports matches found")

def get_esports_matches():
    PANDASCORE_API_KEY = os.getenv("PANDASCORE_API_KEY")
    url = f"https://api.pandascore.co/lol/matches/upcoming_and_running?token={PANDASCORE_API_KEY}"
    response = requests.get(url)

    if response.status_code != 200:
        return None

    matches_data = response.json()
    formatted_matches = "\n".join(
        [
            f"{match['name']} - {match['league']['name']} ({match['scheduled_at']})"
            for match in matches_data
        ]
    )

    return formatted_matches

@bot.command(name='patchnotes')
async def patchnotes_command(ctx):
    latest_patch_notes_url = get_latest_patch_notes_url()
    if latest_patch_notes_url:
        response_text = f"Latest Patch Notes: {latest_patch_notes_url}"
        await ctx.send(response_text)
    else:
        await ctx.send("Could not find the latest patch notes")

def get_latest_patch_notes_url():
    base_url = "https://na.leagueoflegends.com"
    patch_notes_url = f"{base_url}/en-us/news/game-updates/"

    response = requests.get(patch_notes_url)
    if response.status_code != 200:
        return None

    soup = BeautifulSoup(response.text, "html.parser")
    patch_notes_links = soup.find_all("a", class_="style--preview-card")

    if not patch_notes_links:
        return None

    latest_patch_notes_url = base_url + patch_notes_links[0]["href"]
    return latest_patch_notes_url

@bot.command(name='champion')
async def champion_command(ctx, *, champion_name: str):
    champion_data = get_champion_data(champion_name.lower())
    if champion_data:
        response_text = format_champion_data(champion_data)
        await ctx.send(response_text)
    else:
        await ctx.send(f"Could not find champion '{champion_name}'")

def load_champion_data():
    with open("data/champion.json", "r", encoding="utf-8") as file:
        data = json.load(file)
        return data["data"]

@bot.command(name='livegame')
async def livegame_command(ctx, *, summoner_name: str):
    live_game_data = get_live_game_data(summoner_name)
    if live_game_data:
        response_text = format_live_game_data(live_game_data)
        await ctx.send(response_text)
    else:
        await ctx.send(f"No live game found for summoner '{summoner_name}'")

def champion_id_to_name(champion_id: int):
    for champion_key, champion_info in champion_data_cache.items():
        if int(champion_info["key"]) == champion_id:
            return champion_info["name"]
    return "Unknown"

def get_live_game_data(summoner_name: str):
    summoner_data = get_summoner_data(summoner_name)
    if not summoner_data:
        return None

    region = "na1"  # Change this based on the desired region
    summoner_id = summoner_data["id"]
    live_game_url = f"https://{region}.api.riotgames.com/lol/spectator/v4/active-games/by-summoner/{summoner_id}?api_key={RIOT_API_KEY}"
    live_game_response = requests.get(live_game_url)

    if live_game_response.status_code != 200:
        return None

    return live_game_response.json()

def format_live_game_data(live_game_data: dict):
    game_mode = live_game_data["gameMode"]
    game_length = live_game_data["gameLength"] // 60

    participants = live_game_data["participants"]
    formatted_participants = "\n".join(
        [f"{participant['summonerName']} ({champion_id_to_name(participant['championId'])})" for participant in participants]
    )

    response_text = f"Live Game - {game_mode}\nDuration: {game_length} minutes\n\nParticipants:\n{formatted_participants}"
    return response_text

champion_data_cache = load_champion_data()

def get_champion_data(champion_name: str):
    for champion_key, champion_info in champion_data_cache.items():
        if champion_info["name"].lower() == champion_name:
            return champion_info
    return None

def format_champion_data(champion_data: dict):
    title = champion_data["title"]
    name = champion_data["name"]
    passive = champion_data["passive"]
    abilities = champion_data["spells"]

    formatted_abilities = "\n\n".join(
        [f"{ability['name']} ({ability['key']}): {ability['description']}" for ability in abilities]
    )

    response_text = f"{name}, {title}\n\nPassive: {passive['name']} - {passive['description']}\n\nAbilities:\n\n{formatted_abilities}"
    return response_text

@bot.command(name='summoner')
async def summoner_command(ctx, *, summoner_name: str):
    summoner_data = get_summoner_data(summoner_name)
    if summoner_data:
        response_text = f"Summoner '{summoner_name}' has level {summoner_data['summonerLevel']} and is ranked {summoner_data['tier']} {summoner_data['rank']} with {summoner_data['leaguePoints']} LP in Solo/Duo."
        await ctx.send(response_text)
    else:
        await ctx.send(f"Could not find summoner '{summoner_name}'")

def get_summoner_data(summoner_name: str):
    region = "na1"  # Change this based on the desired region
    summoner_url = f"https://{region}.api.riotgames.com/lol/summoner/v4/summoners/by-name/{summoner_name}?api_key={RIOT_API_KEY}"
    summoner_response = requests.get(summoner_url)

    if summoner_response.status_code != 200:
        return None

    summoner_data = summoner_response.json()
    summoner_id = summoner_data["id"]

    league_url = f"https://{region}.api.riotgames.com/lol/league/v4/entries/by-summoner/{summoner_id}?api_key={RIOT_API_KEY}"
    league_response = requests.get(league_url)

    if league_response.status_code != 200:
        return None

    league_data = league_response.json()
    solo_duo_data = None

    for entry in league_data:
        if entry["queueType"] == "RANKED_SOLO_5x5":
            solo_duo_data = entry
            break

    if solo_duo_data:
        summoner_data["tier"] = solo_duo_data["tier"]
        summoner_data["rank"] = solo_duo_data["rank"]
        summoner_data["leaguePoints"] = solo_duo_data["leaguePoints"]
    else:
        summoner_data["tier"] = "Unranked"
        summoner_data["rank"] = ""
        summoner_data["leaguePoints"] = 0

    return summoner_data

@bot.command(name="create_poll")
async def create_poll(ctx, question: str, *options: str):
    if len(options) < 2:
        await ctx.send("You must provide at least two options for the poll.")
        return

    poll_id = f"{ctx.guild.id}-{ctx.channel.id}-{ctx.message.id}"
    poll_options = {str(i): option for i, option in enumerate(options, 1)}

    polls[poll_id] = {
        "question": question,
        "options": poll_options,
        "votes": defaultdict(int)
    }

    options_text = "\n".join([f"{key}. {value}" for key, value in poll_options.items()])
    await ctx.send(f"Poll created with ID: {poll_id}\nQuestion: {question}\nOptions:\n{options_text}")

@bot.command(name="vote")
async def vote(ctx, poll_id: str, option: str):
    poll = polls.get(poll_id)
    if not poll:
        await ctx.send("Invalid poll ID.")
        return

    if option not in poll["options"]:
        await ctx.send("Invalid option.")
        return

    poll["votes"][option] += 1
    await ctx.send(f"Vote recorded for poll {poll_id}.")

@bot.command(name="poll_results")
async def poll_results(ctx, poll_id: str):
    poll = polls.get(poll_id)
    if not poll:
        await ctx.send("Invalid poll ID.")
        return

    results = "\n".join([f"{key}. {value}: {poll['votes'][key]}" for key, value in poll["options"].items()])
    await ctx.send(f"Poll results for {poll_id}:\nQuestion: {poll['question']}\n{results}")

async def fetch_song_data(query):
    url = f"http://api.genius.com/search?q={query}&access_token={GENIUS_API_KEY}"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

async def fetch_lyrics(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            html = await response.text()
            lyrics = re.search(r'<div class="lyrics">([\s\S]+?)<\/div>', html).group(1)
            return re.sub(r"<.*?>", "", lyrics).strip()

@bot.command(name="lyrics")
async def lyrics(ctx, *, song_title: str):
    song_data = await fetch_song_data(song_title)
    if song_data["response"]["hits"]:
        song_url = song_data["response"]["hits"][0]["result"]["url"]
        song_lyrics = await fetch_lyrics(song_url)
        await ctx.send(song_lyrics[:2000] + ("..." if len(song_lyrics) > 2000 else ""))
    else:
        await ctx.send("No lyrics found for that song.")

async def fetch_quote():
    url = "https://zenquotes.io/api/random"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

@bot.command(name="quote")
async def quote(ctx):
    quote_data = await fetch_quote()
    quote = quote_data[0]["q"]
    author = quote_data[0]["a"]
    await ctx.send(f"{quote}\n- {author}")

    # Define the gpt command
@bot.command(name="gpt")
async def gpt(ctx, *, prompt: str):
    # Set up the GPT API call parameters
    gpt_request = {
        "engine": "text-davinci-002",
        "prompt": prompt,
        "max_tokens": 100,
        "n": 1,
        "stop": None,
        "temperature": 0.5,
    }

    # Call the GPT API
    response = openai.Completion.create(**gpt_request)
    answer = response.choices[0].text.strip()

    # Send the generated response back to the Discord channel
    await ctx.send(answer)

async def fetch_youtube_video(query):
    url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=25&q={query}&key={YOUTUBE_API_KEY}&type=video"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

@bot.command(name="youtube")
async def youtube(ctx, *, keyword: str):
    videos_data = await fetch_youtube_video(keyword)
    if videos_data["items"]:
        random_video = random.choice(videos_data["items"])
        video_id = random_video["id"]["videoId"]
        await ctx.send(f"https://www.youtube.com/watch?v={video_id}")
    else:
        await ctx.send("No videos found for that keyword.")

    # Ban command
@bot.command(name="ban")
@commands.has_permissions(ban_members=True)
async def ban(ctx, member_str: str, duration_str: str, *, reason=None):
    member = find_member(ctx, member_str)

    if member is None:
        await ctx.send(f"Member '{member_str}' not found.")
        return
    duration = parse_duration(duration_str)
    await ctx.guild.ban(member, reason=reason)
    await ctx.send(f"{member} has been banned for {duration} seconds. Reason: {reason}")
    await asyncio.sleep(duration)
    await ctx.guild.unban(member)
    await ctx.send(f"{member} has been unbanned after {duration} seconds.")

async def fetch_weather(location):
    url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={OPENWEATHER_API_KEY}&units=metric"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

@bot.command(name="weather")
async def weather(ctx, *, location: str):
    weather_data = await fetch_weather(location)
    if weather_data.get("message"):
        await ctx.send(weather_data["message"])
    else:
        temp = weather_data["main"]["temp"]
        conditions = ", ".join([weather["description"] for weather in weather_data["weather"]])
        await ctx.send(f"Weather in {location}:\nTemperature: {temp}°C\nConditions: {conditions}")

    # Unban command
@bot.command(name="unban")
@commands.has_permissions(ban_members=True)
async def unban(ctx, *, member):
    banned_users = await ctx.guild.bans()
    member_name, member_discriminator = member.split("#")

    for ban_entry in banned_users:
        user = ban_entry.user

        if (user.name, user.discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(f"Unbanned {user.mention}")
            return

    # Mute command
@bot.command(name="mute")
@commands.has_permissions(manage_roles=True)
async def mute(ctx, member_str: str, duration_str: str, *, reason=None):
    member = find_member(ctx, member_str)

    if member is None:
        await ctx.send(f"Member '{member_str}' not found.")
        return
    duration = parse_duration(duration_str)
    guild = ctx.guild
    muted_role = discord.utils.get(guild.roles, name="Muted")

    if not muted_role:
        muted_role = await guild.create_role(name="Muted")

        for channel in guild.channels:
            await channel.set_permissions(muted_role, speak=False, send_messages=False)

    await member.add_roles(muted_role, reason=reason)
    await ctx.send(f"{member} has been muted for {duration} seconds. Reason: {reason}")
    await asyncio.sleep(duration)
    await member.remove_roles(muted_role)
    await ctx.send(f"{member} has been unmuted after {duration} seconds.")

# Unmute command
@bot.command(name="unmute")
@commands.has_permissions(manage_roles=True)
async def unmute(ctx, member: discord.Member):
    muted_role = discord.utils.get(ctx.guild.roles, name="Muted")
    if muted_role in member.roles:
        await member.remove_roles(muted_role)
        await ctx.send(f"{member} has been unmuted.")
    else:
        await ctx.send(f"{member} is not currently muted.")

    # Limit command
@bot.command(name="limit")
@commands.has_permissions(manage_roles=True)
async def limit(ctx, member_str: str, messages_per_interval: int, interval_str: str, *, reason=None):
    member = find_member(ctx, member_str)

    if member is None:
        await ctx.send(f"Member '{member_str}' not found.")
        return
    interval = parse_duration(interval_str)
    # Create a role with limited message permissions
    guild = ctx.guild
    limited_role = discord.utils.get(guild.roles, name="Limited")

    if not limited_role:
        limited_role = await guild.create_role(name="Limited")

        for channel in guild.channels:
            await channel.set_permissions(limited_role, send_messages=False)

    # Assign the limited role
    await member.add_roles(limited_role, reason=reason)
    await ctx.send(f"{member}'s messages have been limited to {messages_per_interval} per {interval} seconds. Reason: {reason}")

    # Remove the limited role after the specified interval
    while True:
        await asyncio.sleep(interval)
        message_count = 0
        async for message in ctx.channel.history(limit=messages_per_interval):
            if message.author == member:
                message_count += 1
                if message_count >= messages_per_interval:
                    await message.delete()

    # Kick command
@bot.command(name="kick")
@commands.has_permissions(kick_members=True)
async def kick(ctx, *, member_str: str, reason=None):
    member = find_member(ctx, member_str)

    if member is None:
        await ctx.send(f"Member '{member_str}' not found.")
        return

    await member.kick(reason=reason)
    await ctx.send(f"{member} has been kicked. Reason: {reason}")

    # Nickname command
@bot.command(name="nickname")
@commands.has_permissions(manage_nicknames=True)
async def nickname(ctx, member_str: str, *, new_nickname):
    member = find_member(ctx, member_str)

    if member is None:
        await ctx.send(f"Member '{member_str}' not found.")
        return

    await member.edit(nick=new_nickname)
    await ctx.send(f"{member}'s nickname has been changed to {new_nickname}")

    # Clear command
@bot.command(name="clear")
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount: int):
    await ctx.channel.purge(limit=amount + 1)
    msg = await ctx.send(f"{amount} messages have been cleared.")
    await asyncio.sleep(5)
    await msg.delete()

# Role command
@bot.command(name="role")
@commands.has_permissions(manage_roles=True)
async def role(ctx, member_str: str, role_name: str, action: str):
    member = find_member(ctx, member_str)

    if member is None:
        await ctx.send(f"Member '{member_str}' not found.")
        return

    role = discord.utils.get(ctx.guild.roles, name=role_name)
    if role is None:
        await ctx.send(f"Role '{role_name}' not found.")
        return

    if action.lower() == "give":
        await member.add_roles(role)
        await ctx.send(f"Role '{role_name}' has been given to {member}.")
    elif action.lower() == "take":
        await member.remove_roles(role)
        await ctx.send(f"Role '{role_name}' has been taken from {member}.")
    elif action.lower() == "change":
        await member.remove_roles(*member.roles[1:])
        await member.add_roles(role)
        await ctx.send(f"{member}'s role has been changed to '{role_name}'.")
    else:
        await ctx.send("Invalid action. Use 'give', 'take', or 'change'.")

async def fetch_joke():
    url = "https://v2.jokeapi.dev/joke/Any"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

@bot.command(name="joke")
async def joke(ctx):
    joke_data = await fetch_joke()

    if joke_data['type'] == 'single':
        await ctx.send(joke_data['joke'])
    else:
        await ctx.send(f"{joke_data['setup']}\n{joke_data['delivery']}")

translator = Translator()

@bot.command(name="translate")
async def translate(ctx, target_language: str, *, text: str):
    try:
        translated = translator.translate(text, dest=target_language)
        await ctx.send(translated.text)
    except ValueError:
        await ctx.send("Invalid target language.")

async def fetch_gif(query):
    url = f"https://api.giphy.com/v1/gifs/search?api_key={GIPHY_API_KEY}&q={query}&limit=25&offset=0&rating=g&lang=en"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

@bot.command(name="gif")
async def gif(ctx, *, keyword: str):
    gifs_data = await fetch_gif(keyword)
    if gifs_data['data']:
        random_gif = random.choice(gifs_data['data'])
        await ctx.send(random_gif['url'])
    else:
        await ctx.send("No GIFs found for that keyword.")

@bot.command(name="help")
async def help_command(ctx):
    help_text1 = """

**!gpt [text]** - Sends a message to the GPT API and returns the response.
**!ban [user] [duration] [duration_unit]** - Bans a user for the specified duration. Duration units: 's' for seconds, 'm' for minutes, 'h' for hours, 'd' for days.
**!unban [user]** - Unbans a user.
**!mute [user] [duration] [duration_unit]** - Mutes a user for the specified duration. Duration units: 's' for seconds, 'm' for minutes, 'h' for hours, 'd' for days.
**!unmute [user]** - Unmutes a user.
**!limit [user] [number_of_messages] [duration] [duration_unit]** - Limits a user to send the specified number of messages within the specified duration. Duration units: 's' for seconds, 'm' for minutes, 'h' for hours, 'd' for days.
**!kick [user]** - Kicks a user from the server.
**!nickname [user] [new_nickname]** - Changes a user's nickname.
**!clear [number_of_messages]** - Clears the specified number of messages from the chat.
**!role [user] [role_name] [action]** - Gives, takes or changes a user's role. Actions: 'give', 'take', 'change'.
**!joke** - Fetches a random joke.
**!translate [text] [target_language]** - Translates the input text to the specified target language.
**!gif [keyword]** - Generates a random GIF based on the provided keyword.
**!weather [location]** - Fetches the weather forecast for the specified location.
**!youtube [keyword]** - Plays a random YouTube video based on the specified keyword.
"""
    help_text2 = """

**!lyrics [song_title] [artist_name]** - Fetches the lyrics for the specified song.
**!quote** - Retrieves a random inspirational quote or daily affirmation.
**!poll [question] [option1] [option2] [...]** - Creates a poll with the specified question and options.
**!trivia** - Generates a random trivia question.
**!prompt** - Generates a random writing prompt or exercise.
**!wikipedia [query]** - Searches for and retrieves information from Wikipedia based on the query.
**!fact** - Generates a random fact or interesting piece of trivia.
**!cat** - Generates a random cat picture.
**!dog** - Generates a random dog picture.
**!wine** - Generates a random wine recommendation.
**!news [query]** - Searches for and retrieves information from news sources based on the query.
**!workout** - Generates a random workout or exercise routine.
"""

    await ctx.send(help_text1)
    await ctx.send(help_text2)

# Error handlers
@clear.error
async def clear_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You don't have permission to use this command.")
    elif isinstance(error, commands.BadArgument):
        await ctx.send("Invalid argument. Correct syntax: `!clear <amount>`")
    else:
        await ctx.send("An error occurred. Please try again.")

@role.error
async def role_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You don't have permission to use this command.")
    elif isinstance(error, commands.BadArgument):
        await ctx.send("Invalid argument. Correct syntax: `!role <member_name> <role_name> <action>`")
    else:
        await ctx.send("An error occurred. Please try again.")

# Other commands and bot.run
@ban.error
async def ban_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You don't have permission to use this command.")
    elif isinstance(error, commands.BadArgument):
        await ctx.send("Invalid argument. Correct syntax: `!ban <member_name> <duration> [reason]`")
    else:
        await ctx.send("An error occurred. Please try again.")

@mute.error
async def mute_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You don't have permission to use this command.")
    elif isinstance(error, commands.BadArgument):
        await ctx.send("Invalid argument. Correct syntax: `!mute <member_name> <duration> [reason]`")
    else:
        await ctx.send("An error occurred. Please try again.")

@limit.error
async def limit_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You don't have permission to use this command.")
    elif isinstance(error, commands.BadArgument):
        await ctx.send("Invalid argument. Correct syntax: `!limit <member_name> <messages_per_interval> <interval> [reason]`")
    else:
        await ctx.send("An error occurred. Please try again.")

@nickname.error
async def nickname_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You don't have permission to use this command.")
    elif isinstance(error, commands.BadArgument):
        await ctx.send("Invalid argument. Correct syntax: `!nickname <member_name> <new_nickname>`")
    else:
        await ctx.send("An error occurred. Please try again.")

@kick.error
async def kick_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You don't have permission to use this command.")
    elif isinstance(error, commands.BadArgument):
        await ctx.send("Invalid argument. Correct syntax: `!kick <member_name> [reason]`")
    else:
        await ctx.send("An error occurred. Please try again.")

# Run the bot
bot.run(DISCORD_TOKEN)