import csv
from numpy import *
#from scipy.interpolate import *
from matplotlib.pyplot import *
#from scipy.stats import *
#import math
set_printoptions(threshold= np.nan)
file = open("ChikmagalurRainTrain.csv")# opening the learning data
reader = csv.reader(file)# creating a reader
flag = 0# for avoiding the headers in csv file from including in arrays
dataRain = array([])# stores the annual rain data
dataYear = array([])# correspnding year
for i in reader:
    if flag == 0:
        flag = 1
    else:
        for j in range(1,13):
            if flag == 1:
                startYearOfTestDataTrain = int(i[0])
                flag = 2
            dataYear = append(dataYear,int(i[0])+(int(i[0])*(j-1))/12)#taking years like for jan 1900 + (1900*0)/12 for feb 1900 + (1900*1)/12
            dataRain = append(dataRain,float(i[j]))
#print("Data Year","Data Rain")
#for i in range(len(dataYear)):
    #print(dataYear[i],dataRain[i])
year = (1920 - startYearOfTestDataTrain)*12
#print(year)
#print(dataRain[year:year+13])
p1 = polyfit(dataYear,dataRain,8)# fitting the data into a quadratic polynomial
plot(dataYear[year:year+13],dataRain[year:year+13],'o')# plotting the actual rain data on graph as blue dots
plot(dataYear[year:year+13],polyval(p1,dataYear[year:year+13]),'r-')# drawing a curve formed by polynomial
xlabel("Years"+str(year/12+startYearOfTestDataTrain))
ylabel("RainFall")
title("Prototype1")
#print(dataYear[year],dataRain[year],polyval(p1,dataYear[year]),sep = " ")
show()

file.close()

testDataYear = array([])# stores the test data years
testDataRain = array([])# stores the test data rain
file = open("ChikmagalurRainTest.csv")
reader = csv.reader(file)
flag1 = 0
for i in reader:
    for j in range(1,13):
            testDataYear = append(testDataYear,int(i[0])+(int(i[0])*(j-1))/12)
            testDataRain = append(testDataRain,float(i[j]))
            if flag1 == 0:
                startYearOfTestData = int(i[0])
                flag1 = 1
#print(startYearOfTestData)
#for i in range(len(testDataYear)):
    #print(testDataYear[i],testDataRain[i])
#predictedData = p1[0] * testDataYear**3 + p1[1] * testDataYear**2 + p1[2] * testDataYear + p1[3]
#predictedData = p1[0] * testDataYear**4 + p1[1] * testDataYear**3 + p1[2] * testDataYear**2 + p1[3] * testDataYear + p1[4]
#predictedData = p1[0] * testDataYear**5 + p1[1] * testDataYear**4 + p1[2] * testDataYear**3 + p1[3] * testDataYear**2 + p1[4] * testDataYear + p1[5]
#predictedData = p1[0] * testDataYear**6 + p1[1] * testDataYear**5 + p1[2] * testDataYear**4 + p1[3] * testDataYear**3 + p1[4] * testDataYear**2 + p1[5] * testDataYear + p1[6]
#predictedData = p1[0] * testDataYear**7 + p1[1] * testDataYear**6 + p1[2] * testDataYear**5 + p1[3] * testDataYear**4 + p1[4] * testDataYear**3 + p1[5] * testDataYear**2 + p1[6] * testDataYear + p1[7]
predictedData = p1[0] * testDataYear**8 + p1[1] * testDataYear**7 + p1[2] * testDataYear**6 + p1[3] * testDataYear**5 + p1[4] * testDataYear**4 + p1[5] * testDataYear**3 + p1[6] * testDataYear**2 + p1[7] * testDataYear + p1[8]
#predictedData = p1[0] * testDataYear**9 + p1[1] * testDataYear**8 + p1[2] * testDataYear**7 + p1[3] * testDataYear**6 + p1[4] * testDataYear**5 + p1[5] * testDataYear**4 + p1[6] * testDataYear**3 + p1[7] * testDataYear**2 + p1[8] * testDataYear + p1[9]
#predictedData = p1[0] * testDataYear**14 + p1[1] * testDataYear**13 + p1[2] * testDataYear**12 + p1[3] * testDataYear**11 + p1[4] * testDataYear**10 + p1[5] * testDataYear**9 + p1[6] * testDataYear**8 + p1[7] * testDataYear**7 + p1[8] * testDataYear**6 + p1[9] * testDataYear**5 + p1[10] * testDataYear**4 + p1[11] * testDataYear**3 + p1[12] * testDataYear**2 + p1[13] * testDataYear + p1[14]
#predictedData = p1[0] * testDataYear**2 + p1[1] * testDataYear + p1[2]# stores the predicted rain data
#predictedData = p1[0] * testDataYear**3 + p1[1] * testDataYear**2 + p1[2] * testDataYear + p1[3]
print("Year"+"\t"+"Month"+"Actual Rain"+"\t"+"Predicted Rain")

#for i in range(testDataYear.size):
    #print(testDataYear[i],"\t",testDataRain[i],"\t",predictedData[i])
year = (2004 - startYearOfTestData)*12
temp = startYearOfTestData
i = 0
print(predictedData[year:year+13])
while i < int(testDataRain.size):
    for j in range(1,13):
        if predictedData[i]<0:
            predictedData[i] = 0
        print(startYearOfTestData,j,"\t\t",testDataRain[i],"\t\t",predictedData[i])
        i+=1
    startYearOfTestData+=1

plot(testDataYear[year:year+13],testDataRain[year:year+13],'r--')# actual curve
plot(testDataYear[year:year+13],predictedData[year:year+13],"b--")# predicted curve
xlabel("Years"+str(year/12+temp))
ylabel("RainFall")
title("Prototype1")
show()

#rainfit = p1[0] * dataYear**2 + p1[1] * dataYear + p1[2]
#rainfit = p1[0] * dataYear**3 + p1[1] * dataYear**2 + p1[2] * dataYear + p1[3]
#rainfit = p1[0] * dataYear**4 + p1[1] * dataYear**3 + p1[2] * dataYear**2 + p1[3] * dataYear + p1[4]
#rainfit = p1[0] * dataYear**5 + p1[1] * dataYear**4 + p1[2] * dataYear**3 + p1[3] * dataYear**2 + p1[4] * dataYear + p1[5]
#rainfit = p1[0] * dataYear**6 + p1[1] * dataYear**5 + p1[2] * dataYear**4 + p1[3] * dataYear**3 + p1[4] * dataYear**2 + p1[5] * dataYear + p1[6]
#rainfit = p1[0] * dataYear**7 + p1[1] * dataYear**6 + p1[2] * dataYear**5 + p1[3] * dataYear**4 + p1[4] * dataYear**3 + p1[5] * dataYear**2 + p1[6] * dataYear + p1[7]
rainfit = p1[0] * dataYear**8 + p1[1] * dataYear**7 + p1[2] * dataYear**6 + p1[3] * dataYear**5 + p1[4] * dataYear**4 + p1[5] * dataYear**3 + p1[6] * dataYear**2 + p1[7] * dataYear + p1[8]
#rainfit = p1[0] * dataYear**9 + p1[1] * dataYear**8 + p1[2] * dataYear**7 + p1[3] * dataYear**6 + p1[4] * dataYear**5 + p1[5] * dataYear**4 + p1[6] * dataYear**3 + p1[7] * dataYear**2 + p1[8] * dataYear + p1[9]
#rainfit = p1[0] * dataYear**14 + p1[1] * dataYear**13 + p1[2] * dataYear**12 + p1[3] * dataYear**11 + p1[4] * dataYear**10 + p1[5] * dataYear**9 + p1[6] * dataYear**8 + p1[7] * dataYear**7 + p1[8] * dataYear**6 + p1[9] * dataYear**5 + p1[10] * dataYear**4 + p1[11] * dataYear**3 + p1[12] * dataYear**2 + p1[13] * dataYear + p1[14]
yresid = dataRain - rainfit
SSresid = sum(pow(yresid,2))
SStotal = len(dataRain)*var(dataRain)
rsq = 1- SSresid/SStotal
print(rsq)
#x = 2017+(2017*8)/12
#jan2018Rainfall = p1[0] * x**8 + p1[1] * x**7 + p1[2] * x**6 + p1[3] * x**5 + p1[4] * x**4 + p1[5] * x**3 + p1[6] * x**2 + p1[7] * x + p1[8]
#print(jan2018Rainfall)


from typing import List, Iterable, cast
from xml.etree.ElementTree import indent, Element

from utils import make_tokenstream, parser_tester, dump

if __name__ == "__main__":
    # NOTE: (<, >, ", and &) can't be printed as-is to XML
    # NOTE: This should already be handled by the XML module
    sample_expressions: List[str] = [
        "null",
        "-1",
        "~4",
        "a[2]",
        "i * (-j)",
        "j / (-2)",
        "i | j",
        "i < j",
        "i > j",
        "i & j",
        "someClass.someMethod() + anotherClass.anotherMethod()"
    ]
    expression_tokenstreams: List[List[Element]] = [make_tokenstream(x) for x in sample_expressions]
    for ts in expression_tokenstreams:
        working_on: str = ''.join([cast(str, x.text) for x in cast(Iterable[Element], ts)])
        print(f"working on: {working_on}")
        res: Element = parser_tester(ts, "expression", debug=True)
        indent(res)
        dump(res)
        print()
        assert res


#Accepted!
#https://www.spoj.pl/problems/TOANDFRO/
#0.03 	3.7M

import sys

def reverse(s):
	#equivalente: s = s[::-1]
	s2 = ""
	for i in range(len(s)-1, -1, -1):
		s2 += s[i]
	return s2

n = input()
while n != 0:
	s = raw_input()
	i = 0;
	l = []
	bien = True
	while i < len(s):
		aux = s[i:i+n]
		if not bien:
			aux = reverse(aux)
		l += [aux]
		bien = not bien
		i += n
	for c in range(n):
		for f in range(len(l)):
			sys.stdout.write(l[f][c])
	print
	n = input()


sizeA = int(input("Введите целое положительное число - количество элементов в массиве: "))
strA = str(input("Введите строку элементов в массиве: "))
listA = strA.split()
numX = str(input("Введите значение искомого числа: "))

if (len(listA) == sizeA):
    result = str(listA.count(numX))
else:
    result = "Вы ввели рассогласованные данные!"

print("-> " + result)


'''A série de Fibonacci é formada pela seqüência 1,1,2,3,5,8,13,21,34,55,... Faça um programa capaz de gerar a série até o n−ésimo termo.
'''

n = int(input("entre com um número:"))
ant1 = 0
ant2 = 1
fibo = 0
for i in range(0,n,1):
    fibo = ant1 + ant2
    ant2 = ant1
    ant1 = fibo

    print(fibo, end=" ")


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

# to find if it is cyclic or not, we use hare and tortoise technique
# if a turtoise and hare run along a cuclic path the hare eventually catch up to turtoise

# we initiate slow and fast as head
# while there is fast and fast.next
# check if slow.next is fast.next.next

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        slow, fast = head, head

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False


from django.http import HttpResponse
from django.shortcuts import  render
def home(request):
    products = ["Swamp Barries", "Worms", "Eyeballs", "brains","Synthetic Cannibinoids"]
    user = request.user
    context = {
        'products': products,
    }

    return render(request, "home.html", context)


import abc
import discord
import asyncio
import urllib.parse
import operator

from redbot.core import Config
from redbot.core import commands
from redbot.core import checks
from redbot.core.utils.predicates import ReactionPredicate
from redbot.core.utils.menus import start_adding_reactions

defaults = {"RoleRanges": {}, "LogChannel": None, "Players": {}, "Results": []}
verify_timeout = 30
k_factor = 30

class SixMansElo(commands.Cog):
    """Manages aspects of Ballchasing Integrations with RSC"""

    def __init__(self, bot):
        self.bot = bot
        self.config = Config.get_conf(self, identifier=1234567893, force_registration=True)
        self.config.register_guild(**defaults)
        self.players = []
        self.six_mans_cog = bot.get_cog("SixMans")

        try:
            self.observe_six_mans()
        except:
            pass

    @commands.guild_only()
    @commands.command()
    @checks.admin_or_permissions(manage_guild=True)
    async def setLogChannel(self, ctx, log_channel: discord.TextChannel):
        """Sets the channel where all transaction messages will be posted"""
        await self._save_log_channel(ctx.guild, log_channel.id)
        await ctx.send("Done")

    @commands.guild_only()
    @commands.command()
    @checks.admin_or_permissions(manage_guild=True)
    async def unsetLogChannel(self, ctx):
        """Sets the channel where all transaction messages will be posted"""
        await self._save_log_channel(ctx.guild, None)
        await ctx.send("Done")

    @commands.command()
    @commands.guild_only()
    @checks.admin_or_permissions(manage_guild=True)
    async def addPlayers(self, ctx, *players_to_add):
        """Add the players provided to the player list.

        Arguments:

        players_to_add -- One or more players in the following format:
        ```
        "['<player_id>','<wins>', '<losses>', '<elo_rating>']"
        ```
        Each player should be separated by a space.

        Examples:
        ```
        [p]addPlayers "['123456789','2', '1', '1000']"
        [p]addPlayers "['123456789','2', '1', '1000']" "['987654321','1', '2', '950']"
        ```
        """
        addedCount = 0
        try:
            for playerStr in players_to_add:
                player = ast.literal_eval(playerStr)
                playerAdded = await self._add_player(ctx, *player)
                if playerAdded:
                    addedCount += 1
                else:
                    await ctx.send("Error adding player: {0}".format(repr(player)))
        finally:
            await ctx.send("Added {0} players(s).".format(addedCount))
        await ctx.send("Done.")

    @commands.command()
    @commands.guild_only()
    @checks.admin_or_permissions(manage_guild=True)
    async def addPlayer(self, ctx, member: discord.Member, wins: int, losses: int, elo_rating: int):
        """Add a single player and their info to the file system."""
        playerAdded = await self._add_player(ctx, member, wins, losses, elo_rating)
        if(playerAdded):
            await ctx.send("Done.")
        else:
            await ctx.send("Error adding player: {0}".format(member.name))

    @commands.command()
    @commands.guild_only()
    @checks.admin_or_permissions(manage_guild=True)
    async def clearEloRoles(self, ctx):
        await self._save_role_ranges(ctx.guild, {})
        await ctx.send("Done")

    @commands.command()
    @commands.guild_only()
    @checks.admin_or_permissions(manage_guild=True)
    async def addEloRole(self, ctx, role: discord.Role, min_elo: float, max_elo: float):
        # Save Elo Role
        await self._register_role_range(role, min_elo, max_elo)

        # Log Role addition
        log_channel = await self._get_log_channel(role.guild)

        # Add roles to appropriate existing players
        for player in self.players:
            if player.elo_rating >= min_elo and player.elo_rating <= max_elo:
                await player.member.add_roles(role)
                if log_channel:
                    message = "{} has had their roles updated!".format(player.member.mention)
                    message += "\n\t - **Added:** {}".format(role.name)
        await ctx.send("Done.")

    @commands.command(aliases=['getEloRoles'])
    @commands.guild_only()
    @checks.admin_or_permissions(manage_guild=True)
    async def getEloRanges(self, ctx):
        guild = ctx.guild
        elos = await self._get_role_ranges(guild)

        elo_roles = []
        for elo_id in elos.keys():
            elo_roles.append(guild.get_role(int(elo_id)))
        elo_roles = sorted(elo_roles, key=operator.attrgetter('position'))
        elo_roles.reverse()

        out = "Elo Ranges"
        for role in elo_roles:
            elo_range = elos[str(role.id)]
            role = ctx.guild.get_role(int(role.id))
            out += "\n- {}: [{}-{}]".format(role.mention, elo_range[0], elo_range[1])

        await ctx.send(out)

    @commands.guild_only()
    @commands.Cog.listener("on_guild_role_delete")
    async def on_guild_role_delete(self, role):
        await self._unregister_elo_role(role)

## OBSERVER PATTERN IMPLEMENTATION ########################

    @commands.command()
    @commands.guild_only()
    @checks.admin_or_permissions(manage_guild=True)
    async def observeForElo(self, ctx):
        self.observe_six_mans()
        await ctx.send("Observing.")

    @commands.guild_only()
    @commands.Cog.listener("on_ready")
    async def on_ready(self):
        pass
        # self.observe_six_mans()

    @commands.guild_only()
    @commands.Cog.listener("on_resumed")
    async def on_resumed(self):
        pass
        # self.observe_six_mans()

    def observe_six_mans(self):
        self.six_mans_cog = self.bot.get_cog("SixMans")
        self.six_mans_cog.add_observer(self)

    async def update(self, game):
        await game.textChannel.send("State: {}".format(game.game_state))
        if game.game_state == "game over":
            await self._finish_series(game)

###########################################################

    async def _finish_series(self, game, update_roles=True):
        if not game.winner or game.winner.lower() not in ['blue', 'orange']:
            return False

        # get blue avg elo
        blue_players = [self._get_player_by_id(blue_player) for blue_player in game.blue]
        orange_players = [self._get_player_by_id(orange_player) for orange_player in game.orange]

        # remove/ignore players who aren't found
        while None in blue_players:
            blue_players.remove(None)
        while None in orange_players:
            orange_players.remove(None)

        avg_blue_elo = self._get_avg_team_rating(blue_players)
        avg_orange_elo = self._get_avg_team_rating(orange_players)

        # determine winner
        blue_wins = 0
        orange_wins = 0
        if game.winner.lower() == 'blue':
            blue_wins = 1
        else:
            orange_wins = 1

        # calculate new team elo
        new_blue_elo, new_orange_elo, = self._update_elo(elo1, elo2, blue_wins/(blue_wins + orange_wins))

        blue_diff = new_blue_elo - avg_blue_elo
        orange_diff = new_orange_elo - avg_orange_elo

        # apply new elo on players
        for player in blue_players:
            self._update_player_info(player, blue_wins, orange_wins, player.elo_rating + blue_diff)
        for player in orange_players:
            self._update_player_info(player, orange_wins, blue_wins, player.elo_rating + orange_diff)

        await self._save_players(blue_players + orange_players)

        if update_roles:
            for player in blue_players + orange_players:
                await self._reassign_elo_roles(player.member, player.elo_rating)

#region Adjust Player Ratings
    async def _reassign_elo_roles(self, player: discord.Member, player_elo: int=None):
        if player_elo == None:
            elo = await self._get_player_rating(player)

        log_channel = await self._get_log_channel(player.guild)

        guild = player.guild
        all_elo_roles = await self._get_sm_roles(guild)
        remove_roles = list(set(all_elo_roles) & set(player.roles))
        add_elo_roles = await self._get_elo_roles(elo)

        keep_roles = list(set(add_elo_roles) & set(remove_roles))
        for role in keep_roles:
            add_elo_roles.remove(role)
            remove_roles.remove(role)

        if add_elo_roles or remove_roles:
            try:
                await player.remove_roles(*remove_roles)
                await player.add_roles(*add_elo_roles)

                # return add_elo_roles, remove_roles
                if log_channel:
                    message = "{} has had their roles updated!".format(player.mention)
                    if add_elo_roles:
                        message += "\n\t - **Added:** {}".format(', '.join(role.name for role in add_elo_roles))
                    if remove_roles:
                        message += "\n\t - **Removed:** {}".format(', '.join(role.name for role in remove_roles))
            except:
                return False

    def _get_avg_team_rating(self, players):
        total = 0
        for member in players:
            total += player.elo_rating

        return total/len(players)

    async def _get_player_rating(self, player: discord.Member):
        pass

    def _update_player_info(self, player, new_wins, new_losses, new_elo_rating):
        player.wins += new_wins
        player.losses += new_losses
        player.elo_rating = new_elo_rating

    async def _get_elo_roles(self, guild: discord.Guild, elo):
        elo_roles = []
        for role, elo_range in (await self._get_role_ranges(guild)):
            min_elo = elo_range[0]
            max_elo = elo_range[1]
            if elo >= min_elo and elo <= max_elo:
                elo_roles.append(role)
        return elo_roles

    async def _get_player_sm_roles(self, player: discord.Member):
        return list(set(await self._get_sm_roles(member.guild)) & set(player.roles))

    def _update_elo(self, elo1: int, elo2: int, result: float):
        """Calculates and returns the new Elo ratings for the two elo ratings based on their match results and the K-factor.
        Result param should be a decimal between 0 and 1 relating to the match results for elo1, i.e. a result of 1
        means player 1 won all the games in the match, a result of .25 means player 1 won 25% of the games in the match, etc."""
        elo_dif = int(player_1_elo) - int(player_2_elo)
        exponent = -1 * (elo_dif / 100)
        expectation = 1 / (1 + pow(10, exponent))
        new_elo1 = round(int(elo1) + (k_factor * (result - expectation)))
        new_elo2 = round(int(elo2) + (k_factor * ((1 - result) - (1 - expectation))))
        return new_elo1, new_elo2

#endRegion Adjust Player Ratings

#region SixMansRoles settings
    async def _register_role_range(self, role: discord.Role, min_elo: float, max_elo: float):
        if min_elo > max_elo:
            return False
        guild = role.guild
        role_ranges = await self._get_role_ranges(guild)
        role_ranges[str(role.id)] = [min_elo, max_elo]
        await self._save_role_ranges(guild, role_ranges)

    async def _unregister_elo_role(self, role: discord.Role):
        guild = role.guild
        role_ranges = await self._get_role_ranges(guild)
        if str(role.id) in role_ranges:
            del role_ranges[str(role.id)]
            await self._save_role_ranges(role_ranges)
            if log_channel:
                await log_channel.send("The Six Mans role **{}** has been removed.".format(role.name))

    async def _get_role_range(self, role: discord.Role):
        guild = role.guild
        role_ranges = await self._get_role_ranges(guild)
        for sm_role_id, role_range in role_ranges.items():
            sm_role = guild.get_role(int(sm_role_id))
            if role == sm_role:
                return role_range[0], rolerange[1]
        return None

    async def _get_sm_roles(self, guild: discord.Guild):
        return [guild.get_role(int(role_id)) for role_id in (await self._get_role_ranges(guild)).keys()]

    async def _get_role_ranges(self, guild: discord.Guild):
        return await self.config.guild(guild).RoleRanges()

    async def _save_role_ranges(self, guild: discord.Guild, role_ranges):
        await self.config.guild(guild).RoleRanges.set(role_ranges)

#endregion SixMansRoles settings

#region uncategoriezed helpers
    def _get_player_by_id(self, member_id: discord.Member, players=None):
        if not players:
            players = self.players
        for player in players:
            if player.member.id == member_id:
                return player
        return None

    async def _add_player(self, ctx, member, wins, losses, elo_rating, assign_elo_roles=True):
        await self.load_players(ctx)
        players = self.players

        wins = int(wins)
        losses = int(losses)
        elo_rating = int(elo_rating)

        # Validation of input
        # There are other validations we could do, but don't
        #     - that there aren't extra args for example
        errors = []
        if not isinstance(member, discord.Member):
            try:
                member = await commands.MemberConverter().convert(ctx, member)
            except:
                errors.append("Member {} not found.".format(member))
        if wins < 0:
            errors.append("Wins cannot be a negative number.")
        if losses < 0:
            errors.append("Losses cannot be a negative number.")
        if not elo_rating:
            errors.append("Elo rating not found.")
        if errors:
            await ctx.send(":x: Errors with input:\n\n  "
                               "* {0}\n".format("\n  * ".join(errors)))
            return

        try:
            player = Player(member, wins, losses, elo_rating, -1)
            players.append(player)
            if add_elo_roles:
                await self._reassign_elo_roles(member, elo_rating)
        except:
            return False
        await self._save_players(ctx, players)
        return True

    async def _remove_player(self, ctx, member: discord.Member):
        await self.load_players(ctx)
        players = self.players

        try:
            player = await self.get_player_by_id(self.players, member.id)
            if not player:
                await ctx.send("{0} does not seem to be a current player.".format(member.name))
                return False
            players.remove(player)
        except ValueError:
            await ctx.send("{0} does not seem to be a current player.".format(member.name))
            return False
        await self._save_players(ctx, players)
        return True

#endregion uncategorized helpers

#region load/save methods
    async def _save_log_channel(self, guild, channel_id):
        await self.config.guild(guild).LogChannel.set(channel_id)

    async def _get_log_channel(self, guild: discord.Guild):
        guild.get_channel(await self.config.guild(guild).LogChannel())

    async def load_players(self, ctx, force_load = False):
        players = await self._players(ctx)
        player_list = []
        remove_player = False
        for value in players.values():
            member = ctx.guild.get_member(value["Id"])
            if not member:
                # Member not found in server, don't add to list of players and
                # re-save list at the end to ensure they get removed
                remove_player = True
                continue
            wins = value["Wins"]
            losses = value["Losses"]
            elo_rating = value["EloRating"]
            # temp_rating = value["TempRating"]
            player = Player(member, wins, losses, elo_rating)
            player_list.append(player)

        self.players = player_list
        if remove_player:
            await self._save_players(ctx, self.players)

    async def _players(self, ctx):
        return await self.config.guild(ctx.guild).Players()

    async def _save_players(self, ctx, players):
        player_dict = {}
        for player in players:
            player_dict[player.member.id] = player._to_dict()
        await self.config.guild(ctx.guild).Players.set(player_dict)

#endregion

class Player:
    def __init__(self, member: discord.Member, wins: int, losses: int, elo_rating: int):
        self.member = member
        self.wins = wins
        self.losses = losses
        self.elo_rating = elo_rating

    def _to_dict(self):
        return {
            "Id": self.member.id,
            "Wins": self.wins,
            "Losses": self.losses,
            "EloRating": self.elo_rating,
            "TempRating": self.temp_rating
        }


k = int(input('Введите число k:'))
list = []

result = 0
i = 1
while i <= k:
    result = round((1 + 1 / i) ** 2, 2)
    list.append(result)
    i += 1

print(list)
print(sum(list))


from exercise9 import list_builder

## Check if a word is in the list
# @param t a sorted list
# @param value the word we want to check
# @param n the max number of times you have to cut the list before returning
# @return True if the word is the list; False otherwise
def in_bisect(t, value, n = 17):
    half = len(t) // 2
    for _ in range (n):
        if value == t[half]:
            return True
        elif value < t[half]:
            t = t[:half]
        elif value > t[half]:
            t = t[half:]
        half = len(t) // 2
    return False

# Call in_bisect function and print the risult
def main():
    # Generate a list of word
    t = list_builder('../tp_chapter8/words.txt')
    print(in_bisect(t, "abatis"))

# Call the main function
if __name__ == "__main__":
    main()


from botocore.exceptions import ClientError
from botocore.config import Config as botocore_config
import json
import logging
import random
import time

from lib import awshelper
from lib import config
from lib import ddb
from lib import utility

def get_source_buckets(input_parameters, account_id):
    """ Get all eligible source buckets

    Arguments:
        input_parameters {config.S3InsightsInput} -- Input parameters for the current execution
        account_id {string} -- AWS account id

    Returns:
        dict<string, dict<string, list(string)>> -- Source buckets
    """
    source_buckets = {}
    account_id = account_id.lower()
    account_config = next(account_config for account_config in input_parameters.accounts if utility.compare_strings(account_config.id, account_id))
    source_buckets[account_id] = {}
    s3_client = awshelper.get_client(
        awshelper.ServiceName.s3,
        None,
        account_id,
        input_parameters.run_id)

    # Exclude the consolidation and inventory destination buckets
    pipeline_buckets = []
    if utility.compare_strings(account_id, awshelper.SessionManager.get_host_account_id()):
        pipeline_buckets.append(config.DeploymentDetails.consolidated_inventory_bucket_name)
        for region in input_parameters.supported_regions:
            bucket_name = get_destination_bucket_name(input_parameters.run_id, region)
            pipeline_buckets.append(bucket_name)
    response = s3_client.list_buckets()
    for bucket in response["Buckets"]:
        name = bucket["Name"].lower()
        if name not in account_config.exclude and name not in pipeline_buckets:
            try:
                location = s3_client.get_bucket_location(
                    Bucket=name)
                region = location['LocationConstraint']
                if region is None:
                    region = 'us-east-1'
                region = region.lower()
                if region in input_parameters.supported_regions:
                    if region not in source_buckets[account_id]:
                        source_buckets[account_id][region] = []
                    source_buckets[account_id][region].append(name)
            except ClientError as e:
                logging.error(f'error while retrieving bucket information for {account_id}:{name}. error details: {e}')

    return source_buckets

def get_destination_bucket_name(run_id, region):
    """ Get destination bucket name for a region

    Arguments:
        run_id {string} -- run_id for the current execution
        region {string} -- AWS region name

    Returns:
        string -- Destination bucket name
    """
    host_account_id = awshelper.SessionManager.get_host_account_id()
    return utility.get_resource_name(
        run_id,
        f'dest-{host_account_id}',
        region)

def is_bucket_empty(s3_resource, bucket_name):
    """ Check if a given S3 bucket is empty

    Arguments:
        s3_resource {Boto3.S3.ServiceResource} -- Boto3 S3 resource
        bucket_name {string} -- bucket name

    Returns:
        boolean -- Flag indicating if the bucket is empty
    """
    empty = True
    client_error = None
    bucket = s3_resource.Bucket(bucket_name)
    try:
        s3_objects = bucket.objects.all()
        for s3_object in s3_objects:
            empty = False
            break
    except ClientError as e:
        logging.error(f'error while listing objects from {bucket_name}. error details:{e}')
        client_error = e
    return empty, client_error

def is_destination_bucket_name(input_parameters, bucket_name):
    """ Check if the given S3 bucket is a destination bucket

    Arguments:
        input_parameters {config.S3InsightsInput} -- Input parameters for the current execution
        bucket_name {string} -- Bucket name

    Returns:
        boolean -- Flag indicating if the bucket is a destination bucket
    """
    for region in input_parameters.supported_regions:
        destination_bucket_name = get_destination_bucket_name(input_parameters.run_id, region)
        if utility.compare_strings(destination_bucket_name, bucket_name):
            return True
    return False

class StackDetails(object):
    def __init__(self, client, name):
        """ Constructor for creating an instance of

        Arguments:
            object {StackDetails} -- Instance of StackDetails
            client {Boto3.CloudFormation.Client} -- Boto3 CloudFormation client
            name {string} -- CloudFormation stack name
        """
        self.client = client
        self.name = name

    def is_complete(self, in_progress_state_name, complete_state_name):
        """ Check if the CloudFormation stack operation has finished

        Arguments:
            in_progress_state_name {string} -- In-progress state name
            complete_state_name {[string} -- Complete state name

        Raises:
            utility.S3InsightsException: When the stack status is neither in-progress nor complete

        Returns:
            boolean -- Flag indicating if the operation has finished successfully
        """
        details = self.client.describe_stacks(StackName=self.name)
        logging.info(f'current stack details: {self.name} {details}')
        current_status = details['Stacks'][0]['StackStatus'].lower()
        if utility.compare_strings(current_status, in_progress_state_name):
            return False
        elif utility.compare_strings(current_status, complete_state_name):
            return True
        else:
            error_message = f'unknown stack status. Stack name:{self.name} current status:{current_status} expected status:{in_progress_state_name}/{complete_state_name} details:{details}'
            raise utility.S3InsightsException(error_message)

def wait_for_stack_operations_to_finish(stacks, in_progress_state_name, complete_state_name, max_iteration_count):
    """ Wait for stack operations to finish

    Arguments:
        stacks {list(StackDetails)} -- List of stacks
        in_progress_state_name {string} -- In-progress state name
        complete_state_name {[string} -- Complete state name
        max_iteration_count {integer} -- Max iteration count

    Raises:
        utility.S3InsightsException: When stacks do not move to the complete state in the alloted time
    """
    are_stacks_ready = False
    attempts = 0
    while are_stacks_ready is False and attempts < max_iteration_count:
        are_stacks_ready = True
        attempts = attempts + 1
        for stack in stacks:
            if stack.is_complete(in_progress_state_name, complete_state_name) == False:
                are_stacks_ready = False
                time.sleep(30)
                break
    if are_stacks_ready is False:
        raise utility.S3InsightsException('stacks did not finish in the alloted time')

def get_stack_name(run_id):
    """ Get CloudFormation stack name

    Arguments:
        run_id {string} -- run_id for the current Step Function execution

    Returns:
        string -- CloudFormation Stack name
    """
    return utility.get_resource_name(
        run_id,
        'stack',
        'dest-resources')

def create_inventory_destination_buckets(input_parameters):
    """ Create inventory destination buckets

    Arguments:
        input_parameters {config.S3InsightsInput} -- Input parameters for the current execution
    """
    template_file_path = utility.get_file_path(__file__, "template/inventory-destination.json")
    with open(template_file_path, "r") as template_file:
        template_text = template_file.read()
    stacks = []
    regions = input_parameters.supported_regions
    for region in regions:
        bucket_name = get_destination_bucket_name(
            input_parameters.run_id,
            region)
        topic_name = utility.get_resource_name(
            input_parameters.run_id,
            'sns',
            'notification-topic')

        acceleration_status = 'Enabled'

        parameters = [
            {
                'ParameterKey': 'BucketName',
                'ParameterValue': bucket_name
            },
            {
                'ParameterKey': 'SQSArn',
                'ParameterValue': config.DeploymentDetails.sqs_arn
            },
            {
                'ParameterKey': 'TopicName',
                'ParameterValue': topic_name
            },
            {
                'ParameterKey': 'AccelerationStatus',
                'ParameterValue': acceleration_status
            }
        ]

        stack_name = get_stack_name(input_parameters.run_id)
        cloudformation_client = awshelper.get_client(
            awshelper.ServiceName.cloudformation,
            region)
        response = cloudformation_client.create_stack(
            StackName=stack_name,
            TemplateBody=template_text,
            Parameters=parameters)
        logging.info(f'create stack response: {response}')
        stacks.append(StackDetails(cloudformation_client, stack_name))
    wait_for_stack_operations_to_finish(
        stacks,
        'create_in_progress',
        'create_complete',
        20)

def create_inventory_configuration_helper(account_id):
    """ Helper function to create inventory configurations

    Arguments:
        account_id {string} -- AWS account id
    """
    input_parameters = ddb.get_input_parameters()
    source_buckets = get_source_buckets(input_parameters, account_id)
    ddb.store_source_buckets(source_buckets)
    create_bucket_inventory_configurations(
        input_parameters.run_id,
        source_buckets)

def create_bucket_inventory_configurations(run_id, source_buckets):
    """ Enable S3 inventory for the given list of source buckets

    Arguments:
        run_id {string} -- run_id for the current Step Function execution
        source_buckets {dict<string, dict<string, list(string)>>} -- Source buckets
    """
    host_account_id = awshelper.SessionManager.get_host_account_id()
    for account_id in source_buckets:
        for region in source_buckets[account_id]:
            s3_resource = awshelper.get_resource(awshelper.ServiceName.s3, account_id, run_id)
            s3_client = awshelper.get_client(
                awshelper.ServiceName.s3,
                region,
                account_id,
                run_id)
            for bucket_name in source_buckets[account_id][region]:
                logging.info(f'Processing {bucket_name} in {region} from {account_id}')
                is_empty, client_error = is_bucket_empty(s3_resource, bucket_name)
                if client_error is None:
                    if is_empty:
                        # Update DB status
                        logging.info(f'{bucket_name} in {region} from {account_id} is empty')
                        ddb.update_source_bucket_inventory_status(bucket_name, ddb.BucketInventoryStatus.bucket_is_empty)
                    else:
                        destination_prefix = account_id + "/" + region
                        destination_bucket = "arn:aws:s3:::" + get_destination_bucket_name(run_id, region)
                        inventory_id = utility.get_resource_name(run_id, 's3-inventory', 'orc')
                        inventory_configuration_orc = {
                            "Schedule": {
                                "Frequency": "Daily"
                            },
                            "IsEnabled": True,
                            "Destination": {
                                "S3BucketDestination": {
                                    "Prefix": destination_prefix,
                                    "Format": "ORC",
                                    "Bucket": destination_bucket,
                                    "AccountId": host_account_id
                                }
                            },
                            "OptionalFields": [
                                "Size",
                                "LastModifiedDate",
                                "StorageClass",
                                "ETag",
                                "ReplicationStatus",
                                "IsMultipartUploaded",
                                "EncryptionStatus",
                                "ObjectLockMode",
                                "ObjectLockRetainUntilDate",
                                "ObjectLockLegalHoldStatus"
                            ],
                            "IncludedObjectVersions": "All",
                            "Id": inventory_id
                        }
                        try:
                            response = s3_client.put_bucket_inventory_configuration(
                                Bucket=bucket_name,
                                Id=inventory_id,
                                InventoryConfiguration=inventory_configuration_orc)
                            logging.info(f'put bucket inventory configuration response:{response}')
                            ddb.update_source_bucket_inventory_status(bucket_name, ddb.BucketInventoryStatus.in_progress)
                        except ClientError as e:
                            logging.error(f'error while creating inventory configuration on {account_id}:{region}:{bucket_name}. error details:{e}')

def remove_bucket_inventory_configurations(input_parameters, source_buckets_ddb):
    """ Remove inventory configurations from the given list of source buckets

    Arguments:
        input_parameters {config.S3InsightsInput} -- Input parameters for the current execution
        source_buckets_ddb {dict<string, dict<string, list(string)>>} -- Source buckets
    """
    for account_id in source_buckets_ddb:
        for region in source_buckets_ddb[account_id]:
            s3_client = awshelper.get_client(
                awshelper.ServiceName.s3,
                region,
                account_id,
                input_parameters.run_id)

            for bucket in source_buckets_ddb[account_id][region]:
                bucket_name = bucket.name
                remove_bucket_inventory_configuration_internal(
                    s3_client,
                    input_parameters.run_id,
                    account_id,
                    region,
                    bucket_name)

def remove_bucket_inventory_configuration(run_id, account_id, region, bucket_name):
    """ Remove inventory configuration from the given S3 bucket

    Arguments:
        run_id {string} -- run_id for the current Step Function execution
        account_id {string} -- AWS account id
        region {string} -- AWS region name
        bucket_name {string} -- Bucket name
    """
    s3_client = awshelper.get_client(
        awshelper.ServiceName.s3,
        region,
        account_id,
        run_id)
    remove_bucket_inventory_configuration_internal(s3_client, run_id, account_id, region, bucket_name)

def remove_bucket_inventory_configuration_internal(s3_client, run_id, account_id, region, bucket_name):
    """ Helper function for removing nventory configuration from the given S3 bucket

    Arguments:
        s3_client {boto3.S3.Client} -- Boto3 S3 client
        run_id {string} -- run_id for the current Step Function execution
        account_id {string} -- AWS account id
        region {string} -- AWS region name
        bucket_name {string} -- Bucket name
    """
    try:
        id = utility.get_resource_name(run_id, 's3-inventory', 'orc')
        response = s3_client.delete_bucket_inventory_configuration(
            Bucket=bucket_name,
            Id=id)
        logging.info(f'delete bucket inventory response for {account_id}:{region}:{bucket_name} = {response}')
    except ClientError as e:
        logging.error(f'error while deleting inventory configuration from {account_id}:{region}:{bucket_name}. error details:{e}')

def get_inventory_prefix_at_consolidated_bucket(run_id):
    """ Get the prefix to use for partitioning inventory objects

    Arguments:
        run_id {string} -- run_id for the current Step Function execution

    Returns:
        string -- S3 prefix
    """
    return f'{config.ServiceParameters.consolidated_inventory_s3_folder}/{run_id}/'

def copy_inventory_object_into_consolidation_bucket(run_id, source_bucket_name, source_object_key, destination_bucket_name):
    """ Copy inventory object into the consolidation bucket

    Arguments:
        run_id {string} -- run_id for the current Step Function execution
        source_bucket_name {string} -- Source bucket name
        source_object_key {string} -- Source object key
        destination_bucket_name {string} -- Destination bucket name
    """
    session = awshelper.SessionManager.get_host_aws_session()
    s3_resource = session.resource('s3', config=botocore_config(s3={'use_accelerate_endpoint': True}))
    object_key_parts = source_object_key.split('/')
    object_key_parts_len = len(object_key_parts)
    new_object_key = "{0}account={1}/region={2}/bucketname={3}/{4}".format(
        get_inventory_prefix_at_consolidated_bucket(run_id),
        object_key_parts[0],
        object_key_parts[1],
        object_key_parts[2],
        object_key_parts[object_key_parts_len - 1])

    copy_source = {
        'Bucket': source_bucket_name,
        'Key': source_object_key
    }

    try:
        s3_resource.meta.client.copy(
            copy_source,
            destination_bucket_name,
            new_object_key)
    except ClientError as e:
        if 'Error' in e.response and 'Code' in e.response['Error']['Code'] and utility.compare_strings(e.response['Error']['Code'], "slowdown"):
            wait_in_seconds = random.randint(1, 120)

            # S3 is throttling upload operations. Let's back off for a few seconds
            logging.warning(f's3 is throttling copy request for {source_bucket_name}:{source_object_key}. wait time in seconds:{wait_in_seconds}')
            time.sleep(wait_in_seconds)
        raise

def delete_regional_s3_inventory_bucket(input_parameters, region):
    """ Delete the staging destination bucket for the given region

    Arguments:
        input_parameters {config.S3InsightsInput} -- Input parameters for the current execution
        region {string} -- AWS region name
    """
    s3_resource = awshelper.get_resource(awshelper.ServiceName.s3)
    bucket_name = get_destination_bucket_name(input_parameters.run_id, region)
    logging.info(f'deleting all objects from {region} {bucket_name}')
    try:
        bucket = s3_resource.Bucket(bucket_name)
        bucket.objects.all().delete()
    except ClientError as e:
        logging.error(f'error while deleting all s3 objects from inventory destination bucket {bucket_name}. error details: {e}')

    cloudformation_client = awshelper.get_client(
        awshelper.ServiceName.cloudformation,
        region)
    stack_name = get_stack_name(input_parameters.run_id)
    logging.info(f'deleting cloudformation stack {stack_name} from {region}')
    try:
        response = cloudformation_client.delete_stack(
            StackName=stack_name)
        logging.info(response)
    except ClientError as e:
        logging.error(f'error while deleting inventory destnation bucket stack {stack_name} for {region} region. error details: {e}')

def update_source_bucket_inventory_status(input_parameters, account_id):
    """ Update inventory status for all applicable source buckets under the given AWS account

    Arguments:
        input_parameters {config.S3InsightsInput} -- Input parameters for the current execution
        account_id {string} -- AWS account id
    """
    source_buckets = get_source_buckets(input_parameters, account_id)
    source_buckets_details = ddb.get_source_buckets_details(account_id)
    s3_resources = {}
    for ddb_bucket in source_buckets_details:
        inventory_status = ddb_bucket[ddb.TableFieldName.inventory_status]
        if utility.compare_strings(inventory_status, ddb.BucketInventoryStatus.in_progress):
            ddb_account_id = ddb_bucket[ddb.TableFieldName.account_id]
            ddb_region = ddb_bucket[ddb.TableFieldName.region]
            ddb_bucket_name = ddb_bucket[ddb.TableFieldName.sortkey]

            if not (ddb_account_id in source_buckets
                    and ddb_region in source_buckets[ddb_account_id]
                    and ddb_bucket_name in source_buckets[ddb_account_id][ddb_region]):
                logging.info(f'{ddb_bucket_name} not available anymore. updating the ddb entry')
                ddb.update_source_bucket_inventory_status(
                    ddb_bucket_name,
                    ddb.BucketInventoryStatus.bucket_not_available)
            else:
                if ddb_account_id not in s3_resources:
                    s3_resources[ddb_account_id] = awshelper.get_resource(awshelper.ServiceName.s3, ddb_account_id, input_parameters.run_id)
                s3_resource = s3_resources[ddb_account_id]
                is_empty, client_error = is_bucket_empty(s3_resource, ddb_bucket_name)
                remove_inventory_configuration = False
                if client_error is not None:
                    logging.info(f'{ddb_bucket_name} bucket access lost for some reason. updating the ddb entry')
                    ddb.update_source_bucket_inventory_status(
                        ddb_bucket[ddb.TableFieldName.sortkey],
                        ddb.BucketInventoryStatus.bucket_access_lost)
                    remove_inventory_configuration = True
                elif is_empty:
                    logging.info(f'{ddb_bucket_name} is empty. Updating the DDB entry')
                    ddb.update_source_bucket_inventory_status(
                        ddb_bucket[ddb.TableFieldName.sortkey],
                        ddb.BucketInventoryStatus.bucket_is_empty)
                    remove_inventory_configuration = True

                if remove_inventory_configuration:
                    remove_bucket_inventory_configuration(
                        input_parameters.run_id,
                        ddb_account_id,
                        ddb_region,
                        ddb_bucket_name)

def process_inventory_object(event):
    """ Process an inventory object once it has been stored in a staging destination bucket

    Arguments:
        event {json} -- S3 notification event
    """
    if 'Records' in event:
        input_parameters = ddb.get_input_parameters()
        for record in event['Records']:
            if 'body' in record:
                body_json = json.loads(record['body'])
                if 'Records' in body_json:
                    for record in body_json['Records']:
                        if 'eventName' in record and record['eventName'] == 'ObjectCreated:Put':
                            source_bucket_name = record['s3']['bucket']['name']
                            if is_destination_bucket_name(input_parameters, source_bucket_name):
                                source_object_key = record['s3']['object']['key']
                                object_key_parts = source_object_key.split('/')
                                object_key_parts_len = len(object_key_parts)

                                bucket_account_id = object_key_parts[0].lower()
                                bucket_region = object_key_parts[1].lower()
                                bucket_name = object_key_parts[2].lower()
                                logging.info(f'source_object_key:{source_object_key} bucket_account_id:{bucket_account_id} bucket_name:{bucket_name}')
                                if ddb.is_inprogress_inventory_job(bucket_account_id, bucket_name):
                                    if object_key_parts_len > 4:
                                        if utility.compare_strings(object_key_parts[object_key_parts_len - 1], 'manifest.checksum'):
                                            ddb.update_source_bucket_inventory_status(object_key_parts[2], ddb.BucketInventoryStatus.done)
                                            remove_bucket_inventory_configuration(
                                                input_parameters.run_id,
                                                bucket_account_id,
                                                bucket_region, bucket_name
                                            )
                                        elif utility.compare_strings(object_key_parts[object_key_parts_len - 2], 'data'):
                                            copy_inventory_object_into_consolidation_bucket(
                                                input_parameters.run_id,
                                                source_bucket_name,
                                                source_object_key,
                                                config.DeploymentDetails.consolidated_inventory_bucket_name
                                            )
                                else:
                                    logging.warning('Received an unexpected SQS notification')


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

def main():
	img_path = '/home/shahadat/Desktop/DIP/white_bird.jpeg'
	rgb = plt.imread(img_path)

	grayscale = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)

	kernel1 = np.ones((3, 3), dtype = np.float32) * 2 / 7
	kernel2 = np.array([[0, 1, 0], [-3, 0, 1], [-1, 2, 1]])
	kernel3 = np.ones((3, 3), dtype = np.float32) * 3 /20
	kernel4 = np.array([[0, 2, 1], [1, -1, -1], [1, -1, 0]])
	kernel5 = np.ones((3, 3), dtype = np.float32) /4
	kernel6 = np.array([[1, 0, -1], [0,1,0], [0,0,1]])

	processed_img1 = cv2.filter2D(grayscale, -1, kernel1)
	processed_img2 = cv2.filter2D(grayscale, -1, kernel2)
	processed_img3 = cv2.filter2D(grayscale, -1, kernel3)
	processed_img4 = cv2.filter2D(grayscale, -1, kernel4)
	processed_img5 = cv2.filter2D(grayscale, -1, kernel5)
	processed_img6 = cv2.filter2D(grayscale, -1, kernel6)

	img_set = [rgb, grayscale, processed_img1, processed_img2,processed_img3,processed_img4,processed_img5,processed_img6]
	title_set = ['RGB', 'Grayscale', 'Kernel1', 'Kernel2','Kernel3', 'Kernel4','Kernel5', 'Kernel6']
	plot_img(img_set, title_set)

def plot_img(img_set, title_set):
	n = len(img_set)
	plt.figure(figsize = (15, 15))
	for i in range(n):
		img = img_set[i]
		ch = len(img.shape)

		plt.subplot(4, 2, i + 1)
		if (ch == 3):
			plt.imshow(img_set[i])
		else:
			plt.imshow(img_set[i], cmap = 'gray')
		plt.title(title_set[i])
		plt.subplots_adjust(left=0.1,
		            bottom=0.01,
		            right=1,
		            top=0.95,
		            wspace=0.0,
		            hspace=0.5)

	plt.show()

if __name__ == '__main__':
	main()


"""
    This package contains the following functionalities:

    1) Example usage of CoAP.
    2) Attacks that is done on CoAP
    3) CoAP Scanner
    4) Old Attack Scripts for CoAP
    5) CoAP Protocol

    Moreover, we have a class which inherits from Protocol class.
"""

from coapthon.client.helperclient import HelperClient

import enum
import logging

FORMAT = "%(asctime)s:%(levelname)s:%(name)s:%(message)s"
logging.basicConfig(level=logging.DEBUG, format=FORMAT)
logger = logging.getLogger("CoAP Init")

class CoAPMethods(enum.Enum):
    EMPTY = 0
    GET = 1
    POST = 2
    PUT = 3
    DELETE = 4

def does_method_have_payload(method):
    """
    :type method: CoAPMethods
    :param method: Method which is tested to have paylaod
    :return: Whether method has payload or not
    """
    return method in [CoAPMethods.POST, CoAPMethods.PUT]

def make_request(client, _path, _method_type, _payload=None):
    """
    :param _path: Path to be fuzzed
    :param _method_type: Which CoAP method will be used while fuzzing
    :param _payload: Payload to be fuzzed
    :type client: HelperClient
    :return response: Response of request if proper request is done, otherwise None
    """
    try:
        response = None
        if _method_type == CoAPMethods.GET:
            response = client.get(_path)
        elif _method_type == CoAPMethods.POST:
            response = client.post(_path, _payload)
        elif _method_type == CoAPMethods.PUT:
            response = client.put(_path, _payload)
        elif _method_type == CoAPMethods.DELETE:
            response = client.delete(_path)
        return response
    except UnicodeEncodeError:
        logger.error("Unicode encoding error is occurred!")

def get_coap_methods_by_name(method_string):
    uppered_method_name = method_string.upper()
    if uppered_method_name == "EMPTY":
        return CoAPMethods.EMPTY
    elif uppered_method_name == "GET":
        return CoAPMethods.GET
    elif uppered_method_name == "POST":
        return CoAPMethods.POST
    elif uppered_method_name == "PUT":
        return CoAPMethods.PUT
    elif uppered_method_name == "DELETE":
        return CoAPMethods.DELETE
    else:
        logger.error("Unknown CoAP Method Type!")
        return CoAPMethods.POST

def get_coap_methods_as_string(method):
    if method == CoAPMethods.EMPTY:
        return "EMPTY"
    elif method == CoAPMethods.GET:
        return "GET"
    elif method == CoAPMethods.POST:
        return "POST"
    elif method == CoAPMethods.PUT:
        return "PUT"
    elif method == CoAPMethods.DELETE:
        return "DELETE"
    else:
        logger.error("Unknown CoAP Method Type!")
        return "None"


# coding=utf-8

from marshmallow import Schema, fields

from sqlalchemy import Column, String

from .entity import Entity, Base

class Pokemon(Entity, Base):
    __tablename__ = 'pokemons'

    name = Column(String)
    elem_type = Column(String)

    def __init__(self, name, elem_type, created_by):
        Entity.__init__(self, created_by)
        self.name = name
        self.elem_type = elem_type

class PokemonSchema(Schema):
    id = fields.Number()
    name = fields.Str()
    elem_type = fields.Str()
    created_at = fields.DateTime()
    updated_at = fields.DateTime()
    last_updated_by = fields.Str()


from poster_details.poster_details import poster
from display.show_recommendations import show
class movie_details:

    def get_details(df):

        movie_list = []
        movie_poster = []
        length = len(df)

        for i in range(length):
            m_name = df.iloc[i].title
            m_id = df.iloc[i].id

            m_poster = poster.fetch_poster(m_id)

            movie_list.append(m_name)
            movie_poster.append(m_poster)

        show.show_details(movie_list, movie_poster)


#!/bin/python3.8
import csv
# read

# write
with open('MOCK_DATA.csv', 'a', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerow([3, 'Corri', 'Campling', 'Female', 'Sweden'])

with open('MOCK_DATA.csv', newline='') as csvfile:
    reader = csv.reader(csvfile )# , delimiter=',', quotechar='"')
    for row in reader:
        print( ', '.join(row))


from django.db import models

def make_list_danish(list_of_strings):
    danish_text = u""
    if len(list_of_strings) > 1:
        first_items = list_of_strings[:-1]
        first_items_as_string = u", ".join(first_items)
        last_item = list_of_strings[-1]
        danish_text = u"%s og %s" % (first_items_as_string, last_item)
    else:
        danish_text = u", ".join(list_of_strings)
    return danish_text

class Profession(models.Model):
    name = models.CharField(
        max_length=255, db_index=True, unique=True, verbose_name="Profession"
    )

    def __str__(self):
        return self.name

    class Meta:
        ordering = ["name"]
        verbose_name = "profession"
        verbose_name_plural = "professioner"

class Nationality(models.Model):
    name = models.CharField(
        max_length=255, db_index=True, unique=True, verbose_name="Nationalitet"
    )

    def __str__(self):
        return self.name

    class Meta:
        ordering = ["name"]
        verbose_name = "nationalitet"
        verbose_name_plural = "nationaliteter"

class Person(models.Model):
    first_name = models.CharField(
        max_length=255,
        blank=True,
        db_index=True,
        verbose_name="Fornavn og evt. mellemnavne",
    )
    last_name = models.CharField(
        max_length=255,
        db_index=True,
        verbose_name="Efternavn (eller fyrstenavn (dvs. f.eks."
        " Alexander den Store))",
    )
    uid = models.CharField(
        max_length=255,
        db_index=True,
        unique=True,
        verbose_name="Unik xml-venlig id. Skriv f.eks. soeren-oegaard, hvis"
        " navnet er Søren Øgård.",
    )
    year_born = models.IntegerField(
        db_index=True, blank=True, null=True, verbose_name="Fødselsår"
    )
    year_born_is_approx = models.BooleanField(
        blank=True, verbose_name="Fødselsåret er omtrentligt"
    )
    year_dead = models.IntegerField(
        db_index=True, blank=True, null=True, verbose_name="Evt. dødsår"
    )
    year_dead_is_approx = models.BooleanField(
        blank=True, verbose_name="Dødsåret er omtrentligt"
    )
    notes_about_life_span = models.CharField(
        max_length=255,
        db_index=True,
        blank=True,
        null=True,
        verbose_name="Alternativ angivelse af leve- el. virketid",
    )
    nationality = models.ForeignKey(
        Nationality, blank=True, null=True, verbose_name="Nationalitet",
        on_delete=models.PROTECT
    )
    secondary_nationality = models.ForeignKey(
        Nationality,
        blank=True,
        null=True,
        related_name="nationality_relation",
        verbose_name='Sekundær Nationalitet. Hvis personen er'
        ' amerikansk-engelsk vælges engelsk i dette felt'
        ' (og amerikansk i feltet "Nationalitet")',
        on_delete=models.PROTECT
    )
    variants = models.TextField(
        blank=True,
        verbose_name="Pseudonymer, tidligere navne eller øgenavne.  Skriv"
        " et pr. linje",
    )
    description_of_profession = models.CharField(
        max_length=255,
        db_index=True,
        blank=True,
        null=True,
        verbose_name='Oplysninger om profession og/eller stand. F.eks.'
        ' "kejserinde af Rusland fra 1730"',
    )
    profession = models.ManyToManyField(
        Profession,
        blank=True,
        verbose_name="Profession og/eller stand. Forfatter",
    )
    profession_order = models.CharField(
        max_length=255,
        blank=True,
        verbose_name="Rækkefølge hvis professionerne ikke skal"
        " vises alfabetisk",
    )
    notes = models.TextField(
        blank=True,
        verbose_name="Andre informationer om personen (vises overalt)",
    )
    editorial_notes = models.TextField(
        blank=True,
        verbose_name="Redaktionelle bemærkninger (bliver ikke vist)",
    )

    def __str__(self):
        full_name = self.last_name + ", " + self.first_name
        if full_name.endswith(", ") or full_name.startswith(", "):
            full_name = full_name.replace(", ", "")

        year_born = self.year_born
        if year_born is not None and str(year_born).startswith("-"):
            year_born = str(year_born)[1:] + " f.Kr."

        year_dead = self.year_dead
        if year_dead is not None and str(year_dead).startswith("-"):
            year_dead = str(year_dead)[1:] + " f.Kr."

        if self.year_born_is_approx:
            year_born = "ca. %s" % year_born
        if self.year_dead_is_approx:
            year_dead = "ca. %s" % year_dead

        if not (year_born and year_dead):
            lifespan = " ({})".format(self.notes_about_life_span)
        else:
            lifespan = " ({}-{})".format(year_born, year_dead)
        if year_born and not year_dead:
            lifespan = " (født {})".format(year_born)
        if not year_born and year_dead:
            lifespan = " (død {})".format(year_dead)
        if self.notes_about_life_span:
            lifespan = " (%s)" % self.notes_about_life_span
        if self.year_born is not None and self.year_dead is not None:
            if self.year_born < 0 and self.year_dead > 0:
                lifespan = lifespan[:-1] + " e.Kr)"

        lifespan = lifespan.replace(" (None)", "").replace("()", "")
        full_name += lifespan

        profession = self.description_of_profession
        if self.nationality is not None:
            full_name += ", %s" % self.nationality.name
        elif profession:
            full_name += ", "
        if self.secondary_nationality is not None:
            full_name += "-%s" % self.secondary_nationality.name

        full_name += " %s" % profession
        if self.notes:
            full_name += " (%s)" % self.notes
        full_name += "."
        return full_name

    class Meta:
        ordering = ["last_name", "first_name", "year_born"]
        verbose_name = "person"
        verbose_name_plural = "personer"
        unique_together = (
            ("first_name", "last_name", "year_born", "year_dead"),
        )

class LocationType(models.Model):
    name = models.CharField(
        max_length=255,
        db_index=True,
        unique=True,
        verbose_name="Geografisk kategori",
    )

    def __str__(self):
        return self.name

    class Meta:
        ordering = ["name"]
        verbose_name = "Geografisk kategori"
        verbose_name_plural = "Geografiske kategorier"

class Country(models.Model):
    name = models.CharField(
        max_length=255, db_index=True, verbose_name="Land", unique=True
    )

    def __str__(self):
        return self.name

    class Meta:
        ordering = ["name"]
        verbose_name = "land"
        verbose_name_plural = "lande"

class City(models.Model):
    name = models.CharField(
        max_length=255, db_index=True, verbose_name="navn", unique=True
    )
    country = models.ForeignKey(
        Country, blank=True, null=True, verbose_name="Land", on_delete=models.PROTECT
    )

    def __str__(self):
        return self.name

    class Meta:
        ordering = ["name"]
        verbose_name = "by"
        verbose_name_plural = "byer"

class Location(models.Model):
    name = models.CharField(
        max_length=255, db_index=True, verbose_name="Officielt navn for stedet"
    )
    uid = models.CharField(
        max_length=255,
        db_index=True,
        unique=True,
        null=True,
        verbose_name='Unik xml-venlig id. Skriv f.eks.  koebenhavns-raadhus,'
        ' hvis navnet er "Københavns Rådhus"',
    )
    variants = models.TextField(
        blank=True,
        verbose_name="Evt. alternative stavemåder eller uofficielle navne"
        " for stedet. Skriv et pr. linje",
    )
    location_type = models.ManyToManyField(
        LocationType, blank=True, verbose_name="Kategori",
    )
    city = models.ForeignKey(City, blank=True, null=True, verbose_name="By",
        on_delete=models.PROTECT
    )
    country = models.ManyToManyField(Country, blank=True, verbose_name="Land",)
    notes = models.TextField(blank=True, verbose_name="Noter (vises overalt)")
    editorial_notes = models.TextField(
        blank=True,
        verbose_name="Redaktionelle bemærkninger (bliver ikke vist)",
    )

    def __str__(self):
        country_list = self.country.all()
        location_list = self.location_type.all()
        countries = make_list_danish([c.name for c in country_list])
        categories = make_list_danish([c.name for c in location_list])
        full_title = ""
        if country_list and location_list:
            full_title = "%s, %s i %s" % (self.name, categories, countries)
        elif location_list:
            full_title = "%s, %s" % (self.name, categories)
        elif country_list:
            full_title = "%s, %s" % (self.name, countries)
        else:
            full_title = self.name

        notes = self.notes
        if notes:
            notes = " (%s)" % notes
        full_title += notes
        full_title += "."
        return full_title

    class Meta:
        ordering = ["name"]
        verbose_name = "sted"
        verbose_name_plural = "steder"

class Genre(models.Model):
    name = models.CharField(
        max_length=255, db_index=True, unique=True, verbose_name="Genre"
    )

    def __str__(self):
        return self.name

    class Meta:
        ordering = ["name"]
        verbose_name = "genre"
        verbose_name_plural = "genrer"

class Publication(models.Model):
    author = models.ManyToManyField(
        Person,
        blank=True,
        # limit_choices_to = {'profession__name': 'forfatter'},
        verbose_name="Forfatter(e)",
    )
    title = models.CharField(
        max_length=255,
        db_index=True,
        blank=True,
        verbose_name="Titel (på originalsproget)",
    )
    danish_title = models.CharField(
        max_length=255, db_index=True, blank=True, verbose_name="Dansk titel"
    )
    uid = models.CharField(
        max_length=255,
        db_index=True,
        unique=True,
        null=True,
        verbose_name="Unik xml-venlig id. Skriv f.eks. "
        "heiberg-en-sjael-efter-doeden",
    )
    part_of = models.CharField(
        max_length=255,
        db_index=True,
        blank=True,
        verbose_name="Trykt/indgår i",
    )
    year_first_published = models.IntegerField(
        db_index=True,
        blank=True,
        null=True,
        verbose_name="Originalens udgivelsesår",
    )
    notes_about_publishing_years = models.CharField(
        max_length=255,
        db_index=True,
        blank=True,
        verbose_name="Noter om udgivelsesår (Hvis værket er udgivet over en"
        " årrække eller hvis der er andre udgivelser)",
    )
    variants = models.TextField(
        blank=True, verbose_name="Alternative titler. Skriv en pr. linje"
    )
    genre = models.ManyToManyField(Genre, blank=True, verbose_name="genre(r)")
    notes = models.TextField(
        blank=True, verbose_name="Andre informationer om værket (vises altid)"
    )
    editorial_notes = models.TextField(
        blank=True,
        verbose_name="Redaktionelle bemærkninger (bliver ikke vist)",
    )

    class Meta:
        ordering = [
            "author__last_name",
            "author__first_name",
            "title",
            "year_first_published",
        ]
        verbose_name = "værk"
        verbose_name_plural = "værker"
        # unique_together = (
        #  ("author__lastname", "title","year_first_published"),
        # )

    def __str__(self, first_name_of_author_first=False):
        authors = self.author.values()
        genre = make_list_danish([genre.name for genre in self.genre.all()])
        if genre:
            genre = ", %s" % genre
        part_of = self.part_of
        if part_of:
            part_of = ", %s" % part_of
        publication_year = self.year_first_published
        if publication_year:
            if publication_year is not None and str(
                publication_year
            ).startswith("-"):
                publication_year = str(publication_year)[1:] + " f.Kr."
            publication_year = ", %s" % (publication_year)
        elif self.notes_about_publishing_years:
            publication_year = ", %s" % (self.notes_about_publishing_years)
        else:
            publication_year = ""

        full_author_names = []

        for author in authors:
            if first_name_of_author_first:
                full_name = author["first_name"] + " " + author["last_name"]
            else:
                full_name = author["last_name"] + ", " + author["first_name"]
            if full_name.endswith(", "):
                full_name = full_name[:-2]
            full_author_names.append(full_name)

        full_author_names = ", ".join(full_author_names).strip()
        if full_author_names == "":
            full_author_names = "(ingen forfatter)"
        title = self.title
        if not title:
            title = self.danish_title

        called_from_character_view = first_name_of_author_first
        notes = ""
        if not called_from_character_view:
            notes = self.notes
            if notes and not called_from_character_view:
                notes = " (%s)" % notes

        full_title = "%s: %s%s%s%s%s" % (
            full_author_names,
            title,
            part_of,
            genre,
            publication_year,
            notes,
        )
        if not called_from_character_view:
            full_title += "."
        if len(full_title) > 250:
            full_title = full_title[:250] + "..."

        return full_title

class Character(models.Model):
    name = models.CharField(
        max_length=255,
        db_index=True,
        verbose_name="fornavn og evt. mellemnavne",
    )
    uid = models.CharField(
        max_length=255,
        db_index=True,
        unique=True,
        verbose_name="Unik xml-venlig id. Skriv f.eks.  soeren-oegaard,"
        " hvis navnet er Søren Øgård",
    )
    variants = models.TextField(
        blank=True,
        verbose_name="Pseudonymer, tidligere navne eller"
        " øgenavne. Skriv et pr. linje",
    )
    publication = models.ForeignKey(
        Publication, blank=True, null=True, verbose_name="Værk",
        on_delete=models.PROTECT,
    )
    notes = models.TextField(
        blank=True, verbose_name="Noter om personen (vises overalt)"
    )
    editorial_notes = models.TextField(
        blank=True,
        verbose_name="Redaktionelle bemærkninger (bliver ikke vist)",
    )

    class Meta:
        ordering = ["name"]
        verbose_name = "litterær figur"
        verbose_name_plural = "litterære figurer"
        # unique_together = (("name","publication.title"),)

    def __str__(self):
        publication = ""
        name_of_character = "%s" % (self.name)
        if self.publication is not None:
            publication = " (%s)" % (
                self.publication.__str__(first_name_of_author_first=True)
            )
        full_title = name_of_character + publication
        full_title += "."
        return full_title

class LiteratureSourceAuthor(models.Model):
    first_name = models.CharField(
        max_length=255,
        blank=True,
        db_index=True,
        verbose_name="Fornavn og evt. mellemnavne",
    )
    last_name = models.CharField(
        max_length=255, blank=True, db_index=True, verbose_name="Efternavn"
    )

    def __str__(self):
        full_name = self.last_name + ", " + self.first_name
        if full_name.endswith(", ") or full_name.startswith(", "):
            full_name = full_name.replace(", ", "")
        return full_name

    class Meta:
        ordering = ["last_name"]
        verbose_name = "forfattere af sekundærlitteratur"
        verbose_name_plural = "forfatter af sekundærlitteratur"
        # unique_together = (("first_name", "last_name"),)

class LiteratureSource(models.Model):
    author = models.ManyToManyField(
        LiteratureSourceAuthor, blank=True, verbose_name="Hovedforfatter"
    )
    other_authors = models.CharField(
        max_length=255,
        db_index=True,
        blank=True,
        verbose_name="Evt. andre forfattere",
    )
    title = models.CharField(
        max_length=255, db_index=True, blank=True, verbose_name="Titel"
    )
    publication_id = models.CharField(
        max_length=255,
        db_index=True,
        unique=True,
        null=True,
        verbose_name="Unik xml-venlig id. Skriv"
        " f.eks. heiberg-en-sjael-efter-doeden",
    )
    editors = models.CharField(
        max_length=255, db_index=True, blank=True, verbose_name="Redaktører"
    )
    anthology = models.CharField(
        max_length=255,
        db_index=True,
        blank=True,
        verbose_name="Del af antologien:",
    )
    journal = models.CharField(
        max_length=255,
        db_index=True,
        blank=True,
        verbose_name="Indgår i denne avis, tidsskrift eller bogserie",
    )
    location_of_publication = models.ManyToManyField(
        City, db_index=True, blank=True, verbose_name="Udgivelsessted (by)"
    )
    publication_year = models.IntegerField(
        db_index=True, blank=True, null=True, verbose_name="Udgivelsesår"
    )
    publication_end_year = models.IntegerField(
        db_index=True,
        blank=True,
        null=True,
        verbose_name="Sidste udgivelsesår, i tilfælde af at publikationen"
        " er udgivet over en årrække",
    )
    publication_is_still_being_published = models.BooleanField(
        blank=True, verbose_name="Værket er fortsat under udgivelse"
    )
    pages = models.CharField(
        max_length=255,
        db_index=True,
        blank=True,
        verbose_name="Sideinterval f.eks. 155-161",
    )
    notes = models.TextField(
        blank=True,
        verbose_name="Andre informationer om værket (vises overalt)",
    )
    editorial_notes = models.TextField(
        blank=True,
        verbose_name="Redaktionelle bemærkninger (bliver ikke vist)",
    )

    class Meta:
        ordering = ["author__last_name"]
        verbose_name = "litteratur"
        verbose_name_plural = "litteratur"
        # unique_together = (("title", "year_first_published"),)

    def __str__(self):
        authors = self.author.values()
        full_author_names = [
            author["first_name"] + " " + author["last_name"]
            for author in authors
        ]
        full_author_names = ", ".join(full_author_names).strip()
        if full_author_names == "":
            full_author_names = "(uden forfatter)"
        title = self.title
        if not title:
            title = self.danish_title
        publication_year_end = ""
        if self.publication_end_year:
            publication_year_end = "-%s" % self.publication_end_year
        if self.publication_is_still_being_published:
            publication_year_end = "-"
        publication_year_text = ", %s%s" % (
            self.publication_year,
            publication_year_end,
        )
        editors = self.editors
        if self.editors:
            editors = ", %s (red.)" % editors
        anthology = self.anthology
        if self.anthology:
            anthology = ", %s" % anthology
        journal = self.journal
        if self.journal:
            journal = ", %s" % journal
        pages = self.pages
        if self.pages:
            pages = ", %s" % pages
        notes = self.notes
        if notes:
            notes = " (%s)" % notes
        return "%s: %s%s%s%s%s%s%s." % (
            full_author_names,
            title,
            editors,
            anthology,
            journal,
            publication_year_text,
            pages,
            notes,
        )

class Note(models.Model):
    volume = models.PositiveIntegerField(
        db_index=True, blank=True, null=True, verbose_name="Bind"
    )
    page = models.PositiveIntegerField(
        db_index=True, blank=True, null=True, verbose_name="Side"
    )
    line = models.PositiveIntegerField(
        db_index=True, blank=True, null=True, verbose_name="Linje"
    )
    note_letter = models.CharField(
        max_length=255,
        blank=True,
        verbose_name="Hvis der er flere noter på en linje, indtastes"
        " her et bogstav, typisk 'b' eller 'c' eller 'd' osv.",
    )
    note_id = models.CharField(
        max_length=255,
        db_index=True,
        null=True,
        verbose_name="Unik xml-venlig id. Indtast f.eks."
        " h-bind-1-side-4-linje-12-b hvis det er anden note i "
        "Hovedstrømninger bind 1, side 4, linje 12.",
    )
    lemma = models.CharField(max_length=1023, blank=True, verbose_name="Lemma")
    text = models.TextField(
        blank=True, verbose_name="Notetekst (vises overalt)"
    )
    literature_reference = models.ForeignKey(
        LiteratureSource,
        blank=True,
        null=True,
        verbose_name="Litteraturhenvisning",
        on_delete=models.PROTECT
    )
    link_text = models.CharField(
        max_length=1023,
        blank=True,
        verbose_name='Linktekst, f.eks. "Heinse 1787:5-6"',
    )
    editorial_notes = models.TextField(
        blank=True,
        verbose_name="Redaktionelle bemærkninger om noten (bliver ikke vist)",
    )

    class Meta:
        ordering = ["volume", "page", "line"]
        verbose_name = "note"
        verbose_name_plural = "noter"

    def __str__(self):
        volume_text = "bind %s" % self.volume
        if self.volume is None:
            volume_text = "(bind ikke angivet)"
        page_text = ""
        line_text = ""
        link_text = ""
        note_letter = ""
        if self.page is not None:
            page_text = ", side %s" % self.page
        if self.line is not None:
            line_text = ", linje %s" % self.line
        if self.link_text:
            link_text = "(%s)" % self.link_text
        if self.note_letter:
            note_letter = ", %s" % self.note_letter

        title = "%s%s%s%s (id=%s): %s] %s %s" % (
            volume_text,
            page_text,
            line_text,
            note_letter,
            self.id,
            self.lemma,
            self.text,
            link_text,
        )
        title = title.strip()
        if not title.endswith("."):
            title = title + "."
        return title

REVISION = "REVISION"
ADDITION = "ADDITION"
OMISSION = "OMISSION"
variant_type_choices = (
    (REVISION, "omarbejdelse"),
    (ADDITION, "tilføjelse"),
    (OMISSION, "udeladelse"),
)

class Variant(models.Model):

    variant_id = models.CharField(  # From the "<div id=.../>".
        max_length=255,
        db_index=True,
        null=True,
        verbose_name="Unik xml-venlig id. Gerne kombination"
        " af værk og tal, f.eks. 'hs1_001'",
    )

    variant_type = models.CharField(  # From the "<h1>...</h1>".
        max_length=128,
        verbose_name="type",
        choices=variant_type_choices,
        default=REVISION
    )
    variant_description = models.CharField(  # From the <h2.../> part.
        max_length=1024,
        db_index=True,
        null=True,
        verbose_name="Beskrivelse"
    )

    variant_text = models.TextField(  # Remainder of "<div>".
        blank=True, verbose_name="Variant-tekst"
    )

    class Meta:
        ordering = ["variant_id",]
        verbose_name = "variant"
        verbose_name_plural = "varianter"

    def __str__(self):
        return "{} - {} - {}".format(
            self.variant_id, self.variant_type, self.variant_description
        )


#
# @lc app=leetcode.cn id=344 lang=python3
#
# [344] 反转字符串
#

# @lc code=start
"""
这个题被修改了，我记得以前用JavaScript做的时候，是返回反转后的数组，现在需要原地修改数组了。
所以，list(reversed(s))和s[::-1]这种方法都用不成了。
那正确解法就是对撞双指针，也没啥难度。
Accepted
477/477 cases passed (44 ms)
Your runtime beats 43.61 % of python3 submissions
Your memory usage beats 20.53 % of python3 submissions (19.3 MB)
"""

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        p1, p2 = 0, len(s) - 1
        while p1 < p2:
            s[p1], s[p2] = s[p2], s[p1] # python的骚操作
            p1 += 1
            p2 -= 1
# @lc code=end


import sys
import pygame
from settings import *
from gmanager import GManager

class Game:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption('Checkers Game')
        # general setup
        self.screen = pygame.display.set_mode((WIDTH, HEIGTH))
        self.background = pygame.Surface((WIDTH, HEIGTH))
        self.background.fill(pygame.Color('#000000'))
        self.clock = pygame.time.Clock()
        self.gm = GManager()
        self.gm.game_init("human", "human")

    def run(self):
        while True:
            for event in pygame.event.get():
                # quit game
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                # game events
                self.gm.game_play(event)

            self.gm.update()
            pygame.display.update()
            self.screen.blit(self.background, (0, 0))
            self.clock.tick(FPS)

if __name__ == '__main__':
    game = Game()
    game.run()


#! /usr/bin/python
# Author: Kai Chen

# Make the Figure 3 for paper: Relationship between SC and Residual.

# %%
from fcpy.core import *
import numpy as np
import matplotlib.pyplot as plt
from MakeFigure1 import axis_log_formater, gen_sc_fc_figure_new
from matplotlib.ticker import MultipleLocator, AutoMinorLocator
# %%
path = 'image/'
data_tdmi = EcogTDMI()
data_tdmi.init_data(path, 'snr_th_kmean_tdmi.pkl')
sc_tdmi, fc_tdmi = data_tdmi.get_sc_fc('ch')
snr_mask_tdmi = data_tdmi.get_snr_mask(path, 'snr_th_kmean_tdmi.pkl')
roi_mask = data_tdmi.roi_mask.copy()

data_package = np.load('data/preprocessed_data.npz', allow_pickle=True)
dist_mat = data_package['d_matrix']
d_mat = {band: dist_mat[roi_mask] for band in data_tdmi.filters}

data_gc = EcogGC()
data_gc.init_data()
sc_gc, fc_gc = data_gc.get_sc_fc('ch')
# %%

fig, ax = plt.subplots(1,2,figsize=(9,4), dpi=400)

band = 'raw'
# new_mask = np.ones_like(snr_mask_tdmi[band])
new_mask = snr_mask_tdmi[band].copy()
new_mask[sc_tdmi[band]==0] = False
new_mask[sc_tdmi[band]==1.5] = False

d_metric = 1./d_mat[band]
# regression with distance to get residue
fc_tdmi_res = fc_tdmi[band].copy()
nan_mask = ~np.isnan(np.log10(fc_tdmi_res))
pval = np.polyfit(d_metric[nan_mask*new_mask], np.log10(fc_tdmi_res[nan_mask*new_mask]), deg=1)
fc_tdmi_res[nan_mask*new_mask] = np.abs(fc_tdmi_res[nan_mask*new_mask] - 10**np.polyval(pval, d_metric[nan_mask*new_mask]))

gen_sc_fc_figure_new(ax[0], fc_tdmi_res, sc_tdmi[band], new_mask,)

# new_mask = np.ones_like(new_mask, dtype=bool)
# new_mask[sc_gc[band]==0] = False
# new_mask[sc_gc[band]==1.5] = False
fc_gc_res = fc_gc[band].copy()
nan_mask = ~np.isnan(np.log10(fc_gc_res))
pval = np.polyfit(d_metric[nan_mask], np.log10(fc_gc_res[nan_mask]), deg=1)
fc_gc_res[nan_mask] = np.abs(fc_gc_res[nan_mask] - 10**np.polyval(pval, d_metric[nan_mask]))
gen_sc_fc_figure_new(ax[1], fc_gc_res, sc_gc[band], new_mask,)

for axi, labeli in zip(ax, ('TDMI', 'GC')):
    axi.set_title(axi.get_title().replace(band, labeli))
    axi.set_ylabel('Residual')
fig.suptitle(band)

fig.savefig(path+'Figure_3.png')
# %%
def Linear_R2(x:np.ndarray, y:np.ndarray, z:np.ndarray, pval:np.ndarray)->float:
    """Compute R-square value for linear fitting.

    Args:
        x (np.ndarray): variable 1 of function
        y (np.ndarray): variable 2 of function
        y (np.ndarray): image of function
        pval (np.ndarray): parameter of linear fitting

    Returns:
        float: R square value
    """
    mask = ~np.isnan(x)*~np.isnan(y)*~np.isnan(z)*~np.isinf(x)*~np.isinf(y)*~np.isinf(z)# filter out nan
    z_predict = x[mask]*pval[0]+y[mask]*pval[1] + pval[2]
    R = np.corrcoef(z[mask], z_predict)[0,1]
    return R**2

@axis_log_formater(axis='both')
def gen_sc_fc_figure_3d(ax, fc:np.ndarray,
                        sc:np.ndarray,
                        dist:np.ndarray,
                        snr_mask:np.ndarray=None,
                        is_log:bool=True,
)->plt.Figure:
    """Generated figure for analysis of causal distributions.

    Args:
        tdmi_flatten (np.ndarray): flattened data for target tdmi statistics.
        sc (np.ndarray): flattened data for true connectome.

    Returns:
        plt.Figure: matplotlib.figure.Figure
    """
    if snr_mask is None:
        snr_mask = np.ones_like(fc).astype(bool)
    if is_log:
        log_fc = np.log10(fc)
    else:
        log_fc = fc.copy()

    log_fc[~snr_mask] = np.nan
    # pval = np.polyfit(np.log10(sc+1e-6)[snr_mask], log_fc[snr_mask], deg=1)
    coef_mat = np.vstack((np.log10(sc+1e-6)[snr_mask], np.log10(dist)[snr_mask])).T
    coef_mat = np.hstack((coef_mat, np.ones((coef_mat.shape[0], 1)))) # adding bias
    b = log_fc[snr_mask]
    pval,_,_,_ = np.linalg.lstsq( coef_mat, b )
    # ax.plot3D(np.log10(sc+1e-6), np.log10(dist), log_fc.flatten(), 'k.', label='TDMI samples')
    ax.scatter3D(np.log10(sc+1e-6), np.log10(dist), log_fc, c='k', s=2, label='TDMI (above SNR th)', zorder=0)
    x_range = (ax.get_xticks()[0], ax.get_xticks()[-1])
    y_range = (ax.get_yticks()[0], ax.get_yticks()[-1])
    z_range = (ax.get_zticks()[0], ax.get_zticks()[-1])
    xx, yy = np.meshgrid(np.linspace(*x_range, 30),np.linspace(*y_range, 30))
    ax.plot_surface(xx, yy, xx * pval[0] + yy * pval[1] + pval[2],
        alpha=.5, cmap=plt.cm.coolwarm,
        edgecolors='royalblue', lw=0.,antialiased=False,
        zorder=0,
    )
    # ax.set_xlabel(r'$log_{10}$(Connectivity Strength)')
    # sc_buffer = sc.copy()
    # sc_buffer[sc_buffer==0] = np.nan
    # ax.set_xlim(*x_range)
    # ax.set_ylim(*y_range)
    # ax.set_zlim(*z_range)
    ax.set_title('r = %5.3f' %
        Linear_R2(np.log10(sc+1e-6), np.log10(dist), log_fc, pval)**0.5,
        fontsize=16,
    )
    return ax

# %%
fig = plt.figure(figsize=(14,6), dpi=400)
gs = fig.add_gridspec(nrows=1, ncols=2,
                        left=0.05, right=0.96, top=0.96, bottom=0.05,
                        wspace=0.15, hspace=0.20)
ax = [fig.add_subplot(i, projection='3d', azim=-20, elev=30) for i in gs]

band = 'raw'
# new_mask = np.ones_like(snr_mask_tdmi[band])
new_mask = snr_mask_tdmi[band].copy()
new_mask[sc_tdmi[band]==0] = False
new_mask[sc_tdmi[band]==1.5] = False

d_metric = 1./d_mat[band]
# regression with distance to get residue

gen_sc_fc_figure_3d(ax[0], fc_tdmi[band], sc_tdmi[band], d_metric, new_mask,)

# new_mask = np.ones_like(new_mask, dtype=bool)
# new_mask[sc_gc[band]==0] = False
# new_mask[sc_gc[band]==1.5] = False
gen_sc_fc_figure_3d(ax[1], fc_gc[band], sc_gc[band], d_metric, new_mask,)

for axi, labeli in zip(ax, ('TDMI', 'GC')):
    axi.set_title(labeli + ' : ' + axi.get_title())
    axi.set_xlabel('SC')
    axi.set_ylabel('1/Distance')
    axi.set_zlabel(r'$\log_{10}$('+labeli+')', rotation=270)
    axi.xaxis.set_major_locator(MultipleLocator(4))
    axi.xaxis.set_minor_locator(MultipleLocator(2))
    axi.yaxis.set_major_locator(MultipleLocator(1))
    axi.yaxis.set_minor_locator(MultipleLocator(0.5))
    axi.zaxis.set_major_locator(MultipleLocator(1))
fig.suptitle(band)

fig.savefig(path+'Figure_3-1.png')
# %%

# %%


def removeCarriage(line):
    return line.strip('\n')

def run():
    f = open("day5.txt", "r")
    row, column = 0, 0
    dictionary = {}
    for line in f:
        line = removeCarriage(line)
        for index in range(len(line)):
            bw_position = len(line) - index - 1
            if(bw_position > 6):
                if(line[bw_position] == 'R'):
                    column += 2**index
            else:
                if(line[bw_position] == 'B'):
                    row += 2**(index-3)
        dictionary[(row * 8 + column)] = 1
        row, column = 0, 0

    for key in range(0, 1000):
        if key not in dictionary.keys():
            print(key)

def main():
    run()

if __name__ == "__main__":
    main()


from torch.utils.data import Dataset, DataLoader
import torch
import matplotlib.pyplot as plt

class Data(Dataset):
    def __init__(self):
        self.x = torch.arange(-3, 3, 0.1).view(-1, 1)
        self.f = 2 * self.x - 1
        self.y = self.f + 0.5*torch.randn((self.x.shape[0],1))

    def __len__(self):
        return self.x.shape[0]

    def __getitem__(self, index):
        return self.x[index], self.y[index]

dataset = Data()
data = DataLoader(dataset, batch_size = 16, shuffle = True)

class LinearRegression1(torch.nn.Module):
    def __init__(self, input_size, output_size):
        torch.nn.Module.__init__(self)
        self.linear = torch.nn.Linear(input_size, output_size)

    def forward(self, x):
        return self.linear(x)

    def train(self, train_data, epochs, optimizer, loss_function):
        for epoch in range(epochs):
            for x, y in train_data:
                yhat = self(x)
                loss = loss_function(yhat, y)
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()

class LinearRegression2(torch.nn.Module):
    def __init__(self, input_size, output_size):
        torch.nn.Module.__init__(self)
        self.w = torch.nn.Parameter(torch.randn(()))
        self.bias = torch.nn.Parameter(torch.randn(()))

    def forward(self, x):
        return self.w*x + self.bias

    def train(self, train_data, epochs, lr):
        for epoch in range(epochs):
            for x, y in train_data:
                yhat = self(x)
                loss = torch.sum((yhat - y)**2)/x.shape[0]
                loss.backward()
                self.w.data -= lr*self.w.grad
                self.bias.data -= lr*self.bias.grad
                self.w.grad.data.zero_()
                self.bias.grad.data.zero_()

class LinearRegression3(torch.nn.Module):
    def __init__(self, input_size, output_size):
        torch.nn.Module.__init__(self)
        self.w = torch.randn(())
        self.bias = torch.randn(())

    def forward(self, x):
        return self.w*x + self.bias

    def train(self, train_data, epochs, lr):
        for epoch in range(epochs):
            for x, y in train_data:
                yhat = self(x)
                loss = torch.sum((yhat - y)**2)/x.shape[0]
                grad_w = (2/x.shape[0]) * torch.sum((y - self.w*x - self.bias)*-x)
                grad_b = (2/x.shape[0]) * torch.sum((y - self.w*x - self.bias)*-1)

                self.w -= lr*grad_w
                self.bias -= lr*grad_b

model1 = LinearRegression1(1, 1)
model2 = LinearRegression2(1, 1)
model3 = LinearRegression3(1, 1)

model1.train(data, 50, torch.optim.SGD(model1.parameters(), lr = 0.01), torch.nn.MSELoss())
model2.train(data, 50, 0.01)
model3.train(data, 50, 0.01)

models = [(model1.linear.weight.item(), model1.linear.bias.item()),
          (model2.w.item(), model2.bias.item()),
          (model3.w.item(), model3.bias.item())]

x = dataset.x.numpy()
fig, axs = plt.subplots(3)
for i in range(3):
        w, b = models[i]
        axs[i].plot(x, dataset.y.numpy(), 'rx', label = 'Data points')
        axs[i].plot(x, dataset.f.numpy(), label = 'Original function (y = 2x - 1)' ,alpha = 0.8)
        axs[i].plot(x, [w*j + b for j in x],
                    label = f"Learned function (y = {round(w, 4)}x + {round(b, 4)})")
        axs[i].legend()
for ax in axs.flat:
    ax.set(xlabel='x', ylabel='y')
    ax.label_outer()
plt.show()


import pygame as pg
from math import sqrt

class Bird(pg.sprite.Sprite):
    def __init__(self, board, alive=False):
        pg.sprite.Sprite.__init__(self)
        self.x, self.y = board.mid
        self.board = board
        self.score = 0

        self.size = (int(26*0.1*board.board_w/18),
                     int(17*0.1*board.board_w/18))
        self.IMGS = [pg.transform.scale(pg.image.load('data/Bird.png'), self.size),
                     pg.transform.scale(pg.image.load('data/Bird_jumping.png'), self.size)]
        self.IMGS = [pg.transform.flip(i, True, False) for i in self.IMGS]
        self.image = self.IMGS[0]

        self.alive = alive
        self.jumping = False
        self.tick = 0
        self.vel = 5

        self.best_gap = (self.board.right, self.board.mid[1])
        self.reset_rect()

    def collision(self, spikes):
        coll = pg.sprite.spritecollideany(self, spikes, False)
        if coll:
            if pg.sprite.spritecollide(self, spikes, False, pg.sprite.collide_mask):
                return True
            return False

    def jump(self):
        self.tick = -20
        self.jumping = True
        self.alive = True

    def move(self):
        self.tick += 1
        parabola = -0.001*self.tick**2+0.5*self.tick
        # 60fps    -0.001*self.tick**2+0.5*self.tick
        self.y += parabola
        self.x += self.vel

        self.reset_rect()

    def collision_check(self, spikes, AI=False):
        # COLISION WITH RIGHT SITE
        if self.x+self.image.get_width()/2 >= self.board.right:
            self.IMGS = [pg.transform.flip(i, True, False) for i in self.IMGS]
            self.vel *= -1
            self.score += 1
            spikes.random_spikes(self.board.left)
        # COLISION WITH LEFT SITE
        elif self.x-self.image.get_width()/2 <= self.board.left:
            self.IMGS = [pg.transform.flip(i, True, False) for i in self.IMGS]
            self.vel *= -1
            self.score += 1
            spikes.random_spikes(self.board.right)
        # COLISION WITH BOTTOM SITE
        elif self.y+self.image.get_height() > self.board.bottom:
            self.reset_bird(spikes)
        # COLISION WITH TOP SITE
        elif self.y < self.board.top:
            self.reset_bird(spikes)
        # COLISION WITH SPIKES
        if self.collision(spikes.spikes):
            self.reset_bird(spikes)

        if AI:
            return self.alive

    def find_best_gap(self, spikes):
        distances = []
        for g in spikes.gaps:
            distances.append(sqrt((self.x - g[0]) ** 2 + (self.y - g[1]) ** 2))
        if len(spikes.gaps) > 0:
            self.best_gap = spikes.gaps[distances.index(min(distances))]

    def draw(self, screen):
        self.image = self.IMGS[0]
        if self.jumping:
            self.image = self.IMGS[1]
            if self.tick > 3:
                self.jumping = False
        screen.blit(self.image, self.rect)

    def reset_bird(self, spikes):
        self.image = self.IMGS[0]
        self.jumping = False
        self.alive = False
        self.score = 0
        self.x, self.y = self.board.mid
        spikes = spikes.initial_spikes()
        self.reset_rect()

    def reset_rect(self):
        self.rect = self.image.get_rect()
        self.rect.center = (self.x, int(self.y+self.image.get_height()/2))
        self.mask = pg.mask.from_surface(self.image)