import sys
import time
import traceback
import discord
from os import getenv
from discord import Game, File
from discord.ext import commands
from discord.utils import get
import logging
import re
from urllib.parse import urlparse
from collections import defaultdict
from sqlalchemy import create_engine, func, update, sql
from sqlalchemy.orm import sessionmaker
from models import Base, Battles, Participants
from datetime import datetime, timezone, timedelta
import math as m
import pandas as pd
import numpy as np

# Server IDs
FRICKS_SERVER_ID = "Placeholder"
CLAP_SERVER_ID = "Placeholder"
KINGSMEN_SERVER_ID = "Placeholder"
OOV_SERVER_ID ="Placeholder"
PING_SERVER_ID ="Placeholder"
FAME_SERVER_ID = "Placeholder"
TEST_SERVER_ID ="Placeholder"
MC_SERVER_ID = "Placeholder"

# User IDs
PUPPYBOT_ID = "Placeholder"

# Channel IDs
BOT_TESTING_CHANNEL_ID = "Placeholder"
GENERAL_CHANNEL_ID = "Placeholder"
SCREENSHOT_APPROVAL_CHANNEL_ID = "Placeholder"
SCREENSHOT_LOG_CHANNEL_ID = "Placeholder"
FUNDS_TRACKING_CHANNEL_ID = "Placeholder"
RECRUITMENT_CHANNEL_ID = "Placeholder"
LOGS_CHANNEL_ID = "Placeholder"
LOOT_SPLIT_CHANNEL_ID = "Placeholder"
# Role IDs
FRICKS_ROLE_ID =  "Placeholder"
KINGSMEN_ROLE_ID = "Placeholder"
SOLDIER_ROLE_ID = "Placeholder"
OOV_ROLE_ID = "Placeholder"
PING_ROLE_ID =  "Placeholder"
FAME_ROLE_ID = "Placeholder"
NKC_ROLE_ID = "Placeholder"
NKC_RECRUIT_ROLE_ID = "Placeholder"
NKC_RED_ROLE_ID = "Placeholder"
NKC_GREEN_ROLE_ID = "Placeholder"
NKC_BLUE_ROLE_ID = "Placeholder"
AK_ROLE_ID = "Placeholder"
AK_RECRUIT_ROLE_ID = "Placeholder"
DARK_ROLE_ID = "Placeholder"
MC_ROLE_ID = "Placeholder"
MC_ROLE_ELITE_ID = "Placeholder"
# Role CLAP id's
FRICKLING_ROLE_ID = "Placeholder"
FRICKS_CLAP_ROLE_ID = "Placeholder"
KINGSMEN_CLAP_ROLE_ID = "Placeholder"
OOV_CLAP_ROLE_ID = "Placeholder"
PING_CLAP_ROLE_ID = "Placeholder"
FAME_CLAP_ROLE_ID = "Placeholder"
ROYAL_CLAP_ROLE_ID = "Placeholder"
AK_CLAP_ROLE_ID = "Placeholder"
DARK_CLAP_ROLE_ID = "Placeholder"
GUEST_CLAP_ROLE_ID = "Placeholder"
ROYAL_SERVER_ID = "Placeholder"
AK_SERVER_ID = "Placeholder"
DARK_SERVER_ID = "Placeholder"
MC_CLAP_ROLE_ID = "Placeholder"

intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix='%', case_insensitive=True, chunk_guilds_at_startup = True, intents=intents)

engine = create_engine('sqlite:///register.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()

def is_url(x):
    try:
        result = urlparse(x)
        return all([result.scheme, result.netloc, result.path])
    except:
        return False

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s:%(levelname)s:%(name)s: %(message)s',
    filename="fricksbot.log",
    filemode='a'
)

# Discord Logger
logger = logging.getLogger('discord')
logger.setLevel(logging.INFO)

def role_check(user, roles):
    role_list = []

    for role in user.roles:
        role_list.append(role.id)

    return any(i in roles for i in role_list)

def find_between(s, first, last):
    try:
        start_idx = s.index(first) + len(first)
        end_idx = s.index(last, start_idx)
        return s[start_idx:end_idx]
    except ValueError:
        return ""

def getBattleTimer(time):
    hour = time.hour

    if hour in (23, 0, 1):
        return 0
    elif hour in (2,3):
        return 3
    elif hour in (4,5,6):
        return 5
    if hour in (11, 12, 13):
        return 12
    if hour in (14,15,16):
        return 15
    if hour in (17, 18, 19):
        return 18
    elif hour in (20,21,22):
        return 21

@client.event
async def on_ready():
    channel = client.get_channel(BOT_TESTING_CHANNEL_ID)
    await client.change_presence(activity=Game('Granting permissions, 24/7'))

@client.command()
async def mc(ctx):
    message = ctx.message
    if ctx.guild and ctx.guild.id == TEST_SERVER_ID:
        mc_server = client.get_guild(MC_SERVER_ID)
        mc_member = mc_server.get_member(message.author.id)

        if mc_member is None:
            await message.channel.send("You are not in MC guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🗡')
            return

        roles = [MC_ROLE_ID, MC_ROLE_ELITE_ID]
        if role_check(mc_member, roles):
            role = get(message.guild.roles, id=MC_CLAP_ROLE_ID)
            rrole = get(message.guild.roles, id=GUEST_CLAP_ROLE_ID)
            await message.author.add_roles(role)
            await message.channel.send("You are in MC guild granting permissions")
            await message.add_reaction('👌')
            await message.author.remove_roles(rrole)
        else:
            await message.channel.send("You are not in MC guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🕵')
            await message.add_reaction('❌')
    else:
        await message.channel.send("Wrong server, bud. You can only use this command in the CLAP discord.")

@client.command()
async def nkc(ctx):
    message = ctx.message
    if ctx.guild and ctx.guild.id == TEST_SERVER_ID:
        royal_server = client.get_guild(ROYAL_SERVER_ID)
        royal_member = royal_server.get_member(message.author.id)

        if royal_member is None:
            await message.channel.send("You are not in NKC guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🗡')
            return

        roles = [NKC_ROLE_ID, NKC_RECRUIT_ROLE_ID, NKC_RED_ROLE_ID, NKC_GREEN_ROLE_ID, NKC_BLUE_ROLE_ID]
        if role_check(royal_member, roles):
            role = get(message.guild.roles, id=ROYAL_CLAP_ROLE_ID)
            rrole = get(message.guild.roles, id=GUEST_CLAP_ROLE_ID)
            await message.author.add_roles(role)
            await message.channel.send("You are in NKC guild granting permissions")
            await message.add_reaction('👌')
            await message.author.remove_roles(rrole)
        else:
            await message.channel.send("You are not in NKC guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🕵')
            await message.add_reaction('❌')
    else:
        await message.channel.send("Wrong server, bud. You can only use this command in the CLAP discord.")

@client.command()
async def dark(ctx):
    message = ctx.message
    if ctx.guild and ctx.guild.id == TEST_SERVER_ID:
        dark_server = client.get_guild(DARK_SERVER_ID)
        dark_member = dark_server.get_member(message.author.id)

        if dark_member is None:
            await message.channel.send("You are not in TheDarkClan guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🗡')
            return

        roles = [DARK_ROLE_ID]
        if role_check(dark_member, roles):
            role = get(message.guild.roles, id=DARK_CLAP_ROLE_ID)
            rrole = get(message.guild.roles, id=GUEST_CLAP_ROLE_ID)
            await message.author.add_roles(role)
            await message.channel.send("You are in TheDarkClan guild granting permissions")
            await message.add_reaction('👌')
            await message.author.remove_roles(rrole)
        else:
            await message.channel.send("You are not in TheDarkClan guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🕵')
            await message.add_reaction('❌')
    else:
        await message.channel.send("Wrong server, bud. You can only use this command in the CLAP discord.")

@client.command()
async def ak(ctx):
    message = ctx.message
    if ctx.guild and ctx.guild.id == TEST_SERVER_ID:
        ak_server = client.get_guild(AK_SERVER_ID)
        ak_member = ak_server.get_member(message.author.id)

        if ak_member is None:
            await message.channel.send("You are not in AK7 guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🗡')
            return

        roles = [AK_ROLE_ID, AK_RECRUIT_ROLE_ID]
        if role_check(ak_member, roles):
            role = get(message.guild.roles, id=AK_CLAP_ROLE_ID)
            rrole = get(message.guild.roles, id=GUEST_CLAP_ROLE_ID)
            await message.author.add_roles(role)
            await message.channel.send("You are in AK7 guild granting permissions")
            await message.author.remove_roles(rrole)
            await message.add_reaction('👌')
        else:
            await message.channel.send("You are not in AK7 guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🕵')
            await message.add_reaction('❌')
    else:
        await message.channel.send("Wrong server, bud. You can only use this command in the CLAP discord.")

@client.command()
async def oov(ctx):
    message = ctx.message
    if ctx.guild and ctx.guild.id == TEST_SERVER_ID:
        oov_server = client.get_guild(OOV_SERVER_ID)
        oov_member = oov_server.get_member(message.author.id)

        if oov_member is None:
            await message.channel.send("You are not in Oath of Vengeance guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🗡')
            return

        roles = [OOV_ROLE_ID]
        if role_check(oov_member, roles):
            role = get(message.guild.roles, id=OOV_CLAP_ROLE_ID)
            rrole = get(message.guild.roles, id=GUEST_CLAP_ROLE_ID)
            await message.author.add_roles(role)
            await message.author.remove_roles(rrole)
            await message.channel.send("You are in Oath of Vengeance guild granting permissions")
            await message.add_reaction('👌')
        else:
            await message.channel.send("You are not in Oath of Vengeance guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🕵')
            await message.add_reaction('❌')
    else:
        await message.channel.send("Wrong server, bud. You can only use this command in the CLAP discord.")

@client.command()
async def fricks(ctx):
    message = ctx.message
    if ctx.guild and ctx.guild.id == TEST_SERVER_ID:
        fricks_server = client.get_guild(FRICKS_SERVER_ID)
        fricks_member = fricks_server.get_member(message.author.id)

        if fricks_member is None:
            await message.channel.send("You are not in Fricks guild, permission not granted")
            return

        roles = [FRICKS_ROLE_ID, FRICKLING_ROLE_ID]
        if role_check(fricks_member, roles):
            role = get(message.guild.roles, id=FRICKS_CLAP_ROLE_ID)
            rrole = get(message.guild.roles, id=GUEST_CLAP_ROLE_ID)
            await message.channel.send("You are in Fricks guild, permission granted")
            await message.author.add_roles(role)
            await message.author.remove_roles(rrole)
        else:
            await message.channel.send("You are not in Fricks guild, permission not granted")

    else:
        await message.channel.send("Wrong server, bud. You can only use this command in the CLAP discord.")

@client.command()
async def kingsmen(ctx):
    message = ctx.message
    if ctx.guild and ctx.guild.id == TEST_SERVER_ID:
        kingsmen_server = client.get_guild(KINGSMEN_SERVER_ID)
        kingsmen_member = kingsmen_server.get_member(message.author.id)

        if kingsmen_member is None:
            await message.channel.send("You are not in TheKingsmen guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🗡')
            return

        roles = [KINGSMEN_ROLE_ID, SOLDIER_ROLE_ID]
        if role_check(kingsmen_member, roles):
            role = get(message.guild.roles, id=KINGSMEN_CLAP_ROLE_ID)
            rrole = get(message.guild.roles, id=GUEST_CLAP_ROLE_ID)
            await message.author.add_roles(role)
            await message.channel.send("You are in TheKingsmen guild granting permissions")
            await message.author.remove_roles(rrole)
            await message.add_reaction('👌')
        else:
            await message.channel.send("You are not in TheKingsmen guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🕵')
            await message.add_reaction('❌')
    else:
        await message.channel.send("Wrong server, bud. You can only use this command in the CLAP discord.")

@client.command()
async def ping(ctx):
    message = ctx.message
    if ctx.guild and ctx.guild.id == TEST_SERVER_ID:
        ping_server = client.get_guild(PING_SERVER_ID)
        ping_member = ping_server.get_member(message.author.id)

        if ping_member is None:
            await message.channel.send("You are not in Always350PinG guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🗡')
            return

        roles = [PING_ROLE_ID]
        if role_check(ping_member, roles):
            role = get(message.guild.roles, id=PING_CLAP_ROLE_ID)
            rrole = get(message.guild.roles, id=GUEST_CLAP_ROLE_ID)
            await message.author.add_roles(role)
            await message.channel.send("You are in Always350PinG guild granting permissions")
            await message.author.remove_roles(rrole)
            await message.add_reaction('👌')
        else:
            await message.channel.send("You are not in Always350PinG guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🕵')
            await message.add_reaction('❌')
    else:
        await message.channel.send("Wrong server, bud. You can only use this command in the CLAP discord.")

@client.command()
async def fame(ctx):
    message = ctx.message
    if ctx.guild and ctx.guild.id == TEST_SERVER_ID:
        fame_server = client.get_guild(FAME_SERVER_ID)
        fame_member = fame_server.get_member(message.author.id)

        if fame_member is None:
            await message.channel.send("You are not in F A M E L E S S guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🗡')
            return

        roles = [FAME_ROLE_ID]
        if role_check(fame_member, roles):
            role = get(message.guild.roles, id=FAME_CLAP_ROLE_ID)
            rrole = get(message.guild.roles, id=GUEST_CLAP_ROLE_ID)
            await message.author.add_roles(role)
            await message.channel.send("You are in F A M E L E S S guild granting permissions")
            await message.add_reaction('👌')
            await message.author.remove_roles(rrole)
        else:
            await message.channel.send("You are not in F A M E L E S S guild, permission not granted")
            await message.add_reaction('🐀')
            await message.add_reaction('🕵')
            await message.add_reaction('❌')
    else:
        await message.channel.send("Wrong server, bud. You can only use this command in the CLAP discord.")

client.run("Placeholder_BOT_TOKEN_HERE")


#pythonlists
thislist  = ["apple","banana","cherry"]
print(thislist)
#lists allow duplicate values
thislist = ["apple","banana","cherry","apple","cherry"]
print(thislist)
#to print the number of items in ths list we use len() function
thislist = ["apple","banana","cherry"]
print(len(thislist))
list1 = ["apple","banana","cherry"]
list2 = [1,5,7,9,3]
list3 = [True,False,False]
#a list can contain diferent data types
list1 = ["abc",34,True,40,"male"]
#data type of the list is list
mylist = ["apple","banana","cherry"]
print(type(mylist))
#we can create a new list by using list() constructor
thislist = list(("apple","banana","cherry"))
print(thislist)
#to print the second item of the list
thislist = ["apple","banana","cherry"]
print(thislist[1])
#negetive indexing
#from the last
thislist = ["apple","banana","cherry"]
print(thislist[-1])
#return the third,fourth and fifth
thislist = ["apple","banana","cherry","orange","kiwi","melon","mango"]
print(thislist[2:5])
#to return the items from the beginning to,but NOT including,"kiwi"
thislist = ["apple","banana","cherry","orange","kiwi","melon","mango"]
print(thislist[:4])
#return the items from "cherry" to the end
thislist = ["apple","banana","cherry","orange","kiwi","melon","mango"]
print(thislist[2:])
#range of negetive indexing
thislist = ["apple","banana","cherry","orange","kiwi","melon","mango"]
print(thislist[-4:-1])
#check if apple is present in the list
thislist = ["apple","banana","cherry"]
if "apple" in thislist:
    print("Yes,'apple' is in the fruits list" )
#chaning list items
#change the second item
thislist = ["apple","banana","cherry"]
thislist[1] = "blackcurrant"
print(thislist)
#change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
thislist = ["apple","banana","cherry","orange","kiwi","mango"]
thislist[1:3] = ["blackcurrant","watermelon"]
print(thislist)
#change the second value by replacing it with two new values:
thislist = ["apple","banana","cherry"]
thislist[1:2] = ["blackcurrant","watermelon"]
print(thislist)
#change the second and third value by replacing it with one value
thislist = ["apple","banana","cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
#insert watermelon as the third item
thislist = ["apple","banana","cherry"]
thislist.insert(2,"watermelon")
print(thislist)
#to add an item at the end of a list we use append()
thislist = ["apple","banana","cherry"]
thislist.append("orange")
print(thislist)
#to append elements from another list to the current list,use the extend() method
thislist = ["apple","banana","cherry"]
tropical = ["mango","pineapple","papaya"]
thislist.extend(tropical)
print(thislist)
#we can add any iterable objects like tuples,sets,dictionariesets using extend() method
#add elements of a tuple to a list
thislist = ["apple","banana","cherry"]
thistuple = ("kiwi","orange")
thislist.extend(thistuple)
print(thislist)
#removing elements froma a list
#remove "banana"
thislist = ["apple","banana","cherry"]
thislist.remove("banana")
print(thislist)
#removing specified index using pop()
#remove the second item
thislis = ["apple","banana","cherry"]
thislist.pop(1)
print(thislist)
#remove the last item
thislis = ["apple","banana","cherry"]
thislist.pop()
print(thislist)
#the del keyword also removes the specified index
thislis = ["apple","cherry","banana"]
del thislis[0]
print(thislist)
#delete the entire list
thislist = ["apple","banana","cherry"]
del thislist
#clear the list content
thislist = ["apple","banana","cherry"]
thislist.clear()
print(thislist)
#printing all the items in a list one by one
thislist = ["apple","banana","cherry"]
for x in thislist:
    print(x)
    #print all the items by refering to thier index number
    thislist = ["apple","banana","cherry"]
    for i in range(len(thislist)):
        print(thislist[i])
    #print all items using a while loop to go through all the index numbers
    thislis = ["apple","banana","cherry"]
    i = 0
    while i< len(thislist) :
        print(thislist[i])
        i = i+1
    #a short hand for loop that will print all items in a list
    thislist = ["apple","banana","cherry"]
    [print(x) for x in thislist]
    #list comprehension
    fruits = ["apple","banana","cherry","kiwi","mango"]
    newlist = []
    for x in fruits:
        if "a" in x:
            newlist.append(x)
            print(newlist)
#list comprehension the code becomes easier
fruits = ["apple","banana","cherry","kiwi","mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
#only accept items that are not apple
newlist = [x for x in fruits if x != "apple" ]
print(newlist)
#with no if statement
newlist = [x for x in fruits]
#we can use the range() function to create an iterable
newlist = [x for x in range(10)]
#accpet only numbers less than five
newlist = [x for x in range(10) if x < 5]
#set the values in the newlist to uppercase
newlist = [x.upper() for x in fruits]
#set all the values in the list to helo
newlist = ["hello" for x in fruits]
#return orange instead of banana
newlist = [x if x != "banana" else "orange" for x in fruits]
#sort the list alphabetically
thislist = ["orange" ,"mango","kiwi","pineapple","banana"]
thislist.sort()
print(thislist)
#sort this list numerically
thislist = [100,50,65,82,23]
thislist.sort()
print(thislist)
#sort the list descending
thislist = ["orange","mango","kiwi","pineapple","banana"]
thislist.sort(reverse =True)
print(thislist)
#sort the list descending
thislist  = ["orange", "mango" ,"kiwi","pineapple","banana"]
thislist.sort(reverse = True)
print(thislist)
#sort the list descending
thislist = [100,50,65,82,23]
thislist.sort(reverse = True)
print(thislist)
#sort the list based on how close the number is to 50
def myfunc(n):
    return abs(n-50)
    thislist = [100,50,65,82,23]
    thislist.sort(key = myfunc)
    print(thislist)
#case insensitive sort
thislist = ["banana","orange","kiwi","cherry"]
thislist.sort()
print(thislist)
#perform a case-insensitive sort of the list
thislist = ["banana","orange","kiwi","cherry"]
thislist.sort(key = str.lower)
print(thislist)
#reverse() method
thislist = ["banana","orange","kiwi","cherry"]
thislist.reverse()
print(thislist)
#make a copy of a list with the copy() method
thislist = ["apple", "banana","cherry"]
mylist = thislist.copy()
print(mylist)
#make a copy of alist with the list() method
thislist = ["apple","banana","cherry"]
mylist  = list(thislist)
print(mylist)
#join two list
list1 = ["a","b","c"]
list2 = [1,2,3]
list3 = list1+list2
print(list3)
#append list2 into list1
list1 = ["a","b","c"]
list2 = [1,2,3]
for x in list2:
    list1.append(x)
    print(list1)
#using extend()
list1 = ["a","b","c"]
list2 = [1,2,3]
list1.extend(list2)
print(list1)


'''
Brute Force would be for each index, multiply the numbers at all other index.
Time Complexity: O(n^2)

This improve this, how can we store information as we calculate the product of numbers? Sliding window

We can do 2 passes of the array:
1. Left to right - For each index, calculate the product of all nums to the left
2. Right to left - For each index, calculate the product of all nums to the right
With these two arrays, we can multiply the numbers at each index in both arrays together to get
the sum of all numbers in array except self.

Time Complexity: O(n)
Space Complexity: O(n)
'''

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:

        # Initialize arrays to ones
        leftProduct = [1] * len(nums)
        rightProduct = [1] * len(nums)
        output = [1] * len(nums)

        # Calculate product of all nums to left of each index
        prod = 1
        for i in range(1, len(nums)):
            prod *= nums[i - 1]
            leftProduct[i] = prod

        prod = 1
        # Calculate product of all nums to right of each index
        for i in range(len(nums) - 2, -1, -1):
            prod *= nums[i + 1]
            rightProduct[i] = prod

        # Multiply leftProduct with rightProduct to get product of all elements except self
        # at each index.
        for i in range(len(nums)):
            output[i] = leftProduct[i] * rightProduct[i]

        return output


T = int(input())
for t in range(0,T):
    a,b,c = map(int, input().split())

    lowerBound = a
    numOfDigit = len(str(lowerBound))
    upperBound = 10**numOfDigit - 1
    currentNumberCount = int((upperBound - lowerBound) / b) + 1;
    currentDigitCount = currentNumberCount * numOfDigit

    while currentDigitCount < c:
        c -= currentDigitCount
        lowerBound += b * currentNumberCount
        numOfDigit += 1
        upperBound = 10**numOfDigit - 1
        currentNumberCount = int((upperBound - lowerBound) / b) + 1;
        currentDigitCount = currentNumberCount * numOfDigit

    numPos = int(c / numOfDigit)
    if c % numOfDigit == 0:
        numPos -= 1

    numC = lowerBound + b * numPos

    c = c - numPos * numOfDigit - 1

    s = str(numC)
    digit = s[c]
    print(digit)


import pandas as pd, numpy as np
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

def parseInput(filename):

    file = open(filename)
    start = True
    prev_f = ""
    values = []
    board = []

    for f in file:
        if start:
            values.append(f[:-2])
            start = False
        else:
            if f!= "\n":
                board.append(f[:-1])
            else:
                values.append(board)
                board = []

    numbers = values[0]
    n_numbers = []
    ns = numbers.split(",")

    #Clean Called Numbers
    for n in ns:
        try:
            n = int(n)
            n_numbers.append(n)
        except:
            pass

    #Clean Boards
    values = values[2::]
    n_vals = []
    for board in values:
        new_board = []
        for row in board:
            new_row = []
            numbers = row.split(" ")
            for n in numbers:
                try:
                    n = int(n)
                    new_row.append(n)
                except:
                    pass
            new_board.append(new_row)
        n_vals.append(new_board)

    return n_numbers,n_vals

n_numbers,n_vals = parseInput("input4.txt")

def checkWinner(board,called_nums):
    for i in range(len(board)):
        col_total = 0
        row_total = 0
        for j in range(len(board)):
            if board[i][j] in called_nums:
                col_total +=1
            if board[j][i] in called_nums:
                row_total +=1
            if col_total == 5 or row_total == 5:
                return True
    return False

def findWinner(numbers,boards):
    called_nums=[]
    for num in numbers:
        called_nums.append(num)
        for board in boards:
            winner = checkWinner(board,called_nums)
            if winner:
                print(board)
                unmarked_sum = 0
                for i in range(len(board)):
                    for j in range(len(board)):
                        if board[i][j] not in called_nums:
                            unmarked_sum += board[i][j]
                final_score = unmarked_sum * num
                return final_score
    return False

called_nums = []

f_score = findWinner(n_numbers,n_vals)
print(f_score)

def findLastWinner(numbers,boards):
    called_nums=[]
    for num in numbers:
        called_nums.append(num)
        for board in boards:
            winner = checkWinner(board,called_nums)
            if winner and len(boards) > 1:
                boards.remove(board)
            elif winner:
                print(board)
                unmarked_sum = 0
                for i in range(len(board)):
                    for j in range(len(board)):
                        if board[i][j] not in called_nums:
                            unmarked_sum += board[i][j]
                final_score = unmarked_sum * num
                return final_score
    return False

f_loser_score = findLastWinner(n_numbers,n_vals)
print(f_loser_score)


# this is a really slow network scanner.
# the idea is that it will slowly poke around and check who's up and whos not
# over the course of a while, ideally without being discoverd or tripping over
# network detection systems. who knows if it works

import socket as s
import netifaces
import arprequest
import argparse
import netaddr
import time
import sys
import os
import common
from random import randint, random
from signal import signal, SIGINT

# set up arguments
parser = argparse.ArgumentParser(description="Slow network scanner")
parser.add_argument('-i', "--interface", metavar="<INTERFACE>", type=str, help="Interface to use when scanning", required=True)
parser.add_argument('-a', "--arp", dest="arpscan", action="store_true", help="Utilize ARP scanning instead of TCP connections")
parser.set_defaults(arpscan=False)

# some random ports to try to connect to while working
random_ports = [80, 443, 8080, 22]

# log file object
log_f = None

# global list of current ips
ips = []
alive_ips = []

# logs some stuff to stdout and log.txt
def log(string, e="\n"):
    global log_f
    if log_f == None:
        log_f = open('log.txt', 'w')

    log_f.write(string)
    print(string, end=e)

# CTRL-C handler
def sig_handler(signal_recvd, frame):
    global alive_ips
    global ips

    print("[INFO] Caught CTRL-C. Halting...")

    f = open(".resume", "w")

    for ip in ips:
        f.write(ip)
        f.write("\n")
    f.close()

    complete()

    sys.exit(1)

# cleans the resume file
def clear_resume():
    os.remove(".resume")

# done with scanning (either quit or completion)
def complete():
    global alive_ips

    # print info
    log("[INFO] COMPLETE")
    log("_" * 40)

    print("[INFO] Alive addresses:")

    for ip in alive_ips:
        print("\t{}".format(ip))

# generates a list of all valid IP addresses on the network
def generate_targets(interface):
    targets = []
    netstr = ""

    # generate the network string
    addr = netifaces.ifaddresses(interface)[2][0]['addr']
    netmask = netifaces.ifaddresses(interface)[2][0]['netmask']

    mask = [int(x) for x in netmask.split(".")]
    cidr = sum((bin(x).count('1') for x in mask))

    netstr = "{}/{}".format(addr, cidr)

    # add all of the valid hosts on the network to the target list
    net = netaddr.IPNetwork(netstr)

    for i in net.iter_hosts():
        targets.append(str(i))

    return targets

# main function
def run(interface, scantype=0):
    global ips
    global alive_ips

    # check if stuff has already been run
    if os.path.exists(".resume"):
        cont = input("[INFO] Detected previously incomplete run\n\tContinue? (y/n) > ").lower()
        if cont == 'n':
            # generate a new set
            ips = generate_targets(interface)
        else:
            print("[INFO] Resuming scan...")
            # read in the old data
            f = open(".resume", "r")
            dat = f.read()
            ips = dat.replace("\00", "").splitlines()[0:-1]
            f.close()
            print("[INFO] Remaining addresses: {}".format(len(ips)))

    else:
        ips = generate_targets(interface)

    # set up the terminating signal handler
    signal(SIGINT, sig_handler)
    num_ips = len(ips)
    total_done = 0

    # normal TCP scan type
    if scantype == 0:
        sock = s.socket(s.AF_INET, s.SOCK_STREAM)
        #sock.setsockopt()

        # loop over the addresses
        for i in range(num_ips):
            # randomly choose an ip from the list
            address = ips[randint(0, len(ips)-1)]
            # try to connect on random known port
            try:
                port = random_ports[randint(0, len(random_ports)-1)]
                log("[INFO] Trying {} on {} ({:>.1f}%)".format(address, port, total_done/len(ips)), e="\r")

                sock.connect((address, port))

                # what are the chances we get this far without exceptions?
                # low... but not impossible
                sock.close()
                alive_ips.append(address)
                log("[INFO] Address '{}' is up AND port '{}' is open".format(address, port))

            # host is up and port is closed
            except ConnectionRefusedError:
                alive_ips.append(address)
                log("[INFO] Address '{}' is up                ".format(address))

            # host is down
            except OSError:
                pass

            # user interrupt
            except KeyboardInterrupt:
                print("[CANCELED]")
                break

            # we have gotten the info we wanted on the address, so remove it
            ips.remove(address)

            total_done += 1
            time.sleep(random())

    # ARP IP scan
    elif scantype == 1:
        for i in range(num_ips):

            # choose an address
            address = ips[randint(0, len(ips)-1)]
            log("[INFO] Trying {} ({:>.1f}%)".format(address, total_done/len(ips)), e="\r")

            # create request
            alive = arprequest.ArpRequest(address, interface)
            if alive.request():
                alive_ips.append(address)
                log("[INFO] Address '{}' is up                ".format(address))

            # move on
            ips.remove(address)
            total_done += 1
            time.sleep(random())

    clear_resume()
    complete()

def main():
    # check privilages
    if not common.has_root():
        print("[ERROR] Insufficient privilages! Please run as root")
        sys.exit(1)

    args = parser.parse_args()
    scantype = 0
    interface = args.interface

    # see if we are scanning using ARP
    if args.arpscan:
        scantype = 1

    run(interface, scantype=1)

if __name__ == '__main__':
    main()


largura = int(input("Digite a largura: "))
altura = int(input("Digite a altura: "))

auxl = largura
auxa = altura

while altura > 0:
    while largura > 0:
        if altura == auxa or altura == 1:
            print('#', end = "")
        else:
            if largura == auxl or largura == 1:
                print('#', end = "")
            else:
                print(' ', end = "")
        largura = largura - 1
    largura = auxl
    altura = altura - 1
    print()


# 1. С клавиатуры вводится 7 значное число. Если четных цифр в нем больше, чем
# нечетных, то найти сумму всех его цифр, если нечетных больше, то найти
# произведение 1 3 и 6 цифры.

s = int(input("Введите 7ми значное число: "))

a = 0  # счетчик четных
b = 0  # счетчик нечетных
t = 0  # счетчик для суммы
#p = 1  # счетчик для произведения

s = str(s)
j = len(s)  # счетчик для знаков

print(j, 'знаков')

if j == 7:

    for i in s:
        i = int(i)
        t += i
        #p *= i

        if i % 2 == 0:
            a += 1
        else:
            b += 1
    print('Чётные: ', a, 'Нечётные: ', b)
    if a > b:
        print('Сумма: ', t)
    elif b > a:
        # print('Произведение: ', p)
        r = int(s[0]) * int(s[2]) * int(s[5])
        print('Произведение 1,3,6:', r)
else:
    print(' число должно быть 7ми значным. Повторите ввод!')

print('конец')


import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

img = cv.imread('tower.jpg', cv.IMREAD_GRAYSCALE)
img_data = []
rows, cols = img.shape

img_data.append(str(rows%256))
img_data.append(str(rows//256))

img_data.append(str(cols%256))
img_data.append(str(cols//256))

for row in range(rows):
	for col in range(cols):
		img_data.append(str(img[row][col]))

cv.imshow('image',img)
cv.waitKey(1000)

line_no = 0

while(True):
	f = open("updates.txt", "r")
	lines = f.readlines()
	while(line_no < len(lines)):
		coordinate, value = lines[line_no][:-1].split(' ')
		line_no += 1
		coordinate = int(coordinate) - 4
		value = int(value)
		try:
			img[coordinate//400][coordinate%400] = value
		except:
			pass
	cv.imshow('image',img)
	cv.waitKey(1)
cv.destroyAllWindows()


dados = dict()
gols = list()

dados['Nome'] = str(input('NOME DO JOGADOR: ')).strip().title()
p = int(input(f'QUANTAS PARTIDAS {dados["Nome"]} JOGOU? '))

cont = 0
for c1 in range(1, p+1):
    p = int(input(f'QUANTOS GOLS {dados["Nome"]} FEZ NA {c1}ª PARTIDA? '))
    gols.append(p)
    cont += p

dados['gols'] = gols
dados['Total'] = cont

print('-='*35)
print(dados)
print('-='*35)
for k, v in dados.items():
    print(f'{k}: {v}')
print('-='*35)
for p, g in enumerate(gols):
    print(f'    => NA PARTIDA {p + 1}, FEZ {g} GOLS.')
print(f'FOI UM TOTAL DE {dados["Total"]} GOLS.')


import numpy as np
from lime import lime_tabular

from ...base import Explainer

class LimeExplainer(Explainer):
    def __init__(self, train_ds, labels, *args, meta_prefix=None, **kwargs) -> None:
        super().__init__(*args, meta_prefix=meta_prefix, **kwargs)

        data = np.array([item["item"] for item in train_ds])
        self._explainer = lime_tabular.LimeTabularExplainer(
            data, feature_selection="none", training_labels=labels
        )
        self._labels = labels

    def predict(self, x, model):
        if not hasattr(model, "predict_proba"):
            raise ValueError("The model should have `predict_proba` method")

        explanations = []
        for item in x:
            ex = self._explainer.explain_instance(
                item,
                model.predict_proba,
                labels=self._labels,
                num_features=len(self._labels),
            )
            predicted_label = np.argmax(ex.predict_proba)
            ex = ex.as_map()[predicted_label]
            # Sorts by the feature order
            importance_scores = [item[1] for item in sorted(ex)]
            explanations.append(importance_scores)
        return np.asarray(explanations)


from matplotlib.colors import ListedColormap
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import numpy as np

def plot_decision_regions(X, y, classifier, test_idx = None, resolution = 0.02):
    labels = np.unique(y)
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'grey', 'cyan')
    cmap = ListedColormap(colors[:len(labels)])

    x1_min = X[:, 0].min() - 1
    x1_max = X[:, 0].max() + 1

    x2_min = X[:, 1].min() - 1
    x2_max = X[:, 1].max() + 1

    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))

    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)

    plt.contourf(xx1, xx2, Z, alpha = 0.3, cmap = cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    for idx, cl in enumerate(labels):
        plt.scatter(x = X[y == cl, 0], y = X[y == cl, 1], alpha = 0.8, c = colors[idx], marker = markers[idx], label = cl, edgecolor = 'black')

    if test_idx:
        X_test, y_test = X[test_idx, :], y[test_idx]

        plt.scatter(X_test[:, 0], X_test[:, 1], c = '', edgecolor = 'black', alpha = 1.0, linewidth = 1, marker = 'o', s = 100, label = 'test set')

def get_accuracy(prediction, target):
    assert len(prediction) == len(target)
    accuracy = accuracy_score(prediction, target)
    return accuracy

def get_mse(prediction, target):
    assert len(prediction) == len(target)
    n = len(prediction)
    dif = (prediction - target) ** 2
    s = dif.sum()
    return s / n


#%%
import re
import pandas as pd
import nltk
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import plotly.express as px
from termcolor import colored
from DataUtility import DataUtility

pd.set_option('display.max_rows', 100)
pd.options.display.max_colwidth = 200
pd.options.mode.chained_assignment = None
# this powers the word_tokenize function
nltk.download('punkt')

#%%
# read in data
url_scriptures = 'https://github.com/wilfordwoodruff/wilford_woodruff_hack23/raw/main/data/lds-scriptures.csv'
url_woodruff = "https://github.com/wilfordwoodruff/Main-Data/raw/main/data/derived/derived_data.csv"

data_scriptures = pd.read_csv(url_scriptures)
data_woodruff = pd.read_csv(url_woodruff)

data_woodruff = data_woodruff.query("`Document Type` == 'Journals'")

# data_woodruff2 = pd.read_csv('../data/data_woodruff.csv')
data_scriptures
data_woodruff

#%%

class Scriptures:

    def __init__(self, data_scriptures) -> None:
        self.data_scriptures = data_scriptures

    def clean(self):
        books = ["New Testament","Book of Mormon", "Docrtine and Covenants", "Pearl of Great Price"]
        self.data_scriptures = self.data_scriptures.query('volume_title == @books')
        self.data_scriptures['scripture_text'] = self.data_scriptures['scripture_text'].str.lower()

class WoodruffPapers:

    def __init__(self, data_woodruff, sample = True) -> None:
        if sample:
            self.data_woodruff = data_woodruff.sample(100)
        else:
            self.data_woodruff = data_woodruff

    # clean suggestions
    @staticmethod
    def clean_suggestions(string):
        pattern = r'\[\[(.*?)\]\]'
        suggestions = re.findall(pattern, string)
        for suggestion in suggestions:
            replacement = suggestion.split('|')[0] # split the words before and after the '|'
            suggestion_exact_match = '[[' + suggestion + ']]'
            string = string.replace(suggestion_exact_match, replacement)
        return string

    @staticmethod
    def clean_ampersands(string):
        string = DataUtility.replace_regex(string, r'\'', r"'")
        string = DataUtility.replace_regex(string, r'\&c', r"'")
        string = DataUtility.replace_regex(string, r'\&', r'and')
        # print(len(re.findall(r'\&', string)))
        return string

    @staticmethod
    def remove_birthyears(string):
        string = re.sub(r'(, b\.)', string)
        return string

    @staticmethod
    def fix_typos(string):
        DataUtility.replace_regex('travling', regex = r'', replacement = r'')

    def clean(self):
        # rename Text Only Transcript to 'text'
        self.data_woodruff = self.data_woodruff.rename(columns={"Text Only Transcript": "text"})
        self.data_woodruff['text'] = self.data_woodruff['text'].apply(DataUtility.replace_regex, regex = r'\[(\w+)\]')
        self.data_woodruff['text'] = self.data_woodruff['text'].apply(DataUtility.replace_regex, regex = r',', replacement = r'')
        self.data_woodruff['text'] = self.data_woodruff['text'].apply(DataUtility.replace_regex, regex = r'[\{\}\~]', replacement = r'')
        self.data_woodruff['text'] = self.data_woodruff['text'].apply(DataUtility.replace_regex, regex = r'\s{2}', replacement = r' ')
        self.data_woodruff['text'] = self.data_woodruff['text'].apply(DataUtility.remove_new_lines)
        self.data_woodruff['text'] = self.data_woodruff['text'].apply(WoodruffPapers.clean_suggestions)
        self.data_woodruff['text'] = self.data_woodruff['text'].apply(WoodruffPapers.clean_ampersands)
        # TODO: implement typos and symbols
        typos = {'sacrafice':'sacrifice',
                 'discours':'discourse'}
        symbols = {
                'b. 1795':'',
                '<U+25CA>':'',
                '&':'and',
                '&c':'and',
                ''':"'",
                '[FIGURE]':'',
                'discours':'discourse'
            }
        things_to_remove = ['WW 1841-2',
                            'Front cover',
                            'THE SECOND BOOK OF WILLFORD FOR 1839',
                            'W\. WOODRUFFs DAILY JOURNAL AND HISTORY IN 1842',
                            "WILFORD WOODRUFF's DAILY JOURNAL AND HISTORY IN 1843",
                            "WILLFORD WOODRUFF'S JOURNAL VOL\. 2\. AND A SYNOPSIS OF VOL\. 1\.",
                            "Willford Woodruff's Journal Containing an Account Of my life and travels from the time of my first connextion with the Church of Jesus Christ of Latter-day Saints",
                            'THE FIRST BOOK OF WILLFORD VOL\. 2\. FOR 1838',
                            r"WILLFORD\. WOORUFF's DAILY JOURNAL AND TRAVELS",
                            r"(\^?FIGURES?\^?)"]

        for regex in things_to_remove:
            self.data_woodruff = DataUtility.regex_filter(self.data_woodruff, column = 'text', regex=regex)
        # lowercase all entries
        self.data_woodruff['text'] = self.data_woodruff['text'].str.lower()

    def preprocess(self):
        self.data_woodruff['phrase'] = self.data_woodruff['text'].apply(DataUtility.split_string_into_list, n = 15)
        # explode dataset so each row contains a single 15 word phrase
        self.data_woodruff = self.data_woodruff.explode('phrase')

    @staticmethod
    def compute_match_percentage(text_woodruff, text_scripture):
        words_woodruff = DataUtility.split_string(text_woodruff)
        words_scripture = DataUtility.split_string(text_scripture)
        vectorizer = TfidfVectorizer()
        ### vectorize words
        # Compute TF-IDF matrices
        tfidf_matrix_woodruff = vectorizer.fit_transform(words_woodruff)
        tfidf_matrix_verse = vectorizer.transform(words_scripture)

        similarity_scores = cosine_similarity(tfidf_matrix_woodruff, tfidf_matrix_verse)
        vectorizer.get_feature_names_out()
        woodruff_word_match_ids   = np.unique(np.where(similarity_scores == 1)[0])
        scriptures_word_match_ids = np.unique(np.where(similarity_scores == 1)[1])
        percent_match_woodruff    = round(len(woodruff_word_match_ids) * 100 / len(words_woodruff), 2)
        return percent_match_woodruff

woodruff_papers = WoodruffPapers(data_woodruff, sample = True)
woodruff_papers.clean()

scriptures = Scriptures(data_scriptures)
scriptures.clean()

scriptures.data_scriptures
woodruff_papers.data_woodruff

#%%

woodruff_papers.preprocess()

woodruff_papers.data_woodruff

#%%
from tqdm import tqdm
results = pd.DataFrame()

for i in tqdm(range(10), desc='processing'):
    verse_title = list(woodruff_papers.data_scriptures['verse_title'])[i]
    text_scripture = list(woodruff_papers.data_scriptures.query('verse_title == @verse_title')['scripture_text'])[0]

    # print('comparing:', verse_title)

    data_sample['text_scripture'] = text_scripture
    data_sample['percentage_match'] = (data_sample['phrase'].apply(WoodruffPapers.compute_match_percentage,
                                                        text_scripture=text_scripture))
    data_sample.sort_values(by = 'percentage_match', ascending=False)

    if data_sample['percentage_match'].max() > 50:
        # print(colored('attaching results', 'green'), data_sample['percentage_match'].max())
        top_3_rows = data_sample.nlargest(3, 'percentage_match')[['phrase', 'text_scripture', 'percentage_match']]
        results = pd.concat([results, top_3_rows])

#%%
data_sample.to_csv('sample.csv', index = False)

#%%
## EDA
text_woodruff = DataUtility.combine_rows(woodruff_papers.data_woodruff.head(1000)['text'])
text_verse = DataUtility.combine_rows(woodruff_papers.data_scriptures.head(1000)['scripture_text'])

print(text_verse)
print(text_woodruff)
freq = DataUtility.create_frequency_distribution(text_woodruff)
print(freq.head(100))
freq.tail(100)

chart = px.bar(freq.head(100), x='frequency', y='word', text_auto='.2s',orientation='h')
chart.show()

# chart = px.bar(freq.tail(100), x='frequency', y='word', text_auto='.2s',orientation='h')
# chart.show()

# chart = px.bar(freq.tail(100), x='frequency', y='word', text_auto='.2s',orientation='h')
# chart.show()

#%%


from utils import timeit

@timeit
def get_data():
    data = []
    with open('input.txt') as input_file:
        for line in input_file:
            value = line.strip()
            data.append(value)
    return data

@timeit
def part_1(data):
    key_pad = [[i*3+j+1 for j in range(3)] for i in range(3)]
    x, y = 1, 1
    code = 0
    for line in data:
        for move in line:
            if move == 'U':
                if y > 0:
                    y -= 1
            elif move == 'D':
                if y < 2:
                    y += 1
            elif move == 'L':
                if x > 0:
                    x -= 1
            elif move == 'R':
                if x < 2:
                    x += 1
            else:
                raise ValueError('Unknown direction.')

        code *= 10
        code += key_pad[y][x]

    return code

@timeit
def part_2(data):

    key_pad = ( "#######",
                "###1###",
                "##234##",
                "#56789#",
                "##ABC##",
                "###D###",
                "#######")

    row, col = 3, 1
    code = []
    for line in data:
        for move in line:
            if move == 'U':
                if key_pad[row-1][col] != '#':
                    row -= 1
            elif move == 'D':
                if key_pad[row+1][col] != '#':
                    row += 1
            elif move == 'L':
                if key_pad[row][col-1] != '#':
                    col -= 1
            elif move == 'R':
                if key_pad[row][col+1] != '#':
                    col += 1

        code.append(key_pad[row][col])

    return ''.join(code)

def main():
    data = get_data()
    part_1(data)
    part_2(data)

if __name__ == "__main__":
    main()


import re

print("Rate, woran ich denke:")
for i in 1, 2, 3, 4, 5, 6, 7:

    z = input()
    if re.findall("[Ll]uhmann", z):     # finds "L/luhmann"
        print("Du kannst ja Gedanken lesen!")
        break
    else:
        print("Nö.")
print("Luhmann, du Eule.")


# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-11-26 16:07
import glob
import json
import re
from urllib.error import HTTPError
import os

from hanlp_common.io import load_json

from elit.datasets.srl.ontonotes4 import ONTONOTES4_TASKS_HOME, ONTONOTES4_HOME
from elit.datasets.srl.ontonotes5._utils import convert_jsonlines_to_IOBES
from elit.utils.io_util import get_resource, path_from_url
from elit.utils.log_util import cprint
from elit.utils.time_util import CountdownTimer

_ONTONOTES4_CHINESE_HOME = ONTONOTES4_HOME + 'files/data/chinese/annotations/'
_ONTONOTES4_CHINESE_TASKS_HOME = ONTONOTES4_TASKS_HOME + 'ner/chinese/'

ONTONOTES4_NER_4TYPES_CHINESE_TRAIN = _ONTONOTES4_CHINESE_TASKS_HOME + 'train.chinese.v4.ner.jsonlines'
ONTONOTES4_NER_4TYPES_CHINESE_DEV = _ONTONOTES4_CHINESE_TASKS_HOME + 'development.chinese.v4.ner.jsonlines'
ONTONOTES4_NER_4TYPES_CHINESE_TEST = _ONTONOTES4_CHINESE_TASKS_HOME + 'test.chinese.v4.ner.jsonlines'

ONTONOTES4_NER_4TYPES_CHINESE_TSV_TRAIN = _ONTONOTES4_CHINESE_TASKS_HOME + 'train.chinese.v4.ner.tsv'
ONTONOTES4_NER_4TYPES_CHINESE_TSV_DEV = _ONTONOTES4_CHINESE_TASKS_HOME + 'development.chinese.v4.ner.tsv'
ONTONOTES4_NER_4TYPES_CHINESE_TSV_TEST = _ONTONOTES4_CHINESE_TASKS_HOME + 'test.chinese.v4.ner.tsv'

ENAMEX = re.compile('<ENAMEX TYPE=\"(\w+?)\".*?>(.+?)</ENAMEX>')

try:
    get_resource(ONTONOTES4_HOME, verbose=False)
except HTTPError:
    intended_file_path = path_from_url(ONTONOTES4_HOME)
    cprint('Ontonotes 4.0 is a [red][bold]copyright[/bold][/red] dataset owned by LDC which we cannot re-distribute. '
           f'Please apply for a licence from LDC (https://catalog.ldc.upenn.edu/LDC2011T03) '
           f'then download it to {intended_file_path}')
    exit(1)

def load_ner(name_file):
    with open(name_file) as src:
        lines = src.readlines()
        lines = lines[1:-1]  # remove <DOC> and </DOC>
        sentences = []
        ner = []
        for line in lines:
            line = line.strip()
            if not line:
                continue
            if line == 'ＥＭＰＴＹ':
                continue
            tokens = []
            entities = []
            offset = 0
            for entity in ENAMEX.finditer(line):
                b, e = entity.span()
                if b > offset:
                    form = line[offset:b]
                    words = tokenize(form)
                    tokens.extend(words)
                tag = entity.group(1).strip()
                form = entity.group(2).strip()
                words = tokenize(form)
                # According to Named Entity Recognition with Bilingual Constraints:
                # In this paper, we selected the four most common named entity types,
                # i.e., PER (Person), LOC (Location), ORG (Organization) and GPE (Geo-Political Entities)
                if tag in ('PERSON', 'LOC', 'ORG', 'GPE'):
                    entities.append((len(tokens), len(tokens) + len(words) - 1, tag))
                tokens.extend(words)
                offset = e
            if offset < len(line):
                form = line[offset:]
                words = tokenize(form)
                tokens.extend(words)

            sentences.append(tokens)
            ner.append(entities)
            # print(tokens)
            # print([(tokens[b: e + 1], l) for b, e, l in entities])
        return {'doc_key': '/'.join(name_file.split(os.path.sep)[-4:])[:-len('.name')], 'sentences': sentences,
                'ner': ner}

def tokenize(form):
    words = [x.strip() for x in form.split()]
    words = [x for x in words if x]
    return words

def make_ner_jsonlines_if_needed():
    root = get_resource(ONTONOTES4_HOME)
    jsonfiles = dict(zip(['train', 'dev', 'test'], [os.path.join(root, x[len(ONTONOTES4_HOME):]) for x in
                                                    [ONTONOTES4_NER_4TYPES_CHINESE_TRAIN,
                                                     ONTONOTES4_NER_4TYPES_CHINESE_DEV,
                                                     ONTONOTES4_NER_4TYPES_CHINESE_TEST]]))
    if all(os.path.isfile(x) for x in jsonfiles.values()):
        return

    for file in jsonfiles.values():
        os.makedirs(os.path.dirname(file), exist_ok=True)

    zh_root = get_resource(_ONTONOTES4_CHINESE_HOME)
    name_files = glob.glob(f'{zh_root}/**/*.name', recursive=True)
    fps = dict((k, open(v, 'w', encoding='utf-8')) for k, v in jsonfiles.items())
    # glyce = load_json('data/ner/ontonotes4/splits.json')
    # glyce_splits = dict()
    # unsure = set()
    # for portion, sents in glyce.items():
    #     for sent in sents:
    #         sent = sent.replace('TYPE=\"PRODUCT\"E_OFF=\"1\">', '')
    #         exsisting = glyce_splits.get(sent, None)
    #         if exsisting and exsisting != portion:
    #             print(f'Conflict {sent} in both {exsisting} and {portion}')
    #             unsure.add(sent)
    #         glyce_splits[sent] = portion
    timer = CountdownTimer(len(name_files))
    for file in sorted(name_files):
        # According to Named Entity Recognition with Bilingual Constraints:
        # This corpus includes about 400 document pairs (chtb 0001-0325, ectb 1001-1078).
        # We used odd-numbered documents as development data and even-numbered documents as test data.
        # We used all other portions of the named entity annotated corpus as training data for the monolingual systems
        basename = os.path.basename(file)
        genre, remaining = basename.split('_')
        fid = int(remaining[:-len('.name')])
        if genre in ('chtb', 'ectb') and (1 <= fid <= 325 or 1001 <= fid <= 1078):
            if fid % 2:
                portion = 'dev'
            else:
                portion = 'test'
        else:
            portion = 'train'
        timer.log(f'Pre-processing {basename} to {portion} set [blink][yellow]...[/yellow][/blink]')
        doc = load_ner(file)
        # for sent in doc['sentences']:
        #     text = ''.join(sent)
        #     expected_portion = glyce_splits.get(text, None)
        #     # from difflib import SequenceMatcher
        #     # similar_keys = sorted(glyce_splits.keys(),
        #     #                       key=lambda k: SequenceMatcher(None, k, text).ratio(),
        #     #                       reverse=True)[:5]
        #     if expected_portion != portion and text not in unsure:
        #         print(text)
        fps[portion].write(json.dumps(doc, ensure_ascii=False) + '\n')
    for f in fps.values():
        f.close()

def make_ner_tsv_if_needed():
    root = get_resource(ONTONOTES4_HOME)
    tsv_files = [os.path.join(root, x[len(ONTONOTES4_HOME):]) for x in
                 [ONTONOTES4_NER_4TYPES_CHINESE_TSV_TRAIN, ONTONOTES4_NER_4TYPES_CHINESE_TSV_DEV,
                  ONTONOTES4_NER_4TYPES_CHINESE_TSV_TEST]]

    if all(os.path.isfile(x) for x in tsv_files):
        return

    for file in tsv_files:
        os.makedirs(os.path.dirname(file), exist_ok=True)

    for j, t in zip(
            [ONTONOTES4_NER_4TYPES_CHINESE_TRAIN, ONTONOTES4_NER_4TYPES_CHINESE_DEV,
             ONTONOTES4_NER_4TYPES_CHINESE_TEST],
            tsv_files):
        convert_jsonlines_to_IOBES(j, t, doc_level_offset=False, normalize_token=True)

make_ner_jsonlines_if_needed()
make_ner_tsv_if_needed()


import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
import pandas as pd
from scipy.stats import hmean
from productiecapaciteit.src.capaciteit_strang import strangWeerstand
import numpy as np
from scipy.optimize import least_squares
from scipy import linalg
from dawacotools import get_daw_ts_meteo

from productiecapaciteit.src.strang_analyse_fun2 import (
    get_config,
    get_false_measurements,
)
from wvp_transient_funs import objective
from wvp_transient_funs import dis

from productiecapaciteit.src.weerstand_pandasaccessors import LeidingResistanceAccessor
from productiecapaciteit.src.weerstand_pandasaccessors import WellResistanceAccessor
from productiecapaciteit.src.weerstand_pandasaccessors import WvpResistanceAccessor

data_fd = os.path.join("..", "data")
config_fn = "strang_props6.xlsx"
config = get_config(os.path.join(data_fd, config_fn))

r = 0.6
kD0 = 200.0  # m/d2 at reference temperature
c = 50.0  # d
S = 0.2

strang = "Q200" # "IK102"
ci = config.loc[strang]

# get observations
df_fp = os.path.join(data_fd, "Merged", f"{strang}-PKA-DSEW036680.feather")
df = pd.read_feather(df_fp)
df["Datum"] = pd.to_datetime(df["Datum"])
df.set_index("Datum", inplace=True)
include_rules = ["Unrealistic flow"]
untrusted_measurements = get_false_measurements(
    df, ci, extend_hours=1, include_rules=include_rules
)
df = df.loc[~np.array(untrusted_measurements)]
df = df.loc[~np.isnan(df.Q)]
dfm = df.resample("12h", label="right").mean()
dfm = dfm.loc[~np.isnan(dfm.Q)]

# get initial estimates
filterweerstand_fp = os.path.join(
    "..", "results", "Filterweerstand", "Filterweerstand_modelcoefficienten.xlsx"
)
wvpweerstand_fp = os.path.join(
    "..", "results", "Wvpweerstand", "Wvpweerstand_modelcoefficienten.xlsx"
)
df_a_wvp = pd.read_excel(wvpweerstand_fp, sheet_name=strang, index_col=0).squeeze(
    "columns"
)

# initial, lower limit, upper limit
params = dict(
    alpha=[(r**2 * S / 4) ** 0.5, 0.0, 100 * (r**2 * S / 4) ** 0.5],
    beta=[(1 / (c * S)) ** 0.5, 0.0, (1 / (c * S)) ** 0.5],
    kD0=[140.0, 50.0, 500.0],
    time_delta=[df_a_wvp.temp_delta, 0.0, 10.0],
    temp_time_offset=[df_a_wvp.time_offset, 31 + 2 * 20, 365],
    # alpha_multi=[(1**2 * S / 4) ** 0.5, 0.0, 100 * (1**2 * S / 4) ** 0.5],
    alpha_multi=[2.7, 0.1, 25.]
)

dx_put = int(ci.dx_tussenputten)
dx_mirrorwell = pd.eval(ci.dx_mirrorwell)  # [li for li in pd.eval(ci.dx_mirrorwell) if li[1] < 200]
nput_model = 15

multiwell = (
    [(li[0], 2 * li[1]) for li in dx_mirrorwell] +
    [(2, i * dx_put) for i in range(1, nput_model + 1)] +
    [(li[0], 2 * dis(i * dx_put, 2 * li[1])) for li in dx_mirrorwell for i in range(1, nput_model + 1)]
)
ds_rain = get_daw_ts_meteo('235', "Neerslag")
pextra = dict(
    index=dfm.index.values[:-1],
    drawdown_obs=(dfm.pandpeil - dfm.gws0).values[:-1],
    Q_obs=dfm.Q.values[1:] / ci.nput,
    temp_ref=dfm.gwt0.median(),
    dt_lower=pd.Timedelta(value=hmean(np.diff(dfm.index) / pd.Timedelta(1, unit='D')), unit="D"),
    multiwell_contains_r_self=False,
    multiwell=multiwell,
    # rain=np.interp(dfm.index[1:], ds_rain.index, ds_rain),
    frac_step_max=0.95
)
assert np.isnan(pextra["Q_obs"]).sum() == 0

args = [i[0] for i in params.values()]

res = least_squares(
    objective,
    x0=[i[0] for i in params.values()],
    bounds=([i[1] for i in params.values()], [i[2] for i in params.values()]),
    # loss="arctan",
    f_scale=0.5,
    kwargs=pextra
)

def get_perr(res):
    if np.any(res.active_mask):
        print(f"{res.active_mask} True for params at bounds")
    U, s, Vh = linalg.svd(res.jac, full_matrices=False)
    tol = np.finfo(float).eps * s[0] * max(res.jac.shape)
    w = s > tol
    cov = (Vh[w].T / s[w]**2) @ Vh[w]  # robust covariance matrix
    chi2dof = np.sum(res.fun**2) / (res.fun.size - res.x.size)
    cov *= chi2dof
    perr = np.sqrt(np.diag(cov))
    perr_rel = perr / res.x

    sl = []
    for xi, perr_ri in zip(res.x, perr_rel):
        sl.append(f"{xi} +/- {perr_ri * 100:.1f}%")

    print('\n'.join(sl))
    return perr

perr = get_perr(res)
a = objective(res.x, return_result=True, **pextra)
plt.plot(pextra["index"], pextra["drawdown_obs"])
plt.plot(pextra["index"], a)

"""
0.11959938975024936 +/- 121.1%
0.3798944820153483 +/- 6.6%
179.63725616239432 +/- 59.3%
6.058479229670381 +/- 5.5%
176.36014752388652 +/- 0.9%
0.16542716576149427 +/- 44.2%
"""
# a = objective((alpha, beta, kD0, temp_delta, temp_time_offset))
print("hoi")


with open('day4/input.txt') as input:
    lines = input.readlines()
    total_part1 = 0
    total_part2 = 0

    def intersection(lst1, lst2):
        return list(set(lst1) & set(lst2))

    for line in lines:
        pair = line.split(',')
        first_elf_section, second_elf_section = pair[0].split('-'), pair[1].split('-')

        #lists containing the ranges of the sections
        first_elf_range = []
        second_elf_range = []

        #build ranges for each line
        for i in range(int(first_elf_section[0]), int(first_elf_section[1])+1):
            first_elf_range.append(i)
        for i in range(int(second_elf_section[0]), int(second_elf_section[1])+1):
            second_elf_range.append(i)

        #part 1
        if all(section in first_elf_range for section in second_elf_range) or all(section in second_elf_range for section in first_elf_range):
            total_part1 += 1

        #part2
        if intersection(first_elf_range, second_elf_range):
            total_part2 += 1

print(total_part1)
print(total_part2)


from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_csv('/home/filip/Desktop/MachineLearning/dataset.csv')
#df.drop('date',axis=1)
y = df['deaths']
X = df[['cases','date']]
benchmark = []
knn = KNeighborsClassifier(n_neighbors = 2)

#Benchmark na test_size
i=0
testSplitNumber=0
XAxisNumbers=[]
XAxisCounter=0
testSplitNumberExponent=0.01
whileLoopLenght = 1 / testSplitNumberExponent -5
while i<=whileLoopLenght:
	print("benchmark loop: ",i)
	testSplitNumber+=testSplitNumberExponent
	XAxisCounter+=testSplitNumberExponent*100
	X_train,X_test, y_train,y_test = train_test_split(X,y,test_size = testSplitNumber, random_state=20)
	knn.fit(X_train,y_train)
	benchmark.append(round(knn.score(X_test,y_test),3)*100)
	XAxisNumbers.append(XAxisCounter)
	i+=1

#Predikce s optimální test_size
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.16, random_state=20)
knn.fit(X_train,y_train)

print("\n \n \n \n")
print("accuracy: ",round(knn.score(X_test,y_test),3)*100,"%")
print("\n accuracy raw:", knn.score(X_test,y_test))

plt.plot(benchmark)
plt.ylabel('Model accuracy %')
plt.xlabel('Size of train split %')
plt.show()
#print(y)


# ******************************************************************************
## GLOBIO - https://www.globio.info
## PBL Netherlands Environmental Assessment Agency - https://www.pbl.nl.
## Reuse permitted under Gnu Public License, GPL v3.
# ******************************************************************************

import os
import numpy as np

import GlobioModel.Core.Error as Err
import GlobioModel.Core.Globals as GLOB
import GlobioModel.Core.Logger as Log
import GlobioModel.Core.Monitor as MON

from GlobioModel.Core.CalculationBase import CalculationBase
from GlobioModel.Core.Raster import Raster
import GlobioModel.Core.RasterUtils as RU

#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
class GLOBIO_CalcAquaticRiverFRHLUMSA(CalculationBase):
  """
  Creates a raster with the landuse MSA for rivers.
  """

  #-------------------------------------------------------------------------------
  def run(self,*args):
    """
    IN EXTENT Extent
    IN CELLSIZE CellSize
    IN RASTER FRHLU
    IN RASTER RiverFractions
    IN FLOAT FACTOR_A
    OUT RASTER RiverFRHLUMSA
    """
    self.showStartMsg(args)

    # Check number of arguments.
    if len(args)<=5:
      Err.raiseGlobioError(Err.InvalidNumberOfArguments2,len(args),self.name)

    # Get arguments.
    extent = args[0]
    cellSize = args[1]
    frhluRasterName = args[2]
    riverFractionsRasterName = args[3]
    FACTOR_A = args[4]
    outRasterName = args[5]

    # Check arguments.
    self.checkExtent(extent)
    self.checkCellSize(cellSize)
    self.checkRaster(frhluRasterName)
    self.checkRaster(riverFractionsRasterName)
    self.checkFloat(FACTOR_A,-100.0,100.0)
    self.checkRaster(outRasterName,True)

    # Align extent.
    extent = RU.alignExtent(extent,cellSize)

    # Set members.
    self.extent = extent
    self.cellSize = cellSize
    self.outDir = os.path.dirname(outRasterName)

    # Enable monitor en show memory and disk space usage.
    MON.showMemDiskUsage(Log,"- ","",self.outDir)

    #-----------------------------------------------------------------------------
    # Read the fractions raster, prepare and select.
    #-----------------------------------------------------------------------------

    # Reads the raster and resizes to extent and resamples to cellsize.
    riverFractionsRaster = self.readAndPrepareInRaster(extent,cellSize,riverFractionsRasterName,"river fractions")

    # Create the mask. Select fraction > 0.0.
    Log.info("Selecting river fractions...")
    fracMask = (riverFractionsRaster.r > 0.0)

    # Close and free the fractions raster.
    riverFractionsRaster.close()
    riverFractionsRaster = None

    #-----------------------------------------------------------------------------
    # Read the FRHLU raster, prepare and select.
    #-----------------------------------------------------------------------------

    # Reads the raster and resizes to extent and resamples to cellsize.
    frhluRaster = self.readAndPrepareInRaster(extent,cellSize,frhluRasterName,"FRHLU")

    #-----------------------------------------------------------------------------
    # Create output raster.
    #-----------------------------------------------------------------------------

    # Create MSA raster.
    # Initialize with NoData.
    Log.info("Creating MSA raster...")
    noDataValue = -999.0
    outRaster = Raster(outRasterName)
    outRaster.initRaster(extent,cellSize,np.float32,noDataValue)

    #-----------------------------------------------------------------------------
    # Calculate river FRHLU MSA.
    #-----------------------------------------------------------------------------

    # Get data mask.
    dataMask = frhluRaster.getDataMask()

    # Combine masks.
    dataMask = np.logical_and(fracMask,dataMask)

    # Cleanup mask.
    fracMask = None

    # MSA = 1.0 - a * FRHLU
    outRaster.r[dataMask] = frhluRaster.r[dataMask]
    outRaster.r[dataMask] *= FACTOR_A
    outRaster.r[dataMask] *= -1.0
    outRaster.r[dataMask] += 1.0

    # Cleanup mask.
    dataMask = None

    #-----------------------------------------------------------------------------
    # Save output.
    #-----------------------------------------------------------------------------

    # Save the MSA raster for river FRHLU.
    Log.info("Writing MSA for river FRHLU...")
    outRaster.write()

    # Cleanup.
    outRaster.close()
    outRaster = None

    # Show used memory and disk space.
    MON.showMemDiskUsage()

    self.showEndMsg()

#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
if __name__ == "__main__":
  try:
    outDir = r"C:\Temp\_Globio4\out"
    if not os.path.isdir(outDir):
      outDir = r"G:\Data\out_v3"
    inDir = outDir

    pCalc = GLOBIO_CalcAquaticRiverFRHLUMSA()

    ext = GLOB.extent_World
    cs = GLOB.cellSize_30sec
    lu = os.path.join(inDir,"frhlu.tif")
    frac = os.path.join(inDir,"river_fractions.tif")
    F_A = 0.70
    out = os.path.join(outDir,"river_frhlu_msa.tif")

    if RU.rasterExists(out):
      RU.rasterDelete(out)

    pCalc.run(ext,cs,lu,frac,F_A,out)
  except:
    Log.err()


from fastai.vision.all import *
from fastai.vision.all import cnn_learner #imports relevant libraries to create a CNN model

from fastaudio.core.all import *
from fastaudio.augment.all import *
from fastaudio.ci import skip_if_ci       #imports relevant libraries to prepare audio data

from pandas.api.types import is_string_dtype, is_numeric_dtype, is_categorical_dtype #imports library for dataframe manipulation
import json #imports library for JSON manipulation
import os   #imports library for directory control
import traceback #library to produce error traces

#function designed to create a JSON file
def writeToJSONFile(fileName,data):
    with open(fileName,'w') as fp:
        json.dump(data,fp)

@skip_if_ci
#function designed to train a cnn model
def run_learner():
    # epochs are a bit longer due to the chosen melspectrogram settings
    learn.fine_tune(10,cbs = CSVLogger())
    out  = pd.read_csv('history.csv')
    print(out.to_string())
    values = {}
    results = []
    print(type(out.to_string()))
    results.append(out.to_string())
    values['results'] = results
    writeToJSONFile('results.json',values) #creates a results json file

try:
    with open("..\experiments\experiment.json", "r") as read_file:
        data = json.load(read_file)
        path = data['train'] #fetches necessary file paths
        for file in os.listdir(os.path.abspath(path)):
            if file.endswith(".csv") and file!='dataset.csv':
                df = pd.read_csv(path+"\\"+file) #initialises dataframe
                break
        #identifies files and their labels
        x = str('filename')
        y = str('label')
        z = path + '\\'

        #Describes necessary data preprocessing for training
        cfg = AudioConfig.BasicMelSpectrogram(n_fft=512)
        a2s = AudioToSpec.from_cfg(cfg)
        item_tfms = [ResizeSignal(4500),a2s]

        #initialises a data block from the dataset
        auds = DataBlock(blocks = (AudioBlock, CategoryBlock),
                         get_x = ColReader(x, pref=z),
                         splitter = TrainTestSplitter(test_size=0.2, random_state=42, stratify=None, shuffle=True),
                         item_tfms = item_tfms,
                         get_y = ColReader(y))

        #converts data block into a data loader
        dbunch = auds.dataloaders(df, bs=32,num_workers=0)
        learn = cnn_learner(dbunch,
                    resnet18,
                    n_in=1,  # <- This is the only audio specific modification here
                    loss_func=CrossEntropyLossFlat(),
                    metrics=[accuracy,error_rate])

        os.chdir(data['trained_cnn'])#changes directory for storing results and exported model

        run_learner() #trains the cnn
        learn.export()#outputs the trained model as a .pkl file
except Exception:
    traceback.print_exc()


from django.http import HttpResponse
from django.shortcuts import render, redirect
from myapp.models import  *
from django.contrib import messages

def show_about_page(request):
    print("requesting show about page")
    name="Channel name is Learn Code with Durgesh"
    link="https://www.youtube.com/watch?v=697_0UGxDPk&t=182s"
    data={
        "name":name,
        "link":link
    }
    return render(request,"about.html",data)

def show_home_page(request):
    images = Image.objects.all()
    cats = Category.objects.all()
    data = {"images":images,"cats":cats}
    return render(request,"home.html",data)

def show_category(request,cid):
    cats = Category.objects.all()
    category=Category.objects.get(pk=cid)

    images = Image.objects.filter(cat=category)
    data = {"images": images, "cats": cats}
    return render(request, "home.html", data)

def home(request):
    return redirect('/home')

def search(request):
    query = request.GET['query']
    if len(query) > 78:
        images = Image.objects.none()
    else:
        imageTitle = Image.objects.filter(title__icontains=query)
        imageDescription = Image.objects.filter(description__icontains=query)
        images = imageTitle.union(imageDescription)

    if images.count() == 0:
        messages.warning(request,"No search results found. Please refine your query")
    cats = Category.objects.all()
    data = {"images": images,"cats": cats,"query":query}
    return render(request,"search.html",data)


import random
from PyQt6.QtWidgets import QPushButton, QApplication, QMainWindow, QWidget, QGridLayout, QLabel
from PyQt6.QtGui import QAction, QIcon
from PyQt6.QtMultimedia import QSoundEffect
from PyQt6.QtCore import QSize, Qt, QCoreApplication, QPoint, QPropertyAnimation, QUrl
from PyQt6 import QtCore

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("Minesweeper by Arthur Dubovik")
        self.setWindowIcon(QIcon("./img/mine.png"))

        #Sounds
        self.sound_click = QSoundEffect()
        self.sound_click.setSource(QUrl.fromLocalFile("./sound/click.wav"))
        self.sound_click.setVolume(0.5)
        self.sound_mine_check = QSoundEffect()
        self.sound_mine_check.setSource(QUrl.fromLocalFile("./sound/mine_check.wav"))
        self.sound_mine_check.setVolume(0.25)
        self.sound_mine_press = QSoundEffect()
        self.sound_mine_press.setSource(QUrl.fromLocalFile("./sound/mine_press.wav"))
        self.sound_mine_press.setVolume(0.25)
        self.sound_win = QSoundEffect()
        self.sound_win.setSource(QUrl.fromLocalFile("./sound/sound_win.wav"))
        self.sound_win.setVolume(0.5)

        #Button icons
        self.img_banner = QIcon("./img/banner.png")
        self.img_mine = QIcon("./img/mine.png")
        self.img_false_mine = QIcon("./img/false_mine.png")
        self.img_explode = QIcon("./img/explode_mine.png")

        #New game button
        button_action = QAction("New game", self)
        button_action.triggered.connect(self.new_game)

        #Difficult buttons
        self.button_action2_1 = QAction("10", self)
        self.button_action2_1.setCheckable(True)
        self.button_action2_1.setChecked(True)
        self.button_action2_1.triggered.connect(self.change_diff)

        self.button_action2_2 = QAction("25", self)
        self.button_action2_2.setCheckable(True)
        self.button_action2_2.triggered.connect(self.change_diff)

        self.button_action2_3 = QAction("40", self)
        self.button_action2_3.setCheckable(True)
        self.button_action2_3.triggered.connect(self.change_diff)

        #Field size buttons
        self.button_action3_1 = QAction("12 x 12", self)
        self.button_action3_1.setCheckable(True)
        self.button_action3_1.setChecked(True)
        self.button_action3_1.triggered.connect(self.change_size)

        self.button_action3_2 = QAction("16 x 16", self)
        self.button_action3_2.setCheckable(True)
        self.button_action3_2.triggered.connect(self.change_size)

        self.button_action3_3 = QAction("20 x 20", self)
        self.button_action3_3.setCheckable(True)
        self.button_action3_3.triggered.connect(self.change_size)

        #Exit button
        button_action4 = QAction("Exit", self)
        button_action4.triggered.connect(QCoreApplication.instance().quit)

        #Creating menu bar
        menu = self.menuBar()

        file_menu = menu.addMenu("Menu")
        file_menu.addAction(button_action)
        #_______________________
        file_menu.addSeparator()
        file_submenu = file_menu.addMenu("Difficult")
        file_submenu.addAction(self.button_action2_1)
        file_submenu.addAction(self.button_action2_2)
        file_submenu.addAction(self.button_action2_3)

        file_submenu = file_menu.addMenu("Field size")
        file_submenu.addAction(self.button_action3_1)
        file_submenu.addAction(self.button_action3_2)
        file_submenu.addAction(self.button_action3_3)
        #_______________________
        file_menu.addSeparator()
        file_menu.addAction(button_action4)

    #Filling the playing field with buttons
    def init(self, height=12, width=12, mines=10):
        #List of buttons
        self.CELLS = []
        #Field size (number of buttons)
        self.HEIGHT = height
        self.WIDTH = width
        #Number of buttons with mines
        self.MINES = mines
        #Number of buttons marked with a flag
        self.CHECK_BUTTONS = 0
        #List of coordinates with cells of correctly marked mines
        self.CHECKED_MINES = []
        #Button size
        self.BUTTON_HEIGHT = self.BUTTON_WIDTH = 38
        #Padding between buttons
        self.BUTTON_INDENT = 1

        #Arrangement of elements in the window
        self.layout = QGridLayout()
        self.widget = QWidget()
        self.widget.setLayout(self.layout)
        self.setCentralWidget(self.widget)

        #Fixed size of the playing field for the number of buttons
        self.WIDTH_SIZE = self.HEIGHT * self.BUTTON_HEIGHT + (self.HEIGHT - 1) * self.BUTTON_INDENT
        self.HEIGHT_SIZE = self.WIDTH * self.BUTTON_WIDTH + (self.WIDTH - 1) * self.BUTTON_INDENT
        self.setFixedSize(QSize(self.WIDTH_SIZE+30, self.HEIGHT_SIZE+40))

        #Creating a grid of buttons
        for i in range(self.HEIGHT):
            for j in range(self.WIDTH):
                self.button = QPushButton("Button ", self)

                #Setting the size of buttons
                self.button.setFixedSize(QSize(self.BUTTON_HEIGHT, self.BUTTON_WIDTH))

                self.button.setCheckable(True)
                self.button.setText('')
                self.button.clicked.connect(self.open_cell)

                #Flag of the pressed button
                self.button.is_pressed = False
                #Flag of a marked mine
                self.button.mine_note = False
                #Status of the buttons after the victory
                self.button.win = False

                #Redefining the right mouse button
                self.button.installEventFilter(self)
                self.layout.addWidget(self.button, i, j)

                #Setting coordinates to buttons
                self.button.x = i
                self.button.y = j

                #Adding buttons to the list
                self.CELLS.append(self.button)

        #Victory label
        self.btn = QLabel(self)
        self.btn.setText('You win!')
        self.btn.resize(200, 60)
        self.btn.setStyleSheet('QLabel {font: bold 44px;}')
        self.btn.hide()

    #Victory
    def victory(self):
        self.btn.show()
        animation = QPropertyAnimation(self.btn, b'pos', self)
        animation.setKeyValueAt(0, QPoint(20, 30))
        animation.setKeyValueAt(0.65, QPoint(self.HEIGHT_SIZE - 200, self.WIDTH_SIZE - 100))
        animation.setKeyValueAt(1, QPoint(int((self.HEIGHT_SIZE - 200) / 2), int((self.WIDTH_SIZE - 100) / 2)))
        animation.setDuration(20000)
        animation.start()
        self.sound_win.play()

    #New game event
    def new_game(self):
        self.sound_win.stop()
        self.btn.hide()
        self.new = False

        window.init(self.HEIGHT, self.WIDTH, self.MINES)
        pole_game.pole = []
        pole_game.init(self.HEIGHT, self.WIDTH, self.MINES)

    #Changing the difficulty
    def change_diff(self):
        sender = self.sender()
        sender.setChecked(True)
        if sender.text() == "10":
            self.MINES = 10
            self.button_action2_2.setChecked(False)
            self.button_action2_3.setChecked(False)
            self.new_game()

        if sender.text() == "25":
            self.MINES = 25
            self.button_action2_1.setChecked(False)
            self.button_action2_3.setChecked(False)
            self.new_game()

        if sender.text() == "40":
            self.MINES = 40
            self.button_action2_1.setChecked(False)
            self.button_action2_2.setChecked(False)
            self.new_game()

    #Field size selection
    def change_size(self):
        sender = self.sender()
        sender.setChecked(True)
        if sender.text() == "12 x 12":
            self.HEIGHT = self.WIDTH = 12
            self.button_action3_2.setChecked(False)
            self.button_action3_3.setChecked(False)
            self.new_game()

        if sender.text() == "16 x 16":
            self.HEIGHT = self.WIDTH = 16
            self.button_action3_1.setChecked(False)
            self.button_action3_3.setChecked(False)
            self.new_game()

        if sender.text() == "20 x 20":
            self.HEIGHT = self.WIDTH = 20
            self.button_action3_1.setChecked(False)
            self.button_action3_2.setChecked(False)
            self.new_game()

    #Opening a field by click
    def open_cell(self):

        #The object of the pressed button
        sender = self.sender()
        sender.setChecked(True)
        if sender.mine_note != True and sender.is_pressed == False:
            self.sound_click.play()
            sender.is_pressed = True

            #Number of buttons pressed
            self.PRESS_BUTTONS = len(list(filter(self.check_true, [i.is_pressed for i in self.CELLS])))

            #Checking the victory conditions (if the last closed cell opens)
            self.win_check()

            #Clicking on a mine
            if pole_game.pole[sender.x][sender.y].mine == True:
                self.sound_mine_press.play()
                self.mine_press(sender)
            #Counting the mines around the pressed button
            elif pole_game.pole[sender.x][sender.y].around_mines > 0:
                    sender.setText(str(pole_game.pole[sender.x][sender.y].around_mines))

                    #Number custom colors
                    if sender.text() == '1':
                        sender.setStyleSheet('QPushButton {color: #3F51B5; font: bold 20px;}')
                    if sender.text() == '2':
                        sender.setStyleSheet('QPushButton {color: #8B0000; font: bold 20px;}')
                    if sender.text() == '3':
                        sender.setStyleSheet('QPushButton {color: #FF0000; font: bold 20px;}')
                    if sender.text() == '4':
                        sender.setStyleSheet('QPushButton {color: #03A9F4; font: bold 20px;}')
                    if sender.text() == '5':
                        sender.setStyleSheet('QPushButton {color: #006400; font: bold 20px;}')

            #If you clicked on an empty cell
            if pole_game.pole[sender.x][sender.y].around_mines == 0 and pole_game.pole[sender.x][sender.y].mine != True:
                self.rec_open(sender.x, sender.y)

    #Clicking on a mine
    def mine_press(self, sender):
        for i in self.CELLS:
            if [i.x, i.y] in pole_game.rij and i.mine_note == False:
                i.setCheckable(True)
                i.setChecked(True)
                i.setIcon(QIcon(self.img_mine))
                i.setIconSize(QSize(35,35))
            if i.isChecked() == False:
                i.setCheckable(False)
            if i.mine_note == True and [i.x, i.y] not in pole_game.rij:
                i.setIcon(QIcon(self.img_false_mine))
                i.setIconSize(QSize(38,38))
            i.is_pressed = True
        sender.setIcon(QIcon(self.img_explode))
        sender.setIconSize(QSize(35,35))

    #Opening empty cells around the selected empty one
    def rec_open(self, x, y):
        for i in self.CELLS:
            if i.is_pressed == False:
                if i.x == x and i.y == y + 1:
                    i.click()
                if i.x == x + 1 and i.y == y:
                    i.click()
                if i.x == x - 1 and i.y == y:
                    i.click()
                if i.x == x and i.y == y - 1:
                    i.click()
                if i.x == x + 1 and i.y == y + 1:
                    i.click()
                if i.x == x - 1 and i.y == y - 1:
                    i.click()
                if i.x == x - 1 and i.y == y + 1:
                    i.click()
                if i.x == x + 1 and i.y == y - 1:
                    i.click()

    @staticmethod
    def check_true(x):
        if x == True:
            return x

    #Right-click processing
    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.Type.MouseButtonPress:
            #if event.button() == Qt.MouseButton.LeftButton:
                #print(obj.objectName(), "Left click")

            if event.button() == Qt.MouseButton.RightButton:
                #print(obj.objectName(), "Right click")

                #Marking of mines on the field
                if obj.is_pressed == False and obj.win == False:
                    if obj.mine_note == False:
                        self.sound_mine_check.play()
                        obj.setIcon(QIcon(self.img_banner))
                        obj.setIconSize(QSize(34,34))
                        obj.mine_note = True
                        obj.setCheckable(False)

                        if pole_game.pole[obj.x][obj.y].mine == True:
                            if [obj.x, obj.y] not in self.CHECKED_MINES:
                                self.CHECKED_MINES.append([obj.x, obj.y])

                    else:
                        self.sound_mine_check.play()
                        obj.mine_note = False
                        obj.setIcon(QIcon())
                        obj.setCheckable(True)
                        if [obj.x, obj.y] in self.CHECKED_MINES:
                                self.CHECKED_MINES.remove([obj.x, obj.y])

                #Number of buttons marked with a flag
                self.check_buttons = len(list(filter(self.check_true, [i.mine_note for i in self.CELLS])))

                self.win_check()
                #elif event.button() == Qt.MouseButton.MiddleButton:
                    #print(obj.objectName(), "Middle click")
        return QtCore.QObject.event(obj, event)

    #Win check
    def win_check(self):
        if sorted(self.CHECKED_MINES) == sorted(pole_game.rij) and self.check_buttons == self.MINES:
            if self.PRESS_BUTTONS == len(self.CELLS) - self.MINES:
                self.CHECKED_MINES = []
                for i in self.CELLS:
                    i.win = True
                self.victory()

#Game cell
class Cell:
    def __init__(self, around_mines, mine):
        self.around_mines = around_mines
        self.mine = mine
        self.fl_open = False

#Game field
class GameField:
    def init(self, height=12, width=12, mines=10):
        #List size
        self.M = height
        self.N = width
        #Number of mines
        self.mines = mines

        #Filling the list of cells with zeros
        self.pole = [[(Cell(0, False)) for i in range(self.N)] for i in range(self.M)]

        #List with mines
        self.rij = []

        #Filling the field with mines
        mine_count = 0
        while mine_count < self.mines:
            r = [random.randrange(self.N), random.randrange(self.M)]
            if r not in self.rij:
                self.rij.append(r)
                self.pole[r[0]][r[1]].mine = True
                mine_count += 1

        #Counting the number of mines around each cell
        for i in range(self.M):
            for j in range(self.N):
                around_mines = 0
                for x in range(-1, 2):
                    for y in range(-1, 2):
                        if (i + x) >= 0 and (j + y) >= 0 and (i + x) < self.M and (j + y) < self.N:
                            if self.pole[i + x][j + y].mine == True:
                                around_mines += 1
                if self.pole[i][j].mine == True and around_mines > 0:
                    around_mines -= 1
                self.pole[i][j].around_mines = around_mines
                around_mines = 0

app = QApplication([])
window = MainWindow()
pole_game = GameField()
window.init()
pole_game.init()
window.show()
app.exec()


import socket

def main():
    # 1. 创建一个 udp 套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 2. 绑定本地信息 如果一个网络程序不绑定，则系统会随机分配
    local_addr = ("", 10789)  # ip地址和端口号，ip一般不用写，表示本机的任何一个ip
    udp_socket.bind(local_addr)
    # 3. 发送信息
    send_msg = input("请输入发送的消息：")
    send_addr = ("192.168.0.105", 104560)
    udp_socket.sendto(send_msg.encode("utf-8"), send_addr)
    # 4. 接收信息
    recv_data = udp_socket.recvfrom(1024)  # 1024表示本次接收的最大字节数
    recv_msg = recv_data[0].decode("gbk")
    recv_addr = recv_data[1]
    print("%s: %s" % (str(recv_addr), recv_msg))
    # 5. 关闭套接字
    udp_socket.close()

if __name__ == "__main__":
    main()


import scrapy

class CompaniesSpider(scrapy.Spider):
    name = "companies"

    def start_requests(self):
        urls = [
            'https://www.nse.co.ke/market-statistics.html'
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        # page = response.url.split("/")[-2]
        delayed_feed = response.xpath('//div[@class="marquee"]/span/text()'
                                      ).extract()
        css_thing = response.css('div').extract()
        print('css thing:', css_thing)
        market_stats = response.xpath('//table/tbody/tr/td/text()').extract()
        filename = 'companies.html'
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log('Saved file %s' % filename)


# Python program to handle simple runtime error
#https://www.geeksforgeeks.org/try-except-python/
n1=10
n2=0
try:
     res= n1/n2
     print("result = ", res)
except ZeroDivisionError:
    print("An error occurred")
else:
    print("No exception")
finally:
    print("in final")


from rest_framework import serializers
from s2016.models import Doctor, LANGUAGE_CHOICES, STYLE_CHOICES

class DoctorSerializer(serializers.Serializer):
  pk = serializers.IntegerField(read_only=True)
  name = serializers.CharField(max_length=100)
  education = serializers.CharField(max_length=100)
  specialty = serializers.CharField(max_length=100)
  is_active = serializers.BooleanField(required=True)

  def create(self, validated_data):
    '''
    Create and return a new Doctor data
    '''
    return Doctor.objects.create(**validated_data)

  def update(self, instance, validated_data):
    '''
    Update and return existing 'Doctor' instance
    '''

    instance.name = validated_data.get('name', instance.name)
    instance.education = validated_data.get('education', instance.education)
    instance.specialty = validated_data.get('specialty', instance.name)
    instance.is_active = validated_data.get('is_active', instance.is_active)
    instance.save()
    return instance


revision = '044'
down_revision = '043'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql.expression import table

MYSQL_ENGINE = 'InnoDB'
MYSQL_CHARSET = 'utf8'

def upgrade(active_plugins=None, options=None):
    op.create_table(
        'story_types',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('created_at', sa.DateTime(), nullable=True),
        sa.Column('updated_at', sa.DateTime(), nullable=True),
        sa.Column('name', sa.String(50), nullable=True),
        sa.Column('icon', sa.String(50), nullable=True),
        sa.Column('restricted', sa.Boolean(), default=False),
        sa.Column('private', sa.Boolean(), default=False),
        sa.Column('visible', sa.Boolean(), default=True),
        sa.PrimaryKeyConstraint('id'),
        mysql_engine=MYSQL_ENGINE,
        mysql_charset=MYSQL_CHARSET
    )

    bind = op.get_bind()

    story_types_table = table(
        'story_types',
        sa.Column('name', sa.String(50), nullable=True),
        sa.Column('icon', sa.String(50), nullable=True),
        sa.Column('restricted', sa.Boolean(), default=False),
        sa.Column('private', sa.Boolean(), default=False),
        sa.Column('visible', sa.Boolean(), default=True),
    )

    bind.execute(story_types_table.insert().values(
        name='bug',
        icon='fa-bug'
    ))

    bind.execute(story_types_table.insert().values(
        name='feature',
        icon='fa-lightbulb-o',
        restricted=True
    ))

    bind.execute(story_types_table.insert().values(
        name='private_vulnerability',
        icon='fa-lock',
        private=True
    ))

    bind.execute(story_types_table.insert().values(
        name='public_vulnerability',
        icon='fa-bomb',
        visible=False
    ))

def downgrade(active_plugins=None, options=None):
    op.drop_table('story_types')


import numpy as np

class AntColonyOptimizer:
    def __init__(self, num_ants, num_iterations, evaporation_rate=0.5, alpha=1.0, beta=1.0):
        self.num_ants = num_ants
        self.num_iterations = num_iterations
        self.evaporation_rate = evaporation_rate
        self.alpha = alpha
        self.beta = beta

    def solve_ship_route(self, distance_matrix):
        num_ports = distance_matrix.shape[0]
        pheromone_matrix = np.ones((num_ports, num_ports))  # Initialize pheromone matrix

        best_route = None
        best_distance = float('inf')

        for iteration in range(self.num_iterations):
            ant_routes = []

            for ant in range(self.num_ants):
                route = self._construct_route(pheromone_matrix, distance_matrix)
                ant_routes.append(route)

                distance = self._calculate_route_distance(route, distance_matrix)

                if distance < best_distance:
                    best_distance = distance
                    best_route = route

            self._update_pheromone_matrix(pheromone_matrix, ant_routes)

        return best_route, best_distance

    def _construct_route(self, pheromone_matrix, distance_matrix):
        num_ports = pheromone_matrix.shape[0]
        current_port = np.random.randint(num_ports)
        unvisited_ports = set(range(num_ports))
        unvisited_ports.remove(current_port)
        route = [current_port]

        while unvisited_ports:
            next_port = self._select_next_port(current_port, unvisited_ports, pheromone_matrix, distance_matrix)
            route.append(next_port)
            unvisited_ports.remove(next_port)
            current_port = next_port

        route.append(route[0])  # Return to the starting port

        return route

    def _select_next_port(self, current_port, unvisited_ports, pheromone_matrix, distance_matrix):
        pheromone_values = pheromone_matrix[current_port, list(unvisited_ports)]
        attractiveness = 1.0 / (distance_matrix[current_port, list(unvisited_ports)] + 1e-8)
        probabilities = (pheromone_values ** self.alpha) * (attractiveness ** self.beta)
        probabilities /= np.sum(probabilities)

        return np.random.choice(list(unvisited_ports), p=probabilities)

    def _calculate_route_distance(self, route, distance_matrix):
        distance = 0
        num_ports = len(route)

        for i in range(num_ports - 1):
            distance += distance_matrix[route[i], route[i + 1]]

        return distance

    def _update_pheromone_matrix(self, pheromone_matrix, ant_routes):
        pheromone_matrix *= self.evaporation_rate

        for route in ant_routes:
            route_distance = self._calculate_route_distance(route, distance_matrix)
            for i in range(len(route) - 1):
                pheromone_matrix[route[i], route[i + 1]] += 1.0 / route_distance
            pheromone_matrix[route[-1], route[0]] += 1.0 / route_distance

# Example usage
if __name__ == "__main__":
    np.random.seed(42)  # For reproducibility

    # Example distance matrix for 10 ports
    distance_matrix = np.array([[0, 10, 15, 20, 25, 30, 35, 40, 45, 50],
                                [10, 0, 12, 18, 20, 25, 33, 35, 40, 45],
                                [15, 12, 0, 15, 17, 22, 28, 30, 35, 40],
                                [20, 18, 15, 0, 10, 12, 18, 20, 25, 30],
                                [25, 20, 17, 10, 0, 8, 15, 18, 22, 25],
                                [30, 25, 22, 12, 8, 0, 10, 12, 15, 20],
                                [35, 33, 28, 18, 15, 10, 0, 6, 10, 12],
                                [40, 35, 30, 20, 18, 12, 6, 0, 8, 10],
                                [45, 40, 35, 25, 22, 15, 10, 8, 0, 8],
                                [50, 45, 40, 30, 25, 20, 12, 10, 8, 0]])

    num_ants = 200
    num_iterations = 500
    aco = AntColonyOptimizer(num_ants=num_ants, num_iterations=num_iterations)
    best_route, best_distance = aco.solve_ship_route(distance_matrix)

    print("Best Route:", best_route)
    print("Best Distance:", best_distance)


#Given an array of integers, find the one that appears an odd number of times.
#[1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time
#(which is odd).
def find_oddint(arr):
    for i in arr:
        if arr.count(i) % 2 != 0:
            result = i
        else:
            continue
    return result

find_oddint([1,1,2,-2,5,2,4,4,-1,-2,5])


n = int(input())
list1 = []
list2 = []
for i in range(0,n):
    min,max1 = list(map(int,input().split()))
    for j in range(min,max1):
        list1.append(j)
for i in range(0,n):
    min,max1 = list(map(int,input().split()))
    for j in range(min,max1):
        list2.append(j)
m = max(list1[-1],list2[-1])+1
count = [0 for i in range(m) ]
for i in list1:
    count[i]+=1
for i in list2:
    count[i]+=1
print(count.count(2))


import numpy as np
from deep_sort.utils.parser import get_config
from deep_sort.deep_sort import DeepSort

class DeepSortTracker:
    """
    DeepSort object tracker.
    """

    def init(self, reid_model_path, max_dist=0.2, min_confidence=0.3, nms_max_overlap=1.0,
             max_iou_distance=0.7, max_age=70, n_init=3, nn_budget=None, use_cuda=True):
        self.deepsort = DeepSort(reid_model_path, max_dist=max_dist, min_confidence=min_confidence,
                                 nms_max_overlap=nms_max_overlap, max_iou_distance=max_iou_distance,
                                 max_age=max_age, n_init=n_init, nn_budget=nn_budget, use_cuda=use_cuda)

    def update(self, detections, iou_threshold):
        detection_list = []
        for detection in detections:
            bbox = detection[:4]
            confidence = detection[4]
            detection_list.append(bbox + [confidence])
        detection_array = np.array(detection_list)

        outputs = self.deepsort.update(detection_array, iou_threshold)

        tracks = []
        for output in outputs:
            bbox = output[:4]
            track_id = int(output[4])
            tracks.append(bbox + [track_id])

        return tracks


# -*- coding: utf-8 -*-
"""Test s3 class."""

import pytest
from unittest.mock import Mock, patch

from s3_client import s3_client

from conftest import BUCKET_NAME

def test_download_object(s3, s3_bucket, tmpdir):
    """Test object download."""
    s3_client.log = Mock()
    obj_name = "my_object"
    obj_body = "Test object content"
    dest_name = "{}/{}".format(tmpdir, obj_name)
    s3_bucket.Bucket(BUCKET_NAME).put_object(Key=obj_name, Body=obj_body)
    s3.download_object(BUCKET_NAME, obj_name, dest_name)
    assert (tmpdir / obj_name).read() == obj_body

@pytest.mark.parametrize(
    "extraargs, versionid", [(None, None), ({"VersionId": "1234567890"}, "1234567890")]
)
def test_download_object_extraargs(s3, extraargs, versionid):
    """Test download object ExtraArgs option."""
    s3_client.log = Mock()
    obj_name = "my_object"
    dest_name = "/tmp"
    with patch.object(s3, "s3_resource"):
        with patch.object(s3_client, "ProgressBar"):
            s3_client.ProgressBar.return_value.__enter__.return_value.update_to = None

            s3.download_object(BUCKET_NAME, obj_name, dest_name, versionid)

            s3.s3_resource.Bucket(BUCKET_NAME).download_file.assert_called_with(
                obj_name, dest_name, ExtraArgs=extraargs, Callback=None
            )