# -*- coding: utf-8 -*-
import re
import os
import sys
import json
import time
import random
import urllib2
import win32gui
import win32con
import win32api

# Current path
ROOT = ""
# Log path
LOG_PATH = "log.txt"
# Replace special chars to this char in file name
NAME_FILL_CHAR = "-"
# Access random index separate
INDEX_FILL_CHAR = "~"
# config path
CONFIG_PATH = "config.json"
# system encode type
SYS_ENCODE = sys.getfilesystemencoding()
# default config
DEFAULT_CONFIG = ('{\n'
                  '    "api_url": "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=8",\n'
                  '    "picture_url_locat": "images [0] url",\n'
                  '    "name_type": "url",\n'
                  '    "wallpaper_fill_type": "fill",\n'
                  '    "picture_store_path": "pics/",\n'
                  '    "picture_postfix": ""\n'
                  '}')

# CurrentDir can get current path
# Because the path is different between run this script and run pyinstaller file
# this func can return the right path
def CurrentDir():
    path = sys.argv[0]
    if path.endswith('.exe'):
        return path[:path.rindex('\\')]
    else:
        return sys.path[0]

# ConcatURL can concat two url
# when the rightURL is a absolute url (such as "http://xxx.com"), it will return the rightURL directly.
def ConcatURL(leftURL, rightURL):
    if rightURL.startswith('http'):
        return rightURL
    host = leftURL
    slashIndex = leftURL.find('/', 7)
    if slashIndex != -1:
        host = leftURL[:slashIndex]
    if rightURL.startswith('/'):
        return host + rightURL
    else:
        return host + "/" + rightURL

# SlashToBacklash as its name
# This func will replace slash("/") to backlash("\") in pathStr
def SlashToBacklash(pathStr):
    return pathStr.replace('/', '\\')

# ConcatPath can concatenate two path
# when the rightURL is a absolute path (such as "C:\Windows"), it will return the rightPath directly.
def ConcatPath(leftPath, rightPath):
    if rightPath.find(':') != -1:
        return rightPath
    if leftPath.endswith('\\'):
        return leftPath + rightPath.strip('\\')
    else:
        return leftPath + '\\' + rightPath.strip('\\')

# MultipleReplace will replace chars, which defined in "excludeStr", to NAME_FILL_CHAR in baseStr
# Example:
#   NAME_FILL_CHAR = "-"
#   > MultipleReplace("123#45*6","#*")
#   "123-45-6"
#
def MultipleReplace(baseStr, excludeStr):
    for char in excludeStr:
        baseStr = baseStr.replace(char, NAME_FILL_CHAR)
    return baseStr

# LegalizeStr can delete some special chars in "baseStr"
def LegalizeStr(baseStr):
    excludeStr = "/:*?<>|\""
    return MultipleReplace(baseStr, excludeStr)

# ReadFile will return file content
def ReadFile(path):
    if not os.path.exists(path):
        Log("%s dosn't exists!" % path, 3, True)
    else:
        if not os.access(path, os.R_OK):
            Log("Can't read %s" % path, 2, True)
    handler = open(path, 'r')
    data = handler.read()
    handler.close()
    return data

# WriteFile will write data to a file
def WriteFile(path, fileName, mode, data):
    if not os.path.exists(path):
        try:
            os.makedirs(path)
        except:
            Log("Can't write %s to %s" % (fileName, path), 2, True)
    else:
        if not os.access(path, os.W_OK):
            Log("Can't write %s to %s" % (fileName, path), 2, True)
    fullPath = ConcatPath(path, fileName)
    handler = open(fullPath, mode)
    handler.write(data)
    handler.close()
    return fullPath

# ReadJSON is a pack of read json
# If important is True, get item failed will lead program to exit
# If important is False, get item failed will return '' and would not lead program to exit
def ReadJSON(jsonObj, key, important=True, isRandom=False):
    if isinstance(jsonObj, dict):
        if jsonObj.has_key(key):
            return jsonObj[key]
        else:
            if important:
                Log("Can't get %s in JSON object!" % key, 1, True)
            else:
                return ''
    else:
        if len(jsonObj) < 1:
            if important:
                Log("The array length is 0", 1, True)
            else:
                return ''
        if isRandom:
            key = random.randrange(0, len(jsonObj))
            return jsonObj[key]
        if not isinstance(key, int):
            Log("Can't use a string key to access array item.key: %s" % key, 1, True)
        if key > len(jsonObj) - 1:
            if important:
                Log("The index is to large.key: %s" % key, 1, True)
            else:
                return ''
        else:
            return jsonObj[key]

# Log is record a log
# When doExit is True, the program will exit after log
def Log(message, code=0, doExit=False):
    errDict = {
        0: "Internal error: ",
        1: "Config file error: ",
        2: "Permission error: ",
        3: "File system error: "
    }
    log = time.ctime() + " " + errDict[code] + message
    WriteFile(ROOT, LOG_PATH, 'a', log + '\n')
    if doExit:
        sys.exit()

# LoadConfig can load a json config file
# and return an object
def LoadConfig(configFilePath):
    if not os.path.exists(configFilePath):
        Log("Config dose not exist!Creating a new config file.", 1)
        WriteFile(ROOT, CONFIG_PATH, 'w', DEFAULT_CONFIG)
    data = ReadFile(configFilePath)
    try:
        obj = json.loads(data)
    except:
        Log("Config file syntax error.",1,True)
    return obj

# Fetch can get data from url
def Fetch(url):
    handler = urllib2.urlopen(url)
    data = handler.read()
    handler.close()
    return data

# FindInJson can get item from json by a special way
# "location" is a new way to access json
# more detail see the README.md file
def FindInJson(json, location):
    steps = location.split(' ')
    restObj = json
    for step in steps:
        isRandomm = False
        if step == ("[" + INDEX_FILL_CHAR + "]"):
           step = 0
           isRandomm = True
        elif step.startswith('[') and step.endswith(']'):
            index = step.strip("[").rstrip("]")
            if index.find(INDEX_FILL_CHAR) != -1:
                indexList = index.split(INDEX_FILL_CHAR)
                minIndex = 0
                maxIndex = 0
                try:
                    if indexList[0] != '':
                        minIndex = int(indexList[0])
                    maxIndex = int(indexList[1])
                    step = random.randrange(minIndex, maxIndex)
                except:
                    Log('locat [] in config file are error.', 1)
                    step = 0
            else:
                step = int(index)
        restObj = ReadJSON(restObj, step, isRandom=isRandomm)
    return restObj

# set wallpaper at windows
def SetWallpaper(imagePath, fillType='fill'):
    tile = "0"
    if fillType == "tile":
        fillType = "center"
        tile = "1"
    fillDict = {
        "fill": "10",
        "fit": "6",
        "Stretch": "2",
        "center": "0",
        "span": "22"
    }
    style = fillDict[fillType]
    key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
                                r"Control Panel\Desktop", 0,
                                win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, style)
    win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, tile)
    win32gui.SystemParametersInfo(
        win32con.SPI_SETDESKWALLPAPER, imagePath, 1 + 2)

# main script
if __name__ == "__main__":
    # Init root path
    ROOT = CurrentDir() + "\\"

    # Load config
    config = LoadConfig(CONFIG_PATH)

    # If 'name_fill_char' dose not exist in config file it will use the default 'NAME_FILL_CHAR'
    if ReadJSON(config, 'name_fill_char', important=False) != '':
        NAME_FILL_CHAR = ReadJSON(config, 'name_fill_char', important=False)

    # Get api url from config
    api = ReadJSON(config, 'api_url')
    # Get data from url
    data = Fetch(api)

    # load api content to json obj
    try:
        obj = json.loads(data)
    except:
        Log("The API content is not recognised to be a json type.")

#   # Get picture url from json with the special syntax
    picURL = FindInJson(obj, ReadJSON(config, 'picture_url_locat'))
    # Concat url can avoid the different between "http://xxx.com/xx.jpg" and "/xx.jpg"
    pic_host = ReadJSON(config, 'picture_url_host', important=False)
    if pic_host != "":
        picURL = ConcatURL(pic_host, picURL)
    else:
        picURL = ConcatURL(api, picURL)

    picName = ""
    # get nameType from config
    nameType = ReadJSON(config, 'name_type')
    # process different nameType
    if ReadJSON(config, 'picture_url_locat').find(INDEX_FILL_CHAR) != -1:
        if nameType != 'url':
            nameType = 'time'
    if nameType == "url":
        if picURL.find("?") == -1:
            picName = picURL[picURL.rindex("/") + 1:]
        else:
            picName = picURL[picURL.rindex("/") + 1:picURL.index("?")]
    elif nameType == "json":
        picName = FindInJson(obj, ReadJSON(config, 'name_locat'))
        picName = MultipleReplace(picName, ReadJSON(config, 'name_exclude_char'))
        try:
            picName.encode(SYS_ENCODE)
        except:
            Log(('The name has special charactor, '
                 'you should use "name_exclude_char" in the config'
                 ' to exclude it.'), 1, True)
    elif nameType == 'time':
        picName = str(int(time.time() * 1000))
    else:
        Log("Don't support this name_type.", 1, True)
    picName = LegalizeStr(picName)

    # Get picture data
    picData = Fetch(picURL)
    fullPath = WriteFile(
        ConcatPath(ROOT, SlashToBacklash(ReadJSON(config, 'picture_store_path'))),
        picName + ReadJSON(config, 'picture_postfix'), 'wb', picData)
    # Set wallpaper
    SetWallpaper(fullPath, ReadJSON(config, 'wallpaper_fill_type'))


import pytest

from privatechats.models import PrivateChatRoom, PrivateChatRoomMessage

@pytest.mark.django_db
def test_private_chat_room_str_method():
    """Test PrivateChatRoom __str__ method"""
    group_chat_room_obj = PrivateChatRoom.objects.create(name='user1user2')
    assert str(group_chat_room_obj) == 'user1user2'

def test_group_chat_room_message_str_method(django_user_model):
    """Test PrivateChatRoomMessage __str__ method"""
    user = django_user_model.objects.create(username='user1')
    room_obj = PrivateChatRoom.objects.create(name='user1user2')
    room_msg_obj = PrivateChatRoomMessage.objects.create(
        user=user,
        room=room_obj,
        content='Hello World!'
    )
    assert str(room_msg_obj) == f"user1user2:user1 | {room_msg_obj.timestamp} => Hello World!"


import discord
from discord.ext import commands
from discord import Embed

from core.classes import *

class Global(CategoryExtension):

    @commands.command()
    @commands.has_permissions(manage_roles=True)
    async def ping(self, ctx):
        await ctx.send(f"Hey, it's me, HarTex! :eyes: Did you need something? - `{str(round(self.bot.latency * 1000))} ms`")

    @commands.command()
    async def about(self, ctx):
        about_me = discord.Embed(colour=0xa6f7ff)
        about_me.set_author(name="HarTex", icon_url="https://media.discordapp.net/attachments/582782144099778560/680318768907419668/your_profile_picture.jpg?width=450&height=450")
        about_me.description = "HarTex is a bot meant for servers with advanced moderation needs, run by Harry.#2450 and maintained by the HarTex Development Team."
        about_me.add_field(name="Whitelisted Servers", value=str(len(self.bot.guilds)), inline=False)

        await ctx.send(embed=about_me)

    @commands.command()
    async def help(self, ctx, command=None):
        """
        .help

        A custom help command.
        """
        if command is None:
            helpEmbed = Embed(title="HarTex Help", description="Common Moderation Commands",
                              footer="Execute `help <command>` to get more information about one command.",
                              colour=0xa6f7ff)
            helpEmbed.add_field(name="kick", value="Kicks a user.", inline=False)
            helpEmbed.add_field(name="ban", value="Bans a user.", inline=False)
            helpEmbed.add_field(name="unban", value="Unbans a user.", inline=False)
            helpEmbed.add_field(name="mute", value="Mutes a user.", inline=False)
            helpEmbed.add_field(name="unmute", value="Unmutes a user.", inline=False)
            helpEmbed.add_field(name="tempmute", value="Temporarily mutes a user.", inline=False)

            await ctx.send(embed=helpEmbed)
        elif command == "kick":
            helpKickEmbed = Embed(title="HarTex Help: Kick", description="Kick: Usage", colour=0xa6f7ff)
            helpKickEmbed.add_field(name="Usage", value="kick <member: **discord.Member**> <reason: **optional**>",
                                    inline=False)
            helpKickEmbed.add_field(name="Description", value="Kicks a member.", inline=False)

            await ctx.send(embed=helpKickEmbed)
        elif command == "ban":
            helpBanEmbed = Embed(title="HarTex Help: Ban", description="Ban: Usage", colour=0xa6f7ff)
            helpBanEmbed.add_field(name="Usage", value="ban <member: **discord.Member**> <reason: **optional**>",
                                   inline=False)
            helpBanEmbed.add_field(name="Description", value="Bans a member.", inline=False)

            await ctx.send(embed=helpBanEmbed)
        elif command == "unban":
            helpUnbanEmbed = Embed(title="HarTex Help: Unban", description="Unban: Usage", colour=0xa6f7ff)
            helpUnbanEmbed.add_field(name="Usage", value="unban <member: **discord.Member**> <reason: **optional**>",
                                     inline=False)
            helpUnbanEmbed.add_field(name="Description", value="Unbans a member.", inline=False)

            await ctx.send(embed=helpUnbanEmbed)
        elif command == "mute":
            helpMuteEmbed = Embed(title="HarTex Help: Mute", description="Mute: Usage", colour=0xa6f7ff)
            helpMuteEmbed.add_field(name="Usage", value="mute <member: **discord.Member**> <reason: **optional**>",
                                    inline=False)
            helpMuteEmbed.add_field(name="Description", value="Mutes a member.", inline=False)

            await ctx.send(embed=helpMuteEmbed)
        elif command == "unmute":
            helpUnmuteEmbed = Embed(title="HarTex Help: Unmute", description="Unmute: Usage", colour=0xa6f7ff)
            helpUnmuteEmbed.add_field(name="Usage", value="unmute <member: **discord.Member**> <reason: **optional**>",
                                      inline=False)
            helpUnmuteEmbed.add_field(name="Description", value="Unmutes a member.", inline=False)

            await ctx.send(embed=helpUnmuteEmbed)
        elif command == "tempmute":
            helpTempmuteEmbed = Embed(title="HarTex Help: Tempmute", description="Tempmute: Usage", colour=0xa6f7ff)
            helpTempmuteEmbed.add_field(name="Usage",
                                        value="tempmute <member: **discord.Member**> <time: **string**> <reason: **optional**>",
                                        inline=False)
            helpTempmuteEmbed.add_field(name="Description", value="Temporarily mutes a member.", inline=False)

            await ctx.send(embed=helpTempmuteEmbed)

    @commands.command()
    async def staff(self, ctx):
        staff_embed = discord.Embed(colour=0xa6f7ff)
        staff_embed.set_author(name="HarTex Staff",
                               icon_url="https://media.discordapp.net/attachments/582782144099778560/680318768907419668/your_profile_picture.jpg?width=450&height=450")
        staff_embed.description = "Without the people above, this bot cannot be this great!"
        staff_embed.add_field(name="Global Administrator & Developer", value="Harry.#2450", inline=False)
        staff_embed.add_field(name="Lead Developer", value="Harry.#2450", inline=False)
        staff_embed.add_field(name="Development Team", value="OfficialAz3#0762", inline=False)
        staff_embed.add_field(name="HarTex Support Team", value="Harry.#2450\nOfficialAz3#0762", inline=False)

        await ctx.send(embed=staff_embed)

def setup(hartex):
    hartex.add_cog(Global(hartex))


import datetime as dt
import platform
from pathlib import Path
from unittest import mock

import pdf2gtfs.user_input.cli as cli
from pdf2gtfs.config import Config
from pdf2gtfs.datastructures.gtfs_output.agency import (
    GTFSAgency, GTFSAgencyEntry)

from test import P2GTestCase

def get_path_with_insufficient_permissions() -> str:
    """ Returns a platform-dependent path, where the user (hopefully) has
    not enough permissions for.
    """
    if platform.system().lower() == "windows":
        return "C:/Windows/pdf2gtfs_test/"
    return "/pdf2gtfs_test"

def create_agency(path: Path, num: int, url: str = None, tz: str = None
                  ) -> GTFSAgency:
    if not url:
        url = "https://www.pdf2gtfs.com"
    if not tz:
        tz = "Europe/Berlin"
    agencies = []
    for i in range(num):
        agency_id = f"agency_{i}"
        agency_entry = GTFSAgencyEntry(agency_id, url, tz, agency_id)
        agencies.append(agency_entry.to_output())

    input_file = path.joinpath("agency.txt")
    with open(input_file, "w", encoding="utf-8") as file:
        file.write("agency_id,agency_name,agency_url,agency_timezone")
        file.write("\n" + "\n".join(agencies) + "\n")
    Config.input_files = [input_file]
    return GTFSAgency(path)

class TestCLI(P2GTestCase):
    @classmethod
    def setUpClass(cls: P2GTestCase, **kwargs) -> None:
        kwargs = {"create_temp_dir": True, "disable_logging": True}
        super().setUpClass(**kwargs)

    @mock.patch("pdf2gtfs.user_input.cli.input", create=True)
    def test__get_input(self, mock_input: mock.Mock) -> None:
        def check(answer: str) -> bool:
            return answer == "valid" or answer == ""

        mock_input.side_effect = ["invalid", "invalid", "valid", "invalid"]
        self.assertEqual("invalid", cli._get_input("test", ["invalid"], ""))
        self.assertEqual(1, mock_input.call_count)
        mock_input.reset_mock()
        mock_input.side_effect = ["invalid", "invalid", "valid", "invalid"]
        self.assertEqual("valid", cli._get_input("test", check, ""))
        self.assertEqual(3, mock_input.call_count)

    @mock.patch("pdf2gtfs.user_input.cli.input", create=True)
    def test__get_inputs(self, mock_input: mock.Mock) -> None:
        def check(answer: str) -> bool:
            return answer == "valid" or answer == ""

        mock_input.side_effect = ["valid", "valid", "invalid", "test", ""]
        results = cli._get_inputs("test", check, "")
        self.assertEqual(["valid", "valid"], results)
        self.assertEqual(5, mock_input.call_count)
        mock_input.reset_mock()

        mock_input.side_effect = ["valid", "valid", "invalid", "test", ""]
        results = cli._get_inputs("", ["invalid", "test", ""], "")
        self.assertEqual(["invalid", "test"], results)
        self.assertEqual(5, mock_input.call_count)
        mock_input.reset_mock()

    def test__to_date(self) -> None:
        dates = ["20221004", "20221231", "20220229", "20240229",
                 "no date", ""]
        results = [dt.datetime(2022, 10, 4), dt.datetime(2022, 12, 31),
                   None, dt.datetime(2024, 2, 29), None, None]
        for i in range(len(dates)):
            with self.subTest(i=i):
                self.assertEqual(results[i], cli._to_date(dates[i]))

    @mock.patch("pdf2gtfs.user_input.cli.input", create=True)
    def test__get_annotation_exceptions(self, mock_input: mock.Mock) -> None:
        # Test valid dates.
        dates = [dt.datetime(2022, 10, 4),
                 dt.datetime(2022, 12, 31),
                 dt.datetime(2024, 2, 29)]
        mock_input.side_effect = (
                [date.strftime("%Y%m%d") for date in dates] + [""])
        self.assertEqual(dates, cli._get_annotation_exceptions())
        self.assertEqual(4, mock_input.call_count)
        mock_input.reset_mock()
        # Test invalid dates.
        dates = [dt.datetime(2022, 10, 4),
                 dt.datetime(2022, 12, 31),
                 dt.datetime(2024, 2, 29)]
        mock_input.side_effect = (
                ["20220229", "test"]
                + [date.strftime("%Y%m%d") for date in dates]
                + [""])
        self.assertEqual(dates, cli._get_annotation_exceptions())
        self.assertEqual(6, mock_input.call_count)

    @mock.patch("pdf2gtfs.user_input.cli.input", create=True)
    def test__get_annotation_default(self, mock_input: mock.Mock) -> None:
        mock_input.side_effect = ["y", "n", "y", "n"]
        self.assertEqual(True, cli._get_annotation_default())
        self.assertEqual(False, cli._get_annotation_default())
        self.assertEqual(True, cli._get_annotation_default())
        self.assertEqual(False, cli._get_annotation_default())
        self.assertEqual(4, mock_input.call_count)

    @mock.patch("pdf2gtfs.user_input.cli.input", create=True)
    def test__handle_annotation(self, mock_input: mock.Mock) -> None:
        mock_input.side_effect = ["s", "e", "a"]
        self.assertEqual((True, False), cli._handle_annotation("annot"))
        self.assertEqual((False, False), cli._handle_annotation("annot"))
        self.assertEqual((False, True), cli._handle_annotation("annot"))
        self.assertEqual(3, mock_input.call_count)

    @mock.patch("pdf2gtfs.user_input.cli.input", create=True)
    def test_handle_annotations(self, mock_input: mock.Mock) -> None:
        annots = ["a", "*"]
        # Skip all.
        mock_input.side_effect = ["a", "s"]
        self.assertEqual({}, cli.handle_annotations(annots))
        self.assertEqual(1, mock_input.call_count)
        mock_input.reset_mock()
        # Skip all single.
        mock_input.side_effect = ["s", "s"]
        self.assertEqual({}, cli.handle_annotations(annots))
        self.assertEqual(2, mock_input.call_count)
        mock_input.reset_mock()

        fmt = "%Y%m%d"
        dates = [dt.datetime(2022, 3, 22),
                 dt.datetime(2022, 10, 4)]
        # Single annotation.
        annots = ["*"]
        mock_input.side_effect = ["e", "y", dates[0].strftime(fmt),
                                  dates[1].strftime(fmt), ""]
        result = {"*": (True, dates)}
        self.assertEqual(result, cli.handle_annotations(annots))
        self.assertEqual(5, mock_input.call_count)
        mock_input.reset_mock()
        # Multiple annotations.
        annots = ["*", "a"]
        mock_input.side_effect = ["e", "y", dates[0].strftime(fmt), "",
                                  "e", "n", dates[1].strftime(fmt), ""]
        result = {"*": (True, [dates[0]]), "a": (False, [dates[1]])}
        self.assertEqual(result, cli.handle_annotations(annots))
        self.assertEqual(8, mock_input.call_count)

    @mock.patch("pdf2gtfs.user_input.cli.input", create=True)
    def test_ask_overwrite_existing_file(self, mock_input: mock.Mock) -> None:
        filename = Path(self.temp_dir.name).joinpath("test.zip")
        with open(filename, "w", encoding="utf-8") as fil:
            fil.write("test_ask_overwrite")
        mock_input.side_effect = ["n", "y", "n"]
        self.assertFalse(cli.ask_overwrite_existing_file(filename))
        self.assertTrue(cli.ask_overwrite_existing_file(filename))
        self.assertFalse(cli.ask_overwrite_existing_file(filename))
        self.assertEqual(3, mock_input.call_count)

    def test__get_agency_string(self) -> None:
        widths = [5, 9, 11, 9, 8]
        agency = ["agency_id", "agency_name", "url", "tz"]
        result = "    0 | agency_id | agency_name |       url |       tz"
        self.assertEqual(result, cli._get_agency_string("0", agency, widths))
        result = "   12 | agency_id | agency_name |       url |       tz"
        self.assertEqual(result, cli._get_agency_string("12", agency, widths))
        agency = ["agency_id", "agency_name", "url", "timezone"]
        result = "   12 | agency_id | agency_name |       url | timezone"
        self.assertEqual(result, cli._get_agency_string("12", agency, widths))

    def test__get_agency_header(self) -> None:
        agency = create_agency(Path(self.temp_dir.name), 0)
        result = ["agency_id", "agency_name", "agency_url", "agency_timezone"]
        self.assertEqual(result, cli._get_agency_header(agency))

    def test__get_agency_column_width(self) -> None:
        path = Path(self.temp_dir.name)
        agency = create_agency(path, 1)
        result = [5, 9, 11, 24, 15]
        self.assertEqual(result, cli._get_agency_column_widths(agency))
        agency = create_agency(path, 1, "a", "agency_test_timezone")
        result = [5, 9, 11, 10, 20]
        self.assertEqual(result, cli._get_agency_column_widths(agency))

    def test__get_agency_prompt(self) -> None:
        result = ("Multiple agencies found:\n\t"
                  "index | agency_id | agency_name "
                  "|      agency_url | agency_timezone\n\t"
                  "    0 |  agency_0 |    agency_0 "
                  "| www.example.com |   Europe/Berlin\n\t"
                  "    1 |  agency_1 |    agency_1 "
                  "| www.example.com |   Europe/Berlin\n\t"
                  "    2 |  agency_2 |    agency_2 "
                  "| www.example.com |   Europe/Berlin\n\n"
                  "Please provide the index of the agency you want to use.")
        agency = create_agency(Path(self.temp_dir.name), 3, "www.example.com")
        self.assertEqual(result, cli._get_agency_prompt(agency))

    @mock.patch("pdf2gtfs.user_input.cli.input", create=True)
    def test__select_agency(self, mock_input: mock.Mock) -> None:
        agency = create_agency(Path(self.temp_dir.name), 3)
        mock_input.side_effect = ["1"]
        self.assertEqual(agency.entries[1], cli.select_agency(agency))
        self.assertEqual(1, mock_input.call_count)
        mock_input.reset_mock()
        # IDs need to be between 1 and number of agencies.
        mock_input.side_effect = ["3", "1"]
        self.assertEqual(agency.entries[1], cli.select_agency(agency))
        self.assertEqual(2, mock_input.call_count)

    @mock.patch("pdf2gtfs.user_input.cli.input", create=True)
    def test_create_output_directory(self, mock_input: mock.Mock) -> None:
        # Enable interactive mode.
        Config.non_interactive = False

        # Test failing creation. (Permission error)
        mock_input.side_effect = ["", "", "", "", "q"]
        path = get_path_with_insufficient_permissions()
        Config.output_path = path
        self.assertFalse(Path(path).exists())
        result = cli.create_output_directory()
        self.assertFalse(result)
        self.assertEqual(5, mock_input.call_count)
        self.assertFalse(Path(path).exists())
        mock_input.reset_mock()

        # Test valid creation.
        path = Path(self.temp_dir.name).joinpath("output_dir_test")
        Config.output_path = path
        self.assertFalse(Path(path).exists())
        result = cli.create_output_directory()
        self.assertTrue(result)
        self.assertTrue(Path(path).exists())
        mock_input.reset_mock()

    def test_create_output_directory__non_interactive(self) -> None:
        # Disable interactive mode.
        Config.non_interactive = True

        # Test failing creation. (Permission error)
        path = get_path_with_insufficient_permissions()
        Config.output_path = path
        self.assertFalse(Path(path).exists())
        result = cli.create_output_directory()
        self.assertFalse(result)
        self.assertFalse(Path(path).exists())

        # Test valid creation.
        path = Path(self.temp_dir.name).joinpath(
            "output_dir_test__non_interactive")
        Config.output_path = path
        self.assertFalse(Path(path).exists())
        result = cli.create_output_directory()
        self.assertTrue(result)
        self.assertTrue(Path(path).exists())


from google.cloud import storage
from configparser import ConfigParser
from google.oauth2 import service_account
from googleapiclient.discovery import build
from utils.demo_io import (
    get_initial_slide_df_with_predictions_only,
    get_fovs_df,
    get_top_level_dirs,
    populate_slide_rows,
    get_histogram_df,
    list_blobs_with_prefix,
)
import polars as pl
from gcsfs import GCSFileSystem
from PIL import Image
import asyncio

from utils.zarr_utils import parse_slide, get_image_from_zarr

# Parse in key and bucket name from config file
cfp = ConfigParser()
cfp.read("config.ini")

service_account_key_json = cfp["GCS"]["gcs_storage_key"]
gs_url = cfp["GCS"]["bucket_url"]

bucket_name = gs_url.replace("gs://", "")

bucket2_name = "octopi-malaria-data-processing"

zipzarr_url = "octopi-malaria-data-processing/072622-D1-3_2022-07-26_17-50-42.852998/version1/spot_images.zip"

# Define GCS file system so files can be read
gcs = GCSFileSystem(token=service_account_key_json)

# Authenticate using the service account key file
credentials = service_account.Credentials.from_service_account_file(
    service_account_key_json, scopes=["https://www.googleapis.com/auth/cloud-platform"]
)

client = storage.Client.from_service_account_json(service_account_key_json)

# Create a storage client
storage_service = build("storage", "v1", credentials=credentials)

spot_img_zarr = parse_slide(gcs, zipzarr_url)

for i in range(25):
    spot_img = Image.fromarray(get_image_from_zarr(spot_img_zarr, 240 + i)["compose"])
    spot_img.show()


from __future__ import print_function
import logging
import re

from db_endpoint import DBEndpoint,TCPFrameClient
from utils import blockify
from thread_executor import ThreadExecutor, ThreadExecutorError
from ida_ts import get_func_length, get_func_data, get_func_comment,\
    set_func_comment, Functions, first_func_addr, GetFunctionName,\
    is_func_chunked, make_name

class FCatalogClientError(Exception): pass

logger = logging.getLogger(__name__)

# Minimum function size (in bytes) to be considered when trying to find
# similars.
MIN_FUNC_LENGTH = 0x60

FCATALOG_FUNC_NAME_PREFIX = 'FCATALOG__'
FCATALOG_COMMENT_PREFIX = '%%%'

# The grade of similarity for each function is a number between 0 and this
# constant (Inclusive):
MAX_SIM_GRADE = 16

# Amount of similar functions to return in every inquiry for similars function
# for a specific function:
NUM_SIMILARS = 1

# Amount of functions to be sent together to remote server when looking for
# similars:
GET_SIMILARS_BATCH_SIZE = 20

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

def is_func_fcatalog(func_addr):
    """
    Have we obtained the name for this function from fcatalog server?
    We know this by the name of the function.
    """
    logger.debug('is_func_fcatalog {}'.format(func_addr))
    func_name = GetFunctionName(func_addr)
    return func_name.startswith(FCATALOG_FUNC_NAME_PREFIX)

def is_func_long_enough(func_addr):
    """
    Check if a given function is of suitable size to be commited.
    """
    logger.debug('is_func_long_enough {}'.format(func_addr))
    func_length = get_func_length(func_addr)
    if func_length < MIN_FUNC_LENGTH:
        return False

    return True

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

def strip_comment_fcatalog(comment):
    """
    Remove all fcatalog comments from a given comment.
    """
    res_lines = []

    # Get only lines that don't start with FCATALOG_COMMENT_PREFIX:
    lines = comment.splitlines()
    for ln in lines:
        if ln.startswith(FCATALOG_COMMENT_PREFIX):
            continue
        res_lines.append(ln)

    return '\n'.join(res_lines)

def add_comment_fcatalog(comment,fcatalog_comment):
    """
    Add fcatalog comment to a function.
    """
    res_lines = []

    # Add the fcatalog_comment lines with a prefix:
    for ln in fcatalog_comment.splitlines():
        res_lines.append(FCATALOG_COMMENT_PREFIX + ' ' + ln)

    # Add the rest of the comment lines:
    for ln in comment.splitlines():
        res_lines.append(ln)

    return '\n'.join(res_lines)

def make_fcatalog_name(func_name,sim_grade,func_addr):
    """
    Make an fcatalog function name using function name and sim_grade.
    """
    lres = []
    lres.append(FCATALOG_FUNC_NAME_PREFIX)
    lres.append('{:0>2}__'.format(sim_grade))
    lres.append(func_name)
    lres.append('__{:0>8X}'.format(func_addr & 0xffffffff))
    return ''.join(lres)

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

class FCatalogClient(object):
    def __init__(self,remote,db_name,exclude_pattern=None):
        # Keep remote address:
        self._remote = remote

        # Keep remote db name:
        self._db_name = db_name

        # A thread executor. Allows only one task to be run every time.
        self._te = ThreadExecutor()

        # A regexp pattern that identifies functions that are not named, and
        # should be ignored.
        self._exclude_pattern = exclude_pattern

        # A thread safe print function. I am not sure if this is rquired. It is
        # done to be one the safe side:
        self._print = print

    def _is_func_named(self,func_addr):
        """
        Check if a function was ever named by the user.
        """
        logger.debug('_is_func_named {}'.format(func_addr))
        func_name = GetFunctionName(func_addr)

        # Avoid functions like sub_409f498:
        if func_name.startswith('sub_'):
            return False

        # If exclude_pattern was provided, make sure that the function
        # name does not match it:
        if self._exclude_pattern is not None:
            mt = re.match(self._exclude_pattern,func_name)
            if mt is not None:
                return False

        # Avoid reindexing FCATALOG functions:
        if is_func_fcatalog(func_addr):
            return False

        return True

    def _is_func_commit_candidate(self,func_addr):
        """
        Is this function a candidate for committing?
        """
        # Don't commit if chunked:
        if is_func_chunked(func_addr):
            return False

        if not self._is_func_named(func_addr):
            return False

        if not is_func_long_enough(func_addr):
            return False

        return True

    def _is_func_find_candidate(self,func_addr):
        """
        Is this function a candidate for finding from database (Finding similars
        for this function?)
        """
        if is_func_chunked(func_addr):
            return False

        if self._is_func_named(func_addr):
            return False

        if not is_func_long_enough(func_addr):
            return False

        return True

    def _iter_func_find_candidates(self):
        """
        Iterate over all functions that are candidates for finding similars from
        the remote database.
        This function is IDA read thread safe.
        """
        for func_addr in Functions():
            if self._is_func_find_candidate(func_addr):
                yield func_addr

    def _commit_funcs_thread(self):
        """
        Commit all the named functions from this idb to the server.
        This is an IDA read thread safe function.
        """
        self._print('Commiting functions...')
        # Set up a connection to remote db:
        frame_endpoint = TCPFrameClient(self._remote)
        fdb = DBEndpoint(frame_endpoint,self._db_name)

        for func_addr in Functions():
            logger.debug('Iterating over func_addr: {}'.format(func_addr))
            if not self._is_func_commit_candidate(func_addr):
                continue

            func_name = GetFunctionName(func_addr)
            func_comment = strip_comment_fcatalog(get_func_comment(func_addr))
            func_data = get_func_data(func_addr)

            # If we had problems reading the function data, we skip it.
            if func_data is None:
                self._print('!> Skipping {}'.format(func_name))
                continue

            fdb.add_function(func_name,func_comment,func_data)
            self._print(func_name)

        # Close db:
        fdb.close()
        self._print('Done commiting functions.')

    def commit_funcs(self):
        """
        Commit all functions from this IDB to the server.
        """
        try:
            t = self._te.execute(self._commit_funcs_thread)
        except ThreadExecutorError:
            print('Another operation is currently running. Please wait.')

    def _batch_similars(self,fdb,l_func_addr):
        """
        Given a list of function addresses, request similars for each of those
        functions. Then wait for all the responses, and return a list of tuples
        of the form: (func_addr,similars)
        This function is IDA read thread safe.
        """
        # Send requests for similars for every function in l_func_addr list:
        for func_addr in l_func_addr:
            func_data = get_func_data(func_addr)
            fdb.request_similars(func_data,1)

        # Collect responses from remote server:
        lres = []
        for func_addr in l_func_addr:
            similars = fdb.response_similars()
            lres.append((func_addr,similars))

        return lres

    def _find_similars_thread(self,similarity_cut,batch_size):
        """
        For each unnamed function in this database find a similar functions
        from the fcatalog remote db, and rename appropriately.
        This thread is IDA write thread safe.
        """
        self._print('Finding similars...')

        # Set up a connection to remote db:
        frame_endpoint = TCPFrameClient(self._remote)
        fdb = DBEndpoint(frame_endpoint,self._db_name)

        # Iterate over blocks of candidate functions addresses:
        for l_func_addr in blockify(self._iter_func_find_candidates(),\
                batch_size):
            # Send block to remote server and get results:
            bsimilars = self._batch_similars(fdb,l_func_addr)
            # Iterate over functions and results:
            for func_addr,similars in bsimilars:

                if len(similars) == 0:
                    # No similars found.
                    continue

                # Get the first entry (Highest similarity):
                fsim = similars[0]

                # Discard if doesn't pass the similarity cut:
                if fsim.sim_grade < similarity_cut:
                    continue

                old_name = GetFunctionName(func_addr)

                # Generate new name:
                new_name = make_fcatalog_name(fsim.name,fsim.sim_grade,func_addr)

                # If name matches old name, skip:
                if new_name == old_name:
                    continue

                # Set function to have the new name:
                make_name(func_addr,new_name)

                # Add the comments from the fcatalog entry:
                func_comment = get_func_comment(func_addr)
                func_comment_new = \
                        add_comment_fcatalog(func_comment,fsim.comment)
                set_func_comment(func_addr,func_comment_new)

                self._print('{} --> {}'.format(old_name,new_name))

        # Close db:
        fdb.close()

        self._print('Done finding similars.')

    def find_similars(self,similarity_cut,batch_size=GET_SIMILARS_BATCH_SIZE):
        """
        For each unnamed function in this database find a similar functions
        from the fcatalog remote db, and rename appropriately.
        """
        try:
            t = self._te.execute(self._find_similars_thread,\
                    similarity_cut,batch_size)
        except ThreadExecutorError:
            print('Another operation is currently running. Please wait.')

def clean_idb():
    """
    Clean all fcatalog marks and names from this idb.
    """
    print('Cleaning idb...')
    for func_addr in Functions():
        # Skip functions that are not fcatalog named:
        if not is_func_fcatalog(func_addr):
            continue

        print('{}'.format(GetFunctionName(func_addr)))
        # Clear function's name:
        make_name(func_addr,'')

        # Clean fcatalog comments from the function:
        func_comment = get_func_comment(func_addr)
        set_func_comment(func_addr,strip_comment_fcatalog(func_comment))
    print('Done cleaning idb.')


"""
Repetição
while(enquanto)
Execute um ação enquanto uma condição for verdadeira
loop infinito ->Quando um código não tem fim
"""

contador = 0

while contador <= 10:
    print(contador)
    contador = contador + 1

print('acabou')


import pytz
import json
import os
import mimetypes
import requests
import tempfile

from django import forms
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from django.core.files.images import ImageFile, get_image_dimensions
from django.conf import settings

from allauth.socialaccount.models import SocialAccount

from .models import User, ScheduledPost

class SplitDateTimeWidget(forms.SplitDateTimeWidget):
    def __init__(self, *args, **kwargs):
        super(SplitDateTimeWidget, self).__init__(*args, **kwargs)
        self.widgets[0].input_type = "date"
        self.widgets[1].input_type = "time"

class ScheduledPostAddForm(forms.ModelForm):
    scheduled_datetime = forms.SplitDateTimeField(
        widget=SplitDateTimeWidget
    )
    scheduled_tz = forms.CharField(widget=forms.HiddenInput,
                                   initial="UTC", required=False)
    status = forms.CharField(
        widget=forms.Textarea(attrs={"rows": None, "cols": None})
    )
    attached_media = forms.ImageField(required=False)
    media_url = forms.URLField(required=False)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop("user")
        super(ScheduledPostAddForm, self).__init__(*args, **kwargs)
        one_hour_hence = timezone.now() + timezone.timedelta(hours=1)
        self.fields["scheduled_datetime"].initial = one_hour_hence
        self.fields["service"].choices = []
        if SocialAccount.objects.filter(user=user, provider="facebook").count():
            self.fields["service"].choices.append(
                ("facebook", "Facebook"),
            )
        if SocialAccount.objects.filter(user=user, provider="twitter").count():
            self.fields["service"].choices.append(
                ("twitter", "Twitter"),
            )

    class Meta:
        model = ScheduledPost
        fields = ("scheduled_datetime", "service", "status", "attached_media")

    def clean_scheduled_datetime(self):
        scheduled_datetime = self.cleaned_data["scheduled_datetime"]
        if scheduled_datetime < timezone.now():
            raise forms.ValidationError(_("Time cannot be in the past"))
        return scheduled_datetime

    def clean(self):
        data = self.cleaned_data

        if data.get("scheduled_datetime"):
            sched_dt = data["scheduled_datetime"]
            sched_tz = timezone.pytz.timezone(data.get("scheduled_tz"))
            sched_dt = sched_tz.localize(sched_dt.replace(tzinfo=None))
            data["scheduled_datetime"] = timezone.localtime(sched_dt)

        if data.get("attached_media") and data.get("media_url"):
            raise forms.ValidationError(_("Only one of media URL or "
                                          "attached media may be provided"))

        if data.get("media_url"):
            response = requests.get(data["media_url"])
            if not response.ok:
                raise forms.ValidationError(_("An error occurred while "
                                              "downloading the media from the URL"))
            ext = mimetypes.guess_extension(response.headers['content-type'])
            ff = tempfile.NamedTemporaryFile(suffix=ext)
            ff.write(response.content)
            img_file = ImageFile(ff, name=ff.name)
            height, width = get_image_dimensions(img_file)
            if height is None or width is None:
                ff.close()
                raise forms.ValidationError(_("Invalid image"))
            data["attached_media"] = img_file
        return data


# This program gets a temperature in Celsius from the user and converts it to Fahrenheit
# 9/25
# CTI-110 P2HW1 - Celsius Fahrenheit Converter
# Darin McDonald
#

# Get temperature value input from user.
# Use formula to convert the value from Celsius to Fahrenheit.
# Display the converted temperature.

temp = float(input("Please enter a temperature: "))

convertedTemp = (9/5)*temp + 32

print(temp,"C in Fahrenheit is",convertedTemp, "F")


class Solution:
    def myAtoi(self, s: str) -> int:
        MIN,MAX = -2**31, 2**31 - 1
        sign, num = +1, 0
        for i,x in enumerate(s.lstrip()):
            if   i==0 and x=="-": sign = -1
            elif i==0 and x=="+": sign = +1
            elif x.isdigit(): num = 10*num + int(x)
            else: break
        return max(min(MAX, sign*num), MIN)


import PyPDF2
import warnings

# Open the PDF file in read-binary mode
pdf_file = open('1.2.826.1.3680043.9.5282.150415.2352.16502352212057.pdf', 'rb')

pdf_reader = PyPDF2.PdfReader(pdf_file)

num_pages = len(pdf_reader.pages)
text = ""

for page_number in range(num_pages):
    page = pdf_reader.pages[page_number]
    page_text = page.extract_text()
    text += page_text
# print(text)
# print(type(text))

import re

# text = "Name MR.JITENDRA BHUPTANI 383669 Patient ID AS_BOR_CT_2746  Accession No 164_02746_212057 Age/Gender 80Y / Male  Referred By Dr.ANAND S. SHENAI MS Date 3-Oct-2021"

name_regex = r"Name\s+([A-Z\. ]+)"
patient_id_regex = r"Patient\s+ID\s+([\w-]+)"
accession_no_regex = r"Accession\s+No\s+([\d_]+)"
age_gender_regex = r"Age\/Gender\s+([\d]+[A-Za-z]*)\s+\/\s+([A-Za-z]+)"
date_regex = r"Date\s+(\d+-[A-Za-z]{3}-\d+)"

name = re.search(name_regex, text).group(1)
patient_id = re.search(patient_id_regex, text).group(1)
accession_no = re.search(accession_no_regex, text).group(1)
age, gender = re.search(age_gender_regex, text).groups()
date = re.search(date_regex, text).group(1)

print(f"Name: {name}")
print(f"Patient ID: {patient_id}")
print(f"Accession No: {accession_no}")
print(f"Age: {age}")
print(f"Gender: {gender}")
print(f"Date: {date}")


from pieces import *

class Player(object):

	def __init__(self, color, position):
		self.color = color
		self.position = position

		self.map = {}
		self.enemy = None
		self.moves = [None]
		self.captured = []
		self.dir = 0
		self.createSet()

	def __str__(self):
		return self.color + " player: What's your next move?"

	"""
	createSet(): is a function that allows the board to create a set of pieces
				 necessary for each player to start a new game.
	"""
	def createSet(self):

		# Set the order in which the pieces should be located on the board
		order=[
				('a','R'),('b','N'),('c','B'),('d','Q'),
				('e','K'),('f','B'),('g','N'),('h','R')
			  ]

		# Depending on the color, the starting rows are selected.
		if self.position == 'down':
			rows = ['1','2']
			self.dir = 1
		else:
			rows = ['8','7']
			self.dir = -1

		# Create a piece based on the order that was set above.
		for col, pieceType in order:

			# Create a special piece and a pawn based on its ID's.
			specialPiece = self.createPiece(pieceType)
			pawnPiece = self.createPiece('P')

			# Place the new pieces in the pieces dictionary, using its
			# position as key.
			self.map[col + rows[0]] = specialPiece
			#self.map[col + rows[1]] = pawnPiece

	"""
	createPiece(): Allows us to create a particular class of piece using
				   its ID to select the correct type of Piece.

				   It takes 1 argument, the "type" which refers to the
				   type of piece you need to create.
	"""
	def createPiece(self, type):
		if type == 'K':
			return King(self.color)
		elif type == 'Q':
			return Queen(self.color)
		elif type == 'R':
			return Rook(self.color)
		elif type == 'B':
			return Bishop(self.color)
		elif type == 'N':
			return Knight(self.color)
		elif type == 'P':
			return Pawn(self.color)
		else:
			return False

	"""
	getKing():  It allows to get the King piece of this player.
	"""
	def getKing(self):

		for position, piece in self.map.iteritems():
			if type(piece) is King:
				return (position, piece)

	"""
	getPiece(): allows to validate that a piece exists at a give position.

				It takes one argument "pos", that refers to the position of a
				piece on the board.
	"""
	def getPiece(self, pos):

		if pos in self.map.keys():
			return self.map[pos]

		return False


# -*- coding: utf-8 -*-
"""
Created on Sat Jun  1 17:39:54 2019

@author: Akshay
"""
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False
def alpha(line):
    temp=[]
    for word in line.split():
        if is_number(word):
            for num in list(word):
                temp.append(num)
        else:
            temp.append(word)
    return " ".join(temp)
def clean_text(text):
    '''not working'''

    #text=re.sub(r'(\d+)',r'',text)
    text=text.replace(u',','')
    text=text.replace(u'"','')
    text=text.replace(u'(','')
    text=text.replace(u')','')
    text=text.replace(u'"','')
    text=text.replace(u':','')
    text=text.replace(u"'",'')
    text=text.replace(u"‘‘",'')
    text=text.replace(u"’’",'')
    text=text.replace(u"''",'')
    text=text.replace(u".",'')
    text=text.replace(u"@",'')
    text=text.replace(u"%",'')
    text=text.replace(u"$",'')
    text=text.replace(u"*",'')
    text=text.replace(u"-",'')
    text=text.replace(u"&",'')
    text=text.replace(u"!",'')
    text=text.replace(u"^",'')
    text=text.replace(u"#",'')
    text=text.replace(u"*",'')
    text=text.replace(u"=",'')
    text=text.replace(u"<",'')
    text=text.replace(u">",'')
    text=text.replace(u"_",'')
    text=text.replace(u"*",'')

    #!"#$%&'()*+,-.:;<=>?@[]^_`{|}~

    return text

def clean_lines(line):
    # prepare a translation table to remove punctuation
    table = str.maketrans('', '', '!"#$%&\'()*+,-.:;<=>?@[\\]^_`{|}~')

    # strip source cnn office if it exists
    """ index = line.find('PUBLISHED:')
    if index > -1:
        line = line[index+len('(CNN)'):]"""
    # tokenize on white space
    line = line.split()
    # convert to lower case
    line = [word.lower() for word in line]
    # remove punctuation from each token
    line = [w.translate(table) for w in line]

    temp = []
    for word in line:
        if is_number(word):
            for num in list(word):
                temp.append(num)
        else:
            temp.append(word)
    line = temp
    # store as string

    # remove empty strings
    #cleaned = [c for c in cleaned if len(c) > 0]
    return ' '.join(line)
def hindi_clean(data):
    input_text=data
    remove_nuktas=False
    factory=IndicNormalizerFactory()
    normalizer=factory.get_normalizer("hi",remove_nuktas)
    output_text=normalizer.normalize(input_text)
    output_text=clean_lines(output_text)
    output_text=alpha(output_text)
    return output_text+'\n'

a = open("monolingual.hi","r",encoding="utf-8")
#data = a.readline()

count = 0
data = ''
while count != 500000:
    try:
        sentence = a.readline()
        sentence = hindi_clean(sentence)
        if 10 <len(sentence.strip().split()) <=50:
            data = data + sentence
            count+=1
            if count%1000==0:
                print(count)
    except UnicodeDecodeError:
        pass
a.close()
with open("hindi_mono_50000_iitB.txt","w",encoding="utf-8") as hindi:
    hindi.write(data)
with open("hindi_mono_50000_iitB.txt","r",encoding="utf-8") as hindi:
    data = hindi.readlines()
import re

INDIC_NLP_LIB_HOME=r"C:\Users\Akshay\Documents\GitHub\indic_nlp_library"

# The path to the local git repo for Indic NLP Resources
INDIC_NLP_RESOURCES=r"C:\Users\Akshay\Documents\GitHub\indic_nlp_resources"
import sys
sys.path.append('{}/src'.format(INDIC_NLP_LIB_HOME))
from indicnlp import common
common.set_resources_path(INDIC_NLP_RESOURCES)
from indicnlp import loader
loader.load()

# formating

from indicnlp.normalize.indic_normalize import IndicNormalizerFactory

input_text=data[2]
remove_nuktas=True
factory=IndicNormalizerFactory()
normalizer=factory.get_normalizer("hi",remove_nuktas)
output_text=normalizer.normalize(input_text)
print(input_text)
print(output_text)
print('Length before normalization: {}'.format(len(input_text)))
print('Length after normalization: {}'.format(len(output_text)))

line = data[1000]
import collections
temp=data.split()
vocab_eng = collections.Counter(temp)
vocab_eng = zip(vocab_eng.keys(),vocab_eng.values())
vocab_eng = list(vocab_eng)
vocab_eng = sorted(vocab_eng,key=lambda x : x[1],reverse=True)
vocab_eng = vocab_eng[:50000]
vocab_eng_text = ''
for word,count in vocab_eng:
    vocab_eng_text+=word+"\n"
with open("hindi_vocab.txt","w",encoding="utf-8") as a:
    a.write(vocab_eng_text)

#def clean_lines(line):
#    # prepare a translation table to remove punctuation
#    table = str.maketrans('', '', '!"#$%&\'()*+,-.:;<=>?@[\\]^_`{|}~')
#
#    # strip source cnn office if it exists
#    """ index = line.find('PUBLISHED:')
#    if index > -1:
#        line = line[index+len('(CNN)'):]"""
#    # tokenize on white space
#    line = line.split()
#    # convert to lower case
#    line = [word.lower() for word in line]
#    # remove punctuation from each token
#    line = [w.translate(table) for w in line]
#
#    temp = []
#    for word in line:
#        if is_number(word):
#            for num in list(word):
#                temp.append(num)
#        else:
#            temp.append(word)
#    line = temp
#    # store as string
#
#    # remove empty strings
#    #cleaned = [c for c in cleaned if len(c) > 0]
#    return ' '.join(line) + '\n'


import numpy as np
import random
import copy
from scipy.sparse import csr_matrix
import scipy.sparse as sp

class Stimuli:
    '''
    A distribution of stimuli classes defined by coreset
    '''

    def __init__(self, num_neurons=1000, nclasses=2, nsamples=50, m=None, r=0.9, q=0.01, k=100, sparse=False):
        '''
        m: size of coreset, default m=k
        r: probability of firing within coreset
        q: probability of firing outside coreset
        '''
        self.sparse = sparse
        self.num_neurons_in_core = k if m == None else m
        self.nclasses = nclasses
        self.nsamples = nsamples
        self.num_neurons = num_neurons  # n

        self.q = q
        self.r = r
        self.k = k

        self.distributions = []

        for iclass in range(self.nclasses):
            class_dist = np.full(self.num_neurons, self.q)
            class_dist[random.sample(
                range(self.num_neurons), self.num_neurons_in_core)] = self.r
            self.distributions.append(class_dist)

    def generate_stimuli_set(self, nsamples=None):
        if nsamples == None:
            nsamples = self.nsamples

        stimuli_set = np.zeros(
            (self.nclasses, nsamples, self.num_neurons), dtype=float)

        for iclass in range(len(self.distributions)):
            for isample in range(nsamples):
                stimuli_set[iclass, isample, :] = np.random.binomial(
                    1, self.distributions[iclass])

        return stimuli_set

    def generate_stimuli_set_recurrence(self, nsamples=None, nrecurrent_rounds=None):
        if nsamples == None:
            nsamples = self.nsamples
        if nrecurrent_rounds == None:
            nrecurrent_rounds = 1

        stimuli_set = np.zeros(
            (self.nclasses, nsamples, nrecurrent_rounds, self.num_neurons), dtype=float)

        for iclass in range(len(self.distributions)):
            for isample in range(nsamples):
                for iround in range(nrecurrent_rounds):
                    stimuli_set[iclass, isample, iround, :] = np.random.binomial(
                        1, self.distributions[iclass])

        return stimuli_set

    def get_distributions(self):
        return self.distributions

    def convert_distributions_to_binary(self):
        '''
        Given a distribution array containing q and r, convert q to 0, and r to 1
        '''
        distributions = copy.deepcopy(self.distributions)
        for dist in distributions:
            # print(dist.shape)
            dist[dist == self.r] = 1
            dist[dist == self.q] = 0
        return distributions

    def perturb_r_and_get_new_dist(self, new_r):
        """
        Change firing probability r of old_dist to new_r,
        then return this new distribution.
        """
        new_dist = [arr.copy() for arr in self.distributions]
        # iterate over the new list and replace self.r with new_r
        for i, arr in enumerate(new_dist):
            new_dist[i] = np.where(arr == self.r, new_r, arr)
        return new_dist

    def perturb_r_and_generate_stimuli_for_new_dist(self, new_dist=None, nsamples=None):
        """
        Generate nsamples of given distribution.
        """
        if nsamples == None:
            nsamples = self.nsamples

        stimuli_set = np.zeros(
            (self.nclasses, nsamples, self.num_neurons), dtype=float)
        for iclass in range(len(new_dist)):
            for isample in range(nsamples):
                stimuli_set[iclass, isample, :] = np.random.binomial(
                    1, new_dist[iclass])

        return stimuli_set

    def get_coreset_index(self):
        """
        Get the index of coreset neurons,
        return as a list of sub-lists, where each sub-list contains coreset indices for a .
        """
        dist_coreset_indices = [[i for i, val in enumerate(
            dist) if val == self.r] for dist in self.distributions]
        return dist_coreset_indices

    def perturbate_coreset(self, ham_dis, coreset):
        """
        Given a coreset, perturb it by ham_dis.
        """
        perturbed_coreset = copy.deepcopy(coreset)
        if ham_dis == 0:
            return perturbed_coreset
        replace = list(np.random.permutation(len(coreset))[
                       :ham_dis])  # elements for replacement
        flag = len(replace)
        # while there are elements left to replace, keep drawing from range(self.n),
        # replace only if they were not a part of the original coreset
        while flag != 0:
            lucky_number = random.randrange(self.num_neurons)
            if lucky_number not in coreset:
                replace_index = replace.pop()
                perturbed_coreset[replace_index] = lucky_number
                flag -= 1
        return perturbed_coreset

    def get_perturbated_coreset_indices(self, ham_dis):
        """
        Given the coreset indices of current distribution,
        perturb each of them by ham_dis.
        """
        dist_coreset_indices = self.get_coreset_index()
        perturb_dist_coreset_indices = []
        for core in dist_coreset_indices:
            perturb_dist_coreset_indices.append(
                self.perturbate_coreset(ham_dis, core))
        return perturb_dist_coreset_indices

    def generate_dist_based_on_coreset_indices(self, coreset_indices):
        """
        Backward version of get_coreset_index.
        Given a list of coreset indices,
        convert it back to a distribution.
        """
        distributions = []
        for indices in coreset_indices:
            dist = [self.q] * self.num_neurons
            for i in indices:
                dist[i] = self.r
            distributions.append(np.array(dist))
        return distributions

    def get_perturbated_coreset_distribution(self, ham_dis):
        """
        Given ham_dis, perturb my distributions by ham_dis.
        """
        perturb_dist_coreset_indices = self.get_perturbated_coreset_indices(
            ham_dis)
        perturb_dist = self.generate_dist_based_on_coreset_indices(
            perturb_dist_coreset_indices)
        return perturb_dist

if __name__ == "__main__":
    x = Stimuli(nclasses=2, num_neurons=10, k=2)
    print(x.get_distributions())
    print(x.perturb_r_and_generate_stimuli_for_new_dist(
        x.get_perturbated_coreset_distribution(2)))


import os
import time
import requests
import telegram
import logging

from dotenv import load_dotenv, find_dotenv

logger = logging.getLogger('__name__')

class TelegramBotHandler(logging.Handler):

    def __init__(self, log_bot, chat_id):
        super().__init__()
        self.chat_id = chat_id
        self.log_bot = log_bot

    def emit(self, record):
        log_entry = self.format(record)
        self.log_bot.send_message(text=log_entry, chat_id=self.chat_id)

def main():
    load_dotenv(find_dotenv())
    token = os.environ['TOKEN']
    bot_token = os.environ['BOT_TOKEN']
    log_bot_token = os.environ['LOG_BOT_TOKEN']
    chat_id = os.environ['CHAT_ID']
    bot = telegram.Bot(bot_token)
    log_bot = telegram.Bot(log_bot_token)

    logger.setLevel(logging.INFO)
    logger.addHandler(TelegramBotHandler(log_bot, chat_id))
    try:
        url = 'https://dvmn.org/api/long_polling/'
        header = {
            'Authorization': f'Token {token}'
            }
        timestamp = ''

        logger.info('Bot started')
        while True:
            try:
                params = {'timestamp': timestamp}
                response = requests.get(url, headers=header, params=params, timeout=120)
                response.raise_for_status()
            except requests.exceptions.ReadTimeout:
                logger.info('Надо ж дать')
                continue
            except requests.ConnectionError as err:
                time.sleep(180)
                logger.error(err)
                continue
            response_attempts = response.json()
            if 'timestamp_to_request' in response_attempts:
                timestamp = response_attempts['timestamp_to_request']
            else:
                timestamp = response_attempts['last_attempt_timestamp']
                new_attempts = response_attempts['new_attempts']
                for attempt in new_attempts:
                    lesson_title = attempt['lesson_title']
                    if attempt['is_negative']:
                        add_text = 'К сожалению, в работе нашлись ошибки.'
                    else:
                        add_text = 'Преподавателю все понравилось, можно приступать к следующему уроку!'
                    lesson_url = attempt['lesson_url']
                    bot.send_message(text=f'У Вас проверили работу «{lesson_title}»\n\n{add_text}\n\n {lesson_url}', chat_id=chat_id)
    except Exception as err:
        logger.fatal(err)

if __name__ == '__main__':
    main()


class Solution:
    def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
        def helper(i,arr,n,k,dp):
            if(i==n):
                return 0

            if(dp[i]!=-1) :
                return dp[i]

            maxi=-10**9
            maxians=-10**9
            leng=0
            for j in range(i,min(n,i+k)):
                leng+=1
                maxi=max(maxi,arr[j])
                cost=(maxi*leng) + helper(j+1,arr,n,k,dp)
                maxians=max(maxians,cost)

            dp[i]=maxians
            return dp[i]
        dp=[-1]*(len(arr))
        return helper(0,arr,len(arr),k,dp)


Filepath = r"C:\Users\Padraig\Desktop\Development\AdventOfCode\2022\P2\p2.txt"

def PreprocessData(filepath):
    input = open(filepath).readlines()
    roundArray = []
    for i in range(len(input)):
        round = input[i].strip().split()
        roundArray.append([round[0], round[1]])

    return roundArray

def SolvePart1(filepath):
    input = PreprocessData(filepath)
    results = []
    for round in input:
        score = 0
        if round[0] == 'A':
            if round[1] == 'X':
                score +=3
            elif round[1] == 'Y':
                score += 6

        elif round[0] == 'B':
            if round[1] == 'Y':
                score += 3
            elif round[1] == 'Z':
                score += 6
        else:
            if round[1] == 'Z':
                score += 3
            elif round[1] == 'X':
                score += 6

        if round[1] == 'X':
            score += 1
        elif round[1] == 'Y':
            score +=2
        else:
             score +=3

        results.append(score)
    return sum(results)

def SolvePart2(filepath):
    input = PreprocessData(filepath)
    results = []
    for round in input:
        score = 0
        if round[0] == 'A':
            if round[1] == 'X':
                score +=3
            elif round[1] == 'Y':
                score += 4
            else:
                score += 8

        elif round[0] == 'B':
            if round[1] == 'X':
                score += 1
            elif round[1] == 'Y':
                score += 5
            else:
                score += 9
        else:
            if round[1] == 'X':
                score += 2
            elif round[1] == 'Y':
                score += 6
            else:
                score += 7

        results.append(score)
    return sum(results)

print("Solution to Part 1: ", SolvePart1(Filepath))
print("Solution to Part 2: ", SolvePart2(Filepath))


import pytest

from src.can_place_flowers import Solution

@pytest.mark.parametrize(
    "flowerbed,n,expected",
    (
        ([1, 0, 0, 0, 1], 1, True),
        ([1, 0, 0, 0, 1], 2, False),
        ([1, 0, 0, 0, 0, 1], 2, False),
        ([0], 1, True),
    ),
)
def test_solution(flowerbed, n, expected):
    assert Solution().canPlaceFlowers(flowerbed, n) is expected


# import math

import requests
import re

def get_url():
  return ''.join([
    'http'+ ':' + '//',
    '.'.join(['www', 'cyber'+'syndrome', 'net']),
    '/'+'search.cgi'+'?' + '&'.join(['q=JP', 'a=A', 'f=d', 's=new', 'n=100'])
  ])

def read_page():
  url = get_url()
  ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
  headers = {
    'User-Agent': ua,
  }
  session = requests.Session()
  session.headers.update(headers)
  res = session.get(url)
  return res.text

def parse_as(html):
  re_str = r'as=\[([\d,]+)\];'
  r = re.search(re_str, html)
  res = ''
  if r:
    res = r.group(1).split(',')
  # print('as:', res)
  return res

def parse_ps(html):
  re_str = r'var ps=\[([\d,]+)\];'
  r = re.search(re_str, html)
  res = ''
  if r:
    res = r.group(1).split(',')
  # print('ps:', res)
  return res

def parse_n(html, ps):
  re_str = r'var n=(\(.+?\)\%\d+);'
  r = re.search(re_str, html)
  res = ''
  if r:
    _n = r.group(1)
    # print('_n:', _n)
    for r2 in re.findall(r'ps\[(\d+)\]', _n):
      # print('n:r2:', r2)
      _n = _n.replace('ps[%s]'%r2, ps[int(r2)])
    # print('_n:', _n)
    res = eval(_n)
  # print('n:', res)
  return res

def decode_ip_addrs(var_as, var_ps, var_n):
  as1 = var_as[0:var_n]
  as2 = var_as[var_n:]

  # tmp = {}
  # for i, a in enumerate(as2+as1):
  #   idx = math.floor(i/4)
  #   # print('idx:', idx)

  #   if not idx in tmp:
  #     # tmp[idx] = [None, None, None, None]
  #     tmp[idx] = []

  #   # if i%4 == 0:
  #   #   tmp[idx].append(a)
  #   # elif i%4 == 3:
  #   #   tmp[idx].append(a)
  #   # else:
  #   #   tmp[idx].append(a)
  #   tmp[idx].append(a)
  # for i in sorted(tmp.keys()):
  # for i in tmp.keys():
  #   # print('n%s:'%(i+1), '%s:%s'%(''.join(tmp[i]), ps[i]))
  #   addrs = '%s:%s'%('.'.join(tmp[i]), var_ps[i])
  #   res.append(addrs)
  #   # print('n%s:'%(i+1),  addrs)
  res = []
  tmp = []
  for i, a in enumerate(as2+as1):
    tmp.append(a)
    if len(tmp) == 4:
      ps_idx = len(res)
      adrs = '.'.join(tmp) + ':' + var_ps[ps_idx]
      res.append(adrs)
      tmp = []

  return res

def get_proxies():
  html = read_page()
  # print(html)

  var_as = parse_as(html)
  var_ps = parse_ps(html)
  var_n = parse_n(html, var_ps)
  ips = decode_ip_addrs(var_as, var_ps, var_n)
  return ips

if __name__ == '__main__':
  proxies = get_proxies()
  print(proxies)


import math
import matplotlib.pyplot as plt

def integral(n):
	val = [1 - math.exp(-1)]
	if n < 1:
		return val
	for i in range(1,n+1):
		val.append(1 - i*val[i-1])
	return val

n = 20
x = range(0,n+1)
y = integral(n)
plt.plot(x, y, 'r')
plt.xlabel('k')
plt.ylabel('I(k)')
plt.show()


# -*- coding: utf-8 -*-
"""
Created on Sun Dec  6 16:56:25 2020

@author: doria
"""
#***Interface graphique***

from tkinter import *
#creation des des fichiers textes
#Path
path_file = open("path_file_IMU.txt","r")#"C:/Users/doria/Desktop/project_5siec/Sensors_file/data/IMU/"
path = path_file.readline()
path=path.replace("\n","")
print(path)
path_file.close()

#function to get value and add it onto a text file wich will serve as imput to C# script

def end():
    sTime = open(path+"sTime.txt","w")
    dTime = open(path+"dTime.txt","w")
    var_accel = open (path+"var_accel.txt","w")
    var_angular = open (path+"var_angular.txt","w")
    biais = open (path+"biais.txt","w")
    failure = open (path+"failure.txt","w")

    sTime.write(str(startTime.get()))
    dTime.write(str(duration.get()))
    var_accel.write(str(saccel.get()))
    var_angular.write(str(sangular.get()))
    biais.write(str(var_biais.get()))
    failure.write(str(var_fail.get()))

    sTime.close()
    dTime.close()
    var_accel.close()
    var_angular.close()
    biais.close()
    failure.close()

    fenetre.destroy

####création de la fenetre
fenetre = Tk()

####definition des cases et de la presentation
#liste d option
option_menu = ["true","false"]

label = Label(fenetre, text="biais actif")
label.grid(row=0,column=0)
var_biais=StringVar(fenetre)
var_biais.set(option_menu[0])
option_biais = OptionMenu(fenetre, var_biais, *option_menu)
option_biais.grid(row=0,column=2)

label = Label(fenetre, text="echec total")
label.grid(row=2,column=0)
var_fail=StringVar(fenetre)
var_fail.set(option_menu[0])
option_echec = OptionMenu(fenetre, var_fail, *option_menu)
option_echec.grid(row=2,column=2)

label = Label(fenetre, text="Variance acceleration")
label.grid(row=4,column=0)
saccel = Entry(fenetre, width=5)
saccel.grid(row=4,column=2)

label = Label(fenetre, text="Variance angular velocity")
label.grid(row=6,column=0)
sangular = Entry(fenetre, width=5)
sangular.grid(row=6,column=2)

label = Label(fenetre, text="Start Time in s")
label.grid(row=10,column=0)
startTime = Entry(fenetre, width=5)
startTime.grid(row=10,column=2)

label = Label(fenetre, text="Duration in s")
label.grid(row=12,column=0)
duration = Entry(fenetre, width=5)
duration.grid(row=12,column=2)

bouton=Button(fenetre, text="Entrée", command=end)
bouton.grid(row=16,column=0)

fenetre.mainloop()


import random

logo = """
.------.            _     _            _    _            _
|A_  _ |.          | |   | |          | |  (_)          | |
|( \/ ).-----.     | |__ | | __ _  ___| | ___  __ _  ___| | __
| \  /|K /\  |     | '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ /
|  \/ | /  \ |     | |_) | | (_| | (__|   <| | (_| | (__|   <
`-----| \  / |     |_.__/|_|\__,_|\___|_|\_\ |\__,_|\___|_|\_\\
      |  \/ K|                            _/ |
      `------'                           |__/
"""
#function to calculate final score
def gameOver(playerScore, cpuScore,choice):
  """This function takes in both decks and user's choice ,then prints the sum of cards and checks if
     value goes over 21
  """
  print(f"Your cards: {playerScore} , current score: {sum(playerScore)}")
  print(f"Computer's Card : {cpuScore}, current score: {sum(cpuScore)}")
  if(choice == "y"):
    if(sum(playerScore) > 21):
      print("Busted !! , Try Again")
    else:
      print("You Win !!")
  else:
    if(sum(player_Deck) > sum(cpu_deck)):
      print("You Win")
    else:
      print("CPU WINS !!!")

# function to add 11 or 1 as per the current score (sum of deck)
def checkAce(deck):
  if(11 in deck):
    if(sum(deck) > 21):
      deck.remove(11)
      deck.append(1)
  return deck

startGame = input("Do you want to play a game of BlackJack ? Type yes or no : ").lower()
if(startGame == "yes"):
  print(logo)

  deck = [11, 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 10 , 10 , 10]
  player_Deck = []
  cpu_deck = []

  for _ in range(2):
    player_Deck.append(random.choice(deck))
    cpu_deck.append(random.choice(deck))

  player_Deck = checkAce(player_Deck)
  cpu_deck = checkAce(cpu_deck)
  print(f"Your cards: {player_Deck} , current score: {sum(player_Deck)}")
  print(f"Computer's Card : {cpu_deck[0]}")
  play = "y"
  while play == "y":
    play = input("Type y to get another card, type n to pass : ")
    if(play == "y"):
      player_Deck.append(random.choice(deck))
      cpu_deck.append(random.choice(deck))
      player_Deck = checkAce(player_Deck)
      cpu_deck = checkAce(cpu_deck)
      if( sum(player_Deck) > 21 or sum(cpu_deck) > 21):
        gameOver(player_Deck,cpu_deck,choice="y")
        break
      print(f"Your cards: {player_Deck} , current score: {sum(player_Deck)}")
      print(f"Computer's Card : {cpu_deck[0]}")
    else:
      gameOver(player_Deck,cpu_deck,choice="n")
else:
  print("GOODBYE !!")


"""
Test executors logic.
"""

import yaml

from unittest import TestCase
from voluptuous import Schema
from six import StringIO

from mock import (
    patch,
    call,
    MagicMock,
)

from plix.executors import (
    BaseExecutor,
    ShellExecutor,
)

from .common import MockDisplay

class ExecutorsTests(TestCase):
    def test_executors_are_yaml_representable(self):
        class MyExecutor(BaseExecutor):
            options_schema = Schema({'foo': str})
            __module__ = 'my_module'

        executor = MyExecutor(options={'foo': 'bar'})

        self.assertEqual(
            yaml.dump({
                'name': 'my_module.MyExecutor',
                'options': {
                    'foo': 'bar',
                }
            }),
            yaml.dump(executor),
        )

    def test_executors_are_yaml_representable_without_options(self):
        class MyExecutor(BaseExecutor):
            options_schema = Schema({'foo': str})
            __module__ = 'my_module'

        executor = MyExecutor(options={})

        self.assertEqual(
            yaml.dump('my_module.MyExecutor'),
            yaml.dump(executor),
        )

    def test_base_executors_requires_a_returncode(self):
        class MyExecutor(BaseExecutor):
            def execute_one(self, environment, command, output):
                pass

        display = MockDisplay()
        executor = MyExecutor()

        with self.assertRaises(RuntimeError):
            executor.execute(
                environment={},
                commands=['a'],
                display=display,
            )

    def test_base_executors_returns_true_on_success(self):
        class MyExecutor(BaseExecutor):
            def execute_one(self, environment, command, output):
                return 0

        display = MockDisplay()
        executor = MyExecutor()

        status = executor.execute(
            environment={},
            commands=['a'],
            display=display,
        )

        self.assertTrue(status)

    def test_base_executors_returns_false_on_failure(self):
        class MyExecutor(BaseExecutor):
            def execute_one(self, environment, command, output):
                return 1

        display = MockDisplay()
        executor = MyExecutor()

        status = executor.execute(
            environment={},
            commands=['a'],
            display=display,
        )

        self.assertFalse(status)

    def test_shell_executor_execute(self):
        environment = {"FOO": "BAR"}
        commands = ["alpha", "beta"]

        display = MockDisplay()
        executor = ShellExecutor()

        def Popen(command, env=None, *args, **kwargs):
            process = MagicMock()
            process.stdout = StringIO(command)
            process.returncode = 0

            self.assertEqual(environment, env)

            return process

        with patch('subprocess.Popen', side_effect=Popen):
            executor.execute(
                environment=environment,
                commands=commands,
                display=display,
            )

        self.assertEqual(
            display.start_command.mock_calls,
            [
                call(index=0, command="alpha"),
                call(index=1, command="beta"),
            ],
        )
        self.assertEqual(
            display.stop_command.mock_calls,
            [
                call(index=0, command="alpha", returncode=0),
                call(index=1, command="beta", returncode=0),
            ],
        )
        self.assertEqual(
            display.command_output.mock_calls,
            [
                call(0, "alpha"),
                call(1, "beta"),
            ],
        )


# Erstelle eine neue datenbank
# exit(1): Verbindungsfehler
# exit(1): Ausführungsfehler
# DB-Modul einbinden
import mysql.connector

# Verbindung zum DB-Server herstellen
try:
    conn = mysql.connector.connect(user="root",
                                   host="localhost")
except mysql.connector.Error as e:
    print(f"Verbindung konnte nicht hergestellt werden: {e}")
    exit(1)

# DB-Cursor-Objekt bereitstellen
cur = conn.cursor()

# SQL-Anweisung zum Erstellen der DB ausführen
# CREATE DATABASE schule_neu
try:
    cur.execute("CREATE DATABASE Schule3")
except mysql.connector.Error as e:
    print(f"Fehler bei der Ausführung der SQL-Anweisung: {e}")
    exit(2)

# Verbindung zum DB-Server herstellen
conn.close()


from math import sin,pi
from tkinter import Tk,Canvas
## from pylab import linspace,sin

import sys
if sys.version_info.major == 2 and sys.version_info.minor == 7 :
    print(sys.version)
    import Tkinter as tk
    import tkFileDialog as filedialog
elif sys.version_info.major == 3 and sys.version_info.minor == 6 :
    print(sys.version)
    import tkinter as tk
    from tkinter import filedialog
else :
    print("Your python version is : ")
    print(sys.version_info.major,sys.version_info.minor)
    print("... I guess it will work !")

class View :
    def __init__(self,parent,bg="white",width=600,height=300):
        self.canvas=Canvas(parent,bg=bg,width=width,height=height)
        self.a,self.f,self.p=1.0,2.0,0.0
        self.signal=[]
        self.width,self.height=width,height
        self.units=1
        self.canvas.bind("<Configure>",self.resize)
    def vibration(self,t,harmoniques=1,impair=True):
        a,f,p=self.a,self.f,self.p
        f=1.0
        somme=0
        for h in range(1,harmoniques+1) :
            somme=somme + (a/h)*sin(2*pi*(f*h)*t-p)
        return somme
    def generate_signal(self,period=2,samples=100):
        del self.signal[0:]
        echantillons=range(int(samples)+1)
        Tech = period/samples
        print("Tech",Tech,period,samples)
        for t in echantillons :
            self.signal.append([t*Tech,self.vibration(t*Tech)])
        print(self.signal)
        return self.signal
    def update(self):
        print("View : update()")
        self.generate_signal()
        if self.signal :
            self.plot_signal(self.signal)
    def plot_signal(self,signal,color="red"):
        w,h=self.width,self.height
        signal_id=None
        if signal and len(signal) > 1:
            print(self.units)
            plot = [(x*w,h/2.0*(1-y/(self.units/2.0))) for (x, y) in signal]
            signal_id=self.canvas.create_line(plot, fill=color, smooth=1, width=3,tags="sound")
        return signal_id
    def grid(self,steps=2):
        self.units=steps
        tile_x=self.width/steps
        for t in range(1,steps+1):
            x =t*tile_x
            self.canvas.create_line(x,0,x,self.height,tags="grid")
            self.canvas.create_line(x,self.height/2-10,x,self.height/2+10,width=3,tags="grid")
        tile_y=self.height/steps
        for t in range(1,steps+1):
            y =t*tile_y
            self.canvas.create_line(0,y,self.width,y,tags="grid")
            self.canvas.create_line(self.width/2-10,y,self.width/2+10,y,width=3,tags="grid")
    def resize(self,event):
        if event:
            print("event")
            self.width,self.height=event.width,event.height
            self.canvas.delete("grid")
            self.canvas.delete("sound")
            self.plot_signal(self.signal)
            self.grid(self.units)
    def packing(self) :
        self.canvas.pack(expand=1,fill="both",padx=6)

if  __name__ == "__main__" :
    root=Tk()
    root.title("Piano : Nom-Prenom")
    view=View(root)
    view.grid(4)
    view.packing()
    view.update()
    root.mainloop()


#!/usr/bin/python3
import pandas as pd
import numpy as np
import seaborn as sns
import statsmodels.formula.api as sm
import pylab as plt
import argparse
import os
import matplotlib
from matplotlib.gridspec import GridSpec
from pathlib import Path
from tqdm import tqdm

plt.style.use('bmh')

HOME = str(Path.home())

PLOT_DIR = os.path.join(HOME, 'source/presentationEAVM/plots')

def RAD(deg):
    return deg * np.pi / 180.0

def CREATE_STATS_PLOTS(num_seg, out_dir):
    df = data_lv.loc[data_lv.Segm == num_seg]
    result = sm.ols(formula="Voltage ~ WT", data=df).fit()

    fig = plt.figure(figsize=(5, 7))

    gs = GridSpec(3, 1)
    ax2 = fig.add_subplot(gs[2, 0])
    ax1 = fig.add_subplot(gs[0:2, 0])
    fig.tight_layout(w_pad=8)

    ax1.set_title('Regression plot for {} segment'.format(num_seg))

    sns.distplot(result.resid, ax=ax2, axlabel='Residuals distribution')
    sns.regplot(x='WT', y='Voltage', data=df, ax=ax1, x_jitter=.1, x_estimator=np.mean)

    box_text = 'r2 = {}\nslope = {}\np = {}\nNum. observations = {}'.format(round(GET_R2(num_seg), 5),
                                                                            round(GET_SLOPE(num_seg), 5),
                                                                            round(result.pvalues['WT'], 10),
                                                                            int(result.nobs))
    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
    ax1.text(0.05, 0.75, box_text, transform=ax1.transAxes, bbox=props)

    plt.savefig(os.path.join(out_dir, '{}.png'.format(num_seg)))
    plt.close()

def GET_R2(num_seg):
    df = data_lv.loc[data_lv.Segm == num_seg]
    result = sm.ols(formula="Voltage ~ WT", data=df).fit()
    return result.rsquared

def GET_SLOPE(num_seg):
    df = data_lv.loc[data_lv.Segm == num_seg]
    result = sm.ols(formula="Voltage ~ WT", data=df).fit()
    return result.params.WT

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('-f', type=str, help='.csv file with data')
    parser.add_argument('-d', type=str, help='directory with *data*.csv')

    args = parser.parse_args()

    if args.f is None and args.d is None:
        raise ValueError('No path to data')
    elif args.d is None:
        data_lv = pd.read_csv(args.f, index_col=0)
        folder = args.f.split('/')[-1].split('.')[0]
        PLOT_DIR = os.path.join(PLOT_DIR, folder)
        if not os.path.isdir(PLOT_DIR):
            os.mkdir(PLOT_DIR)

        for n in tqdm(range(1, 18)):
            CREATE_STATS_PLOTS(n, PLOT_DIR)

    elif args.f is None:
        files = list(os.walk(args.d))[0][2]
        for f in tqdm(files):
            data_lv = pd.read_csv(os.path.join(args.d, f), index_col=0)
            folder = f.split('/')[-1].split('.')[0]
            out_dir = os.path.join(PLOT_DIR, folder)
            if not os.path.isdir(out_dir):
                os.mkdir(out_dir)

            for n in range(1, 18):
                CREATE_STATS_PLOTS(n, out_dir)


import threading
import time

import pygame
import random
import socket
import pickle

"""
10 x 20 square grid
shapes: S, Z, I, O, J, L, T
represented in order by 0 - 6
"""

pygame.font.init()

# GLOBALS VARS
s_width = 1200
s_height = 750
play_width = 300  # meaning 300 // 10 = 30 width per block
play_height = 600  # meaning 600 // 20 = 30 height per block
block_size = 30
top_left_y = s_height - play_height - 30

opponent_grid = None
high_score = 0

host = "127.0.0.1"  # localhost
port = 55555

# SHAPE FORMATS

S = [['.....',
      '......',
      '..00..',
      '.00...',
      '.....'],
     ['.....',
      '..0..',
      '..00.',
      '...0.',
      '.....']]

Z = [['.....',
      '.....',
      '.00..',
      '..00.',
      '.....'],
     ['.....',
      '..0..',
      '.00..',
      '.0...',
      '.....']]

I = [['..0..',
      '..0..',
      '..0..',
      '..0..',
      '.....'],
     ['.....',
      '0000.',
      '.....',
      '.....',
      '.....']]

O = [['.....',
      '.....',
      '.00..',
      '.00..',
      '.....']]

J = [['.....',
      '.0...',
      '.000.',
      '.....',
      '.....'],
     ['.....',
      '..00.',
      '..0..',
      '..0..',
      '.....'],
     ['.....',
      '.....',
      '.000.',
      '...0.',
      '.....'],
     ['.....',
      '..0..',
      '..0..',
      '.00..',
      '.....']]

L = [['.....',
      '...0.',
      '.000.',
      '.....',
      '.....'],
     ['.....',
      '..0..',
      '..0..',
      '..00.',
      '.....'],
     ['.....',
      '.....',
      '.000.',
      '.0...',
      '.....'],
     ['.....',
      '.00..',
      '..0..',
      '..0..',
      '.....']]

T = [['.....',
      '..0..',
      '.000.',
      '.....',
      '.....'],
     ['.....',
      '..0..',
      '..00.',
      '..0..',
      '.....'],
     ['.....',
      '.....',
      '.000.',
      '..0..',
      '.....'],
     ['.....',
      '..0..',
      '.00..',
      '..0..',
      '.....']]

shapes = [S, Z, I, O, J, L, T]
shape_colors = [(0, 255, 0), (255, 0, 0), (0, 255, 255), (255, 255, 0), (255, 165, 0), (0, 0, 255), (128, 0, 128)]

# index 0 - 6 represent shape

class Piece(object):
    def __init__(self, x, y, shape):
        self.x = x
        self.y = y
        self.shape = shape
        self.color = shape_colors[shapes.index(shape)]
        self.rotation = 0

def create_grid(locked_positions={}):
    grid = [[(0, 0, 0) for x in range(10)] for x in range(20)]  # initialize grid with 10 * 20 with each grid color (0, 0, 0)

    for i in range(len(grid)):
        for j in range(len(grid[i])):
            if (j, i) in locked_positions:
                c = locked_positions[(j, i)]
                grid[i][j] = c
    return grid

def convert_shape_format(shape):
    positions = []
    format = shape.shape[shape.rotation % len(shape.shape)]

    for i, line in enumerate(format):
        row = list(line)
        for j, column in enumerate(row):
            if column == "0":
                positions.append((shape.x + j, shape.y + i))

    for i, position in enumerate(positions):
        positions[i] = (position[0] - 2, position[1] - 4)

    return positions

def valid_space(shape, grid):
    # flatten 2d list to 1d list e.g. 20x10 -> 200x1
    # grid[i][j] == (0, 0, 0) is to check whether the position has existing block already
    accepted_position = [[(j, i) for j in range(10) if grid[i][j] == (0, 0, 0)] for i in range(20)]
    accepted_position = [j for sub in accepted_position for j in sub]

    formatted = convert_shape_format(shape)

    for pos in formatted:
        if pos not in accepted_position:
            if pos[1] > -1:
                return False
    return True

def check_lost(positions):
    for pos in positions:
        x, y = pos
        if y < 1:
            return True

    return False

def get_shape():
    return Piece(5, 0, random.choice(shapes))

def draw_text_middle(surface, text, size, color):
    font = pygame.font.SysFont("comicsans", size, bold=True)
    label = font.render(text, 1, color)

    surface.blit(label, (s_width // 2 - label.get_width() / 2,
                         s_height // 2 - label.get_height() / 2))

def draw_grid(surface, grid, top_left_x):
    sx = top_left_x
    sy = top_left_y

    for i in range(len(grid)):
        pygame.draw.line(surface, (128, 128, 128), (sx, sy + i * block_size), (sx + play_width, sy + i * block_size))
        for j in range(len(grid[i])):
            pygame.draw.line(surface, (128, 128, 128), (sx + j * block_size, sy), (sx + j * block_size, sy + play_height))

def clear_rows(grid, locked_positions):
    increment = 0
    for i in range(len(grid) - 1, -1, -1):
        row = grid[i]

        if (0, 0, 0) not in row:
            increment += 1
            row_index = i
            for j in range(len(row)):
                try:
                    del locked_positions[(j, i)]
                except:
                    continue

    if increment > 0:
        for key in sorted(list(locked_positions), key=lambda x: x[1])[::-1]:
            x, y = key
            if y < row_index:   # only shift the blocks above the row index with increment value
                new_key = (x, y + increment)
                locked_positions[new_key] = locked_positions.pop(key)

    return increment

def draw_next_shape(shape, surface, top_left_x, multiplayer):
    font = pygame.font.SysFont("comicsans", 30)
    label = font.render("Next Shape", 1, (255, 255, 255))

    if multiplayer:
        sx = top_left_x + play_width * 2 + 100
    else:
        sx = top_left_x + play_width + 50
    sy = top_left_y + play_height / 2 - 120
    format = shape.shape[shape.rotation % len(shape.shape)]

    for i, line in enumerate(format):
        row = list(line)
        for j, column in enumerate(row):
            if column == "0":
                pygame.draw.rect(surface, shape.color, (sx + j * 30 + 15, sy + i * 30 + 25, block_size, block_size))

    surface.blit(label, (sx + 10, sy - 30))

def draw_window(surface, player_grid, multi_player, top_left_x, opp_top_left_x, score=0, high_score=0):
    surface.fill((0, 0, 0))

    pygame.font.init()
    font = pygame.font.SysFont("comicsans", 40)
    player_label = font.render("You", True, (255, 255, 255))    # Can further change to player's nickname
    opp_label = font.render("Opponent", True, (255, 255, 255))    # Can further change to opponent's nickname

    surface.blit(player_label, (top_left_x + play_width / 2 - (player_label.get_width() / 2), 30))  # middle of the screen
    if multi_player:
        surface.blit(opp_label, (opp_top_left_x + play_width / 2 - (opp_label.get_width() / 2), 30))  # middle of the screen

    # print current score
    font = pygame.font.SysFont("comicsans", 30)
    label = font.render("Score: {0}".format(score), True, (255, 255, 255))

    if multi_player:
        sx = top_left_x + play_width * 2 + 100
    else:
        sx = top_left_x + play_width + 50
    sy = top_left_y + play_height / 2 - 100

    surface.blit(label, (sx + 20, sy + 160))

    # print last score
    label = font.render("High score: {0}".format(high_score), True, (255, 255, 255))

    sx = top_left_x - 250
    sy = top_left_y + 100

    surface.blit(label, (sx + 10, sy + 160))

    for i in range(len(player_grid)):
        for j in range(len(player_grid[i])):
            pygame.draw.rect(surface, player_grid[i][j], (top_left_x + j * block_size, top_left_y + i * block_size, block_size, block_size), 0)
            if multi_player:
                pygame.draw.rect(surface, opponent_grid[i][j], (opp_top_left_x + j * block_size, top_left_y + i * block_size, block_size, block_size), 0)

        pygame.draw.rect(surface, (255, 0, 0), (top_left_x, top_left_y, play_width + 1, play_height), 4)
        if multi_player:
            pygame.draw.rect(surface, (255, 0, 0), (opp_top_left_x, top_left_y, play_width + 1, play_height), 4)

    draw_grid(surface, player_grid, top_left_x)
    if multi_player:
        draw_grid(surface, opponent_grid, opp_top_left_x)

def main(win, multi_player, client):
# def main(win, multi_player):
    if multi_player:
        top_left_x = s_width // 2 - play_width - 30
    else:
        top_left_x = (s_width - play_width) // 2
    opp_top_left_x = s_width // 2 - play_width + 300

    locked_positions = {}
    change_piece = False
    run = True
    current_piece = get_shape()
    next_piece = get_shape()
    clock = pygame.time.Clock()
    fall_time = 0
    fall_speed = 0.27
    level_time = 0
    score = 0

    global opponent_grid
    opponent_grid = create_grid(locked_positions)

    while run:
        player_grid = create_grid(locked_positions)
        fall_time += clock.get_rawtime()    # get time since last clock.tick()
        level_time += clock.get_rawtime()
        clock.tick()

        if level_time / 1000 > 5:
            level_time = 0
            if fall_speed > 0.12:   # max speed = 0.27 - 0.12 = 0.15
                fall_speed -= 0.005

        if fall_time / 1000 > fall_speed:
            fall_time = 0
            current_piece.y += 1
            if not (valid_space(current_piece, player_grid)) and current_piece.y > 0:   # piece is not at the top
                current_piece.y -= 1
                change_piece = True     # lock the piece and generate another piece

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    current_piece.x -= 1
                    if not (valid_space(current_piece, player_grid)):
                        current_piece.x += 1
                if event.key == pygame.K_RIGHT:
                    current_piece.x += 1
                    if not (valid_space(current_piece, player_grid)):
                        current_piece.x -= 1
                if event.key == pygame.K_DOWN:
                    current_piece.y += 1
                    if not (valid_space(current_piece, player_grid)):
                        current_piece.y -= 1
                if event.key == pygame.K_UP:
                    current_piece.rotation += 1
                    if not (valid_space(current_piece, player_grid)):
                        current_piece.rotation -= 1

        shape_positions = convert_shape_format(current_piece)

        for i in range(len(shape_positions)):
            x, y = shape_positions[i]
            if y > -1:
                player_grid[y][x] = current_piece.color

        if change_piece:
            for position in shape_positions:
                pos = (position[0], position[1])
                locked_positions[pos] = current_piece.color    # append frozen pieces to locked positions dict
            current_piece = next_piece
            next_piece = get_shape()
            change_piece = False
            score += clear_rows(player_grid, locked_positions) * 10

        draw_window(win, player_grid, multi_player, top_left_x, opp_top_left_x, score, high_score)
        draw_next_shape(next_piece, win, top_left_x, multi_player)

        if multi_player:
            client.send(pickle.dumps(player_grid))

            data = pickle.loads(client.recv(16384))

            if data == "Lost":
                draw_text_middle(win, "YOU WIN!", 80, (255, 255, 255))
                pygame.display.update()
                pygame.time.delay(1500)
                run = False
                client.send(pickle.dumps("Score,{0}".format(score)))
            else:
                opponent_grid = data

        pygame.display.update()

        if check_lost(locked_positions):
            draw_text_middle(win, "YOU LOST!", 80, (255, 255, 255))
            client.send(pickle.dumps("Lost"))

            pygame.display.update()
            pygame.time.delay(1500)
            run = False
            client.send(pickle.dumps("Score,{0}".format(score)))

def ready(client):
    run = True

    while run:
        message = pickle.loads(client.recv(1024))
        if message == "Game start":
            print(message)
            run = False

    main(win, True, client)
    pygame.display.quit()

def waiting_room(win):
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((host, port))

    message = client.recv(1024).decode()
    if message == "Connected to the server":
        print(message)

        win.fill((0, 0, 0))
        draw_text_middle(win, "Please wait for another player", 60, (255, 255, 255))
        pygame.display.update()

        while True:
            message = client.recv(1024).decode()
            if "Game start" in message:
                print("Game start")

                global high_score
                high_score = int(message.split(',')[1].strip())

                break

        main(win, True, client)
        pygame.display.quit()

    else:
        print("Connection error")
        client.close()

win = pygame.display.set_mode((s_width, s_height))
pygame.display.set_caption("Tetris")

waiting_room(win)  # start game


import math
ceil = 1<<31
floor=(1<<31)
class Node:

    def __init__(self, data):
        self.data = data
        self.child = []

 # Utility function to create a new tree node
def newNode(data):
    temp = Node(data)
    return temp

def constructor(lst,n):
    root = None
    stack = []
    for i in range(0,n):
        if lst[i]==-1:
            stack.pop()
        else:
            t= Node(lst[i])
            if len(stack) > 0:
                stack[-1].child.append(t)

            else:
                root=t

            stack.append(t)
    return root

def ceilndfloor(node, data):
    global floor
    global ceil
    if node.data > data:
        if node.data < ceil:
            ceil = node.data

    if node.data < data:
        if node.data > floor:
            floor = node.data

    for child in node.child:
        ceilndfloor(child,data)

def kthlargest(node,k):
    global floor
    data = floor
    floor = -(1<<31)
    ceilndfloor(node, data)
    for i in range(1, k):
        data = floor
        floor = -(1<<31)
        ceilndfloor(node, data)
    return floor

# number of elements as input
n = int(input())
lst = []
lst = list(map(int, input().split()))

root = constructor(lst,n)
k = int(input())
kth = kthlargest(root, k)
print(kth)


import sys
import threading
import numpy as np

def process_tree(start_index, nodes):
    zzz = 0
    aaa = []

    l = 0
    # np_array = np.array(nodes)

    # aaa = np.where(np_array == start_index)[0]

    aaa = [i for i, e in enumerate(nodes) if e == start_index]

    if len(aaa) == 0:
        return 1

    for k in aaa:
        zzz = max(process_tree(k, nodes), zzz)

    return zzz + 1

def main():
    choice  = input()

    if "F" in choice:
        filename = input()

        if "a" in filename:
            print("Wrong file used")
        else:
            useFile = 'test/' + filename
            file1 = open(useFile, 'r')
            Lines = file1.readlines()

            amount = Lines[0]
            tree = Lines[1]

    elif "I" in choice:

        amount = input()
        tree = input()

    tree = tree.split(" ")
    tree = [int(i) for i in tree]
    start_index = 0

    c = 0
    for a in tree:
        if a == -1:
            start_index = c

        c = c + 1

    # nodes = numpy.array([4, -1, 4, 1, 1])
    # start_index = 1

    zzz = process_tree(start_index, tree)

    print(zzz)

sys.setrecursionlimit(10**7)  # max depth of recursion
threading.stack_size(2**27)   # new thread will get stack of such size
threading.Thread(target=main).start()
# main()


#!/usr/bin/env python
import time
import sys

i = 0
while i < 30000:
    i += 1
    sys.stdout.write('upstream-output: ' + str(i) + '\n')
    sys.stdout.flush()
    if i % 5000 == 0:
        time.sleep(1)