import enum
from secrets import choice
from typing import List
import discord
from discord import app_commands
from discord.ext import commands
import mdtools
import os, uuid, requests, textwrap
import cocapi

class GeneralCog(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    async def __make_screenplay__ (self, interaction, ephemeral=False) -> None:
        if isinstance(interaction.channel, discord.Thread):
            # Get all messages from the channel as a list
            all_messages = [f"{message.content}"
                            async for message in interaction.channel.history(oldest_first=True)]

            # extract the code fence from each message individually, and create a new list
            fountain_md = []
            for message in all_messages:
                fences = mdtools.extract_code_fences(message)
                if len(fences) > 0:
                    fountain_md.append('\n\n'.join(fences))

            # join each line together with a line break.
            fountain_md_joined = '\n\n'.join(fountain_md)

            # make fountain file
            tempfilename = f"{interaction.channel.name}_{uuid.uuid4()}.fountain"
            f = open(tempfilename, "w")
            f.write(fountain_md_joined)
            f.close()

            if len(fountain_md) == 0:
                await interaction.response.send_message(
                    content="There appears to be no screenplay formatted items here.",
                    ephemeral=True)
            else:
                await interaction.response.send_message(
                    file=discord.File(tempfilename),
                    ephemeral=ephemeral)

            os.remove(tempfilename) if os.path.exists(tempfilename) else print("The file does not exist")
        else:
            await interaction.response.send_message(
                content="This only works in threads",
                ephemeral=True)

    async def skill_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:

        # get full skills list
        skills = requests.get(f"http://localhost:8000/api/skill").json()

        skills_to_return = [] # blank results

        if current == "":
            pass
        else:
            for skill in skills:

                # check if search is present in both skill name and specialization
                if current.lower() in skill['name'].lower() + skill['specialization'].lower():
                    name = skill['name']
                    specialization = f"" if skill['specialization'] == "" else f"[{skill['specialization']}]"
                    skills_to_return.append(
                        app_commands.Choice(
                            name=' '.join(filter(None, [name, specialization])),
                            value=int(skill['id']) ) )

        return skills_to_return[0:24]

    async def skillset_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:

        # get full skills list
        skillsets = cocapi.get_skillsets()

        skills_to_return = [] # blank results

        for skillset in skillsets:
            if current.lower() in skillset['name'].lower():
                skills_to_return.append(
                    app_commands.Choice(
                        name=skillset.get('name', ""),
                        value=skillset.get('id')))

        return skills_to_return[0:24]

    async def char_stats_autocomplete(self,
                                           interaction: discord.Interaction,
                                           current: str) -> List[app_commands.Choice[str]]:
        for_return = []

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        character = cocapi.character(player.get('character'))

        if character:

            character_stats = requests.get(f"http://localhost:8000/character-stats/{player.get('character')}").json()

            for_return = [app_commands.Choice(
                name=f"{stat_name} ({stat_value})",
                value=str(stat_name))
                    for stat_name, stat_value in character_stats.items()
                    if current == "" or current.lower() in stat_name.lower()]

        return for_return[0:24]

    async def char_skill_autocomplete(self,
                                           interaction: discord.Interaction,
                                           current: str) -> List[app_commands.Choice[str]]:
        for_return = []

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        character = cocapi.character(player.get('character'))

        if character:

            for_return = [app_commands.Choice(
                name=f"{skill.get('name')} ({skill.get('points')})",
                value=int(skill.get('id')))
                    for skill in character.get('characterskill_set', [])
                    if current.lower() in skill['name'].lower()]

        return for_return[0:24]

    async def attach_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:

        # get full skills list
        characters = requests.get(f"http://localhost:8000/api/character/").json()
        for_return = []

        if current == "":
            # return list of characters.
            for character in characters:
                if character.get('player_fk'):
                    for_return.append(app_commands.Choice(
                        name=f"{character['investigator_name']} (TAKEN)",
                        value=str(character['id'])))
                else:
                    for_return.append(app_commands.Choice(
                        name=f"{character['investigator_name']}",
                        value=str(character['id'])))
        else:
            for character in characters:

                # check if search is present in both skill name and specialization
                if current.lower() in character['investigator_name'].lower():
                    for_return.append(app_commands.Choice(
                        name=character['investigator_name'],
                        value=str(character['id'])))

        return for_return[0:24]

    @app_commands.command(name="hello")
    async def hello(self, interaction: discord.Interaction) -> None:
        """ Say Hello to the bot """
        await interaction.response.send_message(
            content=f"Hi, {interaction.user.mention}, I'm Barnautomaton 3000. I was pieced back together at Miskatonic University and now my brain is in a jar!")

    @app_commands.command(name="skill_info")
    @app_commands.autocomplete(skill=skill_autocomplete)
    @app_commands.describe(
        skill="Skill info. Only top 25 are visible, type to find more.",
        hide="Hide result from channel? Only you will see this." )
    async def skill_info(self, interaction: discord.Interaction, skill: int, hide: bool = True) -> None:
        """ Get detailed information on a skill. """
        skill_json = requests.get(f"http://localhost:8000/api/skill/{skill}").json()
        category = f"" if skill_json['category'] == "" else f"[{skill_json['category']}]"
        specialization = f"" if skill_json['specialization'] == "" else f"[{skill_json['specialization']}]"
        name_row_list = [skill_json['name'], category, specialization]
        name_row = ' '.join(filter(None, name_row_list))

        embed = discord.Embed(title=f"{name_row} | {skill_json['base_points']}%", colour=discord.Colour(0x804423), description=skill_json['description'])

        await interaction.response.send_message(
            embed=embed,
            ephemeral=hide)

    @app_commands.command(name="make_screenplay")
    async def make_screenplay(self, interaction: discord.Interaction) -> None:
        """ Creates a screenplay from the current channel or thread. """
        await self.__make_screenplay__(interaction, ephemeral=True)

    @app_commands.command(name="fadeout")
    async def fadeout(self, interaction: discord.Interaction) -> None:
        """ End the scene, makes a screenplay and lock the thread. """
        await self.__make_screenplay__(interaction, ephemeral=False)
        if isinstance(interaction.channel, discord.Thread) : await interaction.channel.edit(archived=True, locked=True)

    @app_commands.command(name="template")
    async def template(self, interaction: discord.Interaction) -> None:
        """ Get a template for the screenplay format. """
        content = """
        ```
        NAME
        Dialogue.
        ```
        """

        await interaction.response.send_message(
            content=textwrap.dedent(content),
            ephemeral=True)

    @app_commands.command(name="character_create")
    @app_commands.describe(
        skillset="What preset character skillset would you like to attach?")
    @app_commands.autocomplete(skillset=skillset_autocomplete)
    async def character_create(self,
                               interaction: discord.Interaction,
                               investigator_name: str,
                               alias: str,
                               occupation: str,
                               birthplace: str,
                               sex: str,
                               age: int,
                               strength: int,
                               intelligence: int,
                               appearance: int,
                               dexterity: int,
                               education: int,
                               size: int,
                               constitution: int,
                               power: int,
                               luck: int,
                               hp: int,
                               magic: int,
                               san: int,
                               skillset: int,
                               ) -> None:
        """ Create a new character by inputting stats. """

        # get or add player to DB
        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        # TODO If the player already has a character, just make new character.  if the player does NOT, auto-connect it.

        # add new character to DB
        character = cocapi.create_character(json={
            "passcode": "",
            "investigator_name": investigator_name,
            "investigator_alias": alias,
            "occupation": occupation,
            "birthplace": birthplace,
            "sex": sex,
            "age": age,
            "strength": strength,
            "intelligence": intelligence,
            "appearance": appearance,
            "dexterity": dexterity,
            "education": education,
            "size": size,
            "constitution": constitution,
            "power": power,
            "luck": luck,
            "hp": hp,
            "magic": magic,
            "san": san,
            "san_daystart": san,
            "temporary_insanity": False,
            "indefinite_insanity": False,
            "dying_unconcious": False,
            "dying_majorwound": False,
            "location_fk": None,
            "player_fk": None
            })

        # edit the character by updating the skillset they're attached to.
        cocapi.attach_skillset_to_character(
            character_id=character.get('id'),
            skillset_id=skillset)

        embed = discord.Embed(title=f"{character.get('investigator_name')} created!",
                              colour=discord.Colour(0x804423))

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

    @app_commands.command(name="character_attach")
    @app_commands.autocomplete(character=attach_autocomplete)
    @app_commands.describe(
        character="Which character are you taking control?")
    async def character_attach(self, interaction: discord.Interaction, character: str) -> None:
        """ Attach a character to yourself. """

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        # set default embed
        embed = discord.Embed(title=f"Character is already in use.", description=f"", colour=discord.Colour(0x804423))

        # get the chosen character
        character_json = cocapi.character(character)

        # does the chosen character have a player?
        if character_json.get('player_fk'):
            embed.title = f"Character is already in use."
        else:
            # does the player choosing have a character already?
            if player.get('character'):
                requests.get(f"http://localhost:8000/player/{interaction.user.id}/release_character").json()

            requests.get(f"http://localhost:8000/character/{character}/attach_player/{interaction.user.id}").json()
            new_character = cocapi.character(character)
            embed.title = f"You are now {new_character.get('investigator_name')}"

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

    @app_commands.command(name="character_release")
    async def character_release(self, interaction: discord.Interaction) -> None:
        """ Releases the character you currenty have (if you have one). """
        success = requests.get(f"http://localhost:8000/player/{interaction.user.id}/release_character").json()

        embed = discord.Embed(title=f"{interaction.user.name} released a character: {success.get('success')}", colour=discord.Colour(0x804423))

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

    @app_commands.command(name="character_change_name")
    @app_commands.describe(name="Character's full name",
                           alias="Character's shorthand name (as it appears in the script).")
    async def character_change_name(self, interaction: discord.Interaction, name: str = "", alias: str = "") -> None:
        """ Edit your name and alias. """
        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        if player.get('character'):
            character = cocapi.character(player.get('character'))

            name  = character.get('investigator_name') if name == "" else name
            alias = character.get('investigator_alias') if alias == "" else alias

            cocapi.change_stat(
                id=character.get('id'),
                json={"investigator_name": name,
                      "investigator_alias": alias })

            embed = discord.Embed(title=f"You are now {name} aka {alias}.", colour=discord.Colour(0x804423))

        else:
            embed = discord.Embed(title="You have no character attached. You are nobody.", colour=discord.Colour(0x804423))

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

    @app_commands.command(name="character_sheet")
    async def character_sheet(self, interaction: discord.Interaction) -> None:
        """ View your character sheet. """

        def split(a, n):
            k, m = divmod(len(a), n)
            return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        embed = discord.Embed(title=f"Error?",
                              description="Error?",
                              colour=discord.Colour(0x804423))

        if player.get('character'):
            character = cocapi.character(player.get('character'))

            description = f"""
                {character.get('occupation')} | {character.get('age')} | {character.get('sex')}

                **STR** {character.get('strength')} | **INT** {character.get('intelligence')} | **APP** {character.get('appearance')} | **DEX** {character.get('dexterity')}
                **EDU** {character.get('education')} | **SIZ** {character.get('size')} | **CON** {character.get('constitution')} | **POW** {character.get('power')}
                **MOV** {character.get('move')} | **DMG BONUS** {character.get('damage_bonus')} | **BUILD** {character.get('build')}

                **HP** {character.get('hp')} / {character.get('hp_max')}
                **SAN** {character.get('san')} / {character.get('san_max')}  ||  **DAY**: {character.get('san_daystart')}
                **LUCK** {character.get('luck')}

                **MAGIC** {character.get('magic')} / {character.get('magic_max')}

                """

            embed = discord.Embed(

                title=f"{character.get('investigator_name')}",
                description=textwrap.dedent(description),
                colour=discord.Colour(0x804423))

            # split the skills list into 3 columns
            newlist = sorted(character.get('characterskill_set'), key=lambda d: d['name'])
            skill_columns = list(split(newlist, 3))

            for column in skill_columns:
                skills_list = ""
                for skill in column:
                    skills_list += f"{skill.get('name')} {skill.get('points')}\n"

                embed.add_field(name=f"SKILLS", value=f"{skills_list}", inline=True)

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

    @app_commands.command(name="who_am_i")
    async def who_am_i(self, interaction: discord.Interaction) -> None:
        """ Who am I currently playing as? """

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        embed = discord.Embed(title=f"You are nobody.", colour=discord.Colour(0x804423))

        if player.get('character'):
            character = cocapi.character(player.get('character'))
            embed = discord.Embed(title=f"You are {character.get('investigator_name')}", colour=discord.Colour(0x804423))

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

    @app_commands.command(name="change_stat")
    @app_commands.autocomplete(stat=char_stats_autocomplete)
    @app_commands.describe(
        stat="Characteristic modify.",
        modify="New characteristic value.")
    async def change_stat(self, interaction: discord.Interaction, stat: str, modify: int) -> None:
        """ Modify your character's characteristics. """

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        character = cocapi.character(player.get('character'))

        cocapi.change_stat(
            id=character.get('id'),
            json={stat: modify})
        embed = discord.Embed(title=f"{stat} now {modify}.", colour=discord.Colour(0x804423))
        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="add_skill")
    @app_commands.autocomplete(skill=skill_autocomplete)
    @app_commands.describe(
        skill="Skill to add.")
    async def add_skill(self, interaction: discord.Interaction, skill: int) -> None:
        """ Add a skill to your character. """

        embed = discord.Embed(title=f"ERROR", colour=discord.Colour(0x804423))

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        if player.get('character'):
            character = cocapi.character(id=player.get('character'))
            # apply the new fields to the skill
            cocapi.add_charskill(json={"skill_fk": skill,
                                    "character_fk": character.get('id') })

            embed = discord.Embed(title=f"Skill added.", colour=discord.Colour(0x804423))

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

    @app_commands.command(name="change_skill")
    @app_commands.autocomplete(skill=char_skill_autocomplete)
    @app_commands.describe(
        skill="Skill to check or modify.",
        name="Modify the name as it appears on your character sheet, e.g. Language(Other) could be Spanish.",
        stat="New skill value.",
        delete="Delete the selected skill from your character sheet.")
    async def change_skill(self, interaction: discord.Interaction, skill: int, name: str = "", stat: int = -1, delete: bool = False) -> None:
        """ Modify your character's skills. """

        charskill = requests.get(f"http://localhost:8000/api/characterskill/{skill}").json()

        # sets the stat to the default if its not included
        stat = stat if stat >= 0 else charskill.get('points')

        # set name to old name unless changed
        name = charskill.get('name') if name == "" else name

        # get the new experience points based on what the user enters
        difference = stat - charskill.get('points')
        new_experience = charskill.get('experience_points') + difference

        # apply the new fields to the skill
        new_skill = cocapi.change_charskill(
            id=skill,json={"name_override": name,
                           "experience_points": new_experience })

        # delete the skill if delete is selected
        if delete:
            cocapi.delete_charskill(id=skill)

        embed = discord.Embed(title=f"Skill: {new_skill.get('name')} now {new_skill.get('points')}", colour=discord.Colour(0x804423))
        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="skill_favorite")
    @app_commands.autocomplete(skill=char_skill_autocomplete)
    @app_commands.describe(
        skill="Skill to favorite or unfavorite.",
        favorite="True to favorite, False to unfavorite.")
    async def skill_favorite(self, interaction: discord.Interaction, skill: int, favorite: bool) -> None:
        """ Add skill to favorites list. """

        # apply the new fields to the skill
        cocapi.change_charskill(id=skill, json={ "favorite": favorite })
        embed = discord.Embed(title=f"Skill Favorited: {favorite}.", colour=discord.Colour(0x804423))
        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="admin_rolls_testing")
    async def admin_rolls_testing(self, interaction: discord.Interaction, totalmsgs: int) -> None:
        """ Testing for admin use only."""

        rolls = cocapi.get_rolls_history(interaction.channel.id, 4)
        embed = discord.Embed(title=f"check logs.", colour=discord.Colour(0x804423))
        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="admin_testing")
    async def admin_testing(self, interaction: discord.Interaction, totalmsgs: int) -> None:
        """ Testing for admin use only."""

        embed = discord.Embed(title=f"You are not an admin.", colour=discord.Colour(0x804423))

        if interaction.user.id == 222234033650794497:
            async for message in interaction.channel.history(limit=totalmsgs):

                # reference = message.reference.message_id if message.reference is not None and not message.is_system else None

                # check if player is in the system, if not add.
                player = cocapi.get_or_create_player(json={
                    "name": "",
                    "discord_name": message.author.name,
                    "discord_id": message.author.id })

                print (player)

                # check if this particular channel is in the system, if not, add.
                channel = cocapi.get_or_create_channel(json={
                    "name": message.channel.name,
                    "channel_id": message.channel.id,
                    "parent_id": 0 })

                print (channel)

                # save the message to the db
                newmessage = cocapi.create_message(json={
                    "messagetime": message.created_at.isoformat(),
                    "discord_id": message.id,
                    "content": message.content,
                    "reply_msg_id": message.reference.message_id if message.reference is not None else None,
                    "player": player.get('id'),
                    "discordchannel": channel.get('id') })

                print (newmessage)

            embed = discord.Embed(title=f"Added messages to DB.", colour=discord.Colour(0x804423))

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

async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(GeneralCog(bot))


from flask import render_template, Response, make_response
from app import app

import os
import datetime
import geojson
import io
import csv

@app.route('/')
@app.route('/index')
def index():
    response = make_response(render_template('index.html'))
    response.cache_control.max_age = 0 # do not cache this page!
    return response

@app.route('/about')
def about():
    response = make_response(render_template('about.html'))
    response.cache_control.max_age = 0 # do not cache this page!
    return response

@app.route('/download')
def download():
    """Download a csv file of all the data."""

    current_date = str(datetime.date.today())
    csv_name = 'mapping-gun-violence-dump-' + current_date + '.csv'

    cd = os.path.dirname(__file__)
    with open(os.path.join(cd, 'static/final-output.geojson')) as f:
        data = geojson.loads(f.read())

    short_to_long_name = {
        'coordinates': 'coordinates',
        'articleUrl': 'url',
        'articleTitle': 'title',
        'date': 'date',
        'time': 'time',
        'knewEachOther': 'The shooter and the victim knew each other',
        'domesticViolence': 'The incident was a case of domestic violence',
        'anotherCrime': 'The firearm was used during another crime',
        'selfDefense': 'The firearm was used in self defense',
        'alcohol': 'Alcohol was involved',
        'drugs': 'Drugs (other than alcohol) were involved',
        'selfDirected': 'The shooting was self-directed',
        'suicideOrAttempt': 'The shooting was a suicide or suicide attempt',
        'unintentional': 'The shooting was unintentional',
        'byOfficer': 'The shooting was by a police officer',
        'atOfficer': 'The shooting was directed at a police officer',
        'stolen': 'The firearm was stolen',
        'familyOwned': 'The firearm was owned by the victim/victims family'
    }

    fieldnames = ['title', 'url', 'date', 'time', 'coordinates',
                  'The shooter and the victim knew each other',
                  'The incident was a case of domestic violence',
                  'The firearm was used during another crime',
                  'The firearm was used in self defense',
                  'Alcohol was involved',
                  'Drugs (other than alcohol) were involved',
                  'The shooting was self-directed',
                  'The shooting was a suicide or suicide attempt',
                  'The shooting was unintentional',
                  'The shooting was by a police officer',
                  'The shooting was directed at a police officer',
                  'The firearm was stolen',
                  'The firearm was owned by the victim/victims family']

    output = io.StringIO()
    wr = csv.DictWriter(output, fieldnames=fieldnames)
    wr.writeheader()

    for feature in data.features:
        row = {}
        row['coordinates'] = str(feature.geometry.coordinates)

        for key, value in feature.properties.items():
            row[short_to_long_name[key]] = value

        wr.writerow(row)

    return Response(output.getvalue(), mimetype='text/csv', headers={'Content-disposition': 'attachment; filename={}'.format(csv_name)})


from Affine.Vision.classification.src.resnet_blocks import ResnetBottleneck, ResnetBasic, conv_unit
import torch.nn as nn
import torch

class Darknet53( nn.Module ):
    def __init__( self ):
        super().__init__()

        self.layers = nn.ModuleList()
        self.layers.append( conv_unit( 3, 32, 7 ) )
        self.layers.append( conv_unit( 32, 64, 3, stride=2 ) )
        self.layers.append( ResnetBottleneck( 64, 64, 32, 64 ) )
        self.layers.append( conv_unit( 64, 128, 3, stride=2 ) )
        for _ in range( 2 ):
            self.layers.append( ResnetBottleneck( 128, 128, 64, 128 ) )
        self.layers.append( conv_unit( 128, 256, 3, stride=2 ) )
        for _ in range( 8 ):
            self.layers.append( ResnetBottleneck( 256, 256, 128, 256 ) )
        self.layers.append( conv_unit( 256, 512, 3, stride=2 ) )
        for _ in range( 8 ):
            self.layers.append( ResnetBottleneck( 512, 512, 256, 512 ) )
        self.layers.append( conv_unit( 512, 1024, 3, stride=2 ) )
        for _ in range( 4 ):
            self.layers.append( ResnetBottleneck( 1024, 1024, 512, 1024 ) )
        self.fc = nn.Linear( 7 * 7 * 1024, 1000 )

    def forward( self, x ):
        for layer in self.layers:
            x = layer( x )
        x = torch.flatten( x, 1 )
        x = self.fc( x )
        return x

class darknet( nn.Module ):
    def __init__( self ):
        super().__init__()

        self.blocks = nn.Sequential( conv_unit( 3, 64, 7 ),
                                     conv_unit( 64, 64, 3, stride=2 ),
                                     ResnetBasic( 64 ),
                                     conv_unit( 64, 128, 3, stride=2 ),
                                     *[ ResnetBasic( 128 ) for _ in range( 2 ) ],
                                     conv_unit( 128, 256, 3, stride=2 ),
                                     *[ ResnetBasic( 256 ) for _ in range( 8 ) ],
                                     conv_unit( 256, 512, 3, stride=2 ),
                                     *[ ResnetBasic( 512 ) for _ in range( 8 ) ],
                                     conv_unit( 512, 1024, 3, stride=2 ),
                                     *[ ResnetBasic( 1024 ) for _ in range( 4 ) ],
                                     nn.AdaptiveAvgPool2d( ( 1, 1 ) )
                                     )

        self.fc = nn.Linear( 1024, 1000, bias=True )

    def forward( self, x ):
        x = self.blocks( x )
        x = torch.flatten( x, 1 )
        x = self.fc( x )
        return x


from torch.utils.data import DataLoader
import numpy as np
import torch
import cv2
from PIL import Image

import AI_straighten.model as model
import AI_straighten.config as config
from AI_straighten.grid_sample import grid_sample
from AI_straighten.dataset import Data

def convert_image_np(inp):
    """Convert a Tensor to numpy image."""
    inp = inp.numpy().transpose((1, 2, 0))
    # inp_pil = Image.fromarray(inp)
    return inp

def predictStraighten(model, img_list, phase = 'single_imge'):
    if phase == 'single_imge':
        # print(len(img_list))
        valid_dataset = Data(img_list)
        test_loader = DataLoader(valid_dataset, batch_size=20, shuffle=False)
        data = next(iter(test_loader))
        input_tensor = data[1].cpu()
        # print(input_tensor.shape)
        images = data[0].cpu()

        transformed_input_tensor = model.stn(input_tensor).cpu()
        transformered_images = grid_sample(images, transformed_input_tensor)
        numpy_transform_image = np.transpose(transformered_images.detach().numpy(), (0,2,3,1))

#########
        # sample_img = cv2.imread('nice.jpg')
        # sample_img = np.transpose(sample_img, (2,0,1))
        # sample_data =  torch.tensor(np.expand_dims(sample_img, 0), dtype= torch.float).cpu()
        # # print(sample_data.shape)
        # # print(transformered_images.shape)
        # grid2 = model.stn(transformered_images[:,0,:,:]).cpu()
        # trans_img = grid_sample(sample_data, grid2)
        # np_sample_data = np.transpose(trans_img.detach().numpy(), (0,2,3,1))
        # cv2.imwrite('nice2.jpg', np_sample_data[0])

#########
        return numpy_transform_image

    else:
        data_black = torch.tensor(np.expand_dims(img_list[0], 1), dtype= torch.float).cpu()
        data_white = torch.tensor(np.expand_dims(img_list[1], 1), dtype= torch.float).cpu()
        output_grid = model.stn(data_black).cpu()

        out_black = grid_sample(data_black, output_grid)
        out_black = torch.squeeze(out_black, dim=1)
        out_black = out_black.detach().numpy()

        out_white = grid_sample(data_white, output_grid, padding_mode = 'border')
        out_white = torch.squeeze(out_white, dim=1)
        out_white = out_white.detach().numpy()

        for idx, image in enumerate(out_white):
            thresh1 = cv2.threshold(image, 254, 255, cv2.THRESH_BINARY)[1]
            thresh1 = cv2.morphologyEx(thresh1, cv2.MORPH_CLOSE, np.ones((3,3),np.uint8))
            thresh2 = cv2.threshold(thresh1, 254, 255, cv2.THRESH_BINARY_INV)[1]
            thresh2 = thresh2.clip(0,1)
            image = image * thresh2
            image = image + thresh1
            out_white[idx] = image
        return out_black, out_white

if __name__ == '__main__':
    straighten_model = model.get_model(config.TRAINING_CONDITION)
    checkpoint = torch.load('./weight/outputs_transformer_bound_grid7/epoch_40.pth')
    straighten_model.load_state_dict(checkpoint)
    straighten_model.eval()


from django.conf.urls import include, url, patterns
from customers import views
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = format_suffix_patterns([
    url(r'^$',
        views.SegmentList.as_view(),
        name='segment-list'),
    url(r'^(?P<pk>.+)/$',
        views.SegmentDetail.as_view(),
        name='segment-detail'),
])


# https://www.acmicpc.net/problem/6603
from itertools import combinations

while True :
  s = list(map(int,input().split()))

  if s[0] == 0:
    break
  else:
    combine = list(combinations(s[1:],6))
    for i in combine :
      print(*i)
    print()


# -*- coding: utf-8 -*-
import scrapy

import datetime as dt

class Pmb0Spider(scrapy.Spider):
    name = "pmb0"
    allowed_domains = ["www.pmb.ro"]

    SEDINTE_URL = 'http://www4.pmb.ro/wwwt/institutii/CGMB/sedinte/ordinea_de_zi/ordinea_de_zi.php'
    DEZBATERI_URL = 'http://www.pmb.ro/institutii/cgmb/dezb_publica/proiecte/pr_dezb_publica.php?termen=all'

    def start_requests(self):
        yield scrapy.Request(self.SEDINTE_URL, self.parse_sedinte)
        yield scrapy.Request(self.DEZBATERI_URL, self.parse_dezbateri)

    def parse_sedinte(self, response):
        data = response.xpath('//select[@name = "id_sedinta_selectata"]/option/text()')[0].extract()

        itemuri_tmp = response.xpath('//table/tr[2]/td[2]/a[contains(@href, "db/")]')
        itemuri = []
        for item in itemuri_tmp:
            descriere = item.xpath('./text()').extract()[0].strip()
            url = item.xpath('./@href').extract()[0]
            url = 'http://www4.pmb.ro/wwwt/institutii/CGMB/sedinte/ordinea_de_zi/' + url

            itemuri.append({
                'descriere': descriere,
                'url': url
            })

        return {
            'meta': {
                'type': 'sedinte'
            },
            'data': data,
	    'itemuri': itemuri
        }

    def parse_dezbateri(self, response):
        sedinte_aux = response.xpath('//table[@id = "tabel"]/tr[@class != "captab"]')
        sedinte = []
        for sedinta in sedinte_aux:
            numar = int(sedinta.xpath('./td[1]/text()').extract()[0])

            data_publicare = sedinta.xpath('./td[2]/text()').extract()[0]
#            data_publicare = str(dt.datetime.strptime(data_publicare, '%Y-%m-%d'))

            descriere = sedinta.xpath('./td[3]/a/text()').extract()[0].strip()
            url_document = sedinta.xpath('./td[3]/a/@href').extract()[0]

            termen_recomandari = sedinta.xpath('./td[4]/text()').extract()[0]
#            termen_recomandari = str(dt.datetime.strptime(termen_recomandari, '%Y-%m-%d'))

            imbunatatire = sedinta.xpath('./td[6]/a/text()').extract()
            imbunatatire = imbunatatire[0].strip() if imbunatatire else None
            imbunatatire_url = sedinta.xpath('./td[6]/a/@href').extract()
            imbunatatire_url = imbunatatire_url[0] if imbunatatire_url else None

            sedinte.append({
                'numar_proiect': numar,
                'data_publicare': data_publicare,
                'descriere': descriere,
                'url_document': url_document,
                'termen_recomandari': termen_recomandari,
                'imbunatatire': imbunatatire,
                'imbunatatire_url': imbunatatire_url
            })

        return {
            'meta': {
                'type': 'dezbateri'
            },
            'data': sedinte
        }


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Sarvandani
"""
import pandas as pd
import plotly.io as pio
import plotly.express as px
pio.renderers.default='browser'
from sklearn.model_selection import train_test_split
import xgboost as xgb
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score

dataset = pd.read_csv("Housing.csv")
fig = px.scatter_3d(x=dataset['price'], y=dataset['bedrooms'], z=dataset['bathrooms'], color=dataset['price'], title="3D_Info")
fig.update_layout(scene = dict(
                    xaxis_title='price',
                    yaxis_title='bedrooms',
                    zaxis_title='bathrooms'),
                    width=1000,
                    margin=dict(r=20, b=10, l=10, t=10))
fig.show()
# we convert the price to the list
y = list(dataset['price'])
# see the names of all the columns
columns = dataset.columns
# features
X = dataset[columns[0:5]]
#lable
y = dataset[columns[0]]
# we split the data into train and test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
xgb.XGBRegressor().get_params()
xg_reg = xgb.XGBRegressor()
# we train the model
xg_reg.fit(X_train,y_train)
xgb_preds = xg_reg.predict(X_test)
plt.figure(figsize=(20, 8))
# plotting the graphs
plt.plot([i for i in range(len(y_test))],y_test, label="Real Price")
plt.plot([i for i in range(len(y_test))],xgb_preds, label="Predicted Price")
# showing the plot
plt.legend()
plt.show()
# We evaluate the model
print('R score is :', r2_score(y_test, xgb_preds))


import datetime
import glob
import os
import sys

def main(argv):
    # pattern = r'T:\qraleg_service\build\CATS_logs\**\*'
    pattern = argv[0]
    for filename in glob.glob(pattern, recursive=True):
        if os.path.isfile(filename):
            print(filename)
            modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(filename))
            today = datetime.datetime.today()
            if (today - modified_date).days > 7:
                try:
                    os.remove(filename)
                    print("The file is deleted.")
                except :
                    print("Warning: The file is unable to delete.")

if __name__ == '__main__':
    main(sys.argv[1:])


from tensorflow.keras.preprocessing.image import ImageDataGenerator
import numpy as np
from ..CTreader import CTreader
import json
import matplotlib.pyplot as plt

def fixFormat(batch, label = False):
    # change format of image batches to make viewable with ctreader
    if not label: return np.squeeze(batch.astype('uint16'), axis = 3)
    if label: return np.squeeze(batch.astype('uint8'), axis = 3)

def dataGenie(batch_size, data_gen_args, fish_nums = None):
    imagegen = ImageDataGenerator(**data_gen_args, rescale = 1./65535)
    maskgen = ImageDataGenerator(**data_gen_args)
    ctreader = CTreader()
    cc_centres_path = ctreader.dataset_path / 'cc_centres_otoliths.json'
    with open(cc_centres_path, 'r') as fp:
        centres = json.load(fp)

    shuffle = True
    roiZ=125
    roiSize=224
    seed = 2

    ct_list, label_list = [], []
    for num in fish_nums:
        templatePath = '../../Data/HDD/uCT/Labels/CC/otolith_template_10.hdf5'
        labelpath = ctreader.dataset_path / 'Labels/Organs/'
        center = centres[str(num)]

        # take out cc for now
        # template = ctreader.read_label(templatePath, manual=False)
        # projections = ctreader.get_max_projections(num)
        # center, error = cc(num, template, thresh=200, roiSize=50)

        z_center = center[0] # Find center of cc result and only read roi from slices

        ct, stack_metadata = ctreader.read(num, r = (z_center - int(roiZ/2), z_center + int(roiZ/2)), align=True)
        label = ctreader.read_label('Otoliths', n=num,  align=True)

        label = ctreader.crop_around_center3d(label, center = center, roiSize=roiSize, roiZ=roiZ)
        center[0] = int(roiZ/2) # Change center to 0 because only read necessary slices but cant do that with labels since hdf5
        ct = ctreader.crop_around_center3d(ct, center = center, roiSize=roiSize, roiZ=roiZ)

        num_classes = 4

        new_mask = np.zeros(label.shape + (num_classes,))
        for i in range(num_classes):
            #for one pixel in the image, find the class in mask and convert it into one-hot vector
            #index = np.where(mask == i)
            #index_mask = (index[0],index[1],index[2],np.zeros(len(index[0]),dtype = np.int64) + i) if (len(mask.shape) == 4) else (index[0],index[1],np.zeros(len(index[0]),dtype = np.int64) + i)
            #new_mask[index_mask] = 1
            new_mask[label == i,i] = 1

        mask = np.reshape(new_mask,(new_mask.shape[0],new_mask.shape[1],new_mask.shape[2],new_mask.shape[3]))
        label = mask
        ct_list.append(ct)
        label_list.append(label)
        ct, label = None, None

    ct_list = np.vstack(ct_list)
    label_list = np.vstack(label_list)

    ct_list = np.array(ct_list, dtype='float32')
    label_list = np.array(label_list, dtype='float32')

    # import pdb; pdb.set_trace()
    ct_list      = ct_list[:,:,:,np.newaxis] # add final axis to show datagens its grayscale
    # label_list   = label_list[:,:,:,np.newaxis] # add final axis to show datagens its grayscale
    print('[dataGenie] Initialising image and mask generators')

    image_generator = imagegen.flow(ct_list,
        batch_size = batch_size,
        #save_to_dir = 'output/Keras/',
        save_prefix = 'dataGenie',
        seed = seed,
        shuffle=shuffle,
        )
    mask_generator = maskgen.flow(label_list,
        batch_size = batch_size,
        #save_to_dir = 'output/Keras/',
        save_prefix = 'dataGenie',
        seed = seed,
        shuffle=shuffle
        )
    print('Ready.')
    test_batches = [image_generator, mask_generator]
    xdata = []
    ydata = []

    for i in range(0,int(len(ct_list)/batch_size)):
        xdata.extend(np.array(test_batches[0][i]))
        ydata.extend(np.array(test_batches[1][i]))

    sample_weights = []

    datagen = zip(image_generator, mask_generator)
    return np.array(xdata), np.array(ydata), sample_weights

def finalGen(datagen):
    for x_batch, y_batch in datagen:
        #x_batch,y_batch = adjustData(x_batch,y_batch)
        x_batch = x_batch/65535
        y_batch = y_batch/3
        # print(x_batch[0].shape, x_batch[0].dtype, np.amax(x_batch[0]))
        # print(y_batch[0].shape, y_batch[0].dtype, np.amax(y_batch[0]))
        yield (x_batch, y_batch)

def testGenie(num):
    ctreader = CTreader()
    # center, error = cc(num, template, thresh=200, roiSize=50)
    cc_centres_path = ctreader.dataset_path / 'cc_centres_otoliths.json'
    with open(cc_centres_path, 'r') as fp:
        centres = json.load(fp)
    center = centres[str(num)]
    z_center = center[0] # Find center of cc result and only read roi from slices
    roiZ=125
    roiSize=224
    ct, stack_metadata = ctreader.read(num, r = (z_center - int(roiZ/2), z_center + int(roiZ/2)), align=True)#(1400,1600))
    center[0] = int(roiZ/2)
    ct = ctreader.crop_around_center3d(ct, center = center, roiSize=roiSize, roiZ=roiZ)

    ct = np.array([_slice / 65535 for _slice in ct], dtype='float32') # Normalise 16 bit slices
    ct = ct[:,:,:,np.newaxis] # add final axis to show datagens its grayscale

    #print(ct.shape, np.amax(ct))

    # for i in range(0, ct.shape[0], batch_size):
    #     yield ct[i:i+batch_size]
    return ct

if __name__ == '__main__':
    data_gen_args = dict(rotation_range=180,
                        width_shift_range=0.05,
                        height_shift_range=0.05,
                        shear_range=0.2,
                        zoom_range=0.1,
                        horizontal_flip=True,
                        vertical_flip = True,
                        fill_mode='constant',
                        cval = 0)
    batch_size = 100

    sample = [40, 76, 81, 85, 88, 218, 222, 236, 298, 425]
    # change label path to read labels directly

    datagenie = DataGenie(  batch_size = batch_size,
                            data_gen_args = data_gen_args,
                            fish_nums = sample)

    ctreader = ctfishpy.CTreader()

    for x_batch, y_batch in datagenie:
        #print(x_batch.shape)
        #print(y_batch.shape)
        x_batch = fixFormat(x_batch)  # remove last weird axis
        y_batch = fixFormat(y_batch, label = True)  # remove last weird axis

        ctreader.view(x_batch, label = y_batch)

        #break


# The syntax threading and multiprocessing is very similar.

# Process - an instance of program, like
# multiple opened internet explorers

# + takes advantage of CPUs and cores
# + separate memory space - memory is not shared between processes
# + great for CPU bound processing
# + new process is started independently of other processes
# + processes are killable
# + one GIL(global interreter lock) for each process - avoids GIL limitation

# - heavy weight
# - starting a process is slower then starting tread
# - needs more memory
# - inter-process communication is more complicated

# You can check in your desktop system task manager, all the parallel
# python processes, when you execute this code
import concurrent.futures
import multiprocessing
import time
from Python.utilities.separate_text_stdout import SeparateText

def do_something_(seconds):
    print(f'Sleeping {seconds} second(s)...')
    time.sleep(seconds)
    print(f'Done Sleeping...{seconds}')

def do_something(number):
    return number**number**number

# for some reason multiprocessing must be guarded by '__name__ == '__main__'',
# check why
if __name__ == '__main__':
    sep = SeparateText()
    start = time.perf_counter()
    p1 = multiprocessing.Process(target=do_something_, args=(1,))
    p2 = multiprocessing.Process(target=do_something_, args=(1,))

    p1.start()
    p2.start()

    p1.join()
    p2.join()
    finish = time.perf_counter()

    print(f'Finished in {round(finish - start, 2)} second(s)')
    print(sep.separator())

    start = time.perf_counter()
    with concurrent.futures.ProcessPoolExecutor() as executor:
        numbers = [n for n in range(5, 15)]
        results = executor.map(do_something, numbers)

        # here you can get the results, when using the map function
        # for result in results:
        #     print(result)

    finish = time.perf_counter()
    print(f'Finished in {round(finish - start, 2)} second(s)')


from translator.models import Translator
import speech_recognition as sr
import os
import contextlib
import wave
import math
from queue import Queue
from threading import Thread
from translator.utilities import get_audio_duration

def recognize_thread(q: Queue, result):
    while not q.empty():
        work_args_tuple = q.get()
        r = sr.Recognizer()
        _audio = sr.AudioFile(work_args_tuple[1])
        try:
            with _audio as source:
                r.adjust_for_ambient_noise(source)
                audio = r.record(
                    source, offset=work_args_tuple[0]*work_args_tuple[2], duration=work_args_tuple[2])

                # Using Google Speech Recognizer
                text = r.recognize_google(audio, language="en-GB")
                result[work_args_tuple[0]] = text
        except:
            # result[work_args_tuple[0]] = '...'
            # print(f"Failed to transcribe task {work_args_tuple[0]}")
            raise Exception(f"Failed to transcribe task {work_args_tuple[0]}")

        q.task_done()
    return True

def extract_text(object_id):
    """Transcribes audio file to text and saves it to the object"""
    # Get the object
    translator_object = Translator.objects.get(pk=object_id)

    # raise exceptions
    if not translator_object:
        raise Exception("Object not found")
    if not os.path.isfile(translator_object.source_audio.path):
        raise Exception("No source audio exists in the specified path")

    duration = 10
    audio_source_file_path = translator_object.source_audio.path
    total_duration = get_audio_duration(audio_source_file_path) / duration
    total_duration = math.ceil(total_duration)

    # Create queue
    queue = Queue(maxsize=0)
    num_theads = min(50, int(total_duration))

    # Create array to share to store transcriptions in each threads
    transcriptions_list = ['' for x in range(0, total_duration)]
    for task_index in range(0, total_duration):
        queue.put((task_index, audio_source_file_path, duration))

    # Recognize speech
    for thread_index in range(num_theads):
        worker = Thread(target=recognize_thread,
                        args=(queue, transcriptions_list))
        worker.setDaemon(True)
        worker.start()
    queue.join()

    # Joint transcriptions_list into a single string
    transcribed_text = ""
    for text in transcriptions_list:
        transcribed_text += text+" "

    # Save transcribed text to DB
    translator_object.extracted_text = transcribed_text
    translator_object.save()


import json
import leveldb

def make_db(dic, DB_NAME, db):
    """
    leveldbのデータベースを作成する

    Parameters
    -------
    dic : dict[str, dict or str or int or list]
        データベースに保存するデータ
    DB_NAME : str
        データベースの名前
    db : leveldb
        leveldbのインスタンス
    """
    for key, value in dic.items():

        if type(value) in [dict, list]:
            db.Put(key.encode(), json.dumps(value).encode())
        else:
            db.Put(key.encode(), value.encode())

if __name__ == "__main__":
    make_db()


import unittest
from panda3d.core import Plane, LVector3f, LPoint3f
from utils import triangle_plane_intersection

class test_triangle_intersection(unittest.TestCase):
    def setUp(self):
        self.plane = Plane(LVector3f(0, -1, 0), LPoint3f(0, 0, 0))

    def test_simple_intersection(self):
        """
        In this test case, the plane passes through the origin and faces towards the camera

        (z is up and y is depth)

        The triangle is flat on the xz plane and crosses at -2.5, 0, 0 and 2.5, 0, 0
        """
        triangle = [
            LPoint3f( 5, -5, 0),
            LPoint3f(-5, -5, 0),
            LPoint3f( 0,  5, 0)
        ]

        intersection = triangle_plane_intersection(triangle, self.plane)
        assert(len(intersection) == 2)

    def test_triangle_on_plane(self):
        """In this test case, the entire triangle lies on the plane. So we should get three points back"""
        triangle = [
            LPoint3f( 5, 0, -5),
            LPoint3f(-5, 0, -5),
            LPoint3f( 0, 0,  5)
        ]

        intersection = triangle_plane_intersection(triangle, self.plane)
        assert(len(intersection) == 3)

    def test_triangle_edge_on_plane(self):
        """In this test case, one edge of the triangle lies on the plane, so we should get that edge back"""
        triangle = [
            LPoint3f( 5, 0, 0),
            LPoint3f(-5, 0, 0),
            LPoint3f( 0, -5, 0)
        ]

        intersection = triangle_plane_intersection(triangle, self.plane)
        assert(len(intersection) == 2)


#!/usr/bin/env python3
"""
 Open a window and clear it to a specified colour.
 Draw a rectangle in the middle with various possible
 shaders applied to it.
"""
import random
import pyglet
from pyglet.gl import *
from pyglet.window import key
import ctypes
from ctypes import byref, cast, POINTER

from shaders import Shader, ShaderProgram
import tnvmesh

SIMPLE_VSHADER = b"""
void main()
{
  gl_Position = ftransform();
  gl_TexCoord[0] = gl_MultiTexCoord0;
}
"""

GRAPHPAPER_FSHADER = b"""
uniform vec4 paper = vec4(1.0, 1.0, 0.95, 1.0);
uniform vec4 ink = vec4(0.6, 0.9, 1.0, 1.0);

void main()
{
   vec2 texgrid = fract(gl_TexCoord[0] * 10.0).st;
   if (any(lessThan(texgrid,vec2(0.1))))
      gl_FragColor = ink;
   else
      gl_FragColor = paper;
}
"""

GINGHAM_FSHADER = b"""
uniform vec4 paper = vec4(1.0);
uniform vec4 ink = vec4(1.0, 0.6, 0.6, 1.0);

void main()
{
   vec2 texgrid = fract(gl_TexCoord[0] * 10.0).st;
   float cmix = 0.0;
   if (texgrid.s < 0.5) cmix += 0.5;
   if (texgrid.t < 0.5) cmix += 0.5;
   gl_FragColor = mix(paper, ink, cmix);
}
"""

EDGES_FSHADER = b"""
uniform vec4 paper = vec4(1.0);
uniform vec4 ink = vec4(0.7, 0.7, 0.7, 1.0);

void main()
{
   vec2 dists = abs(vec4(0.5) - fract(gl_TexCoord[0])).st;
   float cmix = smoothstep(0.4, 0.5, max(dists.s, dists.t));
   gl_FragColor = mix(paper, ink, cmix);
}
"""

class Mesh:
    def __init__(self, vertexdata, indices=None, contains_texture=False, primitive=GL_TRIANGLES):
        self.bufs = (GLuint*2)()
        glGenBuffers(2, cast(self.bufs, POINTER(GLuint)))
        vbuf, ibuf = self.bufs
        self.prim = primitive
        T = GLfloat * len(vertexdata)
        data = T(*vertexdata)
        glBindBuffer(GL_ARRAY_BUFFER, vbuf)
        glBufferData(GL_ARRAY_BUFFER, len(data) * 4, byref(data), GL_STATIC_DRAW)
        self.pervertex = 3
        self.vtexture = contains_texture
        if contains_texture:
            self.pervertex = 5
        self.nvertices = len(vertexdata) // self.pervertex
        if indices is None:
            indices = range(self.nvertices)
        self.nindices = len(indices)
        T = GLushort * len(indices)
        idata = T(*indices)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(idata) * 2, byref(idata), GL_STATIC_DRAW)

    def __del__(self):
        glDeleteBuffers(2, cast(self.bufs, POINTER(GLuint)))

    def draw(self):
        glBindBuffer(GL_ARRAY_BUFFER, self.bufs[0])
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.bufs[1])
        stride = 20 if self.vtexture else 0
        glVertexPointer(3, GL_FLOAT, stride, 0)
        if self.vtexture:
            glTexCoordPointer(2, GL_FLOAT, stride, 12)
            glEnableClientState(GL_TEXTURE_COORD_ARRAY)
        glEnableClientState(GL_VERTEX_ARRAY)
        glDrawElements(self.prim, self.nindices, GL_UNSIGNED_SHORT, 0)

class TWin:
    def __init__(self, width, height, *args, **kw):
        try:
            self.bg_colour = kw["bg"]
            del kw["bg"]
        except KeyError:
            self.bg_colour = (0,0,0,1)
        w = self.win = pyglet.window.Window(width, height, *args, **kw)
        self.mesh = Mesh(
            (-0.5, -0.5, 0.0, 0.0, 0.0,
              0.5, -0.5, 0.0, 1.0, 0.0,
              0.5,  0.5, 0.0, 1.0, 1.0,
             -0.5,  0.5, 0.0, 0.0, 1.0), contains_texture=True, primitive=GL_QUADS)
#        self.mesh = tnvmesh.make_cuboid(0.5, 0.5, 0.2)
        vshader = Shader(SIMPLE_VSHADER, GL_VERTEX_SHADER)
        gingham = ShaderProgram(vshader, Shader(GINGHAM_FSHADER))
        graph = ShaderProgram(vshader, Shader(GRAPHPAPER_FSHADER))
        edges = ShaderProgram(vshader, Shader(EDGES_FSHADER))
        self.shaders = [gingham, graph, edges]
        self.shaderindex = 0
        w.set_handlers(self.on_draw, self.on_resize, self.on_key_press)

    @property
    def shadprog(self):
        return self.shaders[self.shaderindex]

    def on_resize(self, w, h):
        """ coord system from -1 to 1 with origin in the middle """
        glViewport(0, 0, w, h)
        glMatrixMode(gl.GL_PROJECTION)
        glLoadIdentity()
        glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
        glMatrixMode(gl.GL_MODELVIEW)
        return pyglet.event.EVENT_HANDLED

    def on_key_press(self, sym, modifiers):
        """ switch shader programs and colours """
        if sym == key.SPACE:
            self.shaderindex = (self.shaderindex + 1) % len(self.shaders)
        elif sym == key.P:
            paper = [1.0, 1.0, 1.0, 1.0]
            paper[random.randint(0,2)] = 0.5 * random.random() + 0.5
            self.shadprog.set(paper=paper)
        elif sym == key.I:
            ink = [0.5, 0.5, 0.5, 1.0]
            ink[random.randint(0,2)] = random.random()
            self.shadprog.set(ink=ink)

    def on_draw(self):
        glClearColor(*self.bg_colour)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        glColor4f(1.0, 1.0, 1.0, 1.0)
        glRectf(10, 10, 20, 20)
        self.shadprog.use()
        self.mesh.draw()

if __name__ == '__main__':
    win = TWin(200,200,caption="Test",bg=(0.4, 0.2, 0.5, 1.0), resizable=True)
    pyglet.app.run()


import gym
import random
import time
import signal

import numpy as np

import rospy
from sensor_msgs.msg import Image
from gazebo_msgs.msg import ModelStates
from geometry_msgs.msg import Twist
from std_srvs.srv import Empty

import numpy as np
import matplotlib.pyplot as plt

from util import process_image, interuppt_handler

def simulate(env, q_table, alpha, epsilon, epsilon_decay):
    rewards = []
    avgrewards = []
    try:
        for episode in range(1, MAX_EPISODES):
            print("============= STARTING NEW EPISODE ===============")

            state = env.reset()
            total_reward = 0
            total_steps = 0

            if state == None:
                episode -= 1
                continue

            done = False

            while not done:
                # In the beginning, do random action to learn
                if random.uniform(0, 1) < epsilon:
                    action = env.action_space.sample()
                else:
                    action = np.argmax(q_table[state])

                next_state, reward, done, _ = env.step(action)
                total_reward += reward
                print("-----------------------------")
                print("EPISODE:", episode)
                print("STATE: ", state)
                print("NEXT STATE: ", next_state)
                print("REWARD: ", reward)
                print("TOTAL REWARD: ", total_reward)
                print("EPSILON:", epsilon)
                # print("REWARDS:", rewards)
                print("AVG REWARDS:", avgrewards)
                print("-----------------------------")

                if next_state == None:
                    next_state = env.observation_space.high

                # Q(s, a) <- (1 - α) * Q(s, a) + α * (r + γ + max(Q(s', a)))
                q_table[state][action] = (1 - alpha) * q_table[state][action] \
                                       + alpha * (reward + gamma * np.max(q_table[next_state]))

                best_actions = [np.argmax(q_table[state]) for state in range(q_table.shape[0])]
                print("Best actions:", best_actions)

                state = next_state
                total_steps += 1

            print("Episode %d finished with total reward = %f." % (episode, total_reward))
            rewards.append(total_reward/total_steps)
            avgrewards.append(np.mean(rewards[-50:]))

            if epsilon >= 0.005:
                epsilon *= epsilon_decay

            # if episode % 10 == 0:
            #     np.save("qtable-"+str(episode)+".npy", q_table)
            #     np.save("reward-"+str(episode)+".npy", np.array(rewards))

        plt.plot(np.array(avgrewards))
        plt.xlabel("No. of Episodes")
        plt.ylabel("Avg. Rewards")
        plt.show()

    except KeyboardInterrupt:
        pass

class GazeboAutoVehicleEnv():
    def __init__(self, H, W):
        self.IMAGE_TOPIC = "/vehicle_camera/image_raw"
        self.CMDVEL_TOPIC = "vehicle/cmd_vel"
        self.GZRESET_TOPIC = "/gazebo/reset_world"
        # self.GZPAUSE_TOPIC = '/gazebo/pause_physics'
        # self.GZUNPAUSE_TOPIC = '/gazebo/unpause_physics'
        self.MODEL_TOPIC = '/gazebo/model_states'

        self.H,self.W = H,W
        self.finished = False

        self.action_space = gym.spaces.Discrete(3)
        self.observation_space = gym.spaces.Box(np.array([0]),
                                            np.array([3]),
                                            dtype=np.int32)
        rospy.init_node('gym', anonymous=True)
        rospy.Subscriber(self.IMAGE_TOPIC, Image, self.image_callback)
        rospy.Subscriber(self.MODEL_TOPIC, ModelStates, self.modelstate_callback)
        self.vel_pub = rospy.Publisher(self.CMDVEL_TOPIC, Twist, queue_size=5)

        rospy.wait_for_service(self.GZRESET_TOPIC)
        self.reset_proxy = rospy.ServiceProxy(self.GZRESET_TOPIC, Empty)
        # self.pause = rospy.ServiceProxy(self.GZPAUSE_TOPIC, Empty)
        # self.unpause = rospy.ServiceProxy(self.GZUNPAUSE_TOPIC, Empty)

    def image_callback(self, img):
        state = process_image(img, True)
        if state == None:
            self.state = None
            return

        error = state * 90 * (self.W / 180)

        if error <= -20:
            self.state = 0
        elif -20 < error < 20:
            self.state = 1
        elif error >= 20:
            self.state = 2

    def modelstate_callback(self, states):
        vehicle_pose = states.pose[states.name.index("vehicle")].position
        goal_pose = states.pose[states.name.index("Mailbox")].position
        if vehicle_pose.x > goal_pose.x and vehicle_pose.y > goal_pose.y:
            print("FINISHED!")
            self.finished = True

    def step(self, action):
        self.speed = 0.3
        self.turn = 0.0
        if action == 0:
            self.turn = 0.2
        elif action == 1:
            self.speed = 0.5
        elif action == 2:
            self.turn = -0.2

        twist = Twist()
        twist.linear.x = self.speed
        twist.angular.z = self.turn

        # self.unpause()
        self.vel_pub.publish(twist)
        # self.pause()

        state = self.state
        obs = state

        print("-----------------------------")
        print("STATE:", state)
        print("ACTION:", action)
        print("-----------------------------")

        if state != None:
            done = False
            if action == self.prev_state:
                reward = 1
            else:
                reward = -1
        else:
            done = True
            reward = -1e2

        self.prev_state = state
        if self.finished:
            done = True

        return obs, reward, done, {}

    def reset(self):
        print("======================= RESETTING ==================")

        self.reset_proxy()
        self.finished = False

        # self.unpause()
        time.sleep(1)
        # self.pause()

        state = None
        while state is None:
            state = self.state

        obs = state
        self.prev_state = state

        return obs

if __name__ == "__main__":
    signal.signal(signal.SIGINT, interuppt_handler)

    env = GazeboAutoVehicleEnv(600, 800)

    MAX_EPISODES = 100
    epsilon = 1
    epsilon_decay = 0.9
    # epsilon = 0.1
    # epsilon_decay = 1
    alpha = 0.1
    gamma = 0.6
    num_box = tuple((env.observation_space.high + np.ones(env.observation_space.shape)).astype(int))
    q_table = np.zeros(num_box + (env.action_space.n,))
    print("num_box.shape:", np.array(num_box).shape)
    print("q_table.shape:", q_table.shape)
    print("num_box", num_box)
    print(env.observation_space.high, env.observation_space)

    simulate(env, q_table, alpha, epsilon, epsilon_decay)


import json
import logging
import os
import numpy as np
import equation as eqn
from utility import get_config, DictionaryUtility
from solver import FeedForwardModel

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
# import tensorflow as tf

FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('config_path', './configs/sdg_d2_ma.json',
                           """The path to load json file.""")
tf.app.flags.DEFINE_string('exp_name', None,
                           """The name of numerical experiments.""")
tf.app.flags.DEFINE_integer('num_run', 1,
                            """The number of experiments to repeatedly run for the same problem.""")
tf.app.flags.DEFINE_string('log_dir1', './logs',
                           """Directory where to write event logs and output array.""")

def main():
    config = get_config(FLAGS.config_path)
    bsde = getattr(eqn, config.eqn_config.eqn_name)(config.eqn_config)
    if FLAGS.exp_name is None: # use config name as exp_name
        FLAGS.exp_name = os.path.splitext(os.path.basename(FLAGS.config_path))[0]
    if not os.path.exists(FLAGS.log_dir1):
        os.mkdir(FLAGS.log_dir1)
    path_prefix = os.path.join(FLAGS.log_dir1, FLAGS.exp_name)
    with open('{}_config.json'.format(path_prefix), 'w') as outfile:
        json.dump(DictionaryUtility.to_dict(config), outfile, indent=2)
    logging.basicConfig(level=logging.INFO,
                        format='%(levelname)-6s %(message)s')

    dim = config.eqn_config.dim

    for idx_run in range(1, FLAGS.num_run+1):
        tf.reset_default_graph()
        with tf.Session() as sess:
            logging.info('Begin to solve %s with run %d' % (FLAGS.exp_name, idx_run))
            model = FeedForwardModel(config, bsde, sess)
            if config.eqn_config.eigenpair == 'first':
                model.build()
            else:
                model.build_second()
            result = model.train()
            training_history = result[0]
            # save training history
            np.savetxt('{}_log{}.csv'.format(path_prefix, idx_run),
                       training_history,
                       fmt=['%d', '%.5e', '%.5e', '%.5e', '%.5e', '%.5e', '%.5e', '%.5e', '%.5e', '%d'],
                       delimiter=",",
                       header="step,train_loss, eg_err, egfcn_l2_err, egfcn_infty_err, grad_l2_err, grad_infty_err, consistency_loss, norm_factor, elapsed_time",
                       comments='')
            figure_data = result[1]
            if dim == 1:
                np.savetxt('{}_hist.csv'.format(path_prefix), figure_data, delimiter=",",
                           header="x,y_true,y_NN", comments='')
            else:
                np.savetxt('{}_hist.csv'.format(path_prefix), figure_data, delimiter=",",
                           header="y_true,y_NN", comments='')

if __name__ == '__main__':
    main()


import sys
from itertools import combinations
import re
input = sys.stdin.readline

N, K = map(int, input().split())
answer = 0

if K < 5:  # a, n, t, i, c
    print(0)

elif K >26:  # 알파벳 개수 26
    print(N)

else:
    K -= 5
    words = [0] * N
    for i in range(N):
        temp = set(re.sub(r'[acint]','',input().rstrip()))
        for t in temp:
            words[i] |= (1 << (ord(t)-ord('a'))) # 알파벳 하나씩 비트마스킹

    candidate = ['b','d','e','f','g','h','j','k','l','m','o','p','q','r','s','u','v','w','x','y','z']
    # 조합 만들기
    for c in list(combinations(candidate, K)):
        each = 0
        cnt = 0
        # 조합 비트마스킹 만들기
        for i in c:
            each |= (1 << (ord(i)-ord('a')))

        # 단어와 조합의 비교
        for j in words:
            if each & j == j:
                cnt += 1

        # 최댓값 갱신
        if answer < cnt:
            answer = cnt

    print(answer)


from robotsetting import Link
from robotsetting import Circle

# add module
import os , sys
import tensorflow as tf     # py -3.6
import matplotlib
import numpy as np
import random as rd

class Configuration:
    def __init__(self):
        print("###configuration###")
        self.startpath = os.getcwd()
        self.problem = "random"
        self.ALL_mode = ["baum"]       # object for cnn ex) 研究の対象：an object of study
        self.angle_mode = ["Link1_angle","Link2_angle"]
        matplotlib.use("Agg")   # memory flash

    def setProblemenvironment(self):
        self.train_data_num = 45
        self.test_data_num = 45
        self.problem = "circle"
        # simulation environment??
        if self.problem == "circle":
            self.test_data_num = 36

    def setCompare(self):
        self.comparelist = ["_CGP","_CNN"]

    def setSR(self):
        self.Inputs = ["Link1_x","Link1_y","Link2_x","Link2_y"]
        self.Outputs = ["Link1_angle","Link2_angle"]

    def setRobotsimulation(self):
        # Simulation Experiment
        self.num_Links = 2
        self.L1 = 12
        self.L2 = 10
        self.margin = 2
        self.Link_info = [[0,self.L1],[0,self.L2]]
        self.arm_height = 0.5
        ###train###
        self.train_Links = []
        for i in range(self.num_Links):  # Sampling By Genetic Programming
            self.train_Links.append(Link(self.Link_info[i][0],self.Link_info[i][1]))
        ###test###
        self.test_Links = []
        for i in range(self.num_Links):  # Sampling By Genetic Programming
            self.test_Links.append(Link(self.Link_info[i][0],self.Link_info[i][1]))

        self.circle = Circle()

        # Simulation Environment
        self.train_data_num = 10
        self.test_data_num = 10

    def setCNN(self):
        self.machine = "CPU"
        self.CNN_trial = 3
        self.target_size_Original = 112
        self.optimizer = "Adam"
        self.maxepochs = 300
        self.batch_size = 32
        self.validation_split = 0.2
        self.verbose = 1
        self.shuffle = True
        self.GRAYSCALE = True
        self.verbose = 1

        self.split = 2      # under train dataset size

    def setPreprocess(self):
        self.problem = "random"

    def reset_seed(self,seed=1):    # environment variables
        os.environ['TF_DETERMINISTIC_OPS'] = '{}'.format(seed)
        tf.random.set_seed(seed)
        os.environ['TF_DETERMINISTIC_OPS'] = 'true'
        os.environ['TF_CUDNN_DETERMINISTIC'] = 'true'

        np.random.seed(seed)
        rd.seed(seed)

        session_conf = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=32, inter_op_parallelism_threads=32)
        tf.compat.v1.set_random_seed(seed)
        sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 24 21:28:41 2018
#program that implements a decision tree using the ID3 algorithm presented
#Read a set of attributes and print to xml file
@author: Karthik
"""
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 17 22:38:48 2018

@author: Karthik
"""
import copy
import numpy as np
import pandas as pd
import math
import argparse as ag
import os

flag = 1
treeEntropy = 0

def check_location(loc_file):
    if not os.path.exists(loc_file):
        raise ag.ArgumentTypeError("{0} does not exist".format(loc_file))
    return loc_file

def calculateEntropy(target_col,class_log):
    Entropy = 0
    value, sum1 = np.unique(target_col, return_counts=True)
    for i in range(len(value)):
        Entropy = Entropy-(float(sum1[i])/sum(sum1)) * math.log(float(sum1[i])/sum(sum1),class_log)
    return Entropy

def InformationGain(data, feature, class_log):
    global flag
    total_Entropy = calculateEntropy(data["target_class"], class_log)

    if flag == 1:
        treeEntropy = total_Entropy
    flag = 0
    #print total_Entropy
    Entropy = 0
    value, sum1 = np.unique(data[feature], return_counts=True)
  #  print total_Entropy
   # print value,feature,sum1
    sum11 = sum(sum1)
    weightedEntropy = 0
    #print value,sum1
    Entropy = [0] * len(value)
    for i in range(len(value)):
         Entropy[i] = calculateEntropy(data.where(data[feature] == value[i]).dropna()["target_class"], class_log)
         weightedEntropy = weightedEntropy + ((float(sum1[i])/sum11) * Entropy[i])
  #  print "weighted entropy",weightedEntropy
    InfoGain = total_Entropy - weightedEntropy
    #print feature,attribute_entropy
    return InfoGain

def ID3(data, original_data, remaining_attributes, class_log):
    if len(data) == 0:
        return
    elif len(np.unique(data["target_class"])) == 1:
      #  print np.unique(data["target_class"])
        #print data
        #print remaining_attributes
        print(np.unique(data["target_class"])[0])
        return np.unique(data["target_class"])[0]
    elif len(remaining_attributes) == 0:
        value, count = np.unique(data["target_class"],return_counts = True)
        print(value[np.argmax(count)])
        return value[np.argmax(count)]

    else:
        attribute_values = [InformationGain(data,feature,class_log) for feature in remaining_attributes]
        best_feature = remaining_attributes[np.argmax(attribute_values)]
        tree = {best_feature:{}}
        #remaining_attributes.remove(best_feature)

        remaining_attributes = [i for i in remaining_attributes if i != best_feature]
        for value in data[best_feature].unique():
            split_data = data.where(data[best_feature] == value).dropna()
            entropy = calculateEntropy(split_data["target_class"], class_log)
            print("<node " + " entropy= \"" + str(entropy) + "\" feature=\"" + str(best_feature) + "\" value=\"" + str(value) + "\">")

            subtree = ID3(split_data, original_data, remaining_attributes, class_log)
            print("</node>")
            tree[best_feature][value] = subtree
    return tree

def main():
    parser = ag.ArgumentParser()
    parser.add_argument("--data", help="data filename", type=check_location)
    # parser.add_argument("--output", help="output file for final decision tree")
    args = parser.parse_args()
    file_name = args.data
    data = pd.read_csv(file_name, header=None)
    list = []
    for i in range(len(data.columns)-1):
      list.append("attr"+str(i))
    required_attribute = copy.deepcopy(list)
    list.append("target_class")
    data.columns = list
    class_log = float(len(data["target_class"].unique()))
    tree_entropy = calculateEntropy(data["target_class"], class_log)
    print("<tree " + "entropy = \"" + str(tree_entropy) + "\">")
    tree = ID3(data[:][:-1], data, required_attribute, class_log)
    print("</tree>")

if __name__ == "__main__":
    main()


import torch.nn as nn

class SurvivalModel(nn.Module):

    def __init__(self, n_input_dim=21, n_hidden1 = 300, n_hidden2 = 100, n_output =  1):

        super(SurvivalModel, self).__init__()
        self.n_input_dim = n_input_dim
        self.layer_1 = nn.Linear(n_input_dim, n_hidden1)
        self.layer_2 = nn.Linear(n_hidden1, n_hidden2)
        self.layer_out = nn.Linear(n_hidden2, n_output)

        self.relu = nn.ReLU()
        self.sigmoid =  nn.Sigmoid()
        self.dropout = nn.Dropout(p=0.1)
        self.batchnorm1 = nn.BatchNorm1d(n_hidden1)
        self.batchnorm2 = nn.BatchNorm1d(n_hidden2)

    def forward(self, inputs):
        x = self.relu(self.layer_1(inputs))
        x = self.batchnorm1(x)
        x = self.relu(self.layer_2(x))
        x = self.batchnorm2(x)
        x = self.dropout(x)
        x = self.sigmoid(self.layer_out(x))

        return x

    def serialize_params(self):
        return {
            "model": {
                "n_input_dim": self.n_input_dim
            }
        }


from typing import List
from ..model.results.DecodeResult import DecodeResult
from ..model.results.DetectionResult import DetectionResult
from ..model.BBox import BBox

class InferenceService:

    def __init__(self) -> None:
        pass

    def detection_qr_collision_merge(self, detection_result: DetectionResult, decode_result: DecodeResult) -> List[BBox]:
        detection_result = BBox.toBBoxList(detection_result.labels, detection_result.bboxes, detection_result.type)
        decode_result = BBox.toBBoxList(decode_result.labels, decode_result.bboxes, decode_result.type)

        for bb in decode_result:
            detection_result = sorted(detection_result, key=lambda x: self.find_collision(x, bb), reverse=True)

        return detection_result + decode_result

    def find_collision(self, aa: BBox, bb: BBox) -> float:
        try:
            iou = self.calculate_iou(aa, bb)
            assert aa.label == bb.label
            return iou
        except:
            return 0.0

    def calculate_iou(self, bb1: BBox, bb2: BBox) -> float:
        assert bb1.x1 < bb1.x2
        assert bb1.y1 < bb1.y2
        assert bb2.x1 < bb2.x2
        assert bb2.y1 < bb2.y2

        x_left = max(bb1.x1, bb2.x1)
        y_top = max(bb1.y1, bb2.y1)
        x_right = min(bb1.x2, bb2.x2)
        y_bottom = min(bb1.y2, bb2.y2)

        if x_right < x_left or y_bottom < y_top:
            return 0.0

        intersection_area = (x_right - x_left) * (y_bottom - y_top)
        bb1_area = (bb1.x2 - bb1.x1) * (bb1.y2 - bb1.y1)
        bb2_area = (bb2.x2 - bb2.x1) * (bb2.y2 - bb2.y1)

        iou = intersection_area / (bb1_area + bb2_area - intersection_area)
        assert 0.0 <= iou <= 1.0

        return iou