import os
import json

from Utils.io import loadSingleMrc

from argparse import ArgumentParser

def getMRCData(file_path):
    volumeData, _ = loadSingleMrc(file_path, normalized=False, cache=False)

    data = {
        'file' : '',
        'size' : {
            'x' : volumeData.shape[2],
            'y' : volumeData.shape[1],
            'z' : volumeData.shape[0]
        },
        'ratio' : {
            'x' : 1.0,
            'y' : 1.0,
            'z' : 1.0
        },
        'bytesPerVoxel': 1,
        'usedBits': 8,
        'skipBytes': 0,
        'isLittleEndian': True,
        'isSigned': False,
        'addValue': 0
    }
    return data

def getJSONData(file_path):
    jsonFile = open(file_path)
    jsonData = json.load(jsonFile)

    return jsonData

if __name__=='__main__':
    parser = ArgumentParser('Duplicates JSON description file for new RAW or MRC volume file.')
    parser.add_argument('input_file_path', type=str, help='Input JSON file')
    parser.add_argument('target_file_path', type=str, help='Target RAW file')
    args = parser.parse_args()

    input_path = args.input_file_path
    target_path = args.target_file_path

    input_file = os.path.basename(input_path)
    target_file = os.path.basename(target_path)
    target_dir = os.path.dirname(target_path)

    data = []
    if input_file.lower().endswith(".json"):
        data = getJSONData(input_path)
    elif input_file.lower().endswith(".mrc"):
        data = getMRCData(input_path)

    data["file"] = target_file

    transferFunctionName = ''
    if 'Background' in target_file:
        transferFunctionName = 'tf-Background.json'
    elif 'Spikes' in target_file:
        transferFunctionName = 'tf-Spikes.json'
    elif 'Membrane' in target_file:
        transferFunctionName = 'tf-Membrane.json'
    elif 'Inner' in target_file:
        transferFunctionName = 'tf-Inner.json'
    else:
        transferFunctionName = 'tf-raw.json'
    data['transferFunction'] = transferFunctionName

    target_JSON_file = target_dir + '/' + target_file[0:target_file.rindex('.')] + ".json"

    with open(target_JSON_file, 'w') as f:
        json.dump(data, f, indent=4)


#!/usr/bin/env python
import rospy
import tf

from std_msgs.msg import String
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist, PoseStamped
from actionlib_msgs.msg import GoalStatusArray
from drones_move.srv import *
from move_commands import MoveCommands as MC

import config

class Velocity:

    def __init__(self, linear=[0, 0, 0], angular=[0, 0, 0]):
        self.linear = linear
        self.angular = angular

class ReadyState:
    READY = 'READY'
    BUSY = 'BUSY'

class BotState:
    STATIONARY = 'STATIONARY'
    RPREPARING = 'RPREPARING'
    RSTARTING  = 'RSTARTING'
    ROTATING   = 'ROTATING'
    MOVING     = 'MOVING'

class BotCache:

    def __init__(self):
        self.odom = None
        self.move = None
        self.rstart_pose = None
        self.state = BotState.STATIONARY
        self.velocity = Velocity()
        self.command = MC.STOP

class Publishers:

    def __init__(self, cmdvel=None, movegoal=None, readystate=None):
        self.cmdvel = cmdvel
        self.movegoal = movegoal
        self.readystate = readystate

class Subscribers:

    def __init__(self, subscriptions=[]):
        for s in subscriptions:
            rospy.Subscriber(s[0], s[1], s[2])

class Services:

    def __init__(self, services):
        for s in services:
            rospy.Service(s[0], s[1], s[2])

class TurtlebotMover:

    def __init__(self):
        rospy.init_node(config.bot_mover['name'], anonymous=True)
        self.rate = rospy.Rate(10)
        self.cache = BotCache()
        self.pub = None

    def run(self):
        Subscribers(subscriptions = [ (config.turtlebot['pub']['odom'], Odometry, self.odom_callback )
                                    , (config.move_base['pub']['status'], GoalStatusArray, self.goal_status_callback ) ])
        Services(services = [ (config.bot_mover['srv']['move_bot'], MoveTurtlebot, self.handle_move) ])
        self.pub = Publishers( cmdvel     = rospy.Publisher(config.bot_mover['pub']['cmd_vel'], Twist, queue_size=10)
                             , movegoal   = rospy.Publisher(config.bot_mover['pub']['move_goal'], PoseStamped, queue_size=10)
                             , readystate = rospy.Publisher(config.bot_mover['pub']['ready_state'], String, queue_size=10) )
        self.loop()

    def goal_status_callback(self, data):
        if self.cache.command == MC.MOVETO and self.is_movement_complete(data):
            self.log('I: {0} | {1}'.format(self.cache.state, self.cache.command))
            self.complete_movement()
        else:
            self.log('E: {0} | {1}'.format(self.cache.command, self.is_movement_complete(data)))

    def is_movement_complete(self, data):
        result = False

        if len(data.status_list) == 1:
            if data.status_list[0].status in [2, 3, 4, 5, 8]:
                result = True

        return result

    def complete_movement(self):
        self.cache.command = MC.STOP
        self.cache.state = BotState.STATIONARY

    def handle_move(self, request):
        if request.command == MC.THREE60:
            self.cache.command = MC.THREE60
            self.cache.state = BotState.RPREPARING
        elif request.command == MC.MOVETO:
            self.cache.command = MC.MOVETO
            self.cache.state = BotState.MOVING
            self.publish10(self.pub.movegoal, self.get_pose_stamped(request.pose))
        return MoveTurtlebotResponse('ok')

    def odom_callback(self, data):
        self.cache.odom = data

        if self.cache.state in [BotState.RPREPARING, BotState.RSTARTING, BotState.ROTATING]:
            if self.cache.state == BotState.RPREPARING:
                self.prepare_rotation(data)
            elif self.cache.state == BotState.RSTARTING:
                self.begin_rotation(data)
            elif self.cache.state == BotState.ROTATING:
                self.complete_rotation(data)

    def prepare_rotation(self, data):
        self.cache.rstart_pose = data.pose.pose
        self.cache.state = BotState.RSTARTING

    def begin_rotation(self, data):
        if self.is_rotation_started(data.pose.pose, self.cache.rstart_pose):
            self.cache.state = BotState.ROTATING
        else:
            self.cache.velocity.angular[2] = 0.5

    def complete_rotation(self, data):
        if self.is_rotation_complete(data.pose.pose, self.cache.rstart_pose):
            self.cache.velocity.angular[2] = 0.0
            self.cache.state = BotState.STATIONARY
            self.cache.command = MC.STOP

    def is_rotation_started(self, current, target):
        current_e = tf.transformations.euler_from_quaternion(( current.orientation.x
                                                             , current.orientation.y
                                                             , current.orientation.z
                                                             , current.orientation.w ))
        target_e = tf.transformations.euler_from_quaternion(( target.orientation.x
                                                            , target.orientation.y
                                                            , target.orientation.z
                                                            , target.orientation.w ))
        return False if self.are_angles_almost_equal(current_e[2], target_e[2]) else True

    def is_rotation_complete(self, current, target):
        current_e = tf.transformations.euler_from_quaternion(( current.orientation.x
                                                             , current.orientation.y
                                                             , current.orientation.z
                                                             , current.orientation.w ))
        target_e = tf.transformations.euler_from_quaternion(( target.orientation.x
                                                            , target.orientation.y
                                                            , target.orientation.z
                                                            , target.orientation.w ))
        return True if self.are_angles_almost_equal(current_e[2], target_e[2]) else False

    def are_angles_almost_equal(self, one, two):
        return True if abs(two - one) < 0.005 else False

    def loop(self):
        while not rospy.is_shutdown():
            if self.cache.command == MC.THREE60:
                self.publish( [ (self.pub.cmdvel
                                , self.make_twist( linear  = self.cache.velocity.linear
                                                 , angular = self.cache.velocity.angular )) ] )
            self.publish( [ (self.pub.readystate, self.get_ready_state()) ] )
            self.rate.sleep()

    def get_ready_state(self):
        return ReadyState.READY if self.cache.state == BotState.STATIONARY else ReadyState.BUSY

    def publish(self, actions):
        for a in actions:
            a[0].publish(a[1])

    def publish10(self, publisher, message):
        for i in range(0, 10):
            publisher.publish(message)
            self.rate.sleep()

    def make_twist(self, linear=[0, 0, 0], angular=[0, 0, 0]):
        t = Twist()
        t.linear.x = linear[0]
        t.linear.y = linear[1]
        t.linear.z = linear[2]

        t.angular.x = angular[0]
        t.angular.y = angular[1]
        t.angular.z = angular[2]

        return t

    def log(self, message):
        rospy.loginfo(message)

    def get_pose_stamped(self, pose):
            p = PoseStamped()
            p.header.stamp = rospy.Time.now()
            p.header.frame_id = 'map'
            p.pose = pose
            return p

def main():
    TurtlebotMover().run()

if __name__ == '__main__':
    main()


import os
import numpy as np
import librosa

class FeaturePrep:

    def __init__(self, feature_type, window_size, window_shift, sr, duration, num_features=None, directory = None):
        '''
        Directory == where the extracted features will be saved.
        '''
        self.feature_type = feature_type
        if feature_type == "stft":
            self.num_features = window_size * 8 + 1 #I don't know why the extra 1
        else:
            self.num_features = num_features
        self.window_size = window_size
        self.window_shift = window_shift
        self.sr = sr
        self.duration = duration
        self.directory = directory

    def get_feats(self,wav):
        #set window and shift sizes
        y,sr = librosa.load(wav,sr=self.sr,duration=self.duration)
        n_fft = int(self.window_size*0.001*sr)
        hop_length = int(self.window_shift*0.001*sr)
        if self.feature_type == "stft":
            feats = np.abs(librosa.stft(y,n_fft = n_fft, hop_length = hop_length))
            feats = np.transpose(feats)
            feats -= (np.mean(feats,axis=0)+1e-8)
        #if len(feats) < int(1/((self.window_shift * 0.001)/float(self.duration)))+1:

        return feats

    def create_empty_matrix(self,waves_list):
        self.total_samples = len(waves_list)
        '''
        total number of rows, same for all samples:
        total window (i.e. duration, e.g. 2 seconds)
        feature window (i.e. window_size, e.g. 50 ms)
        feature window overlap (i.e. window_shift, e.g. 25 ms)
        '''
        self.feat_sets_per_wave = int(1/((self.window_shift * 0.001)/float(self.duration)))+1#to be honest, I don't know why I need to add 1.. might not generalize to other data. Works for 25 ms window shift.
        empty_matrix = np.zeros((self.total_samples*self.feat_sets_per_wave,self.num_features+1))
        #+1 for the label
        return empty_matrix

    def fill_matrix(self,matrix, wav,label_int,matrix_index):
        feats = self.get_feats(wav)
        #zero-padding if wave file shorter than desired length
        if len(feats) < self.feat_sets_per_wave:
            diff = self.feat_sets_per_wave - len(feats)
            feats = np.concatenate((feats,np.zeros((diff,feats.shape[1]))))
        for j, samp in enumerate(feats):
            row = np.append(samp,label_int)
            matrix[matrix_index+j] = row
        matrix_index += len(feats)

        return matrix, matrix_index

    def save_feats(self,features_matrix,timestamp):
        print(self.directory)
        if not os.path.exists(self.directory):
            os.makedirs(self.directory)
        np.save("{}/{}{}_feats_{}.npy".format(self.directory,self.feature_type,self.num_features,timestamp),features_matrix)
        return True


import socket
import pickle
from _thread import *
import sys

server = "192.168.1.79"
port = 5555

window_width=1009 #612
window_height=720 #437
shark_x = window_width//2
shark_y = window_height//2

s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)

try:
    s.bind((server, port))
except socket.error as e:
    str(e)

s.listen()
print("Esperando por jogadores...")

#posiçoes dos jogadores
pos = [(0,0), (100,100)]

def client_thread(conn, player):
    conn.send(str.encode(make_pos(pos[player])))
    reply = ""
    while True:
        try:
            data = read_pos(conn.recv(2048).decode())
            pos[player] = data
            if not data:
                print("Desconectado")
                break
            else:
                #nao esquecer de no outro lado fazer split disto como lista de listas
                reply = pos.pop(player)
                print("Recebido: ", reply)
                print("Enviando: ", reply)
            conn.sendall(str.encode(make_pos(reply)))
        except:
            break

#num de jogador
currentPlayer = 0
while True:
    conn, addr = s.accept()
    print("Ligado a: ", addr)
    start_new_thread(client_thread, (conn, currentPlayer))
    currentPlayer += 1


# Ricardo Simines - Tiago Lima Reis - Jhonael Rocha

nomes = ["Júlio","Vitor","Gabriela","Suelem","Ricardo","Tiago"]

def achar_nome(arr):
  nome = (input("Digite o seu nome : ")).title()
  print(nome)
  achou = False

  for i in range(len(arr)):

    if arr[i] == nome:
      achou = True

  if(achou == False):
    print("Nâo achamos o nome " + nome)
  else:
    print("Achamos o nome: " + nome)

achar_nome(nomes)


#coding:utf-8
from os import path
from scipy.misc import imread
import matplotlib.pyplot as plt
import jieba

from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

stopwords = {}
def importStopword(filename=''):
    global stopwords
    f = open(filename, 'r', encoding='utf-8')
    line = f.readline().rstrip()

    while line:
        stopwords.setdefault(line, 0)
        stopwords[line] = 1
        line = f.readline().rstrip()

    f.close()

def processChinese(text):
    seg_generator = jieba.cut(text)  # 使用结巴分词，也可以不使用

    seg_list = [i for i in seg_generator if i not in stopwords]

    seg_list = [i for i in seg_list if i != u' ']

    seg_list = r' '.join(seg_list)

    return seg_list

importStopword(filename='./stopwords.txt')

# 获取当前文件路径
# __file__ 为当前文件, 在ide中运行此行会报错,可改为
# d = path.dirname('.')
d = path.dirname(__file__)

text = open(path.join(d, 'love.txt'),encoding ='utf-8').read()

#如果是中文
text = processChinese(text)#中文不好分词，使用Jieba分词进行

# read the mask / color image
# taken from http://jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-282261010
# 设置背景图片
back_coloring = imread(path.join(d, "./image/love.jpg"))

wc = WordCloud( font_path='./font/叶立群几何体.ttf',#设置字体
                background_color="black", #背景颜色
                max_words=2000,# 词云显示的最大词数
                mask=back_coloring,#设置背景图片
                #max_font_size=100, #字体最大值
                random_state=42,
                )
# 生成词云, 可以用generate输入全部文本(中文不好分词),也可以我们计算好词频后使用generate_from_frequencies函数
wc.generate(text)
# wc.generate_from_frequencies(txt_freq)
# txt_freq例子为[('词a', 100),('词b', 90),('词c', 80)]
# 从背景图片生成颜色值
image_colors = ImageColorGenerator(back_coloring)

plt.figure()
# 以下代码显示图片
plt.imshow(wc)
plt.axis("off")
plt.show()
# 绘制词云
'''plt.figure()

# recolor wordcloud and show
# we could also give color_func=image_colors directly in the constructor
plt.imshow(wc.recolor(color_func=image_colors))
plt.axis("off")

# 绘制背景图片为颜色的图片
plt.figure()
plt.imshow(alice_coloring, cmap=plt.cm.gray)
plt.axis("off")
plt.show()
'''
# 保存图片
wc.to_file(path.join(d, "名称.png"))


import copy
import csv
import subprocess
import numpy as np
from scipy.sparse.csgraph import minimum_spanning_tree
import matplotlib.pyplot as plt

class Graph:

    def __init__(self, points, size):
        self._matrix = np.zeros((size, size))
        self._size = len(points)

        for i, a in enumerate(points):
            for j, b in enumerate(points):
                if self._matrix[i][j] == 0.0:
                    dist = np.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
                    self._matrix[i][j] = dist
                    self._matrix[j][i] = dist

    def size(self):
        return self._size

    def get_distance(self, i, j):
        return self._matrix[i][j]

    def mst(self):
        temp_matrix = self._matrix.copy()

        for i in range(self._size):
            for j in range(self._size):
                if i >= j:
                    temp_matrix[i][j] = 0

        return minimum_spanning_tree(temp_matrix).toarray()

    def remove_node(self, i):
        self._matrix = np.delete(self._matrix, i, 1)
        self._matrix = np.delete(self._matrix, i, 0)
        self._size -= 1

def one_tree(graph):
    short_graph = copy.deepcopy(graph)
    short_graph.remove_node(0)

    cost = np.sum(np.sum(short_graph.mst()))

    min_cost = graph.get_distance(0, 1)
    second_min = min_cost

    for j in range(1, graph.size()):
        dist = graph.get_distance(0, j)
        if dist < min_cost:
            second_min = min_cost
            min_cost = dist

    cost += min_cost + second_min

    return cost

def get_lower_bound(file_name):
    uu = []
    with open(file_name) as file:
        i, spam_reader = 0, csv.reader(file, delimiter=' ')
        _ = next(spam_reader)
        for row in spam_reader:
            if '' in row:
                row.remove('')
            _, x, y = map(float, row)
            uu.append([x, y])
            i += 1

    lb = one_tree(Graph(points=uu, size=len(uu)))

    return lb, 3 * lb / 2

if __name__ == '__main__':

    while True:
        ini = 4
        tt, ss, rr = [], [], []
        for size in range(ini, 1000):

            process = subprocess.Popen(['python3', 'gen_tsp.py', str(size), str(2)])
            process.communicate()

            file_name = 'data_{}.txt'.format(size)

            ot, lb = get_lower_bound(file_name)

            process = subprocess.Popen(['./h_pro', file_name, 'tour_{}.txt'.format(size)], stdout=subprocess.PIPE)
            out, err = process.communicate()
            ds = float(out.decode())

            print(ds / lb, ds, lb)

            print(80 * '-')
            print('SIZE : {}'.format(size))

            tt.append(ds)
            ss.append(lb)
            rr.append(ot)

            plt.figure(figsize=(10, 10))
            plt.title('(3 / 2) 1-Tree (RED)\nH Algorithm Tour Length (BLUE)\n1-Tree (GREEN)\nhttp://twitter.com/maxtuno')
            plt.plot(range(ini, ini + len(ss)), ss, 'r-', label='(3/2) 1-Tree')
            plt.plot(range(ini, ini + len(tt)), tt, 'b-', label='H Algorithm')
            plt.plot(range(ini, ini + len(rr)), rr, 'g-', label='1-Tree')
            plt.savefig('graph.png')
            plt.close()


import os
import svgwrite
from ...Fibaro.Model.tadashiHistory import TadashiHistory
from ...Fibaro.Model.tadashiHistory import Context
from ...Fibaro.Model.room import Place
from .bathroomMapDrawer import BathroomMapDrawer
from .bedroomMapDrawer import BedroomMapDrawer
from .loungeMapDrawer import LoungeMapDrawer
from .outsideMapDrawer import OutsideMapDrawer

class HouseMapper:
    def __init__(self, city):
        self._absolute_path = os.path.abspath(os.path.dirname(__file__))
        self._city = city
        self._tadashi_history = TadashiHistory()
        self._logs = None
        self._context = None
        self._outside_map_drawer = None
        self._lounge_map_drawer = None
        self._bedroom_map_drawer = None
        self._bathroom_map_drawer = None

    def load_tadashi_history(self, input_path=None):
        if not input_path:
            input_path = self._absolute_path + '/../../assets/tmp/tadashi_history.json'
        self._tadashi_history.load(input_path)

    def parse(self):
        self._context = self._tadashi_history.context
        for room in self._tadashi_history.logs:
            if room.place == Place.OUTSIDE:
                self._outside_map_drawer = OutsideMapDrawer(self._city, room)
            elif room.place == Place.LOUNGE:
                self._lounge_map_drawer = LoungeMapDrawer(self._city, room)
            elif room.place == Place.BEDROOM:
                self._bedroom_map_drawer = BedroomMapDrawer(self._city, room)
            elif room.place == Place.BATHROOM:
                self._bathroom_map_drawer = BathroomMapDrawer(self._city, room)

    def draw(self, output_path=None):
        if not output_path:
            output_path = self._absolute_path + '/../../assets/map/test_svg.svg'
        handle = svgwrite.Drawing(output_path, size=("256px", "256px"))

        if self._outside_map_drawer is not None:
            handle = self._outside_map_drawer.draw(handle)

        if self._lounge_map_drawer is not None:
            handle = self._lounge_map_drawer.draw(handle)
            handle = self._lounge_map_drawer.draw_date(handle)

            if self._context is not None and self._context is not Context.UNKNOWN:
                handle = self._lounge_map_drawer.draw_context(handle, self._context.value)

        if self._bedroom_map_drawer is not None:
            handle = self._bedroom_map_drawer.draw(handle)

        if self._bathroom_map_drawer is not None:
            handle = self._bathroom_map_drawer.draw(handle)

        handle.save()


# Ex136
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 1:
            return nums[0]
        nums.sort()
        l = nums
        i = 0
        while i < len(nums):
            #print i, l[i]
            if i == len(nums) -1:
                return l[i]
            if l[i] != l[i+1]:
                return l[i]
            i += 2
        # return reduce(operator.xor, nums)

def singleNumber1(self, nums):
    dic = {}
    for num in nums:
        dic[num] = dic.get(num, 0)+1
    for key, val in dic.items():
        if val == 1:
            return key

def singleNumber2(self, nums):
    res = 0
    for num in nums:
        res ^= num
    return res

def singleNumber3(self, nums):
    return 2*sum(set(nums))-sum(nums)

def singleNumber4(self, nums):
    return reduce(lambda x, y: x ^ y, nums)

def singleNumber(self, nums):
    return reduce(operator.xor, numis)


import requests
from bs4 import BeautifulSoup
from itertools import cycle
import argparse
import io
import math

import pandas as pd
from pandas import DataFrame
from sklearn import linear_model
import statsmodels.api as sm
from sklearn.svm import SVR
import matplotlib.pyplot as plt
import numpy as np
import math
import sys

teamWinsByYear = []
overallTeamStats = []
covTeamStats = []
header = ''

def clean(stng):

    output = ''

    for letter in stng:
        if letter != '[' and letter != ']' and letter != "'": #and letter != ' ':
            output += letter

    return output

def getProxies(inURL):

    page = requests.get(inURL)
    soup = BeautifulSoup(page.text, 'html.parser')
    terms = soup.find_all('tr')
    IPs = []

    for x in range(len(terms)):

        term = str(terms[x])

        if '
' in str(terms[x]):
            pos1 = term.find('d>') + 2
            pos2 = term.find('	')

            pos3 = term.find('	') + 9
            pos4 = term.find('	US<')

            IP = term[pos1:pos2]
            port = term[pos3:pos4]

            if '.' in IP and len(port) < 6:
                IPs.append(IP + ":" + port)
                #print(IP + ":" + port)

    return IPs

proxyURL = "https://www.us-proxy.org/"
pxs = getProxies(proxyURL)
proxyPool = cycle(pxs)

def progress(count, total, status=''):

    bar_len = 60
    filled_len = int(round(bar_len * count / float(total)))

    percents = round(100.0 * count / float(total), 1)
    bar = '=' * filled_len + '-' * (bar_len - filled_len)

    sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', status))
    sys.stdout.flush()

def getTeamNames(year):

    teams = []

    page = requests.get('https://www.basketball-reference.com/leagues/NBA_' + str(year) + '_standings.html', proxies = {"http": next(proxyPool)})
    soup = str(BeautifulSoup(page.text, 'html.parser'))

    for x in range(1, 31):

        indexTo = soup.find('data-stat="ranker" csk="' + str(x) + '"')

        rawTeamStats = soup[indexTo + 80 : indexTo + 500]

        rawTeamSymbol = rawTeamStats[rawTeamStats.find('/teams') + 7 : rawTeamStats.find('/teams') + 15]
        teamSymbol = rawTeamSymbol[0 : rawTeamSymbol.find('/')]

        teamName = rawTeamStats[rawTeamStats.find('>') + 1 : rawTeamStats.find('</')]

        teams.append([teamName, teamSymbol])

    return teams

def generateDataset(year, seasons, datasetName):

    global overallTeamStats
    global covTeamStats
    global header

    overallTeamStats = []
    progressCounter = 0

    for x in range(30):

        yr = year

        for y in range(seasons):

            rawTeams = getTeamNames(yr)
            teams = [sorted(sublist) for sublist in rawTeams]
            teams.sort()

            page = requests.get('https://www.basketball-reference.com/teams/' + teams[x][0] + '/' + str(yr) + '.html', proxies = {"http": next(proxyPool)})
            soup = str(BeautifulSoup(page.text, 'html.parser'))

            teamName = teams[x][1]

            try:

                #Wins
                rawWins = soup[soup.find('data-stat="wins" >') + 15 : soup.find('data-stat="wins" >') + 30]
                wins = float(rawWins[rawWins.find('>') + 1 : rawWins.find('<')])
                #print('Wins', wins)

                #Losses
                rawLosses = soup[soup.find('data-stat="losses" >') + 15 : soup.find('data-stat="losses" >') + 30]
                losses = float(rawLosses[rawLosses.find('>') + 1 : rawLosses.find('<')])
                #print('Losses', losses)

                #Points / Game
                rawPts = soup[soup.find('data-stat="pts_per_g" >') + 15 : soup.find('data-stat="pts_per_g" >') + 30]
                ptsPerGame = float(rawPts[rawPts.find('>') + 1 : rawPts.find('<')])
                #print('Points / Game', ptsPerGame)

                #Offensive Rating
                rawOffRating = soup[soup.find('data-stat="off_rtg" >') + 16 : soup.find('data-stat="off_rtg" >') + 27]
                offRating = float(rawOffRating[rawOffRating.find('>') + 1 : rawOffRating.find('<')])
                #print('Off Rating', offRating)

                #Defensive Rating
                rawDefRating = soup[soup.find('data-stat="def_rtg" >') + 16 : soup.find('data-stat="def_rtg" >') + 27]
                defRating = float(rawDefRating[rawDefRating.find('>') + 1 : rawDefRating.find('<')])
                #print('Def Rating', defRating)

                #Pace
                rawPace = soup[soup.find('data-stat="pace" >') + 16 : soup.find('data-stat="pace" >') + 27]
                pace = float(rawPace[rawPace.find('>') + 1 : rawPace.find('<')])
                #print('Pace', pace)

                #FG%
                rawFgPCT = soup[soup.find('data-stat="fg_pct" >') + 18 : soup.find('data-stat="fg_pct" >') + 25]
                fgPCT = float(rawFgPCT[rawFgPCT.find('>') + 1 : rawFgPCT.find('<')])
                #print('FG%', fgPCT)

                #3P%
                raw3PCT = soup[soup.find('data-stat="fg3_pct" >') + 16 : soup.find('data-stat="fg3_pct" >') + 27]
                fg3PCT = float(raw3PCT[raw3PCT.find('>') + 1 : raw3PCT.find('<')])
                #print('3P%', fg3PCT)

                #FT%
                rawFTPCT = soup[soup.find('data-stat="ft_pct" >') + 16 : soup.find('data-stat="ft_pct" >') + 27]
                ftPCT = float(rawFTPCT[rawFTPCT.find('>') + 1 : rawFTPCT.find('<')])
                #print('FT%', ftPCT)

                #Offensive Rebounds / Game
                rawORB = soup[soup.find('data-stat="orb_per_g" >') + 10 : soup.find('data-stat="orb_per_g" >') + 30]
                orbPerGame = float(rawORB[rawORB.find('>') + 1 : rawORB.find('<')])
                #print('Offensive Rebounds / Game', orbPerGame)

                #Defensive Rebounds / Game
                rawDRB = soup[soup.find('data-stat="drb_per_g" >') + 10 : soup.find('data-stat="drb_per_g" >') + 30]
                drbPerGame = float(rawDRB[rawDRB.find('>') + 1 : rawDRB.find('<')])
                #print('Defensive Rebounds / Game', drbPerGame)

                #Assists / Game
                rawAstPG = soup[soup.find('data-stat="ast_per_g" >') + 15 : soup.find('data-stat="ast_per_g" >') + 30]
                astPerGame = float(rawAstPG[rawAstPG.find('>') + 1 : rawAstPG.find('<')])
                #print('Assists / Game', astPerGame)

                #Steals / Game
                rawStl = soup[soup.find('data-stat="stl_per_g" >') + 15 : soup.find('data-stat="stl_per_g" >') + 30]
                stlPerGame = float(rawStl[rawStl.find('>') + 1 : rawStl.find('<')])
                #print('Steals / Game', stlPerGame)

                #Blocks / Game
                rawBlk = soup[soup.find('data-stat="blk_per_g" >') + 15 : soup.find('data-stat="blk_per_g" >') + 30]
                blkPerGame = float(rawBlk[rawBlk.find('>') + 1 : rawBlk.find('<')])
                #print('Blocks / Game', blkPerGame)

                #Turnovers / Game
                rawTO = soup[soup.find('data-stat="tov_per_g" >') + 15 : soup.find('data-stat="tov_per_g" >') + 30]
                toPerGame = float(rawTO[rawTO.find('>') + 1 : rawTO.find('<')])
                #print('Turnovers / Game', toPerGame)

                #Fouls / Game
                rawF = soup[soup.find('data-stat="pf_per_g" >') + 15 : soup.find('data-stat="pf_per_g" >') + 30]
                foulsPerGame = float(rawF[rawF.find('>') + 1 : rawF.find('<')])
                #print('Fouls / Game', foulsPerGame)

                overallTeamStats.append([teamName, yr, wins, losses, ptsPerGame, offRating, defRating, pace, fgPCT, fg3PCT, ftPCT, orbPerGame, drbPerGame, astPerGame, stlPerGame, blkPerGame, toPerGame, foulsPerGame])
                covTeamStats.append([teamName, yr, wins, losses, ptsPerGame, offRating, defRating, pace, fgPCT, fg3PCT, ftPCT, orbPerGame, drbPerGame, astPerGame, stlPerGame, blkPerGame, toPerGame, foulsPerGame])

            except:

                print('Error', teamName, yr)
                print()

            progress(progressCounter, len(teams) * seasons, status='Loading...')
            progressCounter += 1
            yr -= 1

    print('\nDone!')

    MyFile = open(saveTo + datasetName + '.csv','w')

    header = 'Team Name,Year,Wins,Losses,PPG,Off Rating,Def Rating,Pace,FG%,FG3%,FT%,Off RBG,Def RBG,Assists / Game,Steals / Game,Blocks / Game,Turnovers / Game,Fouls / Game' + '\n'

    MyFile.write(header)

    for row in overallTeamStats:
        MyFile.write(clean(str(row)))
        MyFile.write('\n')

    MyFile.close()

    print('\nSaved as ' + saveTo + datasetName + '.csv')

def applyModel(trainSet, testSet):

    #Load Training Set
    df = pd.read_csv(saveTo + trainSet + '.csv')

    X = df[['PPG', 'Off Rating', 'Def Rating', 'FG%', 'FG3%', 'Def RBG', 'Assists / Game']]
    Y = df['Wins']

    regr = linear_model.LinearRegression()
    regr.fit(X, Y)

    #print('Intercept: \n', regr.intercept_)
    #print('Coefficients: \n', regr.coef_)

    #Predict Team Wins
    testData = pd.read_csv(saveTo + testSet + '.csv')

    predictions = regr.predict(testData[['PPG', 'Off Rating', 'Def Rating', 'FG%', 'FG3%', 'Def RBG', 'Assists / Game']])

    plt.plot(testData['Wins'], label = 'Actual Wins')
    plt.plot(predictions, label = 'Predicted Wins')
    plt.title('NBA Team Win Predictions (' + str(testYear) + '-' + str(testYear - testSeasons + 1) + ' Seasons)')
    plt.legend()
    plt.show()

    teamWins = testData.values.tolist()

    errSum = 0

    print("\n\nTeam Name, Year, Actual Wins, Predicted Wins")

    for x in range(len(testData)):
        print(teamWins[x][0], teamWins[x][1], teamWins[x][2], math.ceil(predictions[x]), 'Error: (' + str(abs(teamWins[x][2] - math.ceil(predictions[x]))) + ')\n')
        errSum += abs(teamWins[x][2] - math.ceil(predictions[x]))

    print('Avg Error', errSum / len(testData))

def findCorrelations():

    global covTeamStats
    global header

    correlations = []
    stat = header[header.find('PPG') : ]
    print()

    for y in range(4, 17):

        wins = []
        stats = []

        for x in range(len(covTeamStats)):

            wins.append(covTeamStats[x][2])
            stats.append(covTeamStats[x][y])
            #print(covTeamStats[x][2], covTeamStats[x][5])

        wins = np.array(wins)
        stats = np.array(stats)
        corre = np.corrcoef(wins, stats)

        correlations.append([stat[0 : stat.find(',')], corre[0][1]])

        print(stat[0 : stat.find(',')])
        print(corre[0][1])
        print()

        stat = stat[stat.find(',') + 1 : ]

    correlations = sorted(correlations,key=lambda l:l[1], reverse=True)

    print(correlations)

saveTo = 'C:\\Users\\faiza\\OneDrive\\Desktop\\NBAData\\' #Change this to the location in which you want to save your files

#Generate Training Set
year = int(input("Enter starting season: "))
seasons = int(input("Enter the number of seasons to gather data from: "))

print('Gathering training data from the ' + str(year) + " - " + str(year - seasons + 1) + " NBA seasons\n")

trainingSet = 'NBAMLTrainingSet' + str(year) + str(seasons) + "Y"

generateDataset(year, seasons, trainingSet)

#findCorrelations()

#Generate Testing Set
testYear = int(input("\nEnter starting season for your testing set: "))
testSeasons = int(input("Enter how many seasons you want to test: "))

print('Gathering testing data from the ' + str(testYear) + " - " + str(testYear - testSeasons + 1) + " NBA seasons\n")

testingSet = "NBAMLTestingSet" + str(testYear) + str(testSeasons) + "Y"

generateDataset(testYear, testSeasons, testingSet)

#Apply Regression Model
applyModel(trainingSet, testingSet)


from __future__ import annotations

from asyncio import create_subprocess_shell
from asyncio.subprocess import PIPE
import json
from typing import Any, Dict, List

from songbird.helpers import ytdl
from songbird.songbird import Metadata

async def get_playlist(playlist: str) -> List[YoutubeVideo]:
    cmd = f"yt-dlp '{playlist}' --flat-playlist --dump-single-json"

    proc = await create_subprocess_shell(cmd, stdout=PIPE, stderr=PIPE)
    stdout, _ = await proc.communicate()

    out: List[YoutubeVideo] = []
    if stdout:
        out.extend(
            YoutubeVideo(entry) for entry in json.loads(stdout)["entries"]
        )

    return out

class YoutubeVideo:
    def __init__(self, video: Dict[str, Any]) -> None:
        self.metadata = Metadata(
            channel=video.get("channel"),
            duration=video.get("duration"),
            source_url=video.get("url"),
            title=video.get("title"),
            thumbnail=video.get("thumbnails", [{"url": None}])[0]["url"]
        )

    def __await__(self):
        return ytdl(self.metadata.source_url).__await__()


from random import choice

def get_file_lines(filename):
    """Returns a list of strings which are the lines of the file passed a the parameter."""

    infile = open(filename, "r")
    file_lines = infile.readlines()

    # this will get rid of \n in every element of the list
    clean_file_lines = []
    for lines in file_lines:
        clean_file_lines.append(lines.strip())

    infile.close()
    return clean_file_lines

def  lines_printed_backwards(lines_list):
    """Prints the list passed as a paramentrs backwards."""

    # .reverse() will reverse the list
    lines_list.reverse()
    # len() will return an integer equaling the length of the list
    lines_list_length = len(lines_list)

    for index in range(lines_list_length):
        line = lines_list[index]
        line_num = lines_list_length - index
        print(f'{line_num} {line}')

def lines_printed_random(lines_list):
    """Prints the the items of the list passes as a parameters randomly."""

    for lines in lines_list:
        print(choice(lines_list))

def lines_printed_custom(lines_list):
    """Prints the poem but in a specific order. The lines with more "e" in it will go first and the ones with less "e" will go last."""

    # this is added because in this specific case we reverse the list already once using lines_printed_backwards() and we want the lines to be sorted with the correct order.
    lines_list.reverse()

    # this are the list that will store the lines with the specific amount of letters e's in it.
    lines_4e = []
    lines_3e = []
    lines_2e = []
    lines_1e = []
    lines_0e = []

    # this loop will go through every item on the poem.
    for line in lines_list:
        amount_letter_e = 0

        #  this loop will go through every character an count of many "e" this line have.
        for character in line:
            if character == "e":
                amount_letter_e += 1

        # depending on the amount of letters e's one of this if elif statement will be run
        if amount_letter_e == 4:
            lines_4e.append(line)

        elif amount_letter_e == 3:
            lines_3e.append(line)

        elif amount_letter_e == 2:
            lines_2e.append(line)

        elif amount_letter_e == 1:
            lines_1e.append(line)

        elif amount_letter_e == 0:
            lines_0e.append(line)

    # print lines that have four e's
    for line in lines_4e:
        print(line)
    # print lines that have three e's
    for line in lines_3e:
        print(line)
    # print lines that have two e's
    for line in lines_2e:
        print(line)
    # print lines that have one e's
    for line in lines_1e:
        print(line)
    # print lines that have zero e's
    for line in lines_0e:
        print(line)

# ------------------------------------------------

woman_works_lines = get_file_lines("Woman Work by Maya Angelou.txt")

print("\nThe original poem:\n")
for line in woman_works_lines:
    print(line)
print("\n\n\n\n")

print("The poem printed backwards:\n")
lines_printed_backwards(woman_works_lines)
print("\n\n\n\n")

print("The peom printed randomly:\n")
lines_printed_random(woman_works_lines)
print("\n\n\n\n")

print("The peom reorginized by the amount of letters e's in each line.\nThe lines with the most e's will go first the one with less go last.\nHere is how it looks like: \n")
lines_printed_custom(woman_works_lines)


import time
from typing import Any, Dict, Optional

import requests

from .exceptions import BirdPlanError

PeeringDBInfo = Dict[str, Any]

# Keep a cache for results returned while loaded into memory
#
# Example:
#  peeringdb_cache = {
#    'objects': {
#        'asn:174': {  # ASN
#            '_timestamp': 0000000000,
#            'value': xxxxxx,
#        }
#    }
#  }
peeringdb_cache: Dict[str, Dict[str, Any]] = {}

PEERINGDB_16BIT_LOWER = 64512
PEERINGDB_16BIT_UPPER = 65534
PEERINGDB_32BIT_LOWER = 4200000000
PEERINGDB_32BIT_UPPER = 4294967294

class PeeringDB:  # pylint: disable=too-few-public-methods
    """PeeringDB support class."""

    def __init__(self) -> None:
        """Initialize object."""

    def get_prefix_limits(self, asn: int) -> PeeringDBInfo:
        """Return our peeringdb info entry, if there is one."""
        # We cannot do lookups on private ASN's
        if (PEERINGDB_16BIT_LOWER <= asn <= PEERINGDB_16BIT_UPPER) or (PEERINGDB_32BIT_LOWER <= asn <= PEERINGDB_32BIT_UPPER):
            return {"info_prefixes4": None, "info_prefixes6": None}

        # Try pull result from our cache
        result = self._cache(f"asn:{asn}")
        # If we can't, grab the result from PeeringDB live
        if not result:
            # Request the PeeringDB info for this AS
            response = requests.get(f"https://www.peeringdb.com/api/net?asn__in={asn}", timeout=10)
            # Check the result is not empty
            if not response:  # pragma: no cover
                raise BirdPlanError("PeeringDB returned and empty result")
            # Decode response
            result = response.json()["data"][0]
            # Cache the result we got
            self._cache(f"asn:{asn}", result)

        # Total cluster .... just to get typing happy
        peeringdb_info = {"info_prefixes4": 1, "info_prefixes6": 1}
        if result and "info_prefixes4" in result:
            peeringdb_info["info_prefixes4"] = result["info_prefixes4"]
        if result and "info_prefixes6" in result:
            peeringdb_info["info_prefixes6"] = result["info_prefixes6"]

        # Lastly return it
        return peeringdb_info

    def _cache(self, obj: str, value: Optional[PeeringDBInfo] = None) -> Optional[Any]:  # noqa: CFQ004
        """Retrieve or store value in cache."""

        if "objects" not in peeringdb_cache:
            peeringdb_cache["objects"] = {}

        if not value:
            # If the cached obj does not exist, return None
            if obj not in peeringdb_cache["objects"]:
                return None
            # Grab the cached object
            cached = peeringdb_cache["objects"][obj]
            # Make sure its timestamp is within 60s of being retrieved, if not, return None
            if cached["_timestamp"] + 60 < time.time():  # pragma: no cover
                return None
            # Else its valid, return the cached value
            return cached["value"]

        # Set the cached value
        peeringdb_cache["objects"][obj] = {
            "_timestamp": time.time(),
            "value": value,
        }

        return value


import matplotlib.pyplot as plt
import numpy,MetaDex,math

compressedtiers = []
tiers = MetaDex.getTiers()
for i in range(0,len(tiers),4):
    compressedtiers.append(tiers[i].split("-")[0])

#compressedtiers=["gen7ou"]

quarters = []
halves = []
thirdquarters =[]

for i in range(len(compressedtiers)):
    plt.figure(i)
    plt.subplot(121)
    plt.title("Usage for "+compressedtiers[i])
    plt.xlabel("Usage")
    plt.ylabel("Frequency")
    plt.axis([-0.05, 0.48, 0, 20])

    plt.subplot(122)
    plt.title("Usage vs. Raw Count for "+compressedtiers[i])
    plt.xlabel("Usage")
    plt.ylabel("Raw Count")

    numbers = ["0","1500","1630","1760"]
    #TODO: interesting...
    if "ou" in compressedtiers[i] and "battlespot" not in compressedtiers[i]:
        numbers = ["0","1500","1695","1825"]
    for n in numbers:
        tier=compressedtiers[i]+"-"+n
        tierfile = tier+".json"
        usageList = []
        rawcountList = []

        data = MetaDex.findTierData(tierfile)
        for poke in MetaDex.findTierData(tierfile):
            usageList.append(data[poke]["usage"])
            rawcountList.append(data[poke]["Raw count"])

        quarterUsage = sorted(usageList)[round(len(usageList)/4)]
        quarters.append(quarterUsage)
        halfUsage = sorted(usageList)[round(len(usageList)/2)]
        halves.append(halfUsage)
        thirdquarterUsage = sorted(usageList)[round(3*len(usageList)/4)]
        thirdquarters.append(thirdquarterUsage)

        usageNP = numpy.array(usageList)

        plt.figure(i)
        plt.subplot(121)
        if n == "0":
            plt.hist(usageNP, 500, color="red",alpha=0.5)
        elif n == "1500":
            plt.hist(usageNP, 500, color="yellow",alpha=0.5)
        elif n in ["1630","1695"]:
            plt.hist(usageNP, 500, color="green",alpha=0.5)
        elif n in ["1760","1825"]:
            plt.hist(usageNP, 500, color="blue",alpha=0.5)
        #plt.plot([quarterUsage, quarterUsage], [0, 20], c="black")
        #plt.plot([halfUsage, halfUsage], [0, 20], c="black")
        #plt.plot([thirdquarterUsage, thirdquarterUsage], [0, 20], c="black")

        plt.subplot(122)
        if n == "0":
            plt.scatter(usageList, rawcountList, s=2,color="red",alpha=0.75)
        elif n == "1500":
            plt.scatter(usageList, rawcountList, s=2,color="yellow",alpha=0.75)
        elif n in ["1630","1695"]:
            plt.scatter(usageList, rawcountList, s=2,color="green",alpha=0.75)
        elif n in ["1760","1825"]:
            plt.scatter(usageList, rawcountList, s=2,color="blue",alpha=0.75)

quarterav = sum(quarters)/len(compressedtiers)
quarterdeviation = 0
for i in quarters:
    quarterdeviation+=(i-quarterav)**2
quarterdeviation = math.sqrt(quarterdeviation/len(compressedtiers))

halfav = sum(halves)/len(compressedtiers)
halfdeviation = 0
for i in halves:
    halfdeviation+=(i-halfav)**2
halfdeviation = math.sqrt(halfdeviation/len(compressedtiers))

thirdquarterav = sum(thirdquarters)/len(compressedtiers)
thirdquarterdeviation = 0
for i in thirdquarters:
    thirdquarterdeviation+=(i-thirdquarterav)**2
thirdquarterdeviation = math.sqrt(thirdquarterdeviation/len(compressedtiers))

#for q in quarters:
#    print("data: %s" % q)
print("Quarter Average: %s" % quarterav)
print("Quarter Standard Deviation: %s" % quarterdeviation)
print()
#for h in halves:
#    print("data: %s" % h)
print("Half Average: %s" % halfav)
print("Half Standard Deviation: %s" % halfdeviation)
print()
#for t in thirdquarters:
#    print("data: %s" % t)
print("Third Quarter Average: %s" % thirdquarterav)
print("Third Quarter Standard Deviation: %s" % thirdquarterdeviation)
plt.show()


class Solution:
    def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:
        topSwaps = 0
        countSame = 0
        for i in range(1, len(tops)):
            if tops[i] == tops[0]:
                countSame += int(tops[i] == bottoms[i])
                continue

            if tops[0] == bottoms[i]:
                topSwaps += 1
            else:
                topSwaps = float("inf")
                break

        topSwaps = min(topSwaps, abs(len(tops) - topSwaps) - countSame)

        bottomSwaps = countSame = 0
        for i in range(1, len(bottoms)):
            if bottoms[i] == bottoms[0]:
                countSame += int(tops[i] == bottoms[i])
                continue

            if bottoms[0] == tops[i]:
                bottomSwaps += 1
            else:
                bottomSwaps = float("inf")
                break

        bottomSwaps = min(bottomSwaps, abs(len(tops) - bottomSwaps) - countSame)
        return min(topSwaps, bottomSwaps) if min(topSwaps, bottomSwaps) != float("inf") else -1


from .errors import TooManyArgumentsError, NotEnoughArgumentsError
from .messages import Messages
from .registry import CommandRegistry

class CommandRegister:
    def register_command(
        self,
        commands: list[str] | tuple[str],
        description: str,
        arguments: list[str] | tuple[str] = (),
        count_arguments: bool = True,
    ):
        arguments = self._prepare_arguments(arguments, count_arguments)
        commands = self._prepare_commands(commands)

        def decorator(func):
            command = CommandRegistry(func, commands, arguments, description)

            command.register()

            def wraper(*args):
                if count_arguments:
                    self._count_arguments(required_args=arguments, provided_args=args)

                func(*args)

            return wraper

        return decorator

    def _count_arguments(self, required_args: list, provided_args: list):
        required_args = len(required_args)

        provided_args = (
            len(provided_args)
            if isinstance(provided_args[0], str)
            else len(provided_args) - 1
        )

        if provided_args > required_args:
            raise TooManyArgumentsError(
                required_args, Messages.TOO_MANY_ARGUMENTS_ERROR
            )

        if provided_args < required_args:
            raise NotEnoughArgumentsError(
                required_args, Messages.NOT_ENOUGH_ARGUMENTS_ERROR
            )

    def _prepare_commands(self, commands: list[str] | tuple[str]) -> tuple:
        self._validate_commands(commands)

        if len(commands) == 1:
            return commands

        return (
            commands
            if len(commands[0]) < len(commands[1])
            else (commands[1], commands[0])
        )

    def _validate_commands(self, commands: list[str] | tuple[str]):
        if not isinstance(commands, tuple) and not isinstance(commands, list):
            raise TypeError(Messages.TYPE_ERROR.format(name_of_arg="commands"))

        if not 0 < len(commands) < 3:
            raise TypeError(Messages.BAD_QUANTITY_OF_COMMANDS_ERROR)

    def _prepare_arguments(
        self, arguments: list[str] | tuple[str], count_arguments: bool
    ) -> list:
        if not count_arguments:
            return [Messages.MULTIPLE_ARGS]

        self._validate_arguments(arguments)

        return [f"<{argument}>" for argument in arguments]

    def _validate_arguments(self, arguments: list[str] | tuple[str]):
        if not isinstance(arguments, tuple) and not isinstance(arguments, list):
            raise TypeError(Messages.TYPE_ERROR.format(name_of_arg="arguments"))


# https://web.dio.me/course/seguranca-da-informacao-com-python/learning/daf1d8ac-bfcd-48a0-bad8-e277a9642c44

import itertools

texto = input('Digite a palavra a ser permutada: ')

resultado = itertools.permutations(texto, len(texto))

for i in resultado:
    print(''.join(i))


'''
Author: Luke Zambella
Date 5/16/20
CSC470 Final Project

Program to compute the cross entropies of training sets against testing sets
This software is hardcoded to only work with the requirements of the project
'''
from TrainingModel import TrainingModel
from TextProcessor import TextProcessor
from math import log2

def __computeCrossEntropy(trainingSet=TrainingModel(), testingSet=TrainingModel()):
    '''
    Compute the cross entropy of a training set agatinst a test set
    Both the training set and testing set are trainingModel objects with only one training classification

    The cross entropy is defined as H(P,Q) = 1/N * SUM(p(x)*log2(q(x_i)), N, i = 1). P is the target distribution (Our trained model) and Q is the approximated distribution (The training set)
    N is the size of the test set, p(x) is the probability of the type in trainingSet and q(x_i) is the probability that the type appears in testingSet. x is the set of types in the test set

    A simpler computation is -1/N * SUM(log2(p_trainingset(W_i)), N, i = 1) where W is the set of types in the test set, N is the count of types in the test set and p_trainingset(W_i) is the probability of W in the training set

    returns the entropy as a float
    '''
    # Get all the types from the test set
    x = testingSet.getTypes()

    # Get probabilities of types for trainingSet
    trainingProbabilities = trainingSet.probabilities
    trainingKeys = list(trainingProbabilities.keys())
    N = len(x)

    # Iterate over all words in the test types and get the probabilities from trainingSet
    log_sum = 0
    for testType in x:
        log_sum += log2(trainingProbabilities[testType])
    entropy = -1 * (1/N) * log_sum
    return float(entropy)

if __name__ == '__main__':
    # Create serparate training models for each directory
    # The models are indexed the the textProcessors training model list in the order the directories are appended
    processor = TextProcessor(['./trainBefore', './trainAfter', './testBefore', './testAfter'])
    # processor = TextProcessor(['./trainBefore', './testBefore'])
    processor.loadArticles()
    # Smooth datasets
    processor.smoothDataset()

    # delist the trainingModels

    models = processor.getTrainingModels()

    # Compute the probabilities (not done automatically)
    '''
    for model in models:
        model.computeProbabilities(smoothing=False, vocabulary=None)
    '''
    # model_trainBefore = models[0]
    # model_testBefore = models[1]
    model_trainBefore = models[0]
    model_trainAfter = models[1]
    model_testBefore = models[2]
    model_testAfter = models[3]

    # Compute the four entropies
    entropy_trainBefore_testBefore = __computeCrossEntropy(trainingSet=model_trainBefore, testingSet=model_testBefore)
    entropy_trainBefore_testAfter = __computeCrossEntropy(trainingSet=model_trainBefore, testingSet=model_testAfter)
    entropy_trainAfter_testBefore = __computeCrossEntropy(trainingSet=model_trainAfter, testingSet=model_testBefore)
    entropy_trainAfter_testAfter = __computeCrossEntropy(trainingSet=model_trainAfter, testingSet=model_testAfter)
    print(f"Entropy of trainBefore-testBefore: {entropy_trainBefore_testBefore}")
    print(f"Entropy of trainBefore-testAfter: {entropy_trainBefore_testAfter}")
    print(f"Entropy of trainAfter-testBefore: {entropy_trainAfter_testBefore}")
    print(f"Entropy of trainAfter-testAfter: {entropy_trainAfter_testAfter}")


'''
Constants for the game
'''

NUMTILES = 12
TILESIZE = 64

WIDTH = NUMTILES * TILESIZE
HEIGHT = 16 * TILESIZE

FRAME = 60
ASSETS = '../assets'
PRIMARY = '#323443'

# DATA = [
#     '            ',
#     '            ',
#     '            ',
#     '   xxxx    x',
#     '  xxx     xx',
#     'xx    xxx xx',
#     'xxx     xxxx',
#     '   xxx      ',
#     '   xxx      ',
#     'x       xxx ',
#     'xx    xxxx  ',
#     'xxxx        ',
#     '  xxx       ',
#     '   p    xx  ',
#     '      xxxx  ',
#     'xxxxxxxxxxxx',
# ]

LEVEL = [
    {
        'background': '../levels/background.csv',
        'ornament': '../levels/ornament.csv',
        'character': '../levels/character.csv',
        'wall': '../levels/wall.csv',
        'bomb': '../levels/bomb.csv',
    }
]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import sys
import urllib.parse
from termcolor import colored

sStandardInput = ""

for x in sys.stdin:
    sStandardInput = sStandardInput + x

#print (sStandardInput)
try:
    json_data = json.loads(sStandardInput)
except:
    pass

for sUrl in json_data["urls"]:
    print (colored("URL = " + sUrl + " (HTTP status "+ str(json_data['urls'][sUrl]['status']) + ")","green"))
#    print (colored("URL = " + sUrl["status"],"green"))

for app in json_data["applications"]:
    if app["version"]:
        sVersion1 = " " + str(app["version"])
        sVersion2 = " \"" + str(app["version"]) + "\""
    else:
        sVersion1 = ""
        sVersion2 = ""

    sExploitdbUrl = "https://www.exploit-db.com/search?q=" + urllib.parse.quote(app["name"])
    sGoogleUrl = "https://www.google.com/search?q=" + urllib.parse.quote("\"" + app["name"] + "\"" + sVersion2 + " cve |exploit |vulnerability |updates |changelog |risk |advisory |cvss")
    print (app["name"] + sVersion1 + " (" + app["confidence"] + "%)")
    print (" - " + app["website"])
    print (" - " + sExploitdbUrl)
    print (" - " + sGoogleUrl)


def selectionSort(alist):
	for i in range(len(alist)):
		max = 0 # Note: will only work for lists with positive numbers
		indx = i
		for j in range(i,len(alist)):
			if alist[j] > max:
				max = alist[j]
				indx = j
		alist[indx], alist[i] = alist[i], alist[indx]
	print(alist)

alist = [3,24,34,2,65,5,54,3,7,6]
selectionSort(alist)

# Decreasing this time, for fun


"""
    Natural Language Processing
"""

import nltk
#nltk.download_shell()
nltk.download("stopwords")

messages = [line.rstrip() for line in open("smsspamcollection/SMSSpamCollection")]

import pandas as pd
messages = pd.read_csv("smsspamcollection/SMSSpamCollection", sep="\t", names=["label","message"])
describe=messages.groupby("label").describe()

#for mess_no, messages in enumerate(messages)
messages["length"] = messages["message"].apply(len)

#import matplotlib.pyplot as plt
#import seaborn as sb
#messages["length"].plot.hist(bins=150)
#plt.show()

#spam ve olmayan mesajların uzunlukı dağılımları.
#messages.hist(column="length", by="label",bins=60,figsize=(12,4))

from nltk.corpus import stopwords as sw
stopwords = sw.words("english")

import string
def text_process(str):
    nopunc = [ch for ch in str if ch not in string.punctuation]
    nopunc = "".join(nopunc)
    ret=  [word for word in nopunc.split() if word.lower() not in stopwords]
    #return ret;
    #print(" ".join(ret))
    return " ".join(ret)

messages["message"] = messages["message"].apply(text_process)

#creatinf bag of words model
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
cv = CountVectorizer()# CountVectorizer(max_features=1500)#☼kolon sayısı
X = cv.fit_transform(messages["message"]).toarray()#matrix. sparse matrix yaptık (o' ı çok olan matrix)
y = messages["label"] == "ham"
y = np.array(y, dtype=int)

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .2, random_state = 0)

def f1_score(cm):
    tp = cm[0][0]
    tn = cm[1][1]
    fp = cm[1][0]
    fn = cm[0][1]

    accuracy = (tp+tn)/(tp+tn+fp+fn)
    precision = tp / (tp+fp)
    recall = tp/(tp+fp)
    score = 2*precision*recall/(precision+recall)
    return (accuracy, score)

from sklearn.metrics import confusion_matrix, classification_report
def test(classifier):
    classifier.fit(X_train, y_train)
    y_pred = classifier.predict(X_test)
    cm = confusion_matrix(y_test, y_pred)
    cr = classification_report(y_test, y_pred)
    return f1_score(cm), cr

from sklearn.naive_bayes import MultinomialNB
f1, cr = test(MultinomialNB())

#başka bir yöntem
#from sklearn.feature_extraction.text import TfidfTransformer
#from sklearn.pipeline import Pipeline
#pipeline = Pipeline([
#        ("bow",CountVectorizer(analyzer=text_process)),
#        ("tfidf", TfidfTransformer()),
#        ("classifier", MultinomialNB())
#        ])
#pipeline.fit(X_train,y_train)
#pred = pipeline.predict(X_test)
#cr_pipeline = classification_report(y_test)


i = 0
a = 0
c = 0
while i!= 2:
    height = int(input("what is your height: "))
    question = input("are you an adult? ")
    if question == "yes" or "Yes":
        a = a +1
    if question == "no":
        if height < 140:
            print("you need support")
            c  = c+ 1
        else:
            print("you can go alone")
            a = a + 1
    i = i + 1


import numpy as np
from gym import utils

from ex2.envs.env_utils import get_asset_xml
from ex2.envs.twod_mjc_env import TwoDEnv

INIT_POS = np.array([0.15,0.15])
TARGET = np.array([0.15, -0.15])
DIST_THRESH = 0.12

class TwoDMaze(TwoDEnv, utils.EzPickle):
    def __init__(self, verbose=False):
        self.verbose = verbose
        utils.EzPickle.__init__(self)
        TwoDEnv.__init__(self, get_asset_xml('twod_maze.xml'), 2, xbounds=[-0.3,0.3], ybounds=[-0.3,0.3])

    def _step(self, a):
        self.do_simulation(a, self.frame_skip)
        ob = self._get_obs()
        pos = ob[0:2]
        if pos[0]>0.0 and pos[1]<-.08:
            dist = np.sum(np.abs(pos-TARGET))
            reward = - (dist) * 5
        else:
            reward = -1

        if self.verbose:
            print(pos, reward)
        done = False
        return ob, reward, done, {}

    def reset_model(self):
        qpos = self.init_qpos + self.np_random.uniform(size=self.model.nq, low=-0.01, high=0.01)
        qvel = self.init_qvel + self.np_random.uniform(size=self.model.nv, low=-0.01, high=0.01)
        self.set_state(qpos, qvel)
        return self._get_obs()

    def _get_obs(self):
        return np.concatenate([self.model.data.qpos]).ravel() - INIT_POS

    def viewer_setup(self):
        v = self.viewer


"""
put the test data evaluation to this file
"""

from __future__ import absolute_import, division, print_function

import random, os, time, shutil, sys, datetime, pickle

import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.utils.data
import torch.utils.data.distributed

import glob
import logging

import time, os, random, json, math
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import transformers
from transformers import (WEIGHTS_NAME, BertConfig, BertModel, BertTokenizer,
                          XLMConfig, XLMModel, XLMTokenizer,
                          XLMRobertaConfig, XLMRobertaModel, XLMRobertaTokenizer)
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler

from model_arch import ModelArch

import imp
config = imp.load_source('config', 'config.py')
args = config.config()

args['output_dir'] = args['output_dir'] + args['distname'] + '/'

print(args)

def seed_all(seed_value):
    random.seed(seed_value)  # Python
    np.random.seed(seed_value)  # cpu vars
    torch.manual_seed(seed_value)  # cpu  vars

    if torch.cuda.is_available():
        torch.cuda.manual_seed(seed_value)
        torch.cuda.manual_seed_all(seed_value)  # gpu vars
        torch.backends.cudnn.deterministic = True  # needed
        torch.backends.cudnn.benchmark = False

MODEL_CLASSES = {
    'bert': (BertConfig, BertModel, BertTokenizer),
    'xlm': (XLMConfig, XLMModel, XLMTokenizer),
    'xlmr': (XLMRobertaConfig, XLMRobertaModel, XLMRobertaTokenizer)
}

# 2. load_data

def load_test(args):
    print(f"  Model will be saved in {args['output_dir']}")
    if not os.path.exists(args['output_dir']):
        os.system('mkdir -p ' + args['output_dir'])
    test_path = args['data_dir'] + "test.cleaned.text.csv"
    # test_path = args['data_dir'] + "/test.hs.clean.csv"
    testdf = pd.read_csv(test_path)
    # testdf = pd.read_csv(test_path, nrows = 1000)
    test_text, test_labels = testdf.comment_text, testdf.label
    return test_text, test_labels

def load_model(args):
    args = args
    model_path = args['model_path']
    config_class, model_class, tokenizer_class = MODEL_CLASSES[args['model_type']]
    # config
    config = config_class.from_pretrained(model_path + 'config.json')
    config.output_hidden_states = False
    # model
    hugg_model = model_class.from_pretrained(model_path, config = config)
    # tokenizer
    tokenizer = tokenizer_class.from_pretrained(model_path)
    model = ModelArch(hugg_model, args)
    return tokenizer, model

def test_data_loader(tokenizer, args):

    test_text, test_labels = load_test(args)

    tokens_test = tokenizer.batch_encode_plus(
        test_text.tolist(),
        max_length = args['max_seq_length'],
        pad_to_max_length=True,
        truncation=True
    )

    test_seq = torch.tensor(tokens_test['input_ids'])
    test_mask = torch.tensor(tokens_test['attention_mask'])
    test_y = torch.tensor(test_labels.tolist())

    test_data = TensorDataset(test_seq, test_mask, test_y)

    return test_data, test_y


# taken from https://matplotlib.org/stable/gallery/widgets/slider_demo.html

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button

# The parametrized function to be plotted

def f(S_w, Lw, Ew, Tw):

    return kOrw*((S_w**Lw)/((S_w**Lw)+Ew*((1-S_w)**Tw)))

#krw = kOrw*((S_w**Lw)/((S_w**Lw)+Ew*((1-S_w)**Tw)))

t = np.linspace(0, 1, 1000)

Swir = 0.1
Sorw = 0.3
kOro = 1
kOrw = 0.6

Sw = np.linspace(Swir, 1-Sorw, 50)

S_w = (Sw - Swir)/(1- Sorw - Swir)

# Define initial parameters

init_Lw = 3
init_Ew = 3
init_Tw = 5

# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()

#ax.plot(Sw, krw, color='b')
#ax.plot(Sw, kro, color='r')

line, = plt.plot(S_w, f(Sw, init_Lw, init_Ew, init_Tw), lw=2)
ax.set_xlabel('Saturation [frac]')

# adjust the main plot to make room for the sliders
plt.subplots_adjust(left=0.25, bottom=0.25)

# Make a horizontal slider to control the frequency.
axLw = plt.axes([0.05, 0.25, 0.0225, 0.63])
Lw_slider = Slider(
    ax=axLw,
    label='L',
    valmin=1,
    valmax=6,
    valinit=init_Lw,
    orientation="vertical"
)
#[0.25, 0.1, 0.65, 0.03],

# Make a vertically oriented slider to control the amplitude
axEw = plt.axes([0.1, 0.25, 0.025, 0.63])
Ew_slider = Slider(
    ax=axEw,
    label="E",
    valmin=1,
    valmax=6,
    valinit=init_Ew,
    orientation="vertical"
)

# Make a vertically oriented slider to control the amplitude
axTw = plt.axes([0.15, 0.25, 0.025, 0.63])
Tw_slider = Slider(
    ax=axTw,
    label="T",
    valmin=1,
    valmax=6,
    valinit=init_Tw,
    orientation="vertical"
)

# The function to be called anytime a slider's value changes
def update(val):
    line.set_ydata(f(S_w, Lw_slider.val, Ew_slider.val, Tw_slider.val))
    fig.canvas.draw_idle()

# register the update function with each slider
Lw_slider.on_changed(update)
Ew_slider.on_changed(update)
Tw_slider.on_changed(update)

# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = plt.axes([0.8, 0.05, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')

def reset(event):
    Lw_slider.reset()
    Ew_slider.reset()
    Tw_slider.reset()
button.on_clicked(reset)

plt.show()


from collections import namedtuple

Algorithm = namedtuple("Algorithm", "name modelname options")

# define your ML algorithm here
analysis = [
Algorithm('NN',
          'DNN_ADAM_leakyReLU_layer256_batch32_GlorotNormalInitializer_l1-0p01_lr0p0001_decay0p0',
          {
          'layers':[256],
          'ncycles':1000,
          'batchSize':32,
          'dropout':0.5,
          'optimizer':'adam',
          'activation':'linear',
          'initializer':'glorot_normal',
          'regularizer':0.01,
          'classWeight':'balanced',
          'learningRate':0.0001,
          'decay':0.0,
          'momentum':0.0,
          'nesterov':False,
          'multiclassification':False
          }
),
Algorithm('BDT',
          'XGBoost_d3_nTrees1000_lr0p1',
          {
           'classifier':'xgboost',
           'learning_rate':0.1,
           'max_depth':3,
           'n_estimators':1000,
           'lambda':1, # Default=1, L2 regularization term on weights (analogous to Ridge regression)
           'alpha':0, # Default=0, L1 regularization term on weight (analogous to Lasso regression)
           'gamma':0, # A node is split only when the resulting split gives a positive reduction in the loss function. Gamma specifies the minimum loss reduction required to make a split.
          'scale_pos_weights':1 # Default=1, A value greater than 0 should be used in case of high class imbalance as it helps in faster convergence.
          }
),
Algorithm('RNN',
          'RNN_jetOnly_ADAM_leakyReLU_LSTM32_128NNlayer_batch32_BatchNorm_GlorotNormalInitializer_l2-0p01_lr0p001_decay0p0',
          {
          'collection':['jet'],
          'removeVar':['_m', '_mv2c10', '_id', '0_pt', '0_eta', '0_phi', '0_e', '1_pt', '1_eta', '1_phi', '1_e'],
          'unit_type':'LSTM',
          'n_units':32,
          'combinedDim':[128],
          'epochs':25,
          'batchSize':32,
          'dropout':0.5,
          'optimizer':'ADAM',
          'activation':'linear',
          'initializer':'glorot_normal',
          'regularizer':0.01,
          'learningRate':0.001,
          'decay':0.0,
          'momentum':0.0,
          'nesterov':False,
          'mergeModels':True,
          'multiclassification':False,
          'classWeight':'balanced'
          }
),
]


#!/usr/bin/env python
"""
Skylineheap.

######################################################################
# @author      : ChatGPT
# @file        : skylineheap
# @created     : Thursday Mar 23, 2023 20:31:21 IST
# @description :
# -*- coding: utf-8 -*-'
######################################################################
"""
import heapq

# pylint: disable=invalid-name
def get_skyline(buildings):
    """
    Solves the Skyline problem using a heap-based algorithm.

    Returns a list of (x, height) tuples representing the skyline.
    """
    skyline = []
    heap = []
    i = 0
    n = len(buildings)

    while i < n or heap:
        if not heap or (i < n and buildings[i][0] <= -heap[0][1]):
            x = buildings[i][0]
            while i < n and buildings[i][0] == x:
                heapq.heappush(heap, (-buildings[i][2], -buildings[i][1]))
                i += 1
        else:
            x = -heap[0][1]
            while heap and -heap[0][1] <= x:
                heapq.heappop(heap)
        height = len(heap) and -heap[0][0]
        if not skyline or height != skyline[-1][1]:
            skyline.append((x, height))

    return skyline

ARR = [
    (1, 5, 11),
    (2, 7, 6),
    (3, 9, 13),
    (12, 16, 7),
    (14, 25, 3),
    (19, 22, 18),
    (23, 29, 13),
    (24, 28, 4),
]
print(get_skyline(ARR))


from abc import ABC, abstractmethod
import nltk
from nltk import sent_tokenize, word_tokenize
from nltk.corpus import stopwords

def bootstrap_nltk() -> None:
    """
    run once to initialize nltk resources

    (developed iteratively)
    """
    import nltk

    nltk.download("punkt")
    nltk.download("stopwords")

class AbsCorpus(ABC):
    @abstractmethod
    def __init__(self, file: str) -> None:
        raise NotImplementedError(
            "Corpus method must implement init method which should init 'file' and 'corpus'"
        )

    @abstractmethod
    def load_corpus(self) -> None:
        raise NotImplementedError("Corpus methods must implement load corpus method")

    @abstractmethod
    def clean_corpus(self) -> None:
        raise NotImplementedError("Corpus methods must implement clean corpus method")

    # @abstractmethod
    # def some_method(self):
    #     raise NotImplementedError("Corpus methods must implement ____ corpus method")

class SimpleCorpus(AbsCorpus):
    def __init__(self, file):
        self.file = file  # for now, a string indicating a full filepath
        self.load_corpus()
        self.clean_corpus()

    def load_corpus(self) -> None:
        self.corpus = ""
        with open(self.file, "rb") as some_txt:
            for line in some_txt.readlines():
                self.corpus = "".join([self.corpus, str(line)])
        self.raw_words = word_tokenize(self.corpus)
        self.sentences = sent_tokenize(self.corpus)

    def clean_corpus(self) -> None:
        sws = stopwords.words("english")
        self.clean_words = []
        no_punc = []
        for w in self.raw_words:
            if w.isalpha():  # only punctuation
                no_punc.append(w.lower())
        for w in no_punc:
            if w not in sws:  # not a stopword
                self.clean_words.append(w)

    def examine_corpus(self):
        print(f"there are {len(self.sentences)} sentences")
        print(f"there are {len(self.clean_words)} words")

        self.fdist = nltk.probability.FreqDist(self.clean_words)
        # print(self.fdist.tabulate())
        for word_count in self.fdist.most_common(250):
            print(word_count)


import logging
from config.global_conf import Global
from analyzer.analyzer import BasicAnalyzer
from trader.market.market import Market
from trader.base_arb_bot import BaseArbBot
from config.shared_mongo_client import SharedMongoClient
from trader.market.trade import Trade, TradeTag, TradeMeta
from trader.market_manager.virtual_market_manager import VirtualMarketManager
from trader.trade_manager.order_watcher_stats import OrderWatcherStats
from trader.market_manager.coinone_market_manager import CoinoneMarketManager
from trader.market_manager.gopax_market_manager import GopaxMarketManager
from trader.market_manager.global_fee_accumulator import GlobalFeeAccumulator
from temp.arbbot_ideas.otimized_tradable_spread import OTSAanlyzer

"""
!!! IMPORTANT NOTE !!!

[NEW Spread] => buy in mm1, sell in mm2
[REV Spread] => buy in mm2, sell in mm1

MODIFY config.global_conf > COIN_FILTER_FOR_BALANCE for balance creation!
"""

class RiskFreeArbBot1(BaseArbBot):
    TARGET_STRATEGY = BasicAnalyzer.buy_sell_strategy_1

    def __init__(self,
                 target_currency: str, target_interval_in_sec: int = 5,
                 should_db_logging: bool = True,
                 is_backtesting: bool = False, start_time: int = None, end_time: int = None):

        # init virtual mm when backtesting
        v_mm1 = VirtualMarketManager(Market.VIRTUAL_CO, 0.001, 4000000, 0.04, target_currency)
        v_mm2 = VirtualMarketManager(Market.VIRTUAL_GP, 0.00075, 400000, 0.4, target_currency)

        super().__init__(v_mm1, v_mm2, target_currency, target_interval_in_sec, should_db_logging,
                         is_backtesting, start_time, end_time)

        self.COIN_TRADING_UNIT = 0.0005
        self.NEW_SPREAD_THRESHOLD = 0
        self.REV_SPREAD_THRESHOLD = 0
        self.MARGIN_KRW_THRESHOLD = 0
        self.SLIPPAGE_HEDGE = 0  # 향후에 거래량을 보고 결정할 parameter, 0.01로 거래한다는 가정하에 0.03으로 설정
        self.REV_FACTOR = 1

        # init mongo related
        self.mm1_data_col = SharedMongoClient.get_coinone_db()[self.target_currency + "_orderbook"]
        self.mm2_data_col = SharedMongoClient.get_gopax_db()[self.target_currency + "_orderbook"]

        self.mm1_buy_coin_trading_unit = self.mm1.calc_actual_coin_need_to_buy(self.COIN_TRADING_UNIT)
        self.mm2_buy_coin_trading_unit = self.mm2.calc_actual_coin_need_to_buy(self.COIN_TRADING_UNIT)

    def run(self):
        # log initial balance
        logging.info("========== [  INITIAL BALANCE  ] ========================================================")
        logging.info(self.mm1.get_balance())
        logging.info(self.mm2.get_balance())

        # if not backtesting
        if not self.is_backtesting:
            while True:
                try:
                    self.execute_trade_loop()
                except Exception as e:
                    Global.send_to_slack_channel("Something happened to StatArbBot! Now it's dying from ... %s" % e)
                    # stop order watcher stats thread
                    OrderWatcherStats.instance().tear_down()
                    raise e
        # if backtesting
        else:
            # collect historical data from db
            logging.info("Collecting historical data, please wait...")
            mm1_data_cursor, mm2_data_cursor = \
                self.get_data_from_db(self.mm1_data_col, self.mm2_data_col,
                                      self.start_time, self.end_time)

            # loop through history data
            for mm1_data, mm2_data in zip(mm1_data_cursor, mm2_data_cursor):
                self.execute_trade_loop(mm1_data, mm2_data)

            # log backtesting result
            self.log_common_stat(log_level=logging.CRITICAL)

    def actual_trade_loop(self, mm1_data=None, mm2_data=None):
        if not self.is_backtesting:
            mm1_data = self.mm1.get_orderbook(self.mm1_currency)
            mm2_data = self.mm2.get_orderbook(self.mm2_currency)
        else:
            self.mm1.apply_history_to_orderbook(mm1_data)
            self.mm2.apply_history_to_orderbook(mm2_data)

        # get current spread
        new_spread, rev_spread, \
        mm1_buy_price, mm1_sell_price, mm2_buy_price, mm2_sell_price, \
        mm1_buy_amount, mm1_sell_amount, mm2_buy_amount, mm2_sell_amount = \
            RiskFreeArbBot1.TARGET_STRATEGY(mm1_data, mm2_data, self.mm1.market_fee, self.mm2.market_fee)

        # log stat
        logging.info("[STAT][%s] buy_price: %d, sell_price: %d" % (self.mm1.get_market_name(),
                                                                   mm1_buy_price, mm1_sell_price))
        logging.info("[STAT][%s] buy_price: %d, sell_price: %d" % (self.mm2.get_market_name(),
                                                                   mm2_buy_price, mm2_sell_price))
        logging.info("[STAT] new_spread: %d, rev_spread: %d" % (new_spread, rev_spread))

        # calculate needed krw
        mm1_buy_krw = self.mm1_buy_coin_trading_unit * mm1_buy_price
        mm2_buy_krw = self.mm2_buy_coin_trading_unit * mm2_buy_price

        # make decision
        if new_spread > self.NEW_SPREAD_THRESHOLD:
            self.new_oppty_counter += 1
            if (
                        self.mm1.has_enough_coin("krw", mm1_buy_krw)
                    and self.mm2.has_enough_coin(self.target_currency, self.COIN_TRADING_UNIT)
            ):
                if (
                                mm1_buy_amount >= self.mm1_buy_coin_trading_unit + self.SLIPPAGE_HEDGE
                        and mm2_sell_amount >= self.COIN_TRADING_UNIT + self.SLIPPAGE_HEDGE
                ):
                    logging.warning("[EXECUTE] New <---- Spread = %.2f / "
                                    "Market amount [mm1 = %.4f, mm2= %.4f]"
                                    % (new_spread, mm1_buy_amount, mm2_sell_amount))
                    buy_order = self.mm1.order_buy(self.mm1_currency, mm1_buy_price, self.mm1_buy_coin_trading_unit)
                    sell_order = self.mm2.order_sell(self.mm2_currency, mm2_sell_price, self.COIN_TRADING_UNIT)
                    self.cur_trade = Trade(TradeTag.NEW, [buy_order, sell_order], TradeMeta({}))
                    self.trade_manager.add_trade(self.cur_trade)
                else:
                    logging.error("[EXECUTE] New -> failed "
                                  "(not enough available amount in market!) "
                                  "<-- Market amount [mm1 = %.4f, mm2= %.4f]" % (mm1_buy_amount, mm2_sell_amount))
            else:
                logging.error("[EXECUTE] New -> failed (not enough balance!)")

        elif rev_spread > self.REV_SPREAD_THRESHOLD:
            self.rev_oppty_counter += 1
            if (
                        self.mm2.has_enough_coin("krw", mm2_buy_krw * self.REV_FACTOR)
                    and self.mm1.has_enough_coin(self.target_currency, self.COIN_TRADING_UNIT * self.REV_FACTOR)
            ):
                if (
                                mm2_buy_amount >= self.mm2_buy_coin_trading_unit * self.REV_FACTOR + self.SLIPPAGE_HEDGE
                        and mm1_sell_amount >= self.COIN_TRADING_UNIT * self.REV_FACTOR + self.SLIPPAGE_HEDGE
                ):
                    logging.warning("[EXECUTE] Reverse <---- Spread = %.2f / "
                                    "Market amount [mm1 = %.4f, mm2= %.4f]"
                                    % (rev_spread, mm1_sell_amount, mm2_buy_amount))
                    buy_order = self.mm2.order_buy(self.mm2_currency, mm2_buy_price,
                                                   self.mm2_buy_coin_trading_unit * self.REV_FACTOR)
                    sell_order = self.mm1.order_sell(self.mm1_currency, mm1_sell_price,
                                                     self.COIN_TRADING_UNIT * self.REV_FACTOR)
                    self.cur_trade = Trade(TradeTag.REV, [buy_order, sell_order], TradeMeta({}))
                    self.trade_manager.add_trade(self.cur_trade)
                else:
                    logging.error("[EXECUTE] Reverse -> failed "
                                  "(not enough available amount in market!) "
                                  "<-- Market amount [mm1 = %.4f, mm2= %.4f]" % (mm1_sell_amount, mm2_buy_amount))
            else:
                logging.error("[EXECUTE] Reverse -> failed (not enough balance!)")

        else:
            logging.info("[EXECUTE] No")

        # if there was any trade
        if self.cur_trade is not None:
            # update & log individual balance
            self.mm1.update_balance()
            self.mm2.update_balance()
            logging.info(self.mm1.get_balance())
            logging.info(self.mm2.get_balance())

            # log combined balance
            combined = BasicAnalyzer.combine_balance(self.mm1.get_balance(), self.mm2.get_balance(),
                                                     (self.target_currency, "krw"))
            for coin_name in combined.keys():
                balance = combined[coin_name]
                logging.info("[TOTAL %s]: available - %.4f, trade_in_use - %.4f, balance - %.4f" %
                             (coin_name, balance["available"], balance["trade_in_use"], balance["balance"]))

"""
<< Explanation about Risk Free Arbitrage Bot2 >>

* Backgrounds
    RFAB1 (Risk Free Arbitrage Bot 1) deals soley with ma[0] and mb[0] of mm1 and mm2 accordingly, restricing
    not too small trading opportunities because of limited quantity of price available at those moments.

* How?
    RFAB2 decides of which combination each trading opportunity would give the best performance by evaluating
    all the variables needed for the profit function (of course, always greater or equal to 0) like price of asks
    and bids, quantity of asks and bids accordingly.
"""

class RiskFreeArbBot2(BaseArbBot):
    TARGET_STRATEGY = OTSAanlyzer.optimized_tradable_spread_strategy
    IS_DATA_EXIST = False

    def __init__(self,
                 target_currency: str, target_interval_in_sec: int = 5,
                 should_db_logging: bool = True,
                 is_backtesting: bool = False, is_init_setting_opt: bool = False,
                 start_time: int = None, end_time: int = None):

        if not is_backtesting:
            mm1 = CoinoneMarketManager()
            mm2 = GopaxMarketManager()
        else:
            mm1 = VirtualMarketManager(Market.VIRTUAL_CO, 0.001, 5000000, 0.5, target_currency)
            mm2 = VirtualMarketManager(Market.VIRTUAL_GP, 0.00075, 500000, 5, target_currency)

        super().__init__(mm1, mm2, target_currency, target_interval_in_sec, should_db_logging,
                         is_backtesting, start_time, end_time)

        self.MAX_COIN_TRADING_UNIT = 1
        self.MIN_COIN_TRADING_UNIT = 0
        self.MAX_OB_INDEX_NUM = 1
        self.NEW_SPREAD_THRESHOLD = 0
        self.REV_SPREAD_THRESHOLD = 0
        self.NEW_FACTOR = 1
        self.REV_FACTOR = 1

        self.mm1_data_cur = None
        self.mm2_data_cur = None
        self.trade_new = 0
        self.trade_rev = 0

        # init mongo related
        self.mm1_data_col = SharedMongoClient.get_coinone_db()[self.target_currency + "_orderbook"]
        self.mm2_data_col = SharedMongoClient.get_gopax_db()[self.target_currency + "_orderbook"]
        self.is_init_setting_opt = is_init_setting_opt

    def run(self):
        # log initial balance
        logging.info("========== [  INITIAL BALANCE  ] ========================================================")
        logging.info(self.mm1.get_balance())
        logging.info(self.mm2.get_balance())

        # if not backtesting
        if not self.is_backtesting:
            while True:
                try:
                    self.execute_trade_loop()
                except Exception as e:
                    Global.send_to_slack_channel("Something happened to StatArbBot! Now it's dying from ... %s" % e)
                    # stop order watcher stats thread
                    OrderWatcherStats.instance().tear_down()
                    raise e
        # if backtesting
        else:
            self.mm1.clear_balance()
            self.mm2.clear_balance()
            self.clear_oppty_counter()
            self.trade_manager.clear_trade_count()

            print(self.trade_new)

            # collect historical data from db
            # If there is no data
            if not RiskFreeArbBot2.IS_DATA_EXIST:
                RiskFreeArbBot2.mm1_data_cur, RiskFreeArbBot2.mm2_data_cur = self.get_data_from_db(
                    self.mm1_data_col, self.mm2_data_col, self.start_time, self.end_time)
                RiskFreeArbBot2.IS_DATA_EXIST = True

            self.mm1_data_cur = RiskFreeArbBot2.mm1_data_cur.clone()
            self.mm2_data_cur = RiskFreeArbBot2.mm2_data_cur.clone()

            # loop through historical data
            for mm1_data, mm2_data in zip(self.mm1_data_cur, self.mm2_data_cur):
                self.execute_trade_loop(mm1_data, mm2_data)

            # log backtesting result
            if not self.is_init_setting_opt:
                self.log_common_stat(log_level=logging.CRITICAL)
            # when initial setting opt
            else:
                self.log_common_stat(log_level=logging.CRITICAL)
                self.total_krw_bal = self.get_krw_total_balance()
                self.trade_new = self.trade_manager.get_trade_count(TradeTag.NEW)
                self.trade_rev = self.trade_manager.get_trade_count(TradeTag.REV)
                last_trade = self.trade_manager.get_last_trade()
                if last_trade:
                    last_trade_dict = last_trade.to_dict()
                    print("last trade")
                    buy_order = last_trade_dict["orders"][0]
                    sell_order = last_trade_dict["orders"][1]
                    print((sell_order.price - buy_order.price) * buy_order.order_amount)

    def actual_trade_loop(self, mm1_data=None, mm2_data=None):
        if not self.is_backtesting:
            mm1_data = self.mm1.get_orderbook(self.mm1_currency)
            mm2_data = self.mm2.get_orderbook(self.mm2_currency)
        else:
            mm1_data = self.mm1.apply_history_to_orderbook(mm1_data)
            mm2_data = self.mm2.apply_history_to_orderbook(mm2_data)

        # get optimized spread infos by using OTS strategy
        (new_spread_in_unit, rev_spread_in_unit, opt_new_spread, opt_rev_spread,
         new_buy_price, new_buy_idx, new_sell_price, new_sell_idx, new_trading_amount,
         rev_buy_price, rev_buy_idx, rev_sell_price, rev_sell_idx, rev_trading_amount,
         new_avail_mm1_qty, new_avail_mm2_qty, rev_avail_mm1_qty, rev_avail_mm2_qty) = \
            RiskFreeArbBot2.TARGET_STRATEGY(mm1_data, mm2_data, self.mm1.market_fee, self.mm2.market_fee,
                                            self.MAX_OB_INDEX_NUM, self.MAX_COIN_TRADING_UNIT)

        # log stat
        logging.info("[STAT][%s] buy_price: %d, sell_price: %d" % (self.mm1.get_market_name(),
                                                                   new_buy_price, new_sell_price))
        logging.info("[STAT][%s] buy_price: %d, sell_price: %d" % (self.mm2.get_market_name(),
                                                                   rev_buy_price, rev_sell_price))
        logging.info("[STAT] new_spread: %d, rev_spread: %d" % (opt_new_spread, opt_rev_spread))

        # calculate needed krw
        mm1_buy_krw = new_trading_amount / (1 - self.mm1.market_fee) * new_buy_price
        mm2_buy_krw = rev_trading_amount / (1 - self.mm2.market_fee) * rev_buy_price

        # make decision
        if new_spread_in_unit > 0:
            self.new_oppty_counter += 1
            if opt_new_spread >= self.NEW_SPREAD_THRESHOLD and not opt_new_spread == 0 \
                    and new_trading_amount >= self.MIN_COIN_TRADING_UNIT:
                fee, should_fee = BasicAnalyzer.get_fee_consideration(self.mm1.get_market_tag(), self.target_currency)
                new_trading_amount = new_trading_amount + fee if should_fee else new_trading_amount
                if (
                            self.mm1.has_enough_coin("krw", mm1_buy_krw * self.NEW_FACTOR)
                        and self.mm2.has_enough_coin(self.target_currency, new_trading_amount * self.NEW_FACTOR)
                ):
                    logging.warning("[EXECUTE] New ->"
                                    "Trading INFOS: Spread in unit = %.2f, BUY_index = %d, "
                                    "SELL_index = %d, T_Spread = %.2f, T_QTY = %.5f, mkt_QTY = [mm1: %.5f, mm2: %.5f] "
                                    % (new_spread_in_unit, new_buy_idx, new_sell_idx,
                                       opt_new_spread, new_trading_amount, new_avail_mm1_qty, new_avail_mm2_qty))
                    buy_order = self.mm1.order_buy(self.mm1_currency, new_buy_price, new_trading_amount)
                    sell_order = self.mm2.order_sell(self.mm2_currency, new_sell_price, new_trading_amount)
                    self.cur_trade = Trade(TradeTag.NEW, [buy_order, sell_order], TradeMeta({}))
                    self.trade_manager.add_trade(self.cur_trade)

                    # subtract considered fee if there was one
                    if should_fee:
                        GlobalFeeAccumulator.sub_fee_consideration(self.mm1.get_market_tag(), self.target_currency, fee)

                else:
                    logging.error("[EXECUTE] New -> failed (not enough balance!) ->"
                                  "Trading INFOS: Spread in unit = %.2f, Psb Traded Spread = %.2f, MKT avail QTY = %.5f"
                                  % (new_spread_in_unit, opt_new_spread, new_trading_amount))
        if rev_spread_in_unit > 0:
            self.rev_oppty_counter += 1
            if opt_rev_spread >= self.REV_SPREAD_THRESHOLD and not opt_rev_spread == 0 \
                    and rev_trading_amount >= self.MIN_COIN_TRADING_UNIT:
                fee, should_fee = BasicAnalyzer.get_fee_consideration(self.mm2.get_market_tag(), self.target_currency)
                rev_trading_amount = rev_trading_amount + fee if should_fee else rev_trading_amount
                if (
                            self.mm2.has_enough_coin("krw", mm2_buy_krw * self.REV_FACTOR)
                        and self.mm1.has_enough_coin(self.target_currency, rev_trading_amount * self.REV_FACTOR)
                ):
                    logging.warning("[EXECUTE] Reverse ->"
                                    "Trading INFOS: Spread = %.2f, BUY_index = %d, "
                                    "SELL_index = %d, T_Spread = %.2f, T_QTY = %.5f, mkt_QTY = [mm1: %.5f, mm2: %.5f]"
                                    % (rev_spread_in_unit, rev_buy_idx, rev_sell_idx,
                                       opt_rev_spread, rev_trading_amount, rev_avail_mm1_qty, rev_avail_mm2_qty))
                    buy_order = self.mm2.order_buy(self.mm2_currency, rev_buy_price, rev_trading_amount)
                    sell_order = self.mm1.order_sell(self.mm1_currency, rev_sell_price, rev_trading_amount)
                    self.cur_trade = Trade(TradeTag.REV, [buy_order, sell_order], TradeMeta({}))
                    self.trade_manager.add_trade(self.cur_trade)

                    # subtract considered fee if there was one
                    if should_fee:
                        GlobalFeeAccumulator.sub_fee_consideration(self.mm2.get_market_tag(), self.target_currency, fee)
                else:
                    logging.error("[EXECUTE] Reverse -> failed (not enough balance!) ->"
                                  "Trading INFOS: Spread in unit = %.2f, Psb Traded Spread = %.2f, MKT avail QTY = %.5f"
                                  % (rev_spread_in_unit, opt_rev_spread, rev_trading_amount))
        else:
            logging.info("[EXECUTE] No")

        # if there was any trade

        if self.cur_trade is not None:
            # update & log individual balance
            self.mm1.update_balance()
            self.mm2.update_balance()
            logging.info(self.mm1.get_balance())
            logging.info(self.mm2.get_balance())

            # log combined balance
            combined = BasicAnalyzer.combine_balance(self.mm1.get_balance(), self.mm2.get_balance(),
                                                     (self.target_currency, "krw"))
            for coin_name in combined.keys():
                balance = combined[coin_name]
                logging.info("[TOTAL %s]: available - %.4f, trade_in_use - %.4f, balance - %.4f" %
                             (coin_name, balance["available"], balance["trade_in_use"], balance["balance"]))

        if not self.is_backtesting:
            self.log_order_watcher_stats()


import sys

input = lambda: sys.stdin.readline().rstrip()

def back_tracking(k, word_letters, learned_ch, index, length):
    if length == k - 5:
        count = 0  # 배울 수 있는 단어 개수
        for word in word_letters:
            flag = True
            for ch in word:
                if not learned_ch[ord(ch) - ord('a')]:
                    flag = False
                    break

            if flag:
                count += 1
        return count

    result = 0
    for i in range(index, 26):
        if not learned_ch[i]:
            learned_ch[i] = True
            new_result = back_tracking(k, word_letters, learned_ch, i, length + 1)
            result = max(result, new_result)
            learned_ch[i] = False

    return result

def solution(n, k, word_letters):
    if k < 5:
        return 0
    if k == 26:
        return n

    learned_ch = [False for _ in range(26)]
    for ch in "antic":
        learned_ch[ord(ch) - ord('a')] = True

    return back_tracking(k, word_letters, learned_ch, 0, 0)

if __name__ == "__main__":
    n, k = map(int, input().split())
    word_letters = [set(input()) for _ in range(n)]

    print(solution(n, k, word_letters))

assert (solution(3, 6, ["antarctica", "antahellotica", "antacartica"]) == 2)
assert (solution(2, 3, ["antaxxxxxxxtica", "antarctica"]) == 0)
assert (solution(9, 8, ["antabtica", "antaxtica", "antadtica", "antaetica", "antaftica",
                        "antagtica", "antahtica", "antajtica", "antaktica"]) == 3)


import urllib.request
import sys
import time
import termcolor
import colorama

import os
colorama.init()
def get_filename(url):
    return url.split("/")[-1]

if len(sys.argv) != 2:
    print("usage:   wget filename")
else:
    url =sys.argv[1]
    filname = get_filename(url)
    data = None
    start = time.time()
    try:
        while data==None or data.length == None:
            print("[+] Conecting with server.... ",end="\r",flush=True)
            data=urllib.request.urlopen(url)
            end = time.time()
            if end-start >20:
                termcolor.cprint("[-] Connection time out 400")
                sys.exit(1)
    except Exception as msg:
        print(msg)
        sys.exit(1)
    termcolor.cprint("[+] Contected with server\n",end="\r",color="green")
    total_length = data.length
    block = 512
    filesize = 0
    with open(filname,"wb") as fh:
        while True:
            buffer = data.read(block)
            # print(buffer)
            if not buffer:
                break
            filesize += len(buffer)
            fh.write(buffer)
            percent = filesize*100/total_length
            termcolor.cprint("Downloading.....   %.2f percent "%percent,end='\r',color="blue", flush=True)
        fh.close()


import numpy as np
import matplotlib.pyplot as plt

# -3.14 ~ 3.14 까지 256개의 값으로 표시해라.
x = np.linspace(-np.pi, np.pi, 256, endpoint=True) #256개 값
print(x.shape)

c = np.cos(x) # 256개 값
s = np.sin(x) # 256개 값

plt.plot(x, c)
plt.plot(x, s)
plt.show()


import sys
from pathlib import Path

ROOT = Path(__file__).parent.parent.parent
sys.path.append(ROOT.as_posix())

import cv2
import lpips
import numpy as np
import pyiqa
import torch
from pytorch_msssim import ms_ssim, ssim
from skimage import feature

from src.tampering.utils import numpy2torch

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
cw_ssim = pyiqa.create_metric("cw_ssim", device=device, as_loss=False)

class LpipsLossSingleton:
    _instance = None

    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            cls._instance = lpips.LPIPS(net="alex").to(device)
        return cls._instance

def compute_lpips(im1: np.ndarray, im2: np.ndarray):
    lpips_loss = LpipsLossSingleton.get_instance()
    res = (
        lpips_loss(
            numpy2torch(im1).int(),
            numpy2torch(im2).int(),
        )
        .squeeze()
        .detach()
        .cpu()
        .numpy()
    )
    return float(res)

def compute_msssim(im1: np.ndarray, im2: np.ndarray):
    res = ms_ssim(
        numpy2torch(im1), numpy2torch(im2), data_range=255, size_average=False
    )
    res = res.squeeze().detach().cpu().numpy()
    return float(res)

def compute_cwssim(im1: np.ndarray, im2: np.ndarray):
    res = cw_ssim(numpy2torch(im1 / 255), numpy2torch(im2 / 255))
    res = res.squeeze().detach().cpu().numpy()
    return float(res)

def compute_ssim(im1: np.ndarray, im2: np.ndarray):
    res = ssim(numpy2torch(im1), numpy2torch(im2), data_range=255, size_average=False)
    res = res.squeeze().detach().cpu().numpy()
    return float(res)

def compute_hog(im1: np.ndarray, im2: np.ndarray):
    im1 = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY).astype(np.uint8)
    im2 = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY).astype(np.uint8)

    # Define the parameters for HOG
    orientations = 9
    pixels_per_cell = (8, 8)
    cells_per_block = (2, 2)

    # Compute HOG features
    hog_features1 = feature.hog(
        im1,
        orientations=orientations,
        pixels_per_cell=pixels_per_cell,
        cells_per_block=cells_per_block,
        transform_sqrt=True,
        block_norm="L1",
    )

    hog_features2 = feature.hog(
        im2,
        orientations=orientations,
        pixels_per_cell=pixels_per_cell,
        cells_per_block=cells_per_block,
        transform_sqrt=True,
        block_norm="L1",
    )

    res = np.linalg.norm(hog_features1 - hog_features2)
    return res

def compute_mse(im1: np.ndarray, im2: np.ndarray):
    return np.mean((im1 / 255 - im2 / 255) ** 2)

def compute_mae(im1: np.ndarray, im2: np.ndarray):
    return np.mean(np.abs(im1 / 255 - im2 / 255))

def compute_sift(im1: np.ndarray, im2: np.ndarray):
    im1 = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY).astype(np.uint8)
    im2 = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY).astype(np.uint8)

    # Initialize SIFT detector
    sift = cv2.xfeatures2d.SIFT_create()

    # Detect keypoints and compute descriptors for both images
    keypoints1, descriptors1 = sift.detectAndCompute(im1, None)
    keypoints2, descriptors2 = sift.detectAndCompute(im2, None)

    # Create a brute-force matcher
    bf = cv2.BFMatcher()

    try:
        # Match the descriptors
        matches = bf.match(descriptors1, descriptors2)

        # Sort the matches by distance
        matches = sorted(matches, key=lambda x: x.distance)

        # Compute the similarity score as the average distance of the matches
        similarity_score = sum([match.distance for match in matches]) / len(matches)
    except:
        similarity_score = 0

    return similarity_score


# Three Cup Monte Game
#we are importing the randome for getting random suffel list elements.
import random

#creating a list to use in the whole game.
mylist=["","O",""]

#creating a function for checking the prediction of player is true or false.
def game(nameOfList):
     guss=int(input("chose between 0 , 1 and 2: "))

    #we are using to check the the number choosen by the user is in between 0 to 2.
     while guss not in [0,1,2]:
          guss=int(input("chose between 0 , 1 and 2:"))
     random.shuffle(mylist)
     print(mylist)
     if mylist[guss]=="O":
          print(mylist)
          print("you won ")
          end_count()
          #calling end_count() function

     else:
          print("you loss")
          end_count()
          #calling end_count () function

 #creating a function for checking that player want to play the game or want to exit
def end_count():
     end_con=int(input("enter 1 to play again and 0 to exit: "))
     while end_con not in [0,1]:
          end_con=int(input("enter 1 to play again and 0 to exit: "))
     if end_con==0:
          pritn("Thanks For Playing Now You'r exit")
     else:
          print("you decided to continue playing game" )
          game(mylist)

game(mylist)