from django.core.management.base import BaseCommand, CommandError

from students.models import Group

class Command(BaseCommand):
    help = 'Show list of groups and students in them.'

    def handle(self, *args, **options):
        try:
            for group in Group.objects.all():
                self.stdout.write('=== {0} ==='.format(group.name))
                if group.students.all():
                    for student in group.students.all():
                        self.stdout.write(student.full_name)
                else:
                    self.stdout.write('There no students in this group.')
        except Group.DoesNotExist:
            raise CommandError('Does not exist any groups.')


import ccxt,config
import pandas as pd
from ta.trend import EMAIndicator
from ta.trend import MACD
import time
import send_msg as tele
import pandas_ta as ta
import functions as func
import key
from binance.client import Client
import gspread

kesisimmacdsayac =0
kesisimmovaverage =0
longgiris =0
shortgiris =0
sayici_giris_control = 0
sheetsymbolx =0
sheetssymboly =0
macdlast = 0

class Macdema():

    def __init__(self,symbol,timeframe,quantity,buyvalue,sellvalue):
        self.symbol=symbol
        self.kesisimmovaverage=kesisimmovaverage
        self.kesisimmacdsayac=kesisimmacdsayac
        self.longgiris=longgiris
        self.shortgiris=shortgiris
        self.timeframe=timeframe
        self.sayici_giris_control=sayici_giris_control
        self.macdlast=macdlast
        self.quantity=quantity
        self.buyvalue=buyvalue
        self.sellvalue=sellvalue

    def addspread(self, sheetsymbolx, sheetsymboly, movkesx, movkesy,
                  macdkesx, macdkesy, shortgirisx, shortgirisy, longirisx,
                  longgirisy, sayicikontx, sayicikonty):
        gc = gspread.service_account(filename='credentials.json')

        sh = gc.open_by_key('1jRT7SlWoqaEscBFEz9835rsyrh9m1TNR_HfnGpItTHU')
        worksheet = sh.sheet1
        worksheet.update_cell(sheetsymbolx, sheetsymboly, self.symbol)
        worksheet.update_cell(movkesx, movkesy, self.kesisimmovaverage)
        worksheet.update_cell(macdkesx, macdkesy, self.kesisimmacdsayac)
        worksheet.update_cell(shortgirisx, shortgirisy, self.shortgiris)
        worksheet.update_cell(longirisx, longgirisy, self.longgiris)
        worksheet.update_cell(sayicikontx, sayicikonty, self.sayici_giris_control)

    def dfall(self,symbol,timeframe):

        exchange = ccxt.binance({
            "apiKey": config.apiKey,
            "secret": config.secretKey,

            'options': {
                'defaultType': 'future'
            },
            'enableRateLimit': True,
            'adjustForTimeDifference': True
        })
        order_approve = func.open_order_number(self.symbol)

        try:
            if self.shortgiris==1 or self.longgiris==1 or order_approve == 0:#alıs satıstan sonra 100 cycledan sonra tekrar işleme açma
                self.sayici_giris_control += 1
                if self.sayici_giris_control ==15:
                    print(symbol,timeframe,self.sayici_giris_control)
                    self.longgiris=0
                    self.shortgiris=0
                    self.sayici_giris_control=0

            else:
                bars = exchange.fetch_ohlcv(symbol, timeframe=timeframe, since=None, limit=40)#son 40 price cek pd yap
                df = pd.DataFrame(bars, columns=["timestamp", "open", "high", "low", "close", "volume"])

                macddf = df.ta.macd(close='close', fast=12, slow=26, signal=9, append=True)
                client = Client(api_key=key.Pkey, api_secret=key.Skey)
                result = client.futures_account_balance(asset='USDT')  # bir listeden asset cektik
                balance = float(result[6]['withdrawAvailable'])  # with drawal codu ile aldık

                x = (macddf.iloc[:, 1]) #pd 1. colonu al
                self.macdlast = (x.iloc[-1]) #pd 1. kolon son item

                df["slow macd"] = macddf.iloc[:, 0]

                macd = MACD(df["close"])

                df["macd"] = macd.macd_signal()
                # LOAD SLOW EMA
                slowEma = EMAIndicator(df["close"], float(12))

                df["Slow Ema"] = slowEma.ema_indicator()

                # LOAD FAST EMA
                FastEma = EMAIndicator(df["close"], float(26))
                df["Fast Ema"] = FastEma.ema_indicator()

                print (symbol,self.kesisimmacdsayac,self.timeframe)

                if self.shortgiris!=1 and self.longgiris!=1:
                    if self.kesisimmacdsayac == 0:
                        if (df["macd"][len(df.index) - 2] < df["slow macd"][len(df.index) - 2] and df["macd"][
                            len(df.index) - 1] > df["slow macd"][len(df.index) - 1]) or (
                                df["macd"][len(df.index) - 2] > df["slow macd"][len(df.index) - 2] and df["macd"][
                            len(df.index) - 1] < df["slow macd"][len(df.index) - 1]):
                            self.kesisimmacdsayac += 1
                            macdkesisim = "macdkesisim"" "+ self.symbol+" "+ self.timeframe
                            tele.telegram_bot(macdkesisim)
                            print(df["macd"])
                            print(df["slow macd"])
                            print(symbol, "macdkesisim",self.kesisimmacdsayac)
                if self.shortgiris != 1 and self.longgiris != 1:

                    if self.kesisimmovaverage == 0:

                        if (df["Fast Ema"][len(df.index) - 2] < df["Slow Ema"][len(df.index) - 2] and df["Fast Ema"][
                            len(df.index) - 1] > df["Slow Ema"][len(df.index) - 1]) or (
                                df["Fast Ema"][len(df.index) - 2] > df["Slow Ema"][len(df.index) - 2] and df["Fast Ema"][
                            len(df.index) - 1] < df["Slow Ema"][len(df.index) - 1]):
                            self.kesisimmovaverage += 1
                            movkesisim = "movkesisim"+" "+ self.symbol+" "+self.timeframe
                            tele.telegram_bot(movkesisim)
                            print(df["Slow Ema"])
                            print(df["Fast Ema"])
                            print(symbol,"movkesisim",self.kesisimmovaverage)
                    try:
                        price = client.futures_symbol_ticker(symbol=self.symbol, recvWindow=25000)

                        tp_price = func.price_sell_buy(price,self.buyvalue,self.sellvalue)
                        price_sell_new = tp_price[0]
                        price_buy_new = tp_price[1]
                        print(price_buy_new)
                        print(price_sell_new)
                        order_approve = func.open_order_number(self.symbol)
                        print("order approve", order_approve)
                        print("quantity",self.quantity)

                        if balance > 200:
                            if self.kesisimmovaverage == 1 and self.kesisimmacdsayac == 1:
                                if order_approve == 1:
                                    if self.macdlast > 0:
                                        print('long gir')
                                        tele.telegram_bot('long gir-macdmov_strategy')
                                        tele.telegram_bot(symbol)
                                        func.long_position(self.symbol, self.quantity,
                                                           price_sell_new)  # alıs olusturma fonk
                                        self.kesisimmovaverage = 0
                                        self.kesisimmacdsayac = 0
                                        self.longgiris += 1
                                        print(symbol, longgiris, "alis_sonrasi")
                                        time.sleep(10)
                                    else:
                                        print("short_gir")

                                        tele.telegram_bot("short_gir-macdmov_strategy")
                                        tele.telegram_bot(symbol)
                                        func.short_position(self.symbol, self.quantity,
                                                            price_buy_new)  # satıs olusturma fonk
                                        self.kesisimmovaverage = 0
                                        self.kesisimmacdsayac = 0
                                        self.shortgiris += 1
                                        print(symbol, shortgiris, "alis_sonrasi")

                                else:
                                    islemfazla="islem sayisi 5 den fazlastrtegy2"+" "+ self.symbol+" "+self.timeframe
                                    tele.telegram_bot(islemfazla)
                        else:
                            print("balance 200 altında")

                    except:
                          tele.telegram_bot('fiyat alamadı')
        except ccxt.BaseError as Error:
            print("[ERROR] ", Error)

coin2=Macdema('ETHUSDT',"1h",0.015,1.01,0.991)
coin1=Macdema('BTCUSDT',"1h",0.001,1.01,0.991)
coin3=Macdema('ATOMUSDT',"1h",2,1.01,0.991)
coin4=Macdema('EOSUSDT',"1h",20,1.01,0.991)
coin5=Macdema('LITUSDT',"1h",40,1.01,0.991)
coin6=Macdema('BNBUSDT',"1h",0.1,1.01,0.991)

coin7=Macdema('CRVUSDT',"1h",22,1.01,0.991)
coin8=Macdema('THETAUSDT',"1h",20,1.01,0.991)
coin9=Macdema('XRPUSDT',"1h",60,1.01,0.991)
coin10=Macdema('RUNEUSDT',"1h",10,1.01,0.991)
coin11=Macdema('ARUSDT',"1h",2,1.01,0.991)
coin12=Macdema('DOTUSDT',"1h",3,1.01,0.991)
coin13=Macdema('ETCUSDT',"1h",1.5,1.01,0.991)
coin14=Macdema('ALGOUSDT',"1h",80,1.01,0.991)
coin15=Macdema('TRXUSDT',"1h",200,1.01,0.991)
coin16=Macdema('LRCUSDT',"1h",50,1.01,0.991)
coin17=Macdema('SANDUSDT',"1h",25,1.01,0.991)
coin18=Macdema('AVAXUSDT',"1h",1,1.01,0.991)
coin19=Macdema('COTIUSDT',"1h",220,1.01,0.991)
coin20=Macdema('LINKUSDT',"1h",4,1.01,0.991)
coin21=Macdema('NEARUSDT',"1h",9,1.01,0.991)

coin24=Macdema('MATICUSDT',"1h",40,1.01,0.991)
coin25=Macdema('BELUSDT',"1h",30,1.01,0.991)
coin26=Macdema('KNCUSDT',"1h",20,1.01,0.991)
coin27=Macdema('BLZUSDT',"1h",200,1.01,0.991)
coin28=Macdema('KAVAUSDT',"1h",15,1.01,0.991)
coin29=Macdema('CHZUSDT',"1h",250,1.01,0.991)
coin30=Macdema('DASHUSDT',"1h",1,1.01,0.991)
coin31=Macdema('QTUMUSDT',"1h",8,1.01,0.991)
coin32=Macdema('CHRUSDT',"1h",150,1.01,0.991)
coin33=Macdema('OCEANUSDT',"1h",100,1.01,0.991)
coin34=Macdema('ALPHAUSDT',"1h",150,1.01,0.991)

coin2a=Macdema('ETHUSDT',"15m",0.015,1.007,0.993)
coin1a=Macdema('BTCUSDT',"15m",0.001,1.007,0.993)
coin3a=Macdema('ATOMUSDT',"15m",2,1.007,0.993)
coin4a=Macdema('EOSUSDT',"15m",20,1.007,0.993)
coin5a=Macdema('LITUSDT',"15m",40,1.007,0.993)
coin6a=Macdema('BNBUSDT',"15m",0.1,1.007,0.9993)

coin7a=Macdema('CRVUSDT',"15m",22,1.007,0.993)
coin8a=Macdema('THETAUSDT',"15m",20,1.007,0.993)
coin9a=Macdema('XRPUSDT',"15m",60,1.007,0.993)
coin10a=Macdema('RUNEUSDT',"15m",10,1.007,0.993)
coin11a=Macdema('ARUSDT',"15m",2,1.007,0.993)
coin12a=Macdema('DOTUSDT',"15m",3,1.007,0.993)
coin13a=Macdema('ETCUSDT',"15m",1.5,1.007,0.993)
coin14a=Macdema('ALGOUSDT',"15m",80,1.007,0.993)
coin15a=Macdema('TRXUSDT',"15m",200,1.007,0.993)
coin16a=Macdema('LRCUSDT',"15m",50,1.007,0.993)
coin17a=Macdema('SANDUSDT',"15m",25,1.007,0.993)
coin18a=Macdema('AVAXUSDT',"15m",1,1.007,0.993)

coin19a=Macdema('COTIUSDT',"15m",220,1.007,0.993)
coin20a=Macdema('LINKUSDT',"15m",4,1.007,0.993)
coin21a=Macdema('NEARUSDT',"15m",9,1.007,0.993)

coin24a=Macdema('MATICUSDT',"15m",40,1.007,0.993)
coin25a=Macdema('BELUSDT',"15m",30,1.007,0.993)
coin26a=Macdema('KNCUSDT',"15m",20,1.007,0.993)
coin27a=Macdema('BLZUSDT',"15m",200,1.007,0.993)
coin28a=Macdema('KAVAUSDT',"15m",15,1.007,0.993)
coin29a=Macdema('CHZUSDT',"15m",250,1.007,0.993)
coin30a=Macdema('DASHUSDT',"15m",1,1.007,0.993)
coin31a=Macdema('QTUMUSDT',"15m",8,1.007,0.993)
coin32a=Macdema('CHRUSDT',"15m",150,1.007,0.993)
coin33a=Macdema('OCEANUSDT',"15m",100,1.007,0.993)
coin34a=Macdema('ALPHAUSDT',"15m",150,1.007,0.993)

while True:

    coin2.dfall('ETHUSDT',"1h")
    time.sleep(10)
    coin1.dfall('BTCUSDT',"1h")
    time.sleep(10)
    coin3.dfall('ATOMUSDT',"1h")
    time.sleep(10)
    coin4.dfall('EOSUSDT',"1h")
    time.sleep(10)
    coin5.dfall('LITUSDT',"1h")
    time.sleep(10)
    coin6.dfall('BNBUSDT', "1h")
    time.sleep(10)
    coin7.dfall('CRVUSDT',"1h")
    time.sleep(10)
    coin8.dfall('THETAUSDT',"1h")
    time.sleep(10)
    coin9.dfall('XRPUSDT',"1h")
    time.sleep(10)
    coin10.dfall('RUNEUSDT',"1h")
    time.sleep(10)
    coin11.dfall('ARUSDT',"1h")
    time.sleep(10)
    coin12.dfall('DOTUSDT',"1h")
    time.sleep(10)
    coin13.dfall('ETCUSDT',"1h")
    time.sleep(10)
    coin14.dfall('ALGOUSDT',"1h")
    time.sleep(10)
    coin15.dfall('TRXUSDT',"1h")
    time.sleep(10)
    coin16.dfall('LRCUSDT',"1h")
    time.sleep(10)
    coin17.dfall('SANDUSDT',"1h")
    time.sleep(10)
    coin18.dfall('AVAXUSDT', "1h")
    time.sleep(10)
    coin19.dfall('COTIUSDT', "1h")
    time.sleep(10)
    coin20.dfall('LINKUSDT', "1h")
    time.sleep(10)
    coin21.dfall('NEARUSDT', "1h")
    time.sleep(10)

    coin24.dfall('MATICUSDT', "1h")
    time.sleep(10)
    coin25.dfall('BELUSDT', "1h")
    time.sleep(10)
    coin26.dfall('KNCUSDT', "1h")
    time.sleep(10)
    coin27.dfall('BLZUSDT', "1h")
    time.sleep(10)
    coin28.dfall('KAVAUSDT', "1h")
    time.sleep(10)
    coin29.dfall('CHZUSDT', "1h")
    time.sleep(10)
    coin30.dfall('DASHUSDT', "1h")
    time.sleep(10)
    coin31.dfall('QTUMUSDT', "1h")
    time.sleep(10)
    coin32.dfall('CHRUSDT', "1h")
    time.sleep(10)
    coin33.dfall('OCEANUSDT', "1h")
    time.sleep(10)
    coin34.dfall('ALPHAUSDT', "1h")
    time.sleep(10)

    coin2a.dfall('ETHUSDT', "15m")
    time.sleep(10)
    coin1a.dfall('BTCUSDT', "15m")
    time.sleep(10)
    coin3a.dfall('ATOMUSDT', "15m")
    time.sleep(10)
    coin4a.dfall('EOSUSDT', "15m")
    time.sleep(10)
    coin5a.dfall('LITUSDT', "15m")
    time.sleep(10)
    coin6a.dfall('BNBUSDT', "15m")
    time.sleep(10)
    coin7a.dfall('CRVUSDT', "15m")
    time.sleep(10)
    coin8a.dfall('THETAUSDT', "15m")
    time.sleep(10)
    coin9a.dfall('XRPUSDT', "15m")
    time.sleep(10)
    coin10a.dfall('RUNEUSDT', "15m")
    time.sleep(10)
    coin11a.dfall('ARUSDT', "15m")
    time.sleep(10)
    coin12a.dfall('DOTUSDT', "15m")
    time.sleep(10)
    coin13a.dfall('ETCUSDT', "15m")
    time.sleep(10)
    coin14a.dfall('ALGOUSDT', "15m")
    time.sleep(10)
    coin15a.dfall('TRXUSDT',"15m")
    time.sleep(10)
    coin16a.dfall('LRCUSDT', "15m")
    time.sleep(10)
    coin17a.dfall('SANDUSDT', "15m")
    time.sleep(10)
    coin18a.dfall('AVAXUSDT', "15m")
    time.sleep(10)
    coin19a.dfall('COTIUSDT', "15m")
    time.sleep(10)
    coin20a.dfall('LINKUSDT', "15m")
    time.sleep(10)
    coin21a.dfall('NEARUSDT', "15m")
    time.sleep(10)

    coin24a.dfall('MATICUSDT', "15m")
    time.sleep(10)
    coin25a.dfall('BELUSDT', "15m")
    time.sleep(10)
    coin26a.dfall('KNCUSDT', "15m")
    time.sleep(10)
    coin27a.dfall('BLZUSDT', "15m")
    time.sleep(10)
    coin28a.dfall('KAVAUSDT', "15m")
    time.sleep(10)
    coin29a.dfall('CHZUSDT', "15m")
    time.sleep(10)
    coin30a.dfall('DASHUSDT', "15m")
    time.sleep(10)
    coin31a.dfall('QTUMUSDT', "15m")
    time.sleep(10)
    coin32a.dfall('CHRUSDT', "15m")
    time.sleep(10)
    coin33a.dfall('OCEANUSDT', "15m")
    time.sleep(10)
    coin34a.dfall('ALPHAUSDT', "15m")
    time.sleep(10)

    coin2a.addspread(1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6)
    time.sleep(10)
    coin1a.addspread(2, 1, 2, 2, 2, 3, 2, 4, 2, 5, 2, 6)
    time.sleep(10)

    coin3a.addspread(3, 1, 3, 2, 3, 3, 3, 4, 3, 5, 3, 6)
    time.sleep(10)

    coin4a.addspread(4, 1, 4, 2, 4, 3, 4, 4, 4, 5, 4, 6)
    time.sleep(10)

    coin5a.addspread(5, 1, 5, 2, 5, 3, 5, 4, 5, 5, 5, 6)
    time.sleep(10)

    coin6a.addspread(6, 1, 6, 2, 6, 3, 6, 4, 6, 5, 6, 6)
    time.sleep(10)

    coin7a.addspread(7, 1, 7, 2, 7, 3, 7, 4, 7, 5, 7, 6)
    time.sleep(10)

    coin8a.addspread(8, 1, 8, 2, 8, 3, 8, 4, 8, 5, 8, 6)
    time.sleep(10)

    coin9a.addspread(9, 1, 9, 2, 9, 3, 9, 4, 9, 5, 9, 6)
    time.sleep(10)

    coin10a.addspread(10, 1, 10, 2, 10, 3, 10, 4, 10, 5, 10, 6)
    time.sleep(10)

    coin11a.addspread(11, 1, 11, 2, 11, 3, 11, 4, 11, 5, 11, 6)
    time.sleep(10)

    coin12a.addspread(12, 1, 12, 2, 12, 3, 12, 4, 12, 5, 12, 6)
    time.sleep(10)
    coin13a.addspread(13, 1, 13, 2, 13, 3, 13, 4, 13, 5, 13, 6)
    time.sleep(10)
    coin14a.addspread(14, 1, 14, 2, 14, 3, 14, 4, 14, 5, 14, 6)
    time.sleep(10)
    coin15a.addspread(15, 1, 15, 2, 15, 3, 15, 4, 15, 5, 15, 6)
    time.sleep(10)
    coin16a.addspread(16, 1, 16, 2, 16, 3, 16, 4, 16, 5, 16, 6)
    time.sleep(10)
    coin17a.addspread(17, 1, 17, 2, 17, 3, 17, 4, 17, 5, 17, 6)
    time.sleep(10)
    coin18a.addspread(18, 1, 18, 2, 18, 3, 18, 4, 18, 5, 18, 6)
    time.sleep(10)
    coin19a.addspread(19, 1, 19, 2, 19, 3, 19, 4, 19, 5, 19, 6)
    time.sleep(10)
    coin20a.addspread(20, 1, 20, 2, 20, 3, 20, 4, 20, 5, 20, 6)
    time.sleep(10)
    coin21a.addspread(21, 1, 21, 2, 21, 3, 21, 4, 21, 5, 21, 6)
    time.sleep(10)

    coin24a.addspread(24, 1, 24, 2, 24, 3, 24, 4, 24, 5, 24, 6)
    time.sleep(10)
    coin25a.addspread(25, 1, 25, 2, 25, 3, 25, 4, 25, 5, 25, 6)
    time.sleep(10)
    coin26a.addspread(26, 1, 26, 2, 26, 3, 26, 4, 26, 5, 26, 6)
    time.sleep(10)
    coin27a.addspread(27, 1, 27, 2, 27, 3, 27, 4, 27, 5, 27, 6)
    time.sleep(10)
    coin28a.addspread(28, 1, 28, 2, 28, 3, 28, 4, 28, 5, 28, 6)
    time.sleep(10)
    coin29a.addspread(29, 1, 29, 2, 29, 3, 29, 4, 29, 5, 29, 6)
    time.sleep(10)
    coin30a.addspread(30, 1, 30, 2, 30, 3, 30, 4, 30, 5, 30, 6)
    time.sleep(10)
    coin31a.addspread(31, 1, 31, 2, 31, 3, 31, 4, 31, 5, 31, 6)
    time.sleep(10)
    coin32a.addspread(32, 1, 32, 2, 32, 3, 32, 4, 32, 5, 32, 6)
    time.sleep(10)
    coin33a.addspread(33, 1, 33, 2, 33, 3, 33, 4, 33, 5, 33, 6)
    time.sleep(10)
    coin34a.addspread(34, 1, 34, 2, 34, 3, 34, 4, 34, 5, 34, 6)
    time.sleep(10)
    tele.telegram_bot('server online2')

    time.sleep(300)


from codepack.storages.storable import Storable
from typing import TypeVar, Optional, Union

Code = TypeVar('Code', bound='codepack.code.Code')  # noqa: F821

class Dependency(Storable):
    def __init__(self, code: Optional[Code] = None, id: Optional[str] = None, serial_number: Optional[str] = None,
                 param: Optional[str] = None) -> None:
        super().__init__(id=id, serial_number=serial_number)
        self.code = None
        self.param = None
        self.bind(code)
        self.depend_on(id=id, serial_number=serial_number, param=param)

    def __lshift__(self, sender: Union[Storable, dict]) -> None:
        if isinstance(sender, Storable):
            self.depend_on(id=sender.id, serial_number=sender.serial_number, param=self.param)
        elif isinstance(sender, dict):
            self.depend_on(id=sender['id'], serial_number=sender['serial_number'], param=self.param)
        else:
            raise TypeError(type(sender))
        self.code.add_dependency(self)

    def bind(self, code: Code) -> None:
        self.code = code

    def depend_on(self, id: Optional[str] = None, serial_number: Optional[str] = None,
                  param: Optional[str] = None) -> None:
        self.id = id
        self.serial_number = serial_number
        self.param = param

    def __eq__(self, other: Union['Dependency', dict]) -> bool:
        if isinstance(other, type(self)):
            ret = True
            ret &= (self.serial_number == other.serial_number)
            ret &= (self.id == other.id)
            ret &= (self.param == other.param)
            return ret
        elif isinstance(other, dict):
            ret = True
            ret &= (self.serial_number == other['serial_number'])
            ret &= (self.id == other['id'])
            ret &= (self.param == other['param'])
            return ret
        else:
            return False

    def __str__(self) -> str:
        return '%s(param: %s, id: %s)' % (self.__class__.__name__, self.param, self.id)  # pragma: no cover

    def __repr__(self) -> str:
        return self.__str__()  # pragma: no cover

    def to_dict(self) -> dict:
        return {'id': self.id, 'serial_number': self.serial_number, 'param': self.param}

    @classmethod
    def from_dict(cls, d: dict) -> 'Dependency':
        return cls(id=d['id'], serial_number=d['serial_number'], param=d['param'])


import threading
from time import sleep

import discum
import datetime

from discum.utils.slash import SlashCommander
from discum.utils.button import Buttoner

self_id = '000000000000000000'
mudae_application_id = '432610292342587392'

def log_to_file(message):
    with open('bot.txt', 'a', encoding='utf-8') as f:
        f.write('[' + str(datetime.datetime.now()) + '] ' + message + '\n')

class c_message:
    def __init__(self, message, command, time, message_id, embed='', components='', raw_components=''):
        self.message = message
        self.message_id = message_id
        self.command = command
        self.embed = embed
        self.time = time
        self.components = components
        self.raw_components = raw_components

class c_command:
    def __init__(self, command, func, target_channels, log=False, allowed_users=None):
        if allowed_users is None:
            allowed_users = []

        self.allowed_users = allowed_users
        self.command = command
        self.do_log = log
        self.target_channels = target_channels

        def wrapper(msg, channel_id, msg_id, msg_author, resp):
            author_id = resp.parsed.auto()['author']['id']
            if len(self.target_channels) > 0 and '*' not in self.target_channels:
                if channel_id not in self.target_channels:
                    # print('Channel ' + channel_id + ' is not allowed to use command ' + self.command)
                    return

            if len(self.allowed_users) > 0 and '*' not in self.allowed_users:
                if author_id not in self.allowed_users:
                    # print('User ' + msg_author + ' is not allowed to use command ' + self.command)
                    return

            if self.do_log:
                embed = ''
                if 'embeds' in resp.parsed.auto() and len(resp.parsed.auto()['embeds']) > 0:
                    embed = resp.parsed.auto()['embeds'][0]
                str_log = 'Invoked command: ' + self.command + ' by ' + msg_author + ' in channel ' + channel_id + \
                          ' with message id ' + msg_id + ' and message: ' + msg + ' and embed: ' + str(embed)
                # print('Invoked command: ' + self.command + ' by ' + msg_author + ' in channel ' + channel_id)
                log_to_file(str_log)

            func(msg, channel_id, msg_id, msg_author, resp)

        self.func = wrapper

class c_listener:
    def __init__(self, func, log, target_channels, target_user):
        self.do_log = log
        self.target_user = target_user
        self.target_channels = target_channels

        def wrapper(msg, channel_id, msg_id, msg_author, resp):
            if channel_id not in self.target_channels:
                return

            resp_parsed = resp.parsed.auto()
            if not 'interaction' in resp_parsed:
                return

            if not resp_parsed['interaction']['user'] or not resp_parsed['interaction']['type'] == 2:
                return

            if resp_parsed['interaction']['user']['id'] != self_id:
                return

            if self.target_user:
                author_id = resp_parsed['author']['id']
                if author_id != self.target_user:
                    return

            if self.do_log:
                embed = ''
                if 'embeds' in resp_parsed and len(resp_parsed['embeds']) > 0:
                    embed = resp_parsed['embeds'][0]
                str_log = 'Invoked listener by ' + msg_author + ' in channel ' + channel_id + \
                          ' with message id ' + msg_id + ' and message: ' + msg + ' and embed: ' + str(embed)
                # print('Invoked listener by ' + msg_author + ' in channel ' + channel_id)
                log_to_file(str_log)

            func(msg, channel_id, msg_id, msg_author, resp)

        self.func = wrapper

class c_discord:
    def __init__(self, live=True, instance_name='Default Instance'):
        self.client = discum.Client(token="your token",
                                    log=False)
        self.live = live
        self.instance_name = instance_name
        # Debug server
        self.target_channel = '000000000000000000'
        self.target_owner = '000000000000000000'
        self.target_mudae = '000000000000000000'
        self.target_guild = '000000000000000000'
        #
        if self.live:
            # Live server
            self.target_channel = '000000000000000000'
            self.target_owner = '000000000000000000'
            self.target_mudae = '000000000000000000'
            self.target_guild = '000000000000000000'
        #
        self.target_debug = '000000000000000000'
        #
        self.commands = {}
        self.listeners = []
        self.mudae_messages = []
        self.last_mudae_message = None
        #
        self.inst_mudae = c_mudae(self)

        def log_mudae(msg, channel_id, msg_id, msg_author, resp):
            embed = None
            if 'embeds' in resp.parsed.auto() and len(resp.parsed.auto()['embeds']) > 0:
                embed = resp.parsed.auto()['embeds'][0]

            if embed is None:
                embed = ''

            components = None
            if 'components' in resp.parsed.auto() and len(resp.parsed.auto()['components']) > 0:
                components = resp.parsed.auto()['components'][0]

            if components is None:
                components = ''

            if 'the roulette is limited to' in msg:
                return

            time = datetime.datetime.now()

            inst_message = c_message(msg, resp.parsed.auto()['interaction']['name'], time, resp.parsed.auto()['id'],
                                     embed, components, resp.parsed.auto()['components'])
            self.last_mudae_message = inst_message
            self.mudae_messages.append(inst_message)

        self.register_listener(log_mudae, True, [self.target_channel], self.target_mudae)

        @self.client.gateway.command
        def on_message(resp):
            if resp.event.message:
                channel_id = resp.parsed.auto()['channel_id']
                msg_author_id = resp.parsed.auto()['id']
                msg_author_user = resp.parsed.auto()['author']['username']
                msg_content = resp.parsed.auto()['content']
                for listener in self.listeners:
                    listener.func(msg_content, channel_id, msg_author_id, msg_author_user, resp)
                for command in self.commands:
                    if msg_content == command:
                        self.commands[command].func(msg_content, channel_id, msg_author_id, msg_author_user, resp)

    def register_command(self, command, func, target_channel, log=False, allowed_users=None):
        if command not in self.commands:
            self.commands[command] = c_command(command, func, target_channel, log, allowed_users)
        else:
            print('Command already registered!')

    def register_listener(self, func, log, target_channels, target_user):
        self.listeners.append(c_listener(func, log, target_channels, target_user))

    def send_claim(self, components, message_id):
        button = Buttoner(components)
        target_button = button.getButton(customID=components[0]['components'][0]['custom_id'])
        if target_button is not None and target_button != []:
            ret = self.client.click(mudae_application_id, channelID=self.target_channel, messageID=message_id,
                                    guildID=self.target_guild, data=target_button, messageFlags=0)
            if ret.status_code == 200 or ret.status_code == 204:
                return True
        else:
            return False

    def send_message_bot(self, msg):
        sleep(1)  # discum bug, needs delay to send messages correctly
        self.client.sendMessage(self.target_debug, '[ ' + str(self.instance_name) + '] ' + msg)

    def send_reply_bot(self, msg, channel_id, msg_id, embed=None):
        sleep(1)  # discum bug, needs delay to send messages correctly
        self.client.reply(channel_id, msg_id, '[:flag_cn: ' + str(self.instance_name) + '] ' + msg, embed=embed)

    def start(self):
        self.client.gateway.run(auto_reconnect=True)

    def run_slash_cmd(self, target_channel, guild_id, command):
        s = SlashCommander(self.client.getSlashCommands(mudae_application_id).json())
        cmd_dict = [command]
        data = s.get(cmd_dict)
        self.client.triggerSlashCommand(mudae_application_id, target_channel, guild_id, data)

class c_mudae_cmd_tu:
    def __init__(self, discord: c_discord):
        self.message = None
        self.inst_discord = discord
        #
        self.last_tu_time = datetime.datetime.now()
        self.rolls = 0
        self.can_claim = False
        self.next_claim_reset = datetime.datetime.now()
        self.next_roll_reset = datetime.datetime.now()
        self.next_roll_reset_time = ""
        self.next_claim_reset_time = ""
        self.has_daily = False
        self.kakera = 0
        self.can_claim_kakera = False
        self.can_dk = False
        self.can_vote = False

    def parse(self, message):
        self.message = message
        self.rolls = 0
        self.can_claim = False
        self.next_claim_reset = datetime.datetime.now()
        self.next_roll_reset = datetime.datetime.now()
        self.next_roll_reset_time = ""
        self.next_claim_reset_time = ""
        self.has_daily = False
        self.kakera = 0
        self.can_claim_kakera = False
        self.can_dk = False
        self.can_vote = False
        #
        lines = self.message.split('\n')
        for line in lines:
            if "you __can__ claim" in line or "you can't claim" in line:
                if "you __can__ claim" in line:
                    self.can_claim = True
                    self.next_claim_reset_time = line.split('in **')[1].split('**')[0]
                else:
                    self.can_claim = False
                    self.next_claim_reset_time = line.split('for another **')[1].split('**')[0]

                if 'h' in self.next_claim_reset_time:
                    hours = int(self.next_claim_reset_time.split('h')[0])
                    minutes = int(self.next_claim_reset_time.split('h')[1].split(' ')[1])
                    self.next_claim_reset = datetime.datetime.now() + datetime.timedelta(hours=hours, minutes=minutes)
                else:
                    minutes = int(self.next_claim_reset_time.split(' ')[0])
                    self.next_claim_reset = datetime.datetime.now() + datetime.timedelta(minutes=minutes)
            elif "You have" in line:
                self.rolls = int(line.split('**')[1])
                self.next_roll_reset_time = line.split('in **')[1].split('**')[0]
                minutes = int(self.next_roll_reset_time.split(' ')[0])
                self.next_roll_reset = datetime.datetime.now() + datetime.timedelta(minutes=minutes)
            elif "$daily is available!" in line:
                self.has_daily = True
            elif "You __can__ react to kakera" in line or "You can't react to kakera" in line:
                if "You __can__ react to kakera" in line:
                    self.can_claim_kakera = True
            elif "$dk is ready!" in line:
                self.can_dk = True
            elif "You may vote right now!" in line:
                self.can_vote = True
            elif "Stock:" in line:
                self.kakera = int(line.split('**')[1])

    def print_states(self):
        return "[" + self.inst_discord.instance_name + "] Claim reset: " + str(self.next_claim_reset_time) + " | " + \
            "Roll reset: " + str(self.next_roll_reset_time) + " | " + \
            "Rolls: " + str(self.rolls) + " | " + \
            "Kakera: " + str(self.kakera) + " | " + \
            "Can claim kakera: " + str(self.can_claim_kakera) + " | " + \
            "Can claim: " + str(self.can_claim) + " | " + \
            "Can dk: " + str(self.can_dk) + " | " + \
            "Can vote: " + str(self.can_vote) + " | " + \
            "Has daily: " + str(self.has_daily)

    def roll_reset_notification(self):
        self.inst_discord.send_message_bot("Roll reset at " + str(self.next_roll_reset))

    def claim_reset_notification(self):
        self.inst_discord.send_message_bot("Claim reset at " + str(self.next_claim_reset))

class c_mudae_cmd_wa:
    def __init__(self):
        self.message = None
        self.kakera_name = None
        self.is_unclaimable = False
        self.has_kakera_button = False
        self.kakera_value = 0
        self.waifu_name = ""
        self.waifu_image = ""
        self.time = datetime.datetime.now()

    def parse(self, message: c_message):
        self.is_unclaimable = False
        self.has_kakera_button = False
        self.kakera_value = 0
        self.waifu_name = ""
        self.waifu_image = ""
        self.time = datetime.datetime.now()
        self.message = message
        #
        embed = self.message.embed
        #
        component = self.message.components
        #
        self.waifu_name = embed['author']['name']
        self.waifu_image = embed['image']['url']
        #
        if embed['description'].split('\n')[1].split('<')[0].replace('**', '') != '':
            self.kakera_value = int(embed['description'].split('\n')[-1]
                                    .split('<')[0].replace('**', ''))
        #
        self.kakera_name = component['components'][0]['emoji']['name']
        if 'kakera' in self.kakera_name:
            self.is_unclaimable = True
            self.kakera_value = 0

class c_mudae_rolls:
    def __init__(self, inst_tu: c_mudae_cmd_tu):
        self.time = datetime.datetime.now()
        self.inst_tu = inst_tu
        self.timeout = datetime.datetime.now()
        self.rolls = []
        # ----------------
        # rolling configuration
        # ----------------
        self.last_hour_claim = True
        self.first_hour_double_value = True
        self.auto_claim_kakera = True
        self.auto_dk = True
        self.auto_daily = True
        self.auto_claim_waifu = True
        self.claim_threshold = 100  # kakera value

    def logic(self):
        if self.inst_tu.rolls > 0 and self.timeout < datetime.datetime.now() and (
                self.inst_tu.can_claim or self.inst_tu.can_claim_kakera):
            self.timeout = datetime.datetime.now() + datetime.timedelta(seconds=4)
            self.inst_tu.inst_discord.run_slash_cmd(self.inst_tu.inst_discord.target_channel,
                                                    self.inst_tu.inst_discord.target_guild,
                                                    'wa')
            self.inst_tu.inst_discord.send_message_bot('Rolls left: {}'.format(self.inst_tu.rolls - 1))
        elif self.inst_tu.rolls == 0 and len(self.rolls) > 0 and self.timeout < datetime.datetime.now():
            self.inst_tu.inst_discord.send_message_bot('No rolls left, picking waifu!')
            self.timeout = datetime.datetime.now() + datetime.timedelta(seconds=6)

            if self.auto_claim_waifu and self.inst_tu.can_claim:
                target_waifu = self.choose_waifu()
                if target_waifu is not None:
                    self.claim_waifu(target_waifu)
                    self.inst_tu.can_claim = False
                else:
                    self.inst_tu.inst_discord.send_message_bot('No waifu to claim!')
            else:
                self.inst_tu.inst_discord.send_message_bot('Waifu claim unavailable!')

            if self.auto_claim_kakera and self.inst_tu.can_claim_kakera:
                target_kakera = self.choose_kakera()
                if target_kakera is not None:
                    self.claim_waifu(target_kakera)
                    self.inst_tu.can_claim_kakera = False
                else:
                    self.inst_tu.inst_discord.send_message_bot('No kakera to claim!')
            else:
                self.inst_tu.inst_discord.send_message_bot('Kakera claim unavailable!')

            self.rolls.clear()

            if self.auto_dk and self.inst_tu.can_dk:
                self.inst_tu.inst_discord.send_message_bot('Claiming dk!')
                self.inst_tu.inst_discord.run_slash_cmd(self.inst_tu.inst_discord.target_channel,
                                                        self.inst_tu.inst_discord.target_guild,
                                                        'dk')
                self.inst_tu.can_dk = False

            if self.auto_daily and self.inst_tu.has_daily and self.inst_tu.can_claim:
                self.inst_tu.inst_discord.send_message_bot('Claiming daily!')
                self.inst_tu.inst_discord.run_slash_cmd(self.inst_tu.inst_discord.target_channel,
                                                        self.inst_tu.inst_discord.target_guild,
                                                        'daily')
                self.inst_tu.has_daily = False
                sleep(5)
                self.inst_tu.inst_discord.run_slash_cmd(self.inst_tu.inst_discord.target_channel,
                                                        self.inst_tu.inst_discord.target_guild,
                                                        'rolls')
                sleep(5)
                self.inst_tu.inst_discord.run_slash_cmd(self.inst_tu.inst_discord.target_channel,
                                                        self.inst_tu.inst_discord.target_guild,
                                                        'tu')

    def choose_waifu(self):
        min_kakera_value = self.claim_threshold
        current_time = datetime.datetime.now()
        if self.first_hour_double_value:
            min_kakera_value *= 2
        time_delta_to_next_claim_reset = self.inst_tu.next_claim_reset - current_time
        if self.last_hour_claim and time_delta_to_next_claim_reset <= datetime.timedelta(hours=1):
            self.inst_tu.inst_discord.send_message_bot('Last hour claim active, delta: {}'
                                                       .format(time_delta_to_next_claim_reset))
            min_kakera_value = 30

        self.rolls.sort(key=lambda x: x.kakera_value, reverse=True)
        claim_list = list(filter(lambda x: not x.is_unclaimable, self.rolls))
        claim_list = list(filter(lambda x: x.kakera_value >= min_kakera_value, claim_list))

        if len(claim_list) > 0:
            return claim_list[0]
        else:
            self.inst_tu.inst_discord.send_message_bot('No waifu to claim')
            return None

    def choose_kakera(self):
        claim_list = list(filter(lambda x: x.kakera_value == 0, self.rolls))

        if len(claim_list) > 0:
            return claim_list[0]
        else:
            self.inst_tu.inst_discord.send_message_bot('No kakera to claim')
            return None

    def claim_waifu(self, inst_wa: c_mudae_cmd_wa):
        if self.auto_claim_waifu:
            self.inst_tu.inst_discord.send_message_bot('Claiming {} for {} kakera'.format(inst_wa.waifu_name,
                                                                                inst_wa.kakera_value))
            result = self.inst_tu.inst_discord.send_claim(inst_wa.message.raw_components, inst_wa.message.message_id)
            if result:
                self.inst_tu.can_claim = False
        else:
            self.inst_tu.inst_discord.send_message_bot('Recommended claim {} value {}'.format(inst_wa.waifu_name,
                                                                                inst_wa.kakera_value))

    def add_roll(self, inst_wa: c_mudae_cmd_wa):
        print('[' + self.inst_tu.inst_discord.instance_name + '] New roll: {} {} {}'.format(inst_wa.waifu_name,
                                                                                inst_wa.kakera_name,
                                                                                inst_wa.kakera_value))
        self.inst_tu.rolls -= 1
        self.rolls.append(inst_wa)

class c_mudae:
    def worker(self):
        last_execution = datetime.datetime.now()
        while True:
            #
            if (datetime.datetime.now() - last_execution).total_seconds() < 1:
                continue
            last_execution = datetime.datetime.now()

            if not self.initial_tu:
                self.initial_tu = True
                self.inst_discord.run_slash_cmd(self.inst_discord.target_channel, self.inst_discord.target_guild, 'tu')
                sleep(5)
                continue
            else:
                #
                time_now = datetime.datetime.now() - datetime.timedelta(seconds=60)
                if self.tu_module.next_roll_reset < time_now:
                    self.tu_module.next_roll_reset = datetime.datetime.now() + datetime.timedelta(hours=1, minutes=1)
                    self.inst_discord.send_message_bot('Roll timer expired')
                    self.inst_discord.run_slash_cmd(self.inst_discord.target_channel,
                                                    self.inst_discord.target_guild,
                                                    'tu')
                    sleep(5)
                    continue

                #
                self.roll_module.logic()

                if len(self.inst_discord.mudae_messages) > 0:
                    #
                    self.inst_discord.mudae_messages.sort(key=lambda x: x.time, reverse=True)
                    #
                    for msg in self.inst_discord.mudae_messages:
                        if msg.command == 'tu' and msg.time > self.last_tu_time:
                            self.last_tu_time = msg.time
                            self.tu_module.parse(msg.message)
                            self.tu_module.roll_reset_notification()
                            self.tu_module.claim_reset_notification()
                            self.inst_discord.send_message_bot(self.tu_module.print_states())
                            print(self.tu_module.print_states())
                            self.inst_discord.mudae_messages.remove(msg)
                            continue
                        if msg.command == 'wa':
                            self.inst_discord.mudae_messages.remove(msg)
                            inst_wa = c_mudae_cmd_wa()
                            inst_wa.parse(msg)
                            self.roll_module.add_roll(inst_wa)

    def __init__(self, instance_discord: c_discord):
        self.inst_discord = instance_discord
        self.initial_tu = False
        #
        self.tu_module = c_mudae_cmd_tu(instance_discord)
        self.last_tu_time = datetime.datetime.now()
        #
        self.roll_module = c_mudae_rolls(self.tu_module)
        #
        self.worker_thread = threading.Thread(target=self.worker)
        self.worker_thread.start()

if __name__ == '__main__':
    inst_discord_live = c_discord(True, 'Name of instance')
    inst_thread_live = threading.Thread(target=inst_discord_live.start)
    inst_thread_live.start()


"""
* Assignment: Serialization CSV DictWriter
* Complexity: easy
* Lines of code: 10 lines
* Time: 8 min

English:
    1. Use data from "Given" section (see below)
    2. Using `csv.DictWriter()` save `DATA` to file
    3. Open file in your spreadsheet program like Microsoft Excel / Libre Office / Numbers etc.
    4. Open file in simple in your IDE and simple text editor (like Notepad, vim, gedit)
    5. Non functional requirements:
        a. All fields must be enclosed by double quote `"` character
        b. Use `,` to separate columns
        c. Use `utf-8` encoding
        d. Use Unix `\n` newline
    6. Compare result with "Tests" section (see below)

Polish:
    1. Użyj danych z sekcji "Given" (patrz poniżej)
    2. Za pomocą `csv.DictWriter()` zapisz `DATA` do pliku
    3. Spróbuj otworzyć plik w arkuszu kalkulacyjnym tj. Microsoft Excel / Libre Office / Numbers itp
    4. Spróbuj otworzyć plik w IDE i prostym edytorze tekstu tj. Notepad, vim lub gedit
    5. Wymagania niefunkcjonalne:
        a. Wszystkie pola muszą być otoczone znakiem cudzysłowu `"`
        b. Użyj `,` do oddzielenia kolumn
        c. Użyj kodowania `utf-8`
        d. Użyj zakończenia linii Unix `\n`
    6. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

Tests:
    >>> result = open(FILE).read()
    >>> print(result)   # doctest: +NORMALIZE_WHITESPACE
    "firstname","lastname"
    "Jan","Twardowski"
    "José","Jiménez"
    "Mark","Watney"
    "Ivan","Ivanovic"
    "Melissa","Lewis"
    >>> from os import remove
    >>> remove(FILE)
"""

# Given
from csv import DictWriter, QUOTE_ALL

FILE = r'_temporary.csv'
DATA = [{'firstname': 'Jan', 'lastname': 'Twardowski'},
        {'firstname': 'José', 'lastname': 'Jiménez'},
        {'firstname': 'Mark', 'lastname': 'Watney'},
        {'firstname': 'Ivan', 'lastname': 'Ivanovic'},
        {'firstname': 'Melissa', 'lastname': 'Lewis'}]

# Solution
with open(FILE, mode='w', encoding='utf-8') as file:
    data = DictWriter(
        f=file,
        fieldnames=['firstname', 'lastname'],
        delimiter=',',
        quotechar='"',
        quoting=QUOTE_ALL,
        lineterminator='\n')

    data.writeheader()
    data.writerows(DATA)


import uuid
from typing import List

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from schemas import MeetingCreate, Meeting, CommentCreate, Comment
from crud import create_meeting, get_meetings, get_meeting, add_participant_to_meeting, create_comment
from auth.database import User, get_async_session, current_user

router = APIRouter()

@router.post("/meetings/", response_model=Meeting)
async def create_meeting_endpoint(meeting_create: MeetingCreate, user: User = Depends(current_user), db: Session = Depends(get_async_session)):
    meeting = create_meeting(db, meeting_create, user.id)
    if not meeting:
        raise HTTPException(status_code=500, detail="Meeting creation failed")
    return meeting

@router.get("/meetings/", response_model=List[Meeting])
async def get_meetings_endpoint(skip: int = 0, limit: int = 10, db: Session = Depends(get_async_session)):
    meetings = get_meetings(db, skip, limit)
    return meetings

@router.get("/meetings/{meeting_id}", response_model=Meeting)
async def get_single_meeting_endpoint(meeting_id: uuid.UUID, db: Session = Depends(get_async_session)):
    meeting = get_meeting(db, meeting_id)
    if not meeting:
        raise HTTPException(status_code=404, detail="Meeting not found")
    return meeting

@router.post("/meetings/{meeting_id}/add-participant/{user_id}", response_model=Meeting)
async def add_participant_endpoint(meeting_id: uuid.UUID, user_id: uuid.UUID, db: Session = Depends(get_async_session)):
    result = add_participant_to_meeting(db, meeting_id, user_id)
    if not result:
        raise HTTPException(status_code=404, detail="Meeting or user not found")
    return result

@router.post("/meetings/{meeting_id}/comments/", response_model=Comment)
async def create_comment_endpoint(meeting_id: uuid.UUID, comment_create: CommentCreate, user: User = Depends(current_user), db: Session = Depends(get_async_session)):
    comment = create_comment(db, meeting_id, user.id, comment_create)
    if not comment:
        raise HTTPException(status_code=404, detail="Meeting not found")
    return comment


class StringArray:
    def __init__(self, size):
        self.size = size
        self.array = [(0, None)] * size

    def set_element(self, index, length, value):
        if index < 0 or index >= self.size:
            print("Index out of range")
            return
        if len(value) != length:
            print("Invalid string length")
            return
        self.array[index] = (length, value)

    def get_element(self, index):
        if index < 0 or index >= self.size:
            print("Index out of range")
            return None
        return self.array[index][1]

    def concatenate(self, other_array):
        if self.size != other_array.size:
            print("Arrays have different sizes")
            return
        concatenated_array = StringArray(self.size)
        for i in range(self.size):
            length1, value1 = self.array[i]
            length2, value2 = other_array.array[i]
            concatenated_array.set_element(i, length1 + length2, value1 + value2)
        return concatenated_array

    def merge(self, other_array):
        if self.size != other_array.size:
            print("Arrays have different sizes")
            return
        merged_array = StringArray(self.size)
        for i in range(self.size):
            length1, value1 = self.array[i]
            length2, value2 = other_array.array[i]
            merged_value = ""
            for j in range(length1):
                if value1[j] not in merged_value:
                    merged_value += value1[j]
            for j in range(length2):
                if value2[j] not in merged_value:
                    merged_value += value2[j]
            merged_array.set_element(i, len(merged_value), merged_value)
        return merged_array

    def print_element(self, index):
        element = self.get_element(index)
        if element is not None:
            print(element)

    def print_all(self):
        for i in range(self.size):
            self.print_element(i)


# to-lua.py
# Script created by @Lumaah7 on Twitter
# Lumaah on GitHub
import xml.etree.ElementTree as ET
import sys

def get_animation_prefix(animation_name, prefixes_file):
    with open(prefixes_file, "r") as file:
        valid_prefixes = [line.strip() for line in file]

    for prefix in valid_prefixes:
        if prefix in animation_name.lower():
            return prefix
    return None

def convert_xml_to_lua(xml_file, lua_output_file, prefixes_file, image_path):
    tree = ET.parse(xml_file)
    root = tree.getroot()

    lua_data = "return graphics.newSprite(\n"
    lua_data += f"\tlove.graphics.newImage(graphics.imagePath(\"{image_path}\")),\n"
    lua_data += "\t{\n"

    animation_data = {}
    frame_indices = {}

    for index, sub_texture in enumerate(root.findall(".//SubTexture")):
        name = sub_texture.get("name")
        x = float(sub_texture.get("x"))
        y = float(sub_texture.get("y"))
        width = float(sub_texture.get("width"))
        height = float(sub_texture.get("height"))
        offsetX = float(sub_texture.get("frameX", 0))
        offsetY = float(sub_texture.get("frameY", 0))
        offsetWidth = float(sub_texture.get("frameWidth", width))
        offsetHeight = float(sub_texture.get("frameHeight", height))

        animation_prefix = get_animation_prefix(name, prefixes_file)

        if animation_prefix is None:
            animation_prefix = name.split(" ")[-1]

        if animation_prefix not in frame_indices:
            frame_indices[animation_prefix] = {
                "start": index + 1,
                "stop": index + 1,
                "speed": 12,
                "offsetX": 0,
                "offsetY": 0
            }

        else:
            frame_indices[animation_prefix]["stop"] = index + 1

        lua_data += f"\t\t{{x = {x}, y = {y}, width = {width}, height = {height}, offsetX = {offsetX}, offsetY = {offsetY}, offsetWidth = {offsetWidth}, offsetHeight = {offsetHeight}}}, -- {index+1}: {name}\n"

    lua_data += "\t},\n"
    lua_data += "\t{\n"

    for anim_prefix, indices in frame_indices.items():
        lua_data += f"\t\t[\"{anim_prefix}\"] = {{start = {indices['start']}, stop = {indices['stop']}, speed = {indices['speed']}, offsetX = {indices['offsetX']}, offsetY = {indices['offsetY']}}},\n"

    lua_data += "\t},\n"
    lua_data += "\t\"i\",\n"  # Default animation name (can be changed)
    lua_data += "\tfalse\n"
    lua_data += ")"

    with open(lua_output_file, "w") as lua_file:
        lua_file.write(lua_data)

    print(f"Conversion complete. Output saved to '{lua_output_file}'")

if __name__ == "__main__":
    if len(sys.argv) != 5:
        print("Usage: python script.py input_xml_file output_lua_file animation_prefixes_file image_path")
    else:
        xml_file = sys.argv[1]
        lua_output_file = sys.argv[2] or sys.argv[1].replace(".xml", ".lua")
        prefixes_file = sys.argv[3] or "default_prefixes.txt"
        image_path = sys.argv[4] or "none"
        convert_xml_to_lua(xml_file, lua_output_file, prefixes_file, image_path)


import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.ticker as plticker
import ROOT
import h5py
from scipy import interpolate
import pickle
import sys
sys.path.append("JPyPlotRatio");

import JPyPlotRatio

toptitle = "ALICE pPb $\\sqrt{s_\\mathrm{NN}}=5.02\\,\\mathrm{TeV}$";
plot = JPyPlotRatio.JPyPlotRatio(panels=(1,2),
	panelsize=(3,5.2),
	colBounds={0:(0,57.5),1:(0,57.5)},
	rowBounds={0:(-100,120)},
	legendPanel={0:0,1:0,2:1,3:1},
	legendLoc={0:(0.21,0.18),1:(0.63,0.18),2:(0.50,0.85),3:(0.2,0.12)},#,,1:(0.16,0.2)},
	ratioBounds={0:(0.80,1.1)},
	panelPrivateScale=[1],
	panelPrivateRowBounds={1:(0.0,2.0)},
	xlabel="Centrality (%)",
	ylabel={0:"$\\mathrm{d}N_\\mathrm{ch}/\\mathrm{d}\\eta$",1:"$\\langle p_\\mathrm{T}\\rangle$ (GeV/$c$)"},
	ylabelRight={0:"$\\langle p_\\mathrm{T}\\rangle$ (GeV/$c$)"},
	panelLabelSize=12,
	panelLabelLoc=(0.58,0.12));

plot.EnableLatex(True);

plot.ax[0,0].set_yscale("log");
plot.GetAxes(0).set_yscale("log");
plot.GetAxes(1).yaxis.tick_right();
plot.GetRatioAxes(1).yaxis.tick_right();

data = {
	"Charged":{
		"x":np.array([2.5,7.5,15,30,50]),
		"dNdy":np.array([44.96,36.05,30.33,23.12,15.89]),
		"dNdy_err":np.array([0.99,0.8,0.67,0.52,0.35])#,0.21,0.09])
	}
}

#obslabels_dNdy = ["$dN/d\\eta_p$","$dN/d\\eta_\\pi$","$dN/d\\eta_K$","$dN/d\\eta_h$"];
#obslabels_pTmean = ["$\\langle p_\\mathrm{T} \\rangle_p$","$\\langle p_\\mathrm{T} \\rangle_\\pi$","$\\langle p_\\mathrm{T} \\rangle_K$"];
species = ["Proton","Pion","Kaon"];
colors = ["red","green","blue"];
labels = ["p","$\\pi$","$K$"];
ms = ["o","D","x"];

dataPlots = {}; #For plotting
#------
dataPlots["502","charged","eta"] = plot.Add(0,(data["Charged"]["x"],data["Charged"]["dNdy"],data["Charged"]["dNdy_err"]),color="black",fmt="s",mfc="none",labelLegendId=0,label="Charged");
#------

f = ROOT.TFile("data/results_QM2018_pPb_502.root");
for si,s in enumerate(species):
	gr = f.Get("gr_mult_{}".format(s));
	p = plot.Add(0,gr,alpha=1,linestyle="-.",color="#5f8dd3",scale=0.5 if si == 1 else 1.0);

	dat = np.loadtxt("data/HEPData-ins1244523-v2-Table_{}.csv".format([18,21,20][si]),skiprows=13,delimiter=',');
	dataPlots["502",s,"ptmean"] = plot.Add(1,(dat[:,3],dat[:,6]),fmt=ms[si],mfc="none",color=colors[si],label=labels[si]);

	gr = f.Get("gr_pTmean_{}".format(s));
	p = plot.Add(1,gr,alpha=1,linestyle="-.",color="#5f8dd3");
	plot.Ratio(p,dataPlots["502",s,"ptmean"],color=colors[si]);

#Only charged particle multiplicity available
gr = f.Get("gr_mult_Charged".format(s));
p = plot.Add(0,gr,alpha=1,linestyle="-.",color="#5f8dd3");
plot.Ratio(p,dataPlots["502","charged","eta"],marker="s",mfc="none");

plot.GetPlot().text(0.56,0.84,"{T\\raisebox{-.5ex}{R}ENTo}+VISH(2+1)+UrQMD",color="black",fontsize=plot.legendSize);
plot.Add(0,(np.array([0]),np.array([4000])),color="#5f8dd3",linestyle="-.",label="MAP(QM2018)",labelLegendId=2);

f.Close();

plot.Plot();
plot.GetPlot().text(0.15,0.83,toptitle,fontsize=12);

plot.Save("figs/dndeta_meanpT_pPb.pdf");
plot.Show();


import json
import os
import argparse

def read_json_simple(json_file, unsolvable_only, exclude=[]):
    # print('Reading file ...')
    with open(json_file) as data_file:
        data = json.load(data_file)
    # print('Grouping data ...')
    excluded = 0
    grouped_data = {}
    existing_problems = {}
    for idx, val in data.items():
        if unsolvable_only and val['unsolvable'] == 0:
            continue
        if val['id'][1] not in grouped_data:
            existing_problems[val['id'][1]] = set()
            grouped_data[val['id'][1]] = {}
        if val['id'][1] in grouped_data and val['id'][2] not in grouped_data[val['id'][1]]:
            existing_problems[val['id'][1]].add(val['id'][2])
            grouped_data[val['id'][1]][val['id'][2]] = {}
        if val['id'][0] not in exclude:
            grouped_data[val['id'][1]][val['id'][2]][val['id'][0]] = val
        else:
            excluded += 1

    if excluded == 0 and len(exclude) > 0:
        print('Warning: no data excluded for exclude=', str(exclude))

    # print('Filtering intersection only data ...')

    counter = {}
    max_counter = 0
    for domain, problems in grouped_data.items():
        counter[domain] = {}
        for problem, algos in problems.items():
            counter[domain][problem] = len(algos)
            max_counter = max(len(algos), max_counter)
    to_del = []
    for domain, problems in grouped_data.items():
        for problem, algos in problems.items():
            if counter[domain][problem] < max_counter:
                to_del.append((domain, problem))
    for domain, problem in to_del:
        del grouped_data[domain][problem]
    to_del = []
    for domain, problems in grouped_data.items():
        if len(grouped_data[domain]) == 0:
            to_del.append(domain)
    for domain in to_del:
        del grouped_data[domain]

    # filtering unused instances

    domain_to_del = []
    for domain, problems in grouped_data.items():
        prob_to_del = []
        for problem, algos in problems.items():
            if len(algos) == 0:
                prob_to_del.append(problem)
        for p in prob_to_del:
            del problems[p]
            existing_problems[domain].remove(p)
        if len(problems) == 0:
            domain_to_del.append(domain)
    for d in domain_to_del:
        del grouped_data[d]
        del existing_problems[d]

    return grouped_data, existing_problems

def print_stats(grouped_data, algorithms, attr, max_val):
    # print('Processing data ...')

    # processing data
    val_data = {}
    for domain, problems in grouped_data.items():
        for problem, algos in problems.items():
            for algo, val_list in algos.items():
                if algo in algorithms:
                    if algo not in val_data:
                        val_data[algo] = []
                    if val_list['unsolvable'] == 0:
                        val_data[algo].append(max_val)
                    else:
                        val_data[algo].append(val_list[attr])
    total_data = 0
    for alg in algorithms:
        if total_data == 0:
            total_data = len(val_data[alg])
        else:
            assert len(val_data[alg]) == total_data

    s = ''
    for alg in algorithms:
        s += alg + ' '
    print(s)
    for i in range(total_data):
        s = ''
        for alg in algorithms:
            s += str(val_data[alg][i]) + ' '
        print(s)

def create_dirs_if_necessary(graph_data, OUTDIR):
    for domain, problems in graph_data.items():
        if not os.path.exists(OUTDIR + '/' + domain):
            os.makedirs(OUTDIR + '/' + domain)

def check_attribute_exists(grouped_data, attr):
    attrs = []
    for domain, problems in grouped_data.items():
        for problem, algos in problems.items():
            for algo, runs in algos.items():
                attrs = runs.keys()
            break
        break
    if attr in attrs:
        return True
    else:
        print('Attribute ' + attr + ' doesn\'t exists.')
        print('Available attributes are:')
        attrs = sorted(attrs)
        for a in attrs:
            print(a)
        return False

def check_algorithm_exists(grouped_data, alg):
    attrs = []
    for domain, problems in grouped_data.items():
        for problem, algos in problems.items():
            algs = algos.keys()
        break
    if alg in algs:
        return True
    else:
        print('Algorithm ' + alg + ' doesn\'t exists.')
        print('Algorithm attributes are:')
        algs = sorted(algs)
        for a in algs:
            print(a)
        return False

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("json_file", help=".json file containing the lab data")
    parser.add_argument("--attribute", "-a", help="attribute to use", default="max_abstraction_states")
    parser.add_argument("--unsolvable-only", "-u", help="only count the unsolvable instances", dest='unsolvable_only',
                        action='store_true')
    parser.add_argument("--max", '-m', help="maximum default value if it is fail", default='0')
    parser.add_argument("--algos", help="histogram range (int)", nargs='+')
    parser.set_defaults(unsolvable_only=False)
    args = parser.parse_args()

    data, problems = read_json_simple(args.json_file, args.unsolvable_only)
    if check_attribute_exists(data, args.attribute):
        for alg in args.algos:
            if not check_algorithm_exists(data, alg):
                return
        print_stats(data, args.algos, args.attribute, args.max)

if __name__ == '__main__':
    main()


from dissect.util import stream

from dissect.target import filesystem
from dissect.target.loader import Loader

BLOCK_SIZE = 64 * 0x100000  # 64 MiB

NTFS_NEEDLE = b"\xeb\x52\x90NTFS    \x00"
EXTFS_NEEDLE = b"\xff\xff\x53\xef"
# The extfs needle is 54 kiB from the start of the extfs volume
EXTFS_NEEDLE_OFFSET = 0x36 * 1024
FS_NEEDLES = [NTFS_NEEDLE, EXTFS_NEEDLE]

def scrape_pos(fp, needles, block_size=BLOCK_SIZE):
    while True:
        file_pos = fp.tell()
        block = fp.read(block_size)

        if not block:
            break

        for needle in needles:
            block_pos = -1
            while True:
                block_pos = block.find(needle, block_pos + 1)
                if block_pos == -1:
                    break

                offset = file_pos + block_pos
                yield needle, offset

class PhobosLoader(Loader):
    @staticmethod
    def detect(path):
        return path.suffix.lower() == ".eight"

    def map(self, target):
        fh = self.path.open("rb")

        fs_idx = 0
        for needle, offset in scrape_pos(fh, FS_NEEDLES):
            cur_seek = fh.tell()

            try:
                if needle == NTFS_NEEDLE:
                    volume = stream.RelativeStream(fh, offset)
                    fs = filesystem.open(volume)
                    size = fs.ntfs.header.sector_count_64 * fs.ntfs.header.bytes_per_sector
                elif needle == EXTFS_NEEDLE:
                    volume = stream.RelativeStream(fh, offset - EXTFS_NEEDLE_OFFSET)
                    fs = filesystem.open(volume)
                    size = fs.extfs.block_count * fs.extfs.block_size

                target.filesystems.add(fs)
                target.fs.mount(f"fs{fs_idx}", fs)
                fs_idx += 1

                fh.seek(offset + size)
            except Exception:
                fh.seek(cur_seek)


# coding=utf-8
import os, time
from convertor import Convertor

def main():
    try:
        xxd = Convertor()
        xxd.toDesktop()
        xxd.toDocx()
        xxd.toBib()
        xxd.toHTML()
        iframes = xxd.fetch_iframes(xxd.content)
        if len(iframes)>0:
            html = xxd.ex_html
            while not os.path.exists(html):
                # 阻塞一下，pandoc转换格式需要时间
                time.sleep(1)
            with open(html, 'r', encoding='utf-8') as f:
                lines = f.readlines()
            idx = 0
            content = []
            for line in lines:
                if line.startswith('<iframe'):
                    line = iframes[idx]
                    idx += 1
                content.append(line)
            content = '\n'.join(content)
            with open(html, 'w', encoding='utf-8') as f:
                f.write(content)
    except Exception as e:
        print(str(e))

def test():
    fp = r"X:\projects\working\README.md"
    try:
        xxd = Convertor(fp)
        xxd.toDesktop()
        xxd.toDocx()
        xxd.toBib()
        xxd.toHTML()
    except Exception as e:
        print(str(e))

if __name__=='__main__':
    main()


import streamlit as st
import numpy as np
import seaborn as sns
import pandas as pd
import random
import matplotlib.pyplot as plt

st.set_page_config(layout="wide")
st.title("Laboratorio 2")

capital_inicial = 20000
años = [i for i in range(1,18)]

def rendimiento_anual(rendimiento):
    return capital_inicial * (1 + rendimiento)

def cumsum(array):
    cumsum_values=[]
    for index, val in enumerate(array):
        cumsum_values[index] = cumsum_values[index] + val
    return cumsum_values

rendimiento_promedio = st.number_input("Tasa de rendimiento promedio (%)")
desviacion = st.number_input("Desviacion estandar (%)")
rendimientos = []
montos_finales = []
dataset_simulacion_rendimiento = pd.DataFrame(columns=años)
dataset_simulacion_monto = pd.DataFrame(columns=años)

numero_simulaciones = st.number_input("Cantidad de simulaciones")

for i in range(0, int(numero_simulaciones)):
    rendimientos_actuales = np.random.normal(rendimiento_promedio / 100, desviacion/100, 17)
    capital_final = [rendimiento_anual(x) for x in rendimientos_actuales]
    rendimiento_promedio_actual = np.mean(rendimientos_actuales)
    rendimientos.append(rendimiento_promedio_actual)
    monto_final = np.sum(capital_final)
    montos_finales.append(monto_final)
    dataset_simulacion_rendimiento.loc[len(dataset_simulacion_rendimiento)] = rendimientos_actuales
    dataset_simulacion_monto.loc[len(dataset_simulacion_monto)] = capital_final

if len(rendimientos) > 0:
    rendimientos_promedio_por_año = (list(dataset_simulacion_rendimiento.mean(axis=0)))
    monto_promedio_por_año = (list(dataset_simulacion_monto.mean(axis=0)))
    suma_por_iteracion = list(dataset_simulacion_monto.sum(axis=1))
    mejores_rendimientos = dataset_simulacion_rendimiento.iloc[np.argmax(suma_por_iteracion), :]
    peores_rendimientos = dataset_simulacion_rendimiento.iloc[np.argmin(suma_por_iteracion), :]
    montos_acumulados = np.cumsum(monto_promedio_por_año)
    rendimiento_promedio_simulacion = np.mean(rendimientos)
    monto_promedio_simulacion = np.mean(montos_finales)

    '''### Rendimiento promedio total al finalizar los 17 años.'''
    st.write(f'''{round(rendimiento_promedio_simulacion, 2) * 100}%''')
    '''### Monto promedio acumulado al finalizar los 17 años.'''
    st.write(f'''{round(monto_promedio_simulacion, 2)}''')
    '''### Escenario de ahorro pesimista y optimista.'''
    st.write(f'''El mejor escenario es {np.argmax(suma_por_iteracion)} con un monto de  {round(np.max(suma_por_iteracion),2)}''')
    st.table(np.array(mejores_rendimientos))
    st.write(f'''El peor escenario es {np.argmin(suma_por_iteracion)} con un monto de  {round(np.min(suma_por_iteracion),2)}''')
    st.table(np.array(peores_rendimientos))

    '''### Gráfica de los rendimientos obtenidos por cada año.'''
    plot = sns.barplot(x=años, y=rendimientos_promedio_por_año)
    plt.title('Rendimiento Promedio por Año')
    plt.xlabel("Año")
    plt.ylabel("Rendimiento")
    st.pyplot(plot.get_figure())
    '''### Grafica del monto ahorrado por cada año.'''
    plot = sns.barplot(x=años, y=monto_promedio_por_año)
    plt.title('Monto Promedio por Año')
    plt.xlabel("Año")
    plt.ylabel("Ahorro Promedio")
    st.pyplot(plot.get_figure())
    '''###  Grafica del monto acumulado por cada año dentro de los 17 años.'''
    plot = sns.barplot(x=años, y=montos_acumulados)
    plt.title('Montos Acumulados')
    plt.xlabel("Año")
    plt.ylabel("Ahorro Anual")
    st.pyplot(plot.get_figure())


from selenium import webdriver     # 导入webdriver模块

browser_c = webdriver.Chrome()     # 打开谷歌浏览器
browser_c.get("https://www.baidu.com")

'''
print("设置浏览器宽480、高800的显示")
browser_c.set_window_size(480, 800)  #设置窗口高宽
'''

# input = browser_c.find_element_by_id("kw")  # 通过ID定位输入框
input = browser_c.find_element_by_xpath('//*[@id="kw"]')
input.send_keys('python')   # 在输入框输入Python

print(browser_c.current_url)  # 打印当前网页地址
print(browser_c.page_source)  # 打印网页源码

browser_c.close()    #关闭浏览器


cards = input()

list_cards = cards.split(' ')
all_cards = set(list_cards)
team_A = 11
team_B = 11

for card in all_cards:
    if 'A' in card:
        team_A -= 1
    else:
        team_B -= 1
    if team_A < 7 or team_B < 7:
        break

print(f"Team A - {team_A}; Team B - {team_B}")
if team_A < 7 or team_B < 7:
    print("Game was terminated")


#Ходьба по диогонали
n = int(input())
s = list(input())
i = 1
while i < len(s):
    if s[i] + s[i-1] == 'RU':
        n -= 1
        s[i] = 'D'
    elif s[i] + s[i-1] == 'UR':
        n -= 1
        s[i] = 'D'
    i += 1

print(n)


from pprint import pprint

def adjencymatrix(file):
	filecontents = []
	with open(file) as input_file:
		for line in input_file:
			filecontents.append( line.split() )

	count = []
	for x in range(len(filecontents)):
		for y in range(len(filecontents[x])):
			if filecontents[x][y] not in count:
				count.append(filecontents[x][y])

	counter_list = list(enumerate(count))

	matrix = []
	for x in range(len(count)):
		submatrix=[]
		for y in range(len(count)):
			submatrix.append(0)
		matrix.append(submatrix)

	for c1, e1 in counter_list:
		for c2,e2 in counter_list:
			if[e1,e2] in filecontents:
				matrix[c1][c2] = 1
				matrix[c2][c1] = 1

	del count
	return matrix, counter_list

def cTable(M, H):

	C = []

	for x in range(len(M)):

		C.append([])
		for y in range(len(H[0])):
			sum = 0
			for k in range(len(H)):
				sum = sum + M[x][k]*H[k][y]

			C[x].append(sum)

	return C

def mTable(A, B):

	m = [[0 for x in range(len(B))] for y in range(len(A))]

	adegree = 0
	bdegree = 0

	for i in range(len(A)):
		adegree = sum(A[i])
		for j in range(len(B)):
			bdegree = sum(B[j])
			if bdegree >= adegree:
				m[i][j] = 1

	return m

def transposeTable(T):
	transpose = [[0 for x in range(len(T))] for y in range(len(T[0]))]
	for i in range(len(transpose)):
		for j in range(len(transpose[0])):
			transpose[i][j] = T[j][i]
	return transpose

recursions = 0
output = None

def simple_enumeration(A,B,Morg,d):
	global recursions,output
	recursions+=1

	if d >= len(A):
		return None

	#e is for each element in the dth row of M
	for e in range(len(Morg[d])):
		if Morg[d][e] != 0:

			M = [[i for i in row] for row in Morg]

			#k starts zero out all non-zero elements in the eth row
			for k in range(len(M[d])):
				if k != e:
					M[d][k] = 0
			for j in range(len(M)):
				if j != d:
					M[j][e] = 0
			if d == len(A)-1:
				product = cTable(M, B)
				transpose = transposeTable(product)
				C = cTable(M, transpose)

				if C==A:
					output=M
			else:
				simple_enumeration(A,B,M,d+1)

	return output

def are_neighbours_mapped(A,B,M,i,j):
	for k in range(len(A)):
		if A[i][k] != 0:
			found = False
			for l in range(len(B)):
				if B[j][l] != 0:
					if M[k][l] != 0:
						found = True
			if found == False:
				return False
	return True

def refine(A,B,M):
	done = False
	while not done:
		done = True
		for i in range(len(M)):
			rs = 0
			for j in range(len(M[0])):
				if M[i][j] != 0:
					if are_neighbours_mapped(A,B,M,i,j) == False:
						M[i][j] = 0
						done = False
					else:
						rs = rs + 1
			if rs == 0:
				return False
	return True

def refined_enumeration(A,B,Morg,d):
	global recursions,output
	recursions+=1

	if d >= len(A):
		return None

	#e is for each element in the dth row of M
	for e in range(len(Morg[d])):
		if Morg[d][e] != 0:

			M = [[i for i in row] for row in Morg]

			#k starts zero out all non-zero elements in the eth row
			for k in range(len(M[d])):
				if k != e:
					M[d][k] = 0
			for j in range(len(M)):
				if j != d:
					M[j][e] = 0

			proceed = refine(A,B,M)
			if proceed == True:
				if d == len(A)-1:
					product = cTable(M, B)
					transpose = transposeTable(product)
					C = cTable(M, transpose)

					if C==A:
						output=M
				else:
					refined_enumeration(A,B,M,d+1)

	return output

a_matrix, c1 = adjencymatrix("C:\\Users\\user\\Desktop\\assignment-2019-4\\graph_4.txt")
b_matrix, c2 = adjencymatrix("C:\\Users\\user\\Desktop\\assignment-2019-4\\graph_5.txt")
m_matric = mTable(a_matrix, b_matrix)
ret = simple_enumeration(a_matrix, b_matrix, m_matric, 0)

for i in range(len(ret)):
	for j in range(len(ret[i])):
		if ret[i][j]==1:
			print(c1[i][1],'->', c2[j][1])

print(recursions)


def build_triangle(nlines):
    triangle = []
    if (nlines >= 1):
        linha1 = [1]
        triangle.append(linha1)

    if (nlines >= 2):
        linha2 = [1, 1]
        triangle.append(linha2)

    if (nlines >= 3):
        previous_line = [1, 1]

        for linha in range(3, nlines + 1):
            current_line = []

            for elemento in range(0, linha):
                if (elemento == 0):
                    current_line.append(1)
                elif (elemento == linha - 1):
                    current_line.append(1)
                else:
                    current_line.append(previous_line[elemento] + previous_line[elemento - 1])

            triangle.append(current_line)
            previous_line = current_line

    return triangle

number_of_lines = int(input("digite o número de linhas do triângulo:\n> "))
built_triangle = build_triangle(number_of_lines)

for line in built_triangle:
    print(line)


from flask import Flask

from flask_assets import Environment
from flask_assets import Bundle

from config import Config

from flask_sqlalchemy import SQLAlchemy

from flask_migrate import Migrate

from flask_restful import Api

from flask_login import LoginManager

from flask_mail import Mail

app = Flask(__name__)
app.config.from_object(Config)

app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024
app.config['ALLOWED_EXTENSIONS'] = ['png', 'jpg', 'jpeg']

db = SQLAlchemy(app)
migrate = Migrate(app, db)
api = Api(app)
login = LoginManager(app)
login.login_view = 'get_sign_in'
mail = Mail(app)

assets = Environment(app)

js = Bundle('script/toggle-sign-mode.js',
            'script/check-form.js',
            'script/modal-windows.js',
            'script/main-page.js',
            'script/count-view-product.js',
            'script/show-frequently-asked-question.js',
            'script/marketplace-news-list.js',
            'script/user-question.js',
            filters='jsmin', output='bundle.min.js')
assets.register('js_all', js)

js_vendors = Bundle('lib/jquery/3.4.0/jquery-3.4.0.min.js',
                    'lib/bootstrap/4.3.1/js/bootstrap.min.js',
                    'lib/pace/1.0.2/js/pace.min.js',
                    'lib/fancybox/3.5.7/js/jquery.fancybox.min.js',
                    filters='jsmin', output='vendors.min.js')
assets.register('js_vendors', js_vendors)

css = Bundle('css/main-page.css',
             'css/sign-form.css',
             'css/cart.css',
             'css/popup-window.css',
             'css/profile.css',
             'css/advantage-marketplace.css',
             'css/frequently-asked-questions.css',
             'css/card-item.css',
             filters='cssmin', output='bundle.min.css')
assets.register('css_all', css)

css_vendors = Bundle('lib/pace/1.0.2/css/pace-theme-minimal.css',
                     'lib/fancybox/3.5.7/css/jquery.fancybox.min.css',
                     'lib/bootstrap/4.3.1/css/bootstrap.min.css')
assets.register('css_vendors', css_vendors)

from xcrafter import routes
from xcrafter import models
from xcrafter import server_api


"""Main app/routing for Twitter"""

from flask import Flask, render_template
from models import DB, User, Tweet
from twitter import *

# function to intialize the flask instance

# create the application
def create_app():
    """Create and configuring an instance of the Flask application"""

    # location of the Flask application and look in the current directory
    app = Flask(__name__)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # with app.app_context():
    DB.init_app(app)

    # DB.init_app(app)  # initialize the DB with this application, DB is an instance of SQLAlchemy class

    # add a decorator
    @app.route('/')
    def root():
        # DB.drop_all()
        # DB.create_all()
        # app_user = User(id=1, name='app_user')
        # DB.session.add(app_user)
        # DB.session.commit()

        # return render_template('base.html',
        #                        title='Home',
        #                        users=User.query.all())
        return "text"
        # PS muse: when you are using Title = Home you are using Jinja2

    return app

#
# if __name__ == '__main__':
#     create_app().run()


import random
from math import sqrt
from matplotlib import pyplot as plt
from DT.data_manager import Dataset
from DT.data_manager import estimate
from DT.data_manager import make_dataset
from DT.decision_tree import DecisionTree
import numpy as np

TREES_IN_FOREST = 50
MAX_DEPTH = 100
BINARY_TREE = 2
DATASET = 2

def make_tree(general, tree):
    features_sub_amount = int(sqrt(general.features_amount))
    selected_samples = [random.randint(0, general.obj_amount - 1) for _ in range(general.obj_amount)]
    selected_features = set()
    while len(selected_features) != features_sub_amount:
        selected_features.add(random.randint(0, general.features_amount - 1))
    features = np.take(general.features, selected_samples, axis=0)
    targets = np.take(general.targets, selected_samples)
    cut_features = np.take(features, list(selected_features), axis=1)
    tree_dataset = Dataset(np.concatenate((cut_features, targets[:, None]), axis=1))
    print("Building tree #%s" % tree)
    return DecisionTree(tree_dataset, MAX_DEPTH, BINARY_TREE), selected_features

def vote(single_predictions):
    amount = len(single_predictions[0])
    cooperative_predictions = np.empty(amount, dtype=int)
    for obj in range(amount):
        targets, votes = np.unique(single_predictions[:, obj], return_counts=True)
        major = targets[np.argmax(votes)]
        cooperative_predictions[obj] = major
    return cooperative_predictions

def draw_plot(test, train):
    x = np.arange(1, TREES_IN_FOREST + 1)
    plt.title("Influence of forest size on accuracy")
    plt.xlabel("Trees in forest")
    plt.ylabel("Accuracy")
    plt.grid(True)
    plt.plot(x, train, 'b', label="train")
    plt.plot(x, test, 'r', label="test")
    plt.legend()
    plt.show()

test_quality, train_quality = list(), list()
general_train, general_test = make_dataset(str(DATASET))
forest = list()
for forest_size in range(1, TREES_IN_FOREST + 1):
    forest.append(make_tree(general_train, forest_size))
    test_predictions = np.empty((forest_size, general_test.obj_amount))
    train_predictions = np.empty((forest_size, general_test.obj_amount))
    for tree in range(forest_size):
        test_features = np.take(general_test.features, list(forest[tree][1]), axis=1)
        train_features = np.take(general_train.features, list(forest[tree][1]), axis=1)
        test_predictions[tree] = forest[tree][0].predict(test_features)
        train_predictions[tree] = forest[tree][0].predict(train_features)
    test_quality.append(estimate(vote(test_predictions), general_test.targets))
    train_quality.append(estimate(vote(train_predictions), general_train.targets))
draw_plot(test_quality, train_quality)


import pandas as pd
import ccxt, config

import time

import firebase_admin
from firebase_admin import credentials, firestore
from tradingview_ta import TA_Handler, Interval, Exchange
import calendar

longgiris = 0
shortgiris = 0
sayici_giris_control = 0
sheetsymbolx = 0
sheetssymboly = 0
macdlast = 0
engulfing = 0
buysignallast = 0
sellsignallast = 0
coipricefloat = 0
sellsignallast1 = 0
sellsignallast2 = 0
str_sellsignallast1 = 0
str_sellsignallast2 = 0
kimlik = credentials.Certificate("ema_class.json")

app = firebase_admin.initialize_app(kimlik)

class Macdema():

    def __init__(self, symbol, timeframe, quantity, buyvalue, sellvalue):
        self.symbol = symbol
        self.longgiris = longgiris
        self.shortgiris = shortgiris
        self.timeframe = timeframe
        self.sayici_giris_control = sayici_giris_control
        self.quantity = quantity
        self.buyvalue = buyvalue
        self.sellvalue = sellvalue
        self.buysignallast = buysignallast
        self.sellsignallast = sellsignallast
        self.sellsignallast1 = sellsignallast1
        self.sellsignallast2 = sellsignallast2
        self.str_sellsignallast1 = str_sellsignallast1
        self.str_sellsignallast2 = str_sellsignallast2

        self.coipricefloat = coipricefloat

    def dfall(self, symbol, timeframe):

        try:
            handler = TA_Handler(
                symbol=symbol,
                exchange="BINANCE",
                screener="crypto",
                interval=timeframe,
                timeout=None,
                proxies={'http': '47.242.84.173:3128', 'http': '181.205.20.195:999', 'http': '192.111.135.17:18302',
                         'http': '103.108.228.185:7497'}
            )

            analysis = handler.get_analysis().summary

            analysis_str = str(analysis)

            symbolrec = analysis['RECOMMENDATION']
            dt = time.gmtime()
            ts = calendar.timegm(dt)
            ts_str = str(ts)

            x = self.symbol + self.timeframe + ts_str

            db = firestore.client()  # db e baglantı

            docs = db.collection (self.symbol + self.timeframe).get()

            for doc in docs:
                key = doc.id
                db.collection(self.symbol + self.timeframe).document(key).delete()
                print("silindi" + self.symbol + self.timeframe)

            document = db.collection(self.symbol + self.timeframe).document(x)
            docId = document.id
            document.set({
                "id": ts_str,

                "position": symbolrec,

            })

        except :
            print("silindi2")

coin2 = Macdema('API3USDT', "1h", 15, 1.007, 0.993)
coin1 = Macdema('WOOUSDT', "1h", 100, 1.007, 0.993)
coin3 = Macdema('CELOUSDT', "1h", 30, 1.007, 0.993)
coin4 = Macdema('ARPAUSDT', "1h", 600, 1.007, 0.993)
coin5 = Macdema('LPTUSDT', "1h", 3, 1.007, 0.993)
coin6 = Macdema('KLAYUSDT', "1h", 3, 1.007, 0.993)

coin7 = Macdema('OMGUSDT', "1h", 15, 1.007, 0.993)
coin8 = Macdema('OPUSDT', "1h", 40, 1.007, 0.993)
coin9 = Macdema('UNFIUSDT', "1h", 6, 1.007, 0.993)

coin11 = Macdema('ARUSDT', "1h", 2, 1.007, 0.993)
coin12 = Macdema('DOTUSDT', "1h", 3, 1.007, 0.993)
coin13 = Macdema('ETCUSDT', "1h", 1.5, 1.007, 0.993)
coin14 = Macdema('ALGOUSDT', "1h", 80, 1.007, 0.993)
coin15 = Macdema('TRXUSDT', "1h", 200, 1.007, 0.993)
coin16 = Macdema('LRCUSDT', "1h", 50, 1.007, 0.993)
coin17 = Macdema('SANDUSDT', "1h", 25, 1.007, 0.993)

coin18 = Macdema('YFIUSDT', "1h", 0.005, 1.007, 0.993)
coin19 = Macdema('MASKUSDT', "1h", 3, 1.007, 0.993)
coin20 = Macdema('SUSHIUSDT', "1h", 30, 1.007, 0.993)

coin21 = Macdema('NEARUSDT', "1h", 9, 1.007, 0.993)
coin24 = Macdema('MATICUSDT', "1h", 40, 1.007, 0.993)
coin25 = Macdema('BELUSDT', "1h", 30, 1.007, 0.993)
coin26 = Macdema('DOGEUSDT', "1h", 20, 1.007, 0.993)
coin27 = Macdema('BLZUSDT', "1h", 200, 1.007, 0.993)
coin28 = Macdema('KAVAUSDT', "1h", 15, 1.007, 0.993)
coin29 = Macdema('CHZUSDT', "1h", 250, 1.007, 0.993)

coin31 = Macdema('QTUMUSDT', "1h", 8, 1.007, 0.993)
coin32 = Macdema('CHRUSDT', "1h", 150, 1.007, 0.993)
coin33 = Macdema('OCEANUSDT', "1h", 100, 1.007, 0.993)
coin34 = Macdema('ALPHAUSDT', "1h", 150, 1.007, 0.993)
coin35 = Macdema('XRPUSDT', "1h", 100, 1.006, 0.994)
coin36 =  Macdema('BNBUSDT', "1h", 0.13, 1.006, 0.994)
coin37 = Macdema('ATOMUSDT', "1h", 4, 1.006, 0.994)

coin2a = Macdema('API3USDT', "2h", 20, 1.007, 0.993)
coin1a = Macdema('WOOUSDT', "2h", 125, 1.007, 0.993)
coin3a = Macdema('CELOUSDT', "2h", 40, 1.007, 0.993)
coin4a = Macdema('ARPAUSDT', "2h", 700, 1.007, 0.993)
coin5a = Macdema('LPTUSDT', "2h", 4, 1.007, 0.993)
coin6a = Macdema('KLAYUSDT', "2h", 3, 1.007, 0.993)

coin7a = Macdema('OMGUSDT', "2h", 20, 1.007, 0.993)
coin8a = Macdema('OPUSDT', "2h", 55, 1.007, 0.993)
coin9a = Macdema('UNFIUSDT', "2h", 8, 1.007, 0.993)

coin11a = Macdema('ARUSDT', "2h", 3, 1.007, 0.993)
coin12a = Macdema('DOTUSDT', "2h", 4, 1.007, 0.993)
coin13a = Macdema('ETCUSDT', "2h", 1.8, 1.007, 0.993)
coin14a = Macdema('ALGOUSDT', "2h", 100, 1.007, 0.993)
coin15a = Macdema('TRXUSDT', "2h", 240, 1.007, 0.993)
coin16a = Macdema('LRCUSDT', "2h", 70, 1.007, 0.993)
coin17a = Macdema('SANDUSDT', "2h", 30, 1.007, 0.993)

coin18a = Macdema('YFIUSDT', "2h", 0.005, 1.007, 0.993)
coin19a = Macdema('MASKUSDT', "2h", 3, 1.007, 0.993)
coin20a = Macdema('SUSHIUSDT', "2h", 30, 1.007, 0.993)
coin21a = Macdema('NEARUSDT', "2h", 12, 1.007, 0.993)
coin24a = Macdema('MATICUSDT', "2h", 45, 1.007, 0.993)
coin25a = Macdema('BELUSDT', "2h", 55, 1.007, 0.993)
coin26a = Macdema('DOGEUSDT', "2h", 66,1.007, 0.993)
coin27a = Macdema('BLZUSDT', "2h", 77, 1.007, 0.993)
coin28a = Macdema('KAVAUSDT', "2h", 20, 1.007, 0.993)
coin29a = Macdema('CHZUSDT', "2h", 280, 1.007, 0.993)

coin31a = Macdema('QTUMUSDT', "2h", 10, 1.007, 0.993)
coin32a = Macdema('CHRUSDT', "2h", 180, 1.007, 0.993)
coin33a = Macdema('OCEANUSDT', "2h", 90, 1.007, 0.993)
coin34a = Macdema('ALPHAUSDT', "2h", 170, 1.007, 0.993)
coin35a = Macdema('XRPUSDT', "2h", 100, 1.006, 0.994)

coin36a = Macdema('BNBUSDT', "2h", 0.13, 1.006, 0.994)
coin37a = Macdema('ATOMUSDT', "2h", 4, 1.006, 0.994)

while True:
    coin2.dfall('API3USDT', "1h")
    time.sleep(2)
    coin1.dfall('WOOUSDT', "1h")
    time.sleep(2)
    coin3.dfall('CELOUSDT', "1h")
    time.sleep(2)
    coin4.dfall('ARPAUSDT', "1h")
    time.sleep(2)
    coin5.dfall('LPTUSDT', "1h")
    time.sleep(2)
    coin6.dfall('KLAYUSDT', "1h")
    time.sleep(2)

    coin7.dfall('OMGUSDT', "1h")
    time.sleep(2)
    coin8.dfall('OPUSDT', "1h")
    time.sleep(2)
    coin9.dfall('UNFIUSDT', "1h")
    time.sleep(2)
    coin11.dfall('ARUSDT', "1h")
    time.sleep(2)
    coin12.dfall('DOTUSDT', "1h")
    time.sleep(2)
    coin13.dfall('ETCUSDT', "1h")
    time.sleep(2)
    coin14.dfall('ALGOUSDT', "1h")
    time.sleep(2)
    coin15.dfall('TRXUSDT', "1h")
    time.sleep(2)
    coin16.dfall('LRCUSDT', "1h")
    time.sleep(2)
    coin17.dfall('SANDUSDT', "1h")
    time.sleep(2)

    coin18.dfall('YFIUSDT', "1h")
    time.sleep(30)
    coin19.dfall('MASKUSDT', "1h")
    time.sleep(30)

    coin20.dfall('SUSHIUSDT', "1h")
    time.sleep(30)

    coin21.dfall('NEARUSDT', "1h")
    time.sleep(2)

    coin24.dfall('MATICUSDT', "1h")
    time.sleep(2)
    coin25.dfall('BELUSDT', "1h")
    time.sleep(2)
    coin26.dfall('DOGEUSDT', "1h")
    time.sleep(2)
    coin27.dfall('BLZUSDT', "1h")
    time.sleep(2)
    coin28.dfall('KAVAUSDT', "1h")
    time.sleep(2)
    coin29.dfall('CHZUSDT', "1h")
    time.sleep(2)

    coin31.dfall('QTUMUSDT', "1h")
    time.sleep(2)
    coin32.dfall('CHRUSDT', "1h")
    time.sleep(2)
    coin33.dfall('OCEANUSDT', "1h")
    time.sleep(2)
    coin34.dfall('ALPHAUSDT', "1h")
    time.sleep(2)
    coin35.dfall('XRPUSDT', "1h")
    time.sleep(2)
    coin36.dfall('BNBUSDT', "1h")
    time.sleep(2)
    coin37.dfall('ATOMUSDT', "1h")
    time.sleep(2)

    coin2a.dfall('API3USDT', "2h")
    time.sleep(2)
    coin1a.dfall('WOOUSDT', "2h")
    time.sleep(2)
    coin3a.dfall('CELOUSDT', "2h")
    time.sleep(2)
    coin4a.dfall('ARPAUSDT', "2h")
    time.sleep(2)
    coin5a.dfall('LPTUSDT', "2h")
    time.sleep(2)
    coin6a.dfall('KLAYUSDT', "2h")
    time.sleep(2)

    coin7a.dfall('OMGUSDT', "2h")
    time.sleep(2)
    coin8a.dfall('OPUSDT', "2h")
    time.sleep(2)
    coin9a.dfall('UNFIUSDT', "2h")
    time.sleep(2)
    coin11a.dfall('ARUSDT', "2h")
    time.sleep(2)
    coin12a.dfall('DOTUSDT', "2h")
    time.sleep(2)
    coin13a.dfall('ETCUSDT', "2h")
    time.sleep(2)
    coin14a.dfall('ALGOUSDT', "2h")
    time.sleep(2)
    coin15a.dfall('TRXUSDT', "2h")
    time.sleep(2)
    coin16a.dfall('LRCUSDT', "2h")
    time.sleep(2)
    coin17a.dfall('SANDUSDT', "2h")
    time.sleep(2)

    coin18a.dfall('YFIUSDT', "2h")
    time.sleep(30)
    coin19a.dfall('MASKUSDT', "2h")
    time.sleep(30)

    coin20a.dfall('SUSHIUSDT', "2h")
    time.sleep(30)
    coin21a.dfall('NEARUSDT', "2h")
    time.sleep(2)

    coin24a.dfall('MATICUSDT', "2h")
    time.sleep(2)
    coin25a.dfall('BELUSDT', "2h")
    time.sleep(2)
    coin26a.dfall('DOGEUSDT', "2h")
    time.sleep(2)
    coin27a.dfall('BLZUSDT', "2h")
    time.sleep(2)
    coin28a.dfall('KAVAUSDT', "2h")
    time.sleep(2)
    coin29a.dfall('CHZUSDT', "2h")
    time.sleep(2)

    coin31a.dfall('QTUMUSDT', "2h")
    time.sleep(2)
    coin32a.dfall('CHRUSDT', "2h")
    time.sleep(2)
    coin33a.dfall('OCEANUSDT', "2h")
    time.sleep(2)
    coin34a.dfall('ALPHAUSDT', "2h")
    time.sleep(2)
    coin35a.dfall('XRPUSDT', "2h")
    time.sleep(2)
    coin36a.dfall('BNBUSDT', "2h")
    time.sleep(2)
    coin37a.dfall('ATOMUSDT', "2h")
    time.sleep(2)

    time.sleep(3600)


#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Cemre ALPSOY <cemre.alpsoy@agem.com.tr>

import json
import subprocess
from base.plugin.abstract_plugin import AbstractPlugin

class ServiceList(object):
    def __init__(self):
        self.service_list = []

class ServiceListItem:
    def __init__(self, service_name, status, auto):
        self.serviceName = service_name
        self.serviceStatus = status
        self.startAuto = auto

def encode_service_object(obj):
    if isinstance(obj, ServiceListItem):
        return obj.__dict__
    return obj

class GetServices(AbstractPlugin):
    def __init__(self, data, context):
        super(AbstractPlugin, self).__init__()
        self.data = data
        self.context = context
        self.logger = self.get_logger()
        self.message_code = self.get_message_code()

        self.temp_file_name = str(self.generate_uuid())
        self.file_path = '{0}{1}'.format(str(self.Ahenk.received_dir_path()), self.temp_file_name)
        self.service_status = 'systemctl status {}'
        self.isRecordExist = 0

    def handle_task(self):
        try:
            self.logger.debug('Executing command for service list.')
            self.get_service_status()

            self.logger.debug('Command executed.')

            if self.is_exist(self.file_path):
                data = {}
                self.logger.debug(str(self.file_path))
                md5sum = self.get_md5_file(str(self.file_path))
                self.logger.debug('{0} renaming to {1}'.format(self.temp_file_name, md5sum))
                self.rename_file(self.file_path, self.Ahenk.received_dir_path() + '/' + md5sum)
                self.logger.debug('Renamed.' + self.Ahenk.received_dir_path() + '/' + md5sum)
                data['md5'] = md5sum
                self.context.create_response(code=self.message_code.TASK_PROCESSED.value,
                                             message='Servis listesi başarıyla okundu.',
                                             data=json.dumps(data),
                                             content_type=self.get_content_type().TEXT_PLAIN.value)
                self.logger.debug("Execution Info fetched succesfully. ")
                self.logger.debug("Execution Info has sent")
            else:
                self.context.create_response(code=self.message_code.TASK_ERROR.value,
                                             message='Servis listesi getirilemedi')
            self.logger.debug('Service list created successfully')
        except Exception as e:
            self.logger.error(str(e))
            self.context.create_response(code=self.message_code.TASK_ERROR.value,
                                         message='Servis listesi oluşturulurken hata oluştu: ' + str(e))

    def add_file(self, name, status, auto_start):
        if self.isRecordExist == 0:
            self.execute('echo { \\"agent\\" : \\"'+ self.Ahenk.dn() + '\\", \\"service_list\\" :[ >> ' + self.file_path)
            self.isRecordExist = 1
        t_command = 'echo "{ \\"serviceName\\": \\"' + name + '\\", \\"serviceStatus\\": \\"' + status + '\\", \\"startAuto\\":\\"' + auto_start + '\\"}" >> ' + self.file_path
        self.execute(t_command)
        self.execute('echo , >> ' + self.file_path)

    def add_agentDnToFile(self):
        t_command = 'echo "{ \\"agent\\": \\"' + self.Ahenk.dn() +'\\"}" >> ' + self.file_path
        self.execute(t_command)
        self.execute('echo , >> ' + self.file_path)

    def get_service_status(self):
        try:
            (result_code, p_out, p_err) = self.execute("systemctl list-units --type service --all | grep loaded")
            self.create_file(self.file_path)
            # service_list = ServiceList()
            lines = p_out.split('\n')
            for line in lines:
                line_split = line.split(' ')
                service=[]
                for word in line_split:
                    if word != '' :
                        service.append(word)
                if len(service)>0 and '.service' not in service[0]:
                    del service[0]

                if len(service)>0 and '.service' in service[0]: # service[0] = service name, service[1] is loaded, service[2] active or not,
                    result, out, err = self.execute(self.service_status.format(service[0])) # check service is enable or not on auto start
                    auto='INACTIVE'
                    if 'disabled' in out:
                        auto='INACTIVE'
                    elif 'enabled' in out:
                        auto='ACTIVE'

                    if service[2] == 'active':
                        self.add_file(service[0], "ACTIVE", auto)
                    else:
                        self.add_file(service[0], 'INACTIVE',auto)

                    print(service)

            if self.isRecordExist == 1:
                self.execute("sed -i '$ d' " + self.file_path)
                self.execute('echo "]}" >> ' + self.file_path)

        except Exception as e:
            print(str(e))
            self.logger.error(str(e))

def handle_task(task, context):
    plugin = GetServices(task, context)
    plugin.handle_task()


""" App initialization module."""
import os
from flask import Flask
from backend import config, exercise, training
from backend.extension import api, socketio, mongo, jwt
from backend.config import Struct

def create_app(configs: Struct = None):
    """
    Create and configure the Flask app
    """
    app = Flask("backend")

    # load configuration
    if not configs:
        configs = os.getenv("CONFIG")
        configs = config.load_config_as_object(additional_config_files=configs)

    app.config.from_object(configs)

    register_extensions(app)
    register_blueprints(app)

    app.logger.info("App ready!!")  # pylint: disable=no-member

    return app

def register_extensions(app):
    """ Initialize App extensions."""
    jwt.init_app(app)
    app.logger.debug("jwt.init_app successfully processed.")

    mongo.init_app(app)
    app.logger.debug("mongo.init_app successfully processed.")

    socketio.init_app(app)
    app.logger.debug("socketio.init_app successfully processed.")

def register_blueprints(app):
    """ Store App APIs blueprints."""
    api.init_app(
        app,
        spec_kwargs={
            "info": {"description": "The `Backend` OpenAPI 3.0 specification."},
            "components": {
                "securitySchemes": {
                    "bearerAuth": {
                        "type": "http",
                        "scheme": "bearer",
                        "bearerFormat": "JWT",
                    }
                }
            },
        },
    )

    # register bluprints
    api.register_blueprint(exercise.blueprint.bp)
    api.register_blueprint(training.blueprint.bp)

if __name__ == "__main__":
    socketio.run(create_app(), debug=True, use_reloader=False)


from pwn import *
from pwnlib.util.packing import p32, u32

# context.terminal = ['tmux','splitw','-h']
# context(os='windows', arch='arm', log_level='debug')

p = remote('comp6447.wtf', 20478)

p.recvuntil(b'{')
number = int(p.recvuntil(b'}', drop=True), 16)

p.sendlineafter(b'form!\n', bytes(str(number), 'utf-8'))
p.sendlineafter(b'0x103!\n', bytes(hex(number - 0x103), 'utf-8'))

p.recvuntil(b'me ')
number = int(p.recvuntil(b' ', drop=True), 16)
p.sendlineafter(b'form!\n', p32(number))

p.recvuntil(b')\n')
address = p.recvline().strip()

p.sendlineafter(b'form!\n', str(u32(address)))
p.sendlineafter(b'form!\n', hex(u32(address)))

p.recvuntil(b'is ')
num1 = int(p.recvuntil(b' +', drop=True))
num2 = int(p.recvuntil(b'?', drop=True))
p.sendlineafter(b'\n', str(num1 + num2))

p.sendlineafter(b'?\n', 'password\n')
# p.sendline('cat flag')

p.interactive()
p.close()


'''
문자열 A가 주어졌을 때 문자열 A에 Run-Length Encoding을 적용한 이후의 결과를 구해보려고 합니다.
Run-Length Encoding이란 간단한 비손실 압축 방식으로, 연속해서 나온 문자와 연속해서 나온 개수로 나타내는 방식입니다.

예를 들어, 문자열 A가 aaabbbbcbb인 경우 순서대로 a가 3번, b가 4번, c가 1번 그리고 b가 2번 나왔으므로 Run-Length Encoding을 적용하게 되면 a3b4c1b2가 됩니다.
문자열 A가 주어졌을 때, Run-Length Encoding을 적용한 이후의 결과를 출력하는 프로그램을 작성해보세요.

입력 형식
첫 번째 줄에 문자열 A가 주어집니다. 문자열 A는 소문자 알파벳으로만 이루어져 있습니다.
1 ≤ 문자열 A의 길이 ≤ 1,000

출력 형식
첫 번째 줄에는 문자열 A에 Run-Length Encoding을 적용한 이후의 길이를 출력합니다.
두 번째 줄에는 문자열 A에 Run-Length Encoding을 적용한 이후의 결과를 출력합니다.

입출력 예제
예제1
입력:
aaabbbbcbb

출력:
8
a3b4c1b2

예제2
입력:
aaaaaaaaaabb

출력:
5
a10b2
'''
arr = [i for i in input().strip()]
ans = []

if len(arr) == 1:
    ans.append(arr[0])
    ans.append(len(arr))

while True:

    compare = arr[0]
    del arr[0]

    if len(arr) == 0:
        break

    cnt = 1

    for i in arr:
        if compare != i:
            ans.append(compare)
            #print(1)
            ans.append(cnt)
            #print(2)
            compare = i
            cnt = 1

        else:
            cnt += 1
            compare = i

    if compare == arr[-1]:
        ans.append(compare)
        #print(3)
        ans.append(cnt)
        #print(4)
        break

length = len(ans)

for k in range(1,len(ans),2):
    if ans[k] >= 10 and ans[k] < 100:
        length += 1

    if ans[k] >= 100 and ans[k] < 1000:
        length += 2

    if ans[k] == 1000:
        length += 2

print(length, "" .join(map(str, ans)), sep="\n")