import numpy as np
from abacusnbody.data.compaso_halo_catalog import CompaSOHaloCatalog
import os

f_ijk2ind = lambda i,j,k,Nmesh: i*Nmesh**2 + j*Nmesh + k

def f_ind2ijk(ind, Nmesh):
    i = int(ind/Nmesh**2)
    j = int((ind - i*Nmesh**2)/Nmesh)
    k = ind - i*Nmesh**2 - j*Nmesh
    return i,j,k

def get_ic_path(sim):
    ic_path = '/mnt/marvin2/'
    if not os.path.exists(ic_path):
        ic_path = '/mnt/store2/'
    ic_path += 'xwu/AbacusSummit/'
    N = 1152
    if 'small' in sim:
        if 'small/' not in sim:
            sim = 'small/'+sim
        N = 576
    return ic_path + '/%s/ic_%d/' % (sim, N)

def load_particle_data(islab, sim, z, Rf, qname):
    _path = '/mnt/marvin2'
    if not os.path.exists(_path):
        _path = '/mnt/store2'

    if 'small' in sim:
        if 'small/' not in sim:
            sim = 'small/'+sim

    if qname == 'pos': # position
        cat_path = _path+'/bigsims/AbacusSummit/%s/halos/z%.3f/halo_info/halo_info_%03d.asdf' % (sim,z,islab)
        cat1 = CompaSOHaloCatalog(cat_path, fields=[], load_subsamples='A_field_rv')
        cat2 = CompaSOHaloCatalog(cat_path, fields=[], load_subsamples='A_halo_rv')
        q = np.concatenate((cat1.subsamples['pos'], cat2.subsamples['pos']))
        del cat1, cat2
    elif qname == 'delta1': # delta1
        with np.load(_path+'/xwu/AbacusSummit/%s/z%s_tilde_operators_nbody/Rf%.3g/slab%d_sdelta1.npz'
                     % (sim,str(z),Rf,islab)) as tmp:
            q = np.concatenate((tmp['field'], tmp['halo']))
    elif qname in ['nabla2d1', 'G2']: # nabla2d1 or G2
        with np.load(_path+'/xwu/AbacusSummit/%s/z%s_tilde_operators_nbody/Rf%.3g/slab%d_%s.npz'
                     % (sim,str(z),Rf,islab,qname)) as tmp:
            q = np.concatenate((tmp['field'], tmp['halo']))
    else:
        print(qname, 'not recognized')
        return
    return q

def load_particle_features(sim, z, islab, Rfs, qs):
    '''
    Rfs is a list of Rf values, and qs is a list of quantities to be used.
      e.g. Rfs = [3, 4], qs = ['dnG', 'dnG'], where d, n, G stand for delta1, nabla2d1, G2.
    '''
    # load in particle position
    pos = load_particle_data(islab, sim, z, None, 'pos')

    # load in features
    n_inputs = 0
    for i in qs:
        n_inputs += len(i)

    features = np.zeros((n_inputs, len(pos)), dtype=np.float32)
    n = 0
    ic_path = get_ic_path(sim)
    for i in range(len(Rfs)):
        Rf = Rfs[i]
        for q in qs[i]:
            if q == 'd':
                features[n] = load_particle_data(islab, sim, z, Rf, 'delta1')/\
                    np.std(np.load(ic_path+'/sdelta1_Rf%.3g.npy' % Rf).astype(np.float64))
            elif q == 'n':
                features[n] = load_particle_data(islab, sim, z, Rf, 'nabla2d1')/\
                    np.std(np.load(ic_path+'/nabla2d1_Rf%.3g.npy' % Rf).astype(np.float64))
            elif q == 'G':
                tmp = np.load(ic_path+'/G2_Rf%.3g.npy' % Rf).astype(np.float64)
                features[n] = (load_particle_data(islab, sim, z, Rf, 'G2') -\
                    np.mean(tmp))/np.std(tmp)
            n += 1

    return pos, features

def decorrelate_features(features, Rfs, qs, eigvecs=None, eigvals=None):
    '''
    Move into a feature space where the delta, nabla, G2's are decorrelated.
    '''
    if eigvecs is None:
        eigvecs = np.zeros((len(features), len(features)))
        eigvals = np.zeros(len(features))
        # determine which ones are G2
        ii = np.zeros(len(eigvals), dtype=bool)
        n = 0
        for i in range(len(Rfs)):
            for q in qs[i]:
                if q == 'G':
                    ii[n] = True
                n += 1
        # calculate covariance matrix for the G2's
        n_G2 = ii.sum()
        if n_G2 > 0:
            covmat = features[ii].astype(np.float64).dot(features[ii].T)/(features.shape[1]-1.)
            # eigvals and eigvecs
            eigvals_, eigvecs_ = np.linalg.eigh(covmat)
            eigvals[:n_G2] = eigvals_
            eigvecs[:,:n_G2][ii] = eigvecs_
        # now the delta's and nabla's
        covmat = features[~ii].astype(np.float64).dot(features[~ii].T)/(features.shape[1]-1.)
        # eigvals and eigvecs
        eigvals_, eigvecs_ = np.linalg.eigh(covmat)
        eigvals[n_G2:] = eigvals_
        eigvecs[:,n_G2:][~ii] = eigvecs_
        # try:
        #     covmat = features.astype(np.float64).dot(features.T)/(features.shape[1]-1.)
        # except: # out of memory
        #     covmat = np.zeros((features.shape[0], features.shape[0]), dtype=np.float64)
        #     for i in range(features.shape[0]):
        #         for j in range(features.shape[0]):
        #             covmat[i,j] = features[i].astype(np.float64).dot(features[j])/(features.shape[1]-1.)
        # eigvals, eigvecs = np.linalg.eigh(covmat)
    features_new = eigvecs.T.dot(features)
    # normalize before return; mean should already be 0
    return eigvals, eigvecs, (features_new/(eigvals**0.5).reshape(-1,1)).astype(np.float32)

def choose_decorrelated_features(eigvals, Rfs, qs):
    '''
    The input features array should be decorrelated and normalized to std=1.
    Choose the first n+1 decorrelated delta and nabla's (largest eigvalues),
      where n is the number of smoothing scales.
    Keep all G2's.
    '''
    # determine which ones are G2
    ii = np.zeros(len(eigvals), dtype=bool)
    n = 0
    for i in range(len(Rfs)):
        for q in qs[i]:
            if q == 'G':
                n += 1
    # keep all G2's, but only keep the first n+1 delta and nabla
    ii[:n] = True
    ii[(n+np.argsort(eigvals[n:]))[-(len(Rfs)+1):]] = True
    return ii


from django.db.models import Q
from django.db.models.signals import post_save, m2m_changed, post_delete
from django.dispatch import receiver

from namastenepal.chat_messages.models import ChatUsersGroup, Message
from namastenepal.core.models import User
from .models import (
    CelebVerification,
    AuditLogs,
    Friend,
    BlockedUser,
    FriendRequest,
    Profile,
)
from ..common import get_exact_match

@receiver(post_save, sender=User)
def create_user_profile(**kwargs):
    instance = kwargs.pop("instance")
    created = kwargs.pop("created")

    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(**kwargs):
    instance = kwargs.pop("instance")

    instance.profile.save()

@receiver(post_save, sender=Friend)
def add_versa_friend(**kwargs):
    instance = kwargs.pop("instance", None)
    created = kwargs.pop("created", None)

    if created:
        Friend.objects.get_or_create(
            from_user=instance.to_user, to_user=instance.from_user
        )

@receiver(post_delete, sender=Friend)
def clear_friend_traces(**kwargs):
    instance = kwargs.pop("instance", None)

    user1 = instance.from_user
    user2 = instance.to_user

    Friend.objects.filter(
        Q(from_user=user1, to_user=user2) | Q(from_user=user2, to_user=user1)
    ).delete()
    FriendRequest.objects.filter(
        Q(from_user=user1, to_user=user2) | Q(from_user=user2, to_user=user1)
    ).delete()
    # Message.objects.filter(
    #     Q(author=user1, message_to=user2) | Q(author=user2, message_to=user1)
    # ).delete()
    # RecentChat.objects.filter(
    #     Q(author=user2, message_to=user1) | Q(author=user1, message_to=user2)
    # ).delete()
    # ChatUsersGroup.objects.annotate(
    #     participants_ids=SubqueryAggregate("participants__id", Aggregate=ArrayAgg)
    # ).filter(
    #     participants_ids=Array(user1.id, user2.id)
    #     # Q(user1=user2, user2=user1) | Q(user1=user1, user2=user2)
    # ).delete()
    group = get_exact_match(ChatUsersGroup, "participants", [user1.id, user2.id])
    Message.objects.filter(group__in=group).delete()
    group.delete()

@receiver(post_save, sender=FriendRequest)
def accept_friend_request(**kwargs):
    instance = kwargs.pop("instance", None)
    created = kwargs.pop("created", None)

    if not created and instance.accepted:
        Friend.objects.filter(
            Q(from_user=instance.from_user, to_user=instance.to_user)
            | Q(from_user=instance.to_user, to_user=instance.from_user)
        ).get_or_create(
            defaults={"from_user": instance.from_user, "to_user": instance.to_user}
        )

@receiver(m2m_changed, sender=BlockedUser.blocked_users.through)
def unfriend_after_block(**kwargs):
    instance = kwargs.pop("instance", None)
    action = kwargs.pop("action", None)
    pk_set = kwargs.pop("pk_set", None)

    if action == "post_add":
        for f_id in pk_set:
            Friend.objects.filter(
                Q(from_user__pk=instance.user.pk, to_user__pk=f_id)
                | Q(from_user__pk=f_id, to_user__pk=instance.user.pk)
            ).delete()

@receiver(post_save, sender=CelebVerification)
def respond_user_verification_request(**kwargs):
    sender = kwargs.pop("sender", None)
    instance = kwargs.pop("instance", None)
    created = kwargs.pop("created", None)

    task = AuditLogs.objects.create(user=instance.user)

    if created:
        task.action = f"requested to be verified as {instance.category_verbose}"
    else:
        if instance.status_verbose == "Accepted":
            sender.category = instance.category
        task.action = f"requested to be verified as {instance.category_verbose}, which was {instance.status_verbose}"
        CelebVerification.objects.filter(user=instance.user).delete()

    task.save()


import json
import sys
import os

def get_config():
    config = {}
    with open("config.json") as conffile:
        config = json.loads(conffile.read())

    for item in (item for item in sys.argv if len(item) > 0 and item[0] == "-"):
        if "=" in item:
            groups = re.match('^(.+)=(.+)$', item[1:]).groups()
            try:
                config[groups[0]] = int(groups[1])
            except:
                config[groups[0]] = groups[1]
        else:
            config[item[1:]] = True

    if os.getuid() != 0 and config.get('escalate'):
        os.execv('/usr/bin/sudo',
                    ['/usr/bin/sudo', '/usr/bin/env', 'python', sys.argv[0]])
    return config


#!/usr/bin/env python
# coding: utf-8

# IMPORTS
import random
import os
import math
import time

#clears the screen
os.system("cls")

#defines the amount of players
global amount_players

print("Welcome to Fernito's Blackjack\n")

#before anything, we ask how many players will be playing

#check for errors in input
error_check = True

while error_check:
    try:
        amount_players = int(input("How many players will be playing (1 to 4)? "))

    except:
        print("That's not a valid number!")
        continue

    else:
        if amount_players not in [1,2,3,4]:
            print("That's not a valid number!")
        else:
            error_check = False

class Deck:

    def __init__(self):
        #we prepare the deck here

        deck_suits = ["♣","♠","♥","♦"]
        deck_numbers = ["A",2,3,4,5,6,7,8,9,"X","J","Q","K"]
        deck_prep = []

        for i in deck_suits:
            for j in deck_numbers:
                #1 copy of each card per player
                for k in range(amount_players):
                    deck_prep.append([i,j])

        #the deck gets shuffled!

        random.shuffle(deck_prep)

        self.cards = deck_prep

    """
    PRINTS THE DECK
    """
    def print_deck(self):

        #number of cards left in deck
        cards_left = len(self.cards)

        #defines the thickness of the deck (just for aesthetic purposes)
        thiccness = math.floor((cards_left/10) + 1)

        #defines the standoff for the printing of the cards (so they're not stuck to the left side of the screen)
        standoff = " " * (9 - thiccness)

        #takes care of the standoff whether the number of cards has 1 or 2 digits
        number_standoff = "▒" * (4-len(str(cards_left)))

        #if there are no cards left, print an empty space!
        if cards_left < 1:

            deck_repr  = standoff + "╔─────╗\n"
            deck_repr += standoff + "│ \ / │\n"
            deck_repr += standoff + "│  X  │\n"
            deck_repr += standoff + "│ / \ │\n"
            deck_repr += standoff + "╚─────╝\n"

        else:
            #prints the deck!

            deck_repr  = standoff + "╔═════" + "╗" * thiccness + "\n"
            deck_repr += standoff + "║▒▒▒▒▒" + "║" * thiccness + "\n"
            #in the third line, we can see the number of cards left in the deck
            deck_repr += standoff + "║▒" + str(cards_left) + number_standoff +"║" * thiccness + "\n"
            deck_repr += standoff + "║▒▒▒▒▒" + "║" * thiccness + "\n"
            deck_repr += standoff + "╚═════" + "╝" * thiccness + "\n"

        print(deck_repr)

class Entity:

    #AN ENTITY CAN BE EITHER THE PLAYER OR THE BANK

    def __init__(self):

        #entity attributes (shared by players and bank)
        self.hand = []

    """
    ENTITY DRAWS A CARD
    """
    def draws(self,deck):

        #if deck is empty, replenishes it
        if len(deck.cards) == 0:
            deck.__init__()

        drawn_card = deck.cards[-1]
        deck.cards.pop()
        self.hand.append(drawn_card)

    """
    COUNTS THE POINTS IN THE ENTITY'S HAND
    """
    def points(self):

        #counts amount of aces in the player's hand
        ace_counter = 0
        for i in range(len(self.hand)):
            if self.hand[i][1] == "A":
                ace_counter += 1

        #proceeds to count points, but not aces!
        points = 0
        for i in range(len(self.hand)):
            if self.hand[i][1] in ["X", "J", "Q", "K"]:
                points += 10
            elif self.hand[i][1] == "A":
                pass
            else:
                points += self.hand[i][1]

        #now we count the aces
        if ace_counter > 0 and (points + (10 + ace_counter)) <= 21:
            points += 10 + ace_counter

        else:
            points += ace_counter

        return points

class Player(Entity):

    def __init__(self,player_number):

        #inherits class Entity
        Entity.__init__(self)

        #player only attributes

        self.name          = ""
        self.money         = 100
        self.current_bet   = 0
        self.player_number = player_number
        self.in_game       = True

    """
    ASKS FOR PLAYER'S NAME
    """
    def name_input(self):

        #checks for a name too long (more than 20 characters)
        error_check = True

        while error_check:
            pname = input("Player " + str(self.player_number + 1) + ", what's your name? ")

            if len(pname) > 20:
                print("Wow! That's a long name. Could you make it shorter?")
            else:
                error_check = False

        #asigns the name
        self.name = pname

    """
    PRINTS THE PLAYERS'S HAND
    """
    def print_hand(self):

        #defines the standoff for the printing of the cards (so they're not stuck to the left side of the screen)
        standoff    = " " * math.floor(69 / (amount_players + 1)) + " " * 13 * (self.player_number)

        """
        OLD STANDOFF
        standoff = " " * 13 * (self.player_number + 1)
        """
        #first determines how many cards the player has in his/her hand
        hand_count = len(self.hand)

        #if player has cards in the hand
        if hand_count > 0:

            #upper border of hand
            hand_repr = standoff + "╔═" * hand_count + "════╗\n" + standoff

            #2nd row
            for i in range(hand_count):
                hand_repr += "║"+str(self.hand[i][1])
            hand_repr += "    ║\n" + standoff

            #3rd row
            for i in range(hand_count - 1):
                hand_repr += "║" + str(self.hand[i][0])
            hand_repr += "║  " + str(self.hand[hand_count - 1][0]) + "  ║\n" + standoff

            #4th row
            for i in range(hand_count - 1):
                hand_repr += "║ "
            hand_repr += "║    " + str(self.hand[hand_count - 1][1]) + "║\n" + standoff

            #lower border of hand
            hand_repr += "╚═" * hand_count + "════╝" #\n"

        #when player has no cards in the hand, print empty space
        else:
            hand_repr = "\n" * 4

        print(hand_repr)

class Bank(Entity):

    def __init__(self):

        #inherits class Entity
        Entity.__init__(self)

    """
    PRINTS THE BANK'S HAND
    """
    def print_hand(self, first_move = False):

        #defines the standoff for the printing of the cards (so they're not stuck to the left side of the screen)
        standoff = " " * 31

        #first determines how many cards the bank has in its hand
        hand_count = len(self.hand)

        #upper border of hand
        hand_repr = standoff + "╔═════╗" * hand_count + "\n" + standoff

        #the first time the bank plays, one card is face down

        if first_move:
            #2nd row
            for i in range(hand_count-1):
                hand_repr = hand_repr + "║"+str(self.hand[i][1])+"    ║║▒▒▒▒▒║"
            hand_repr += "\n" + standoff

            #3rd row
            for i in range(hand_count-1):
                hand_repr = hand_repr + "║  "+str(self.hand[i][0])+"  ║║▒▒▒▒▒║"
            hand_repr += "\n" + standoff

            #4th row
            for i in range(hand_count-1):
                hand_repr = hand_repr + "║    "+str(self.hand[i][1])+"║║▒▒▒▒▒║"
            hand_repr += "\n" + standoff

        #Hand with all cards face up
        else:
            #2nd row
            for i in range(hand_count):
                hand_repr = hand_repr + "║"+str(self.hand[i][1])+"    ║"
            hand_repr += "\n" + standoff

            #3rd row
            for i in range(hand_count):
                hand_repr = hand_repr + "║  "+str(self.hand[i][0])+"  ║"
            hand_repr += "\n" + standoff

            #4th row
            for i in range(hand_count):
                hand_repr = hand_repr + "║    "+str(self.hand[i][1])+"║"
            hand_repr += "\n" + standoff

        #lower border of hand
        hand_repr += "╚═════╝" * hand_count # + "\n"

        print(hand_repr)

class Playfield():

    def __init__(self):
        pass

    """
    PRINTS THE PLAYFIELD
    """
    def print_playfield(self,deck,player,bank,first_move=False):

        #clears the screen before drawing
        os.system("cls")

        print(" " * 35 + "B A N K")
        #just for debugging:
        #print(" " * 27 + "Points: " + str(bank.points()))
        bank.print_hand(first_move)

        #money on the stack
        print(" " * 36 + "STACK:")

        #ATTENTION! The variable "player" is a list with every player
        stack = ""

        for i in range(amount_players):
            stack += player[i].name + ": $" + str(player[i].current_bet)
            if i < (amount_players - 1):
                stack += " / "

        #calculates a standoff for the stack, so it's kinda centered
        stack_standoff = math.floor((78 - len(stack))/2)

        stack = " "*stack_standoff + stack

        #prints stack
        print(stack)

        #prints deck
        deck.print_deck()

        #print("\n")

        #prints every player's hand

        for i in range(amount_players):

            #is the player still playing?
            if player[i].in_game:
                p_ingame = ""
            else:
                p_ingame = " (OUT!)"

            print(" " * math.floor(69 / (amount_players + 1)) + " " * 13 * (player[i].player_number) + player[i].name + p_ingame)
            print(" " * math.floor(69 / (amount_players + 1)) + " " * 13 * (player[i].player_number) + "Money:  $" + str(player[i].money))
            """
            WITH OLD STANDOFF
            print(" " * 13 * (player[i].player_number + 1) + player[i].name + p_ingame)
            print(" " * 13 * (player[i].player_number + 1) + "Money:  $" + str(player[i].money))
            #print(" " * 10 * (player[i].player_number + 1) + "Points: " + str(player[i].points()))
            """
            player[i].print_hand()

        #print("(q) to quit the game")
        #print("\n")

    """
    MAKES AN ANIMATION FOR THE FIRST MOVE OF EVERY GAME
    """
    def first_move(self,deck,player,bank):

        #resets the hands of bank and players and in_game status
        for i in range(amount_players):
            player[i].hand        = []
            #player plays only if he has money
            if player[i].money > 0:
                player[i].in_game     = True
            player[i].current_bet = 0

        bank.hand = []

        self.print_playfield(deck,player,bank)

        #every player draws 2 cards
        for i in range(2):
            for j in range(amount_players):
                if player[j].in_game:
                    player[j].draws(deck)
                    time.sleep(.5)
                self.print_playfield(deck,player,bank)

        #bank draws first card
        bank.draws(deck)
        time.sleep(.5)
        self.print_playfield(deck,player,bank)

        #bank draws second card
        bank.draws(deck)
        time.sleep(.5)
        self.print_playfield(deck,player,bank,True)

    """
    PLAYER PLACES A BET
    """
    def place_bet(self,deck,player,bank):

        #every player places a bet

        for i in range(amount_players):

            #check if the player has any money
            if player[i].money > 0:

                #checks for errors in input
                error_check = True

                while error_check:

                    #checks that it's an integer
                    try:
                        p_bet = int(input(f"{player[i].name}, place your bet: "))

                    except:
                        print("That's not a valid bet! Try again\n")
                        continue

                    #checks that the player has enough money for the bet
                    else:
                        if p_bet > player[i].money:
                            print("You don't have that much money! Try again\n")

                        else:
                            error_check = False

                #sets bet and re-prints playfield
                player[i].current_bet = p_bet
                player[i].money = player[i].money - p_bet
                self.print_playfield(deck,player,bank,True)

    """
    CHECK IF THE PLAYER HAS MORE THAN 21 POINTS, HE LOSES AUTOMATICALLY
    """
    def check_player_points(self,deck,player,bank):

        if player.points() > 21:
            #loses the bet!
            player.current_bet = 0
            player.in_game     = False
            #return False

        else:
            pass
            #return True

    """
    ASKS THE PLAYER IF HE WANTS TO STAY OR DRAW ANOTHER CARD
    """
    def draw_another(self,deck,player,bank):

        #draw cycle for every player

        for i in range(amount_players):

            #the loop repeats itself until player decides to stays
            keep_drawing = True

            while player[i].in_game and keep_drawing:

                #checks for errors in input
                error_check = True

                while error_check:
                    stay_or_draw = input(f"{player[i].name}, would you like to stay (s), draw another card (d)? ")

                    if stay_or_draw not in ["s","d"]:
                        print("That's not a valid answer! Try again\n")
                    else:
                        error_check = False

                #draws another card, re-prints the playfield and returns True
                #if player exceeds 21 points, the cycle stops automatically
                if stay_or_draw == "d":
                    player[i].draws(deck)
                    self.check_player_points(deck,player[i],bank)
                    self.print_playfield(deck,player,bank,True)
                    keep_drawing = player[i].in_game
                    if not player[i].in_game:
                        input("Sorry " + player[i].name + ", you lose! Better luck next time\n")

                #stays and returns False
                elif stay_or_draw == "s":
                    self.print_playfield(deck,player,bank,True)
                    keep_drawing = False

                """
                elif stay_or_draw == "q":
                    self.print_playfield(deck,player,bank,True)
                    keep_drawing = False
                    return "q"
                """

    """
    CHECKS THE BET
    """
    def check_bet(self,deck,player,bank):

        #this method runs once the bet has been placed (for every player)

        #we check first if the player and/or bank have a blackjack
        player_blackjack = [False] * amount_players

        for i in range(amount_players):
            player_blackjack[i] = len(player[i].hand) == 2 and player[i].points() == 21

        bank_blackjack   = len(bank.hand) == 2 and bank.points() == 21

        #re-prints the playfield, this time with all cards face up

        self.print_playfield(deck,player,bank)

        for i in range(amount_players):

        #checks if the bank has already more points than the players
            if bank.points() > player[i].points() and player[i].in_game:
                #the bank wins, player loses the bet
                player[i].current_bet = 0
                player[i].in_game = False
                self.print_playfield(deck,player,bank)
                input("Sorry " + player[i].name + ", you lose! Better luck next time")
                #return False

            #checks if it's a tie
            elif bank.points() == player[i].points() and player[i].in_game:
                player[i].money += player[i].current_bet
                player[i].current_bet = 0
                player[i].in_game = False
                self.print_playfield(deck,player,bank)
                input(player[i].name + ": it's a tie! You don't lose any money")
                #return False

        #if the bank has fewer points, must draw until it wins or loses
        bank_check = True

        #if all players are out of the game, there's no bank drawing cycle
        all_players_out = 0
        for i in range(amount_players):
            if player[i].in_game:
                all_players_out += 1

        if all_players_out == 0:
            bank_check = False

        while bank_check:

            #gives it a delay, for some sort of animation feeling
            time.sleep(2)

            #bank draws
            """
            AQUI IF SI TIENE MÁS DE 17 PUNTOS BANK?????
            """
            bank.draws(deck)
            self.print_playfield(deck,player,bank)

            for i in range(amount_players):

                #checks the bank points
                if bank.points() <= 21 and player[i].in_game:

                    if bank.points() > player[i].points():
                        #the bank wins, player loses the bet
                        player[i].current_bet = 0
                        self.print_playfield(deck,player,bank)
                        player[i].in_game = False
                        input("Sorry " + player[i].name + ", you lose! Better luck next time")
                        #bank_check = False
                        #break
                        #return False

                    elif bank.points() == player[i].points():
                         #it's a tie!
                        player[i].money += player[i].current_bet
                        player[i].current_bet = 0
                        self.print_playfield(deck,player,bank)
                        player[i].in_game = False
                        input(player[i].name + ": it's a tie! You don't lose any money")
                        #bank_check = False
                        #break
                        #return False

                elif bank.points() > 21 and player[i].in_game:
                    #player wins the bet!
                    if not player_blackjack[i]:
                        player[i].money += player[i].current_bet * 2
                        player[i].in_game = False
                        input("You win, " + player[i].name + "! Congratulations")

                    #player wins and has a blackjack
                    elif player_blackjack[i]:
                        player[i].money += player[i].current_bet * 3
                        player[i].in_game = False
                        input("BLACKJACK for " + player[i].name + "! You win the double of the amount in the stack")

                    self.print_playfield(deck,player,bank)
                    player[i].current_bet = 0

                #if all players are out of the game, breaks the cycle
                all_players_out = 0
                for i in range(amount_players):
                    if player[i].in_game:
                        all_players_out += 1

                if all_players_out == 0:
                    bank_check = False
                    #return False

#we initialize the classes
playfield = Playfield()
deck      = Deck()
bank      = Bank()
player    = []

for i in range(amount_players):
    player.append(Player(player_number = i))

#asks for the player's name
for i in range(amount_players):
    player[i].name_input()

#the game loop begins!
game_runs = True

while game_runs:

    #the turn begins!
    game_turn = True

    while game_turn:

        #if all players ran out of money, the game ends
        money_check = 0

        for i in range(amount_players):
            if player[i].money > 0:
                money_check += 1

        if money_check == 0:
            print("\nAll players ran out of money!")
            game_runs = False
            break

        #makes the first move (draws 2 cards for each entity, with an animation)
        playfield.first_move(deck,player,bank)

        #player places bet
        playfield.place_bet(deck,player,bank)

        #player draw cycle
        playfield.draw_another(deck,player,bank)

        #if player has more than 21 points, in_game status is false
        for i in range(amount_players):
            playfield.check_player_points(deck,player[i],bank)

        #bet checking cycle
        playfield.check_bet(deck,player,bank)

print("Thanks for playing!")


from collections import deque

def machine(memory, signal):
    PC = 0
    RB = 0
    while True:
        opcode = memory[PC]
        mode = ((opcode // 100) % 10), ((opcode // 1000) % 10), ((opcode // 10000) % 10)
        opcode = opcode % 100
        assert mode[2] != 1, "Wrong assuption"
        if opcode == 99:
            break
        elif opcode == 1:
            a = memory[memory[PC+1]] if mode[0] == 0 else memory[PC+1]
            a = memory[a + RB] if mode[0] == 2 else a
            b = memory[memory[PC+2]] if mode[1] == 0 else memory[PC+2]
            b = memory[b + RB] if mode[1] == 2 else b
            addr = memory[PC+3] + (RB if mode[2] == 2 else 0)
            memory[addr] = a + b
            PC += 4
        elif opcode == 2:
            a = memory[memory[PC+1]] if mode[0] == 0 else memory[PC+1]
            a = memory[a + RB] if mode[0] == 2 else a
            b = memory[memory[PC+2]] if mode[1] == 0 else memory[PC+2]
            b = memory[b + RB] if mode[1] == 2 else b
            addr = memory[PC+3] + (RB if mode[2] == 2 else 0)
            memory[addr] = a * b
            PC += 4
        elif opcode == 3:
            a = next(signal)
            if mode[0] == 0:
                memory[memory[PC+1]] = a
            elif mode[0] == 1:
                memory[PC+1] = a
            elif mode[0] == 2:
                memory[RB + memory[PC+1]] = a
            PC += 2
        elif opcode == 4:
            a = memory[memory[PC+1]] if mode[0] == 0 else memory[PC+1]
            a = memory[a + RB] if mode[0] == 2 else a
            yield a
            PC += 2
        elif opcode == 5:
            a = memory[memory[PC+1]] if mode[0] == 0 else memory[PC+1]
            a = memory[a + RB] if mode[0] == 2 else a
            b = memory[memory[PC+2]] if mode[1] == 0 else memory[PC+2]
            b = memory[b + RB] if mode[1] == 2 else b
            if a != 0:
                PC = b
            else:
                PC += 3
        elif opcode == 6:
            a = memory[memory[PC+1]] if mode[0] == 0 else memory[PC+1]
            a = memory[a + RB] if mode[0] == 2 else a
            b = memory[memory[PC+2]] if mode[1] == 0 else memory[PC+2]
            b = memory[b + RB] if mode[1] == 2 else b
            if a == 0:
                PC = b
            else:
                PC += 3
        elif opcode == 7:
            a = memory[memory[PC+1]] if mode[0] == 0 else memory[PC+1]
            a = memory[a + RB] if mode[0] == 2 else a
            b = memory[memory[PC+2]] if mode[1] == 0 else memory[PC+2]
            b = memory[b + RB] if mode[1] == 2 else b

            addr = memory[PC+3] + (RB if mode[2] == 2 else 0)
            memory[addr] = int(a < b)
            PC += 4
        elif opcode == 8:
            a = memory[memory[PC+1]] if mode[0] == 0 else memory[PC+1]
            a = memory[a + RB] if mode[0] == 2 else a
            b = memory[memory[PC+2]] if mode[1] == 0 else memory[PC+2]
            b = memory[b + RB] if mode[1] == 2 else b

            addr = memory[PC+3] + (RB if mode[2] == 2 else 0)
            memory[addr] = int(a == b)
            PC += 4
        elif opcode == 9:
            if mode[0] == 0:
                a = memory[memory[PC+1]]
            elif mode[0] == 1:
                a = memory[PC+1]
            elif mode[0] == 2:
                a = memory[RB + memory[PC+1]]
            RB += a
            PC += 2

def print_grid(grid):
    for row in grid:
        print(''.join(row))
    print()

def signals(grid, state):
    i, j = len(grid) // 2, len(grid[0]) // 2
    grid[i][j] = 'D'
    while True:
        last_move, last_response, history, s, _ = state
        if last_response == 2:
            state[4] = (i, j)
        if state[4] is not None:
            grid[state[4][0]][state[4][1]] = '*'
        if last_move is not None and last_response is not None:
            ni, nj = i, j
            # north (1), south (2), west (3), and east (4)
            if last_move == 1:
                ni -= 1
            elif last_move == 2:
                ni += 1
            elif last_move == 3:
                nj -= 1
            elif last_move == 4:
                nj += 1

            if last_response == 0:
                grid[ni][nj] = '#'
            else:
                if s == "explore":
                    history.append(last_move)
                grid[i][j] = ' '
                i, j = ni, nj
                grid[i][j] = 'D'
        # print_grid(grid)
        x = None
        if grid[i][j+1] == '.':
            x = 4
        elif grid[i][j-1] == '.':
            x = 3
        elif grid[i-1][j] == '.':
            x = 1
        elif grid[i+1][j] == '.':
            x = 2
        if x is None:
            state[3] = "backtrack"
            if not history:
                yield 5
            a = history.pop()
            if a == 1:
                x = 2
            elif a == 2:
                x = 1
            elif a == 3:
                x = 4
            elif a == 4:
                x = 3
        else:
            state[3] = "explore"

        state[0] = x
        yield x

def find_start(grid):
    for i in range(len(grid)):
        for j in range(len(grid[0])):
            if grid[i][j] == 'D':
                return (i, j)

def resolve(grid, goal):
    start = find_start(grid)
    q = deque([(1, start)])
    seen = set([start])
    while q:
        c, (i, j) = q.popleft()
        if (i, j) == goal:
            return c
        for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            ni, nj = i + di, j + dj
            if grid[ni][nj] == '#' or (ni, nj) in seen:
                continue
            q.append((c+1, (ni, nj)))
            seen.add((ni, nj))

def resolve2(grid, goal):
    start = find_start(grid)
    i, j = start
    grid[i][j] = ' '
    i, j = goal
    ans = 1
    grid[i][j] = ans
    while True:
        found_space = False
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == ans:
                    for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                        ni, nj = i + di, j + dj
                        if grid[ni][nj] == ' ':
                            found_space = True
                            grid[ni][nj] = ans + 1
        if not found_space:
            break
        ans += 1
    return ans

def main():
    grid = [['.'] * 80 for _ in range(50)]
    with open("input15.txt") as f:
        memory = [int(i) for i in f.read().strip().split(",")]

    state = [None, None, [], "explore", None]
    g = machine(memory + [0] * 4000, signals(grid, state))
    while True:
        try:
            state[1] = next(g)
        except StopIteration:
            break
    print_grid(grid)
    print(state[4])
    ans = resolve(grid, state[4])
    print("Part 1 Ans:", ans)

    ans = resolve2(grid, state[4])
    print("Part 2 Ans:", ans)

main()


from django.urls import path
from . import views

urlpatterns= [
    path('',views.main, name='home'),
    path('jobCreate/', views.createJob, name='elon'),
    path('find/<int:id>/', views.category, name='category'),
    path('filter/<int:id>/', views.location, name='location'),
    path('found/', views.search, name='search'),
    path('details/<int:id>/', views.details, name='details'),
    path('delete/<int:id>', views.delete, name='delete'),
    path('update/<int:id>', views.update, name='update'),

]


from __future__ import print_function, absolute_import
from .c_base import error_msg, warning_msg, info_msg

def dt_py_log_hook_init():
    import logging

    class dt_py_log_hook_t(logging.Handler):
        def __init__(self):
            logging.Handler.__init__(self)
            log = logging.getLogger()
            log.setLevel(logging.DEBUG)

        def emit(self, record):
            if isinstance(record.msg, str) and (isinstance(record.args, list) or isinstance(record.args, tuple)):
                msg = 'PyLog: [%s] : "%s"' % (record.module, record.msg % record.args)
            else:
                msg = 'PyLog: [%s] : "%s"' % (record.module, record.msg)
            if record.levelno < 30:
                info_msg(msg)
            elif record.levelno < 40:
                warning_msg(msg)
            else:
                error_msg(msg)

    log = logging.getLogger()
    log.addHandler(dt_py_log_hook_t())


# This is a Python module that allows driving a Mitsubishi robot.
# This Python module can be run directly in console mode to test its functionality.
# This module allows communicating with a robot through the command line.
# The same commands we can input manually are used by RoboDK to drive the robot from the PC.
# RoboDK Drivers are located in /RoboDK/api/Robot/ by default. Drivers can be PY files or EXE files.
#
# Drivers are modular. They are not part of the RoboDK executable but they must be placed in C:/RoboDK/api/robot/, then, linked in the Connection parameters menu:
#   1. right click a robot in RoboDK, then, select "Connect to robot".
#   2. In the "More options" menu it is possible to update the location and name of the driver.
# Driver linking is automatic for currently available drivers.
#
# Alternatively to the standard programming methods (where a program is generated, then, transferred to the robot and executed) it is possible to run a program simulation directly on the robot
# The robot movement in the simulator is then synchronized with the real robot.
# Programs generated from RoboDK can be run on the robot by right clicking the program, then selecting "Run on robot".
#   Example:
#   https://www.youtube.com/watch?v=pCD--kokh4s
#
# Example of an online programming project:
#   https://robodk.com/blog/online-programming/
#
# It is possible to control the movement of a robot from the RoboDK API (for example, from a Python or C# program using the RoboDK API).
# The same code is used to simulate and optionally move the real robot.
#   Example:
#   https://robodk.com/offline-programming
#
#   To establish connection from RoboDK API:
#   https://robodk.com/doc/en/PythonAPI/robolink.html#robolink.Item.ConnectSafe
#
# Example of a quick manual test in console mode:
#  User entry: CONNECT 192.168.123.1
#  Response:   SMS:Response from the robot or failure to connect
#  Response:   SMS:Ready
#  User entry: MOVJ 10 20 30 40 50 60
#  Response:   SMS:Working...
#  Response:   SMS:Ready
#  User entry: CJNT
#  Response:   SMS:Working...
#  Response:   JNTS: 10 20 30 40 50 60
#
#---------------------------------------------------------------------------------

import sys
import time
import socket
import threading
import queue
import serial

#----------- communication class for the Mitsubishi robot -------------
# This class handles communication between this driver (PC) and the Mitsubishi robot
class RobotCom:
    """Robot class for programming Mitsubishi robots"""
    LAST_MSG = ""       # Keep a copy of the last message received
    CONNECTED = False   # Connection status is known at all times

    # This is executed when the object is created
    def __init__(self):
        self.BUFFER_SIZE = 512 # bytes
        self.TIMEOUT = 60 # seconds # No robot movement should take more than 60 seconds
        #self.TIMEOUT = 10 # seconds
        self.sock = None
        self.sockjnts = None

    # Disconnect from robot
    def disconnect(self):
        """self.CONNECTED = False
        try:
            self.sockjnts.close()
        except:
            pass
        try:
            if self.sock is not None:
                self.Run('1;1;CLOSE')
                self.sock.close()
        except:
            pass
        return True"""

        #ser = serial.Serial('COM4', 19200, timeout=0,stopbits=2, parity=serial.PARITY_EVEN, rtscts=1)  # open serial port

    # Connect to robot
    def connect(self, ip, port=10001):
        """global ROBOT_MOVING
        self.disconnect()
        print_message('Connecting to robot %s:%i' % (ip, port))
        # Create new socket connection
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(4)
        self.sockjnts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sockjnts.settimeout(4)
        UpdateStatus(ROBOTCOM_WORKING)
        self.sock.connect((ip, port))
        self.CONNECTED = True
        ROBOT_MOVING = False
        print_message('Waiting for welcome message...')
        UpdateStatus(ROBOTCOM_WORKING)
        #time.sleep(2)

        # receive welcome message and output to the log
        self.Run('1;1;OPEN=ROBODK',False)
        #print(self.recv_str())
        # notify status that the robot is still working
        UpdateStatus(ROBOTCOM_WORKING)

        # send activate robot and read confirmation
        self.Run('1;1;RSTALRM',False)
        self.Run('1;1;CNTLON',False)
        self.Run('1;1;SRVON')
        # RoboDK provides xyzwpr data for the TCP with respect to the robot reference frame for linear movements
        #self.Run('SetWRF', [0, 0, 0, 0, 0, 0])
        #self.sock.settimeout(self.TIMEOUT)
        #self.sockjnts.connect((ip, 10002))

        #q = queue.Queue()
        #t = threading.Thread(target=robot_monitor, args=(q, self.sockjnts))
        #t.daemon = True
        #t.start()
        return True"""

        ser = serial.Serial(ip, 19200, timeout=0,stopbits=2, parity=serial.PARITY_EVEN, rtscts=1)  # open serial port

        ser.write(b'1;0;STOP\r')
        ser.write(b'1;1;SRVOFF\r')

        ser.close()

    # Send a line to the robot through the communication port (TCP/IP)
    def send_str(self, msg):
        try:
            sent = self.sock.send(bytes(msg+'\0','ascii'))
            if sent == 0:
                return False
            return True
        except ConnectionAbortedError as e:
            self.CONNECTED = False
            print(str(e))
            return False

    # Receive a line from the robot through the communication port (TCP/IP)
    def recv_str(self):
        bdata = b''
        try:
            bdata = self.sock.recv(self.BUFFER_SIZE)
        except ConnectionAbortedError as e:
            self.CONNECTED = False
            print(str(e))
            return

        if bdata == b'':
            return None

        self.LAST_MSG = bdata.decode('ascii')
        return self.LAST_MSG

    # Run a specific command and provide required parameters
    def Run(self, cmd, send_ready=True):
        # Skip the command if the robot is not connected
        if not self.CONNECTED:
            UpdateStatus(ROBOTCOM_NOT_CONNECTED)
            return

        #---------- Send robot command -------
        # notify RoboDK
        print('sending: %s' % str_send)
        UpdateStatus(ROBOTCOM_WORKING)

        # Try to send the command
        if self.send_str(str_send) is False:
            print_message("Robot connection broken")
            UpdateStatus(ROBOTCOM_NOT_CONNECTED)
            return

        # Try to receive a response
        robot_msg = self.recv_str()
        if self.LAST_MSG is None:
            print_message("Robot connection broken")
            UpdateStatus(ROBOTCOM_NOT_CONNECTED)
            return

        problems = False

        if 'Qer' in robot_msg:
            self.send_str("1;1;ERROR")
            errno = self.recv_str()[3:7]
            self.send_str("1;1;ERRORMES" + str(errno))
            print_message(self.recv_str()[3:])
            return

        if "JPOSF" in cmd:
            # robot response after a GetJoints request
            print_joints(robot_msg.split(";")[1:12:2])
            UpdateStatus(ROBOTCOM_READY)
            return

        # Any other acknowledge message (assumed to be successful)
        # By default, we will send the command Ready at every instruction (one Run per instruction in general)
        print(robot_msg)
        if send_ready:
            UpdateStatus(ROBOTCOM_READY)
        else:
            # Save the Ready status to send later and notify RoboDK that the instruction was completed
            global STATUS
            STATUS = ROBOTCOM_READY

# Receives a string through TCP/IP. It reads until if finds NULL character
def read_line(socket):
    data = socket.recv(512)
    s = data.decode("ascii")
    return s

def send_line(socket, msg):
    data = msg.encode("ascii")
    socket.sendall(data)

# Specific thread to monitor robot communication
# This thread establishes a permanent link between the robot and the PC to retrieve the robot position at all times
# The robot position is displayed only when the robot is executing a motion command
# When the communication link is broken it will notify the user
def robot_monitor(q, socket):

    try:
        while True:

            send_line(socket, "1;1;JPOSF")
            response = read_line(socket)
            robot_msg = response.split(';')
            #bdata = socket.recv(512)
            #if bdata == b'':
            #    print_message("Invalid monitoring response")
            #    return
            #robot_msg = bdata.decode('ascii')
            print_joints(robot_msg[1:12:2], True)
            #msg_id = int(robot_msg[1:5])
            #if msg_id == 3007:
                # monitoring stream of data: [3007][j1, j2, j3, j4, j5, j6]
                #print_joints(robot_msg[7:-2].replace(',',''), True)
            #elif msg_id == 3010:
                # position data is also part of the stream. Ignore
                # [3010][212.985, -93.965, 34.273, 180.000, -1.967, 63.936]
            #    pass
            #elif msg_id == 3000:
                # Welcome message is:
                # [3000][Connected to Mecademic Meca500 Robot.]
            #    pass
            #else:
            #    print(robot_msg)
            #    print_message("Unknown monitoring response")
            #    return

    except Exception as e:
            print(str(e))
            print_message("Robot not connected")
            return

#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Generic RoboDK driver for a specific Robot class
global ROBOT
global ROBOT_IP
global ROBOT_PORT
global ROBOT_MOVING

ROBOT = RobotCom()
ROBOT_IP = "127.0.0.1"      # IP of the robot
ROBOT_PORT = 10000          # Communication port of the robot
ROBOT_MOVING = False

#------------ robot connection -----------------
# Establish connection with the robot
def RobotConnect():
    global ROBOT
    global ROBOT_IP
    #global ROBOT_PORT
    ROBOT.connect(ROBOT_IP)

# Disconnect from the robot
def RobotDisconnect():
    global ROBOT
    ROBOT.disconnect()

#-----------------------------------------------------------------------------
# Generic RoboDK driver tools

# Note, a simple print() will flush information to the log window of the robot connection in RoboDK
# Sending a print() might not flush the standard output unless the buffer reaches a certain size

def print_message(message):
    """print_message will display a message in the log window (and the connexion status bar)"""
    print("SMS:" + message)
    sys.stdout.flush() # very useful to update RoboDK as fast as possible

def show_message(message):
    """show_message will display a message in the status bar of the main window"""
    print("SMS2:" + message)
    sys.stdout.flush() # very useful to update RoboDK as fast as possible

def print_joints(joints, ismoving = False):
    if ismoving:
        # Display the feedback of the joints when the robot is moving
        if ROBOT_MOVING:
            #print("CJNT_MOVING " + " ".join(format(x, ".5f") for x in joints)) # if joints is a list of float
            print("JNTS_MOVING " + " ".join(joints))
    else:
        #print("CJNT " + " ".join(format(x, ".5f") for x in joints)) # if joints is a list of float
        print("JNTS " + " ".join(joints))
    sys.stdout.flush() # very useful to update RoboDK as fast as possible

# ---------------------------------------------------------------------------------
# Constant values to display status using UpdateStatus()
ROBOTCOM_UNKNOWN                = -1000
ROBOTCOM_CONNECTION_PROBLEMS    = -3
ROBOTCOM_DISCONNECTED           = -2
ROBOTCOM_NOT_CONNECTED          = -1
ROBOTCOM_READY                  =  0
ROBOTCOM_WORKING                =  1
ROBOTCOM_WAITING                =  2

# Last robot status is saved
global STATUS
STATUS = ROBOTCOM_DISCONNECTED

# UpdateStatus will send an appropriate message to RoboDK which will result in a specific coloring
# for example, Ready will be displayed in green, Waiting... will be displayed in Yellow and other messages will be displayed in red
def UpdateStatus(set_status=None):
    global STATUS
    if set_status is not None:
        STATUS = set_status

    if STATUS == ROBOTCOM_CONNECTION_PROBLEMS:
        print_message("Connection problems")
    elif STATUS == ROBOTCOM_DISCONNECTED:
        print_message("Disconnected")
    elif STATUS == ROBOTCOM_NOT_CONNECTED:
        print_message("Not connected")
    elif STATUS == ROBOTCOM_READY:
        print_message("Ready")
    elif STATUS == ROBOTCOM_WORKING:
        print_message("Working...")
    elif STATUS == ROBOTCOM_WAITING:
        print_message("Waiting...")
    else:
        print_message("Unknown status");

# Sample set of commands that can be provided by RoboDK of through the command line
def TestDriver():
    RunCommand("CONNECT 127.0.0.1 10000")
    #RunCommand("SETTOOL -0.025 -41.046 50.920 60.000 -0.000 90.000")
    #RunCommand("MOVJ -5.362010 46.323420 20.746290 74.878840 -50.101680 61.958500")
    #RunCommand("SPEED 250")
    #RunCommand("MOVL 0 0 0 0 0 0 -5.362010 50.323420 20.746290 74.878840 -50.101680 61.958500")
    #RunCommand("PAUSE 2000") # Pause 2 seconds

#-------------------------- Main driver loop -----------------------------
# Read STDIN and process each command (infinite loop)
# IMPORTANT: This must be run from RoboDK so that RoboDK can properly feed commands through STDIN
# This driver can also be run in console mode providing the commands through the console input
def RunDriver():
    for line in sys.stdin:
        RunCommand(line)

# Each line provided through command line or STDIN will be processed by RunCommand
def RunCommand(linecmd):
    global ROBOT_IP
    global ROBOT
    global ROBOT_MOVING

    # strip a line of words into a list of numbers
    def line_2_values(words):
        values = []
        for word in words:
            try:
                number = float(word)
                values.append(number)
            except:
                pass
        return values

    linecmd = linecmd
    words = linecmd.split(' ')
    values = line_2_values(words)
    nvalues = len(values)
    nwords = len(words)

    if linecmd == "":
        # Skip if no command is provided
        return

    elif nwords >= 2 and linecmd.startswith("CONNECT"):
        # Connect to robot provided the IP and the port
        ROBOT_IP = words[1]
        if nwords >= 3 and nvalues >= 1 and values[0] != 10000:
            #ROBOT_PORT = values[0]
            print("Using default port 10000, not %i" % ROBOT_PORT)
        RobotConnect()

    elif nvalues >= 6 and linecmd.startswith("MOVJ"):
        # Activate the monitor feedback
        ROBOT_MOVING = True

        # Execute a joint move. RoboDK provides j1,j2,...,j6,x,y,z,w,p,r
        ROBOT.Run("1;1;FDELMRL", False)
        ROBOT.Run("1;1;NEW", False)
        ROBOT.Run("1;1;LOAD=MRL", False)
        ROBOT.Run("1;1;EDATA 1 J1=(" + (','.join(format(vi, ".6f") for vi in values[:6])) + ")", False)
        ROBOT.Run('1;1;EDATA 2 MOV J1', False)
        ROBOT.Run('1;1;EDATA 3 END', False)
        ROBOT.Run("1;1;SAVE", False)
        ROBOT.Run("1;1;RSTPRG", False)
        ROBOT.Run("1;1;PRGLOAD=MRL", False)
        ROBOT.Run("1;1;RSTPRG", False)
        ROBOT.Run("1;1;RUNMRL;1")

    elif nvalues >= 12 and linecmd.startswith("MOVL"):
        # Activate the monitor feedback
        ROBOT_MOVING = True

        # Execute a linear move. RoboDK provides j1,j2,...,j6,x,y,z,w,p,r
        ROBOT.Run('1;1;EXECMVS ' + '(' + (','.join(format(vi, ".6f") for vi in values[6:])) + ")(7,0)")

    elif linecmd.startswith("CJNT"):
        # Retrieve the current position of the robot
        ROBOT.Run('1;1;JPOSF')

    elif nvalues >= 1 and linecmd.startswith("SPEED"):
        # First value is linear speed in mm/s
        # IMPORTANT! We should only send one "Ready" per instruction
        if values[0] > 0:
            # make sure we do not exceed maximum speed (robot turns into error mode)
            ROBOT.Run('1;1;EXECSPD (%.3f)' % min(10000.0, values[0]), False)

        # Provokes sending Ready:
        UpdateStatus()
    elif nvalues >= 1 and linecmd.startswith("SETROUNDING"):
        # Set the rounding/smoothing value. Also known as ZoneData in ABB or CNT for Fanuc
        #ROBOT.Run('SetCornering', [1] if values[0] > 0 else [0])
        pass

    elif nvalues >= 1 and linecmd.startswith("PAUSE"):
        UpdateStatus(ROBOTCOM_WAITING)
        # Run a pause
        if values[0] > 0:
            import time
            time.sleep(values[0] * 0.001)
        UpdateStatus(ROBOTCOM_READY)

    elif nvalues >= 2 and linecmd.startswith("SETDO"):
        UpdateStatus(ROBOTCOM_WORKING)
        dIO_id = values[0]
        dIO_value = values[1]
        print_message("Warning: Setting DO[%i] = %.1f not implemented" % (dIO_id, dIO_value))
        UpdateStatus(ROBOTCOM_READY)

    elif nvalues >= 2 and linecmd.startswith("WAITDI"):
        UpdateStatus(ROBOTCOM_WORKING)
        dIO_id = values[0]
        dIO_value = values[1]
        print_message("Warning: Waiting DI[%i] = %.1f not implemented" % (dIO_id, dIO_value))
        UpdateStatus(ROBOTCOM_READY)

    elif nvalues >= 6 and linecmd.startswith("SETTOOL"):
        # Set the Tool reference frame provided the 6 XYZWPR values by RoboDK
        ROBOT.Run('1;1;EXECTOOL (' + (','.join(format(vi, ".6f") for vi in values)) + ')')

    elif nvalues >= 1 and nwords >= 2 and linecmd.startswith("RUNPROG"):
        UpdateStatus(ROBOTCOM_WORKING)
        prog_id = int(values[0])
        prog_name = "Program %i" % prog_id
        if nwords >= 3:
            prog_name = words[1]

        print_message("Warning: Running program %s not implemented" % (prog_name))
        UpdateStatus(ROBOTCOM_READY)

    elif nwords >= 2 and linecmd.startswith("POPUP "):
        UpdateStatus(ROBOTCOM_WORKING)
        message = linecmd[6:]
        print_message("Warning: Display message %s not implemented" % (message))
        UpdateStatus(ROBOTCOM_READY)

    elif linecmd.startswith("DISCONNECT"):
        # Disconnect from robot
        ROBOT.disconnect()
        UpdateStatus(ROBOTCOM_DISCONNECTED)

    elif linecmd.startswith("TEST"):
        # Call custom procedure for quick testing
        TestDriver()

    elif linecmd.startswith("QUIT"):
        # Stop the driver
        ROBOT.disconnect()
        UpdateStatus(ROBOTCOM_DISCONNECTED)
        quit(0) # Stop the driver

    else:
        print("Unknown command: " + linecmd)

    # Stop monitoring feedback
    ROBOT_MOVING = False

if __name__ == "__main__":
    """Call Main procedure"""
    # Flush Disconnected message
    UpdateStatus()

    # Run the driver from STDIN
    RunDriver()

    # Test the driver with a sample set of commands
    #TestDriver()


import collections
from json_reader import read_matches

def extract_item_features_csv(match):
    row = [
        ('match_id_hash', match['match_id_hash']),
    ]

    for slot, player in enumerate(match['players']):
        if slot < 5:
            player_name = 'r%d' % (slot + 1)
        else:
            player_name = 'd%d' % (slot - 4)

        row.append( (f'{player_name}_items', list(map(lambda x: x['id'][5:], player['hero_inventory'])) ) )

    return collections.OrderedDict(row)

def create_item_features_from_jsonl(matches_file):
    df_new_features = []

    # Process raw data and add new features
    for match in read_matches(matches_file):
        features = extract_item_features_csv(match)
        df_new_features.append(features)

    df_new_features = pd.DataFrame.from_records(df_new_features).set_index('match_id_hash')
    return df_new_features

def add_items_dummies(train_df, test_df):

    full_df = pd.concat([train_df, test_df], sort=False)
    train_size = train_df.shape[0]

    for team in 'r', 'd':
        players = [f'{team}{i}' for i in range(1, 6)]
        item_columns = [f'{player}_items' for player in players]

        d = pd.get_dummies(full_df[item_columns[0]].apply(pd.Series).stack()).sum(level=0, axis=0)
        dindexes = d.index.values

        for c in item_columns[1:]:
            d = d.add(pd.get_dummies(full_df[c].apply(pd.Series).stack()).sum(level=0, axis=0), fill_value=0)
            d = d.loc[dindexes]

        full_df = pd.concat([full_df, d.add_prefix(f'{team}_item_')], axis=1, sort=False)
        full_df.drop(columns=item_columns, inplace=True)

    train_df = full_df.iloc[:train_size, :]
    test_df = full_df.iloc[train_size:, :]

    return train_df, test_df

def drop_consumble_items(train_df, test_df):

    full_df = pd.concat([train_df, test_df], sort=False)
    train_size = train_df.shape[0]

    for team in 'r', 'd':
        consumble_columns = ['tango', 'tpscroll',
                            'bottle', 'flask',
                            'enchanted_mango', 'clarity',
                            'faerie_fire', 'ward_observer',
                            'ward_sentry']

        starts_with = f'{team}_item_'
        consumble_columns = [starts_with + column for column in consumble_columns]
        full_df.drop(columns=consumble_columns, inplace=True)

    train_df = full_df.iloc[:train_size, :]
    test_df = full_df.iloc[train_size:, :]

    return train_df, test_df

def create_item_features(train_data, test_data, path_to_data):
    train_items_df = create_item_features_from_jsonl(os.path.join(path_to_data, 'train_matches.jsonl')).fillna(0)
    test_items_df = create_item_features_from_jsonl(os.path.join(path_to_data, 'test_matches.jsonl')).fillna(0)

    train_items_df, test_items_df = add_items_dummies(train_items_df, test_items_df)
    train_items_df, test_items_df = drop_consumble_items(train_items_df, test_items_df)

    train_features = pd.concat([train_data, train_items_df], axis=1)
    test_features = pd.concat([test_data, test_items_df], axis=1)

    return train_features, test_features


import turtle
t = turtle.Turtle()
t.shape("turtle")

clist = ["yellow", "red", "blue", "green"] # 색상 리스트
for i in range(4):
    t.penup() # 펜을 올린다는뜻 : 펜이 안그려진다. -> 테두리기 필요 없을 때 사용
    t.forward(50)
    t.fillcolor(clist[i]) # 채우기 색상 지정
    t.pencolor(clist[i]) # 펜 색상 지정
    t.begin_fill() # 채우기 시작 -> end와 꼭 같이 사용, 채우기 색을 정한 다음 begin
    t.pendown() # 펜을 내린다는 뜻 : 펜이 다시 그려진다.
    t.circle(100)
    t.end_fill() # 채우기 끝

색상 리스트로 여러 원 그리기.py


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        l = [root]
        r = [root]
        while l:
            p1 = l.pop()
            p2 = r.pop()
            if not p1 and not p2:
                continue
            elif not p1 or not p2:
                return False
            if p1.val == p2.val:
                l.append(p1.left)
                r.append(p2.right)
                l.append(p1.right)
                r.append(p2.left)
            else:
                return False
        if r:
            return False
        return True


'''clients = {
    "INFO" : 0.5,
    "DATA" : 0.2,
    "SOFT" : 0.2,
    "INTER" : 0.1,
    "OMEGA" : 0.0
}

myClient = input("Enter client's name: ")
totalCost = 7200

try:

    print(" The % ratio for {} is {}".format(myClient, clients[myClient]))

except Exception as e:

    print("Sorry we have an error... \n Detalis: \n {}".format(e))

else:

    print("The costs for {} is {}".format(myClient, clients[myClient] * totalCost))

finally:

    print("-= Calcutaion finiszed =-")
'''

import requests
import os
import shutil

def save_url_to_file(url, file_path):
    r = requests.get(url, stream=True)
    with open(file_path, "wb") as f:
        f.write(r.content)

url = 'http://www.mobilo24.eu/spis/'
dir = 'N:/temp/'
tmpfile = 'download.tmp'
file = 'spis.html'

tmpfile_path = os.path.join(dir, tmpfile)
file_path = os.path.join(dir, file)

try:
    if os.path.exists(tmpfile_path):
        os.remove(tmpfile_path)

    print("Dowloading..")
    save_url_to_file(url, tmpfile_path)

    print("Copy..")
    #kopiowanie pliku tmpfile_path do file_path
    shutil.copy(tmpfile_path, file_path)

except Exception as e:
    print("We have a error. Detalis: {}".format(e))

else:
    print("Succesful")

finally:
    print("Delect..")
    if os.path.exists(tmpfile_path):
        os.remove(tmpfile_path)


import collections

def unikati(s):
    nov = []
    for a in s:
        if a not in nov:
            nov.append(a)
    return nov

def avtor(tvit):
    return tvit.split(":")[0]

def vsi_avtorji(tviti):
    imena = []
    for tvit in tviti:
        imena.append(avtor(tvit))
    return unikati(imena)

def izloci_besedo(beseda):
    while beseda and not beseda[0].isalnum():
        beseda = beseda[1:]
    while beseda and not beseda[-1].isalnum():
        beseda = beseda[:-1]
    return beseda

def se_zacne_z(tvit, c):
    besede = []
    for beseda in tvit.split():
        if beseda[0] == c:
            besede.append(izloci_besedo(beseda))
    return besede

def zberi_se_zacne_z(tviti, c):
    afne = []
    for tvit in tviti:
        afne += se_zacne_z(tvit, c)
    return unikati(afne)

def vse_afne(tviti):
    return unikati(zberi_se_zacne_z(tviti, "@"))

def vsi_hashtagi(tviti):
    return unikati(zberi_se_zacne_z(tviti, "#"))

def vse_osebe(tviti):
    return sorted(unikati(vsi_avtorji(tviti) + vse_afne(tviti)))

def custva(tviti, hashtagi):
    avtorji = []
    for tvit in tviti:
        if neprazen_presek(se_zacne_z(tvit, "#"), hashtagi):
            avtorji.append(avtor(tvit))
    avtorji.sort()
    return unikati(avtorji)

def neprazen_presek(s, t):
    for e in s:
        if e in t:
            return True
    return False

def se_poznata(tviti, oseba1, oseba2):
    for tvit in tviti:
        pisec = avtor(tvit)
        omenjeni = se_zacne_z(tvit, "@")
        if oseba1 == pisec and oseba2 in omenjeni or \
                oseba2 == pisec and oseba1 in omenjeni:
            return True
    return False

'''Funkcija besedilo(tvit) prejme tvit in vrne besedilo - torej vse, kar sledi prvemu dvopičju.
Klic besedilo("ana: kdo so te: @berta, @cilka, @dani?") vrne "kdo so te: @berta, @cilka, @dani?.'''
def besedilo(tvit):
    x = tvit.split(":",1)[1]
    if x and not x[0].isalnum():
        x = x[1:]
    return x

'''Funkcija zadnji_tvit(tviti) prejme seznam tvitov in vrne slovar, katerega ključi so avtorji tvitov, vrednosti
pa njihovi tviti. Če je en in isti avtor napisal več tvitov, naj bo v slovarju njegov zadnji tvit. Rezultat je lahko,
recimo

{"berta": "@sandra Delaj domačo za #programiranje1",
 "sandra": "@berta Ne maram #programiranje1 #krneki",
 "ana": "kdo so te: @berta, @cilka, @dani? #krneki"}
če so to edini trije avtorji in so to njihovi (zadnji) tviti.'''
def zadnji_tvit(tviti):
    slovar = {}
    for tvit in tviti:
        slovar[avtor(tvit)]=besedilo(tvit)
    return slovar

'''Funkcija prvi_tvit(tviti) je jako podobna, le da v primeru, da je ista oseba napisala več tvitov, obdrži njen prvi tvit.'''
def prvi_tvit(tviti):
    slovar = {}
    for tvit in tviti:
        x = avtor(tvit)
        if x not in slovar:
            slovar[x]=besedilo(tvit)
    return slovar

'''Funkcija prestej_tvite(tviti) vrne slovar, katerega ključi so (spet) avtorji, pripadajoče vrednosti pa število tvitov,
ki so jih napisali, na primer {"sandra": 2, "berta": 1, "ana": 1, "cilka": 4, "benjamin": 1}'''
def prestej_tvite(tviti):
    stevec=collections.defaultdict(int)
    for tvit in tviti:
        stevec[avtor(tvit)] += 1
    return stevec

'''Funkcija omembe(tviti) vrne slovar, katerega ključi so avtorji tvitov, vrednosti pa seznami oseb, ki so jih ti
avtorji omenjali v svojih tvitih. Vrstni red oseb mora biti enak vrstnemu redu omenjanj. Funkcija lahko vrne, recimo

{"sandra": ["berta", "benjamin", "ana"],
"benjamin": [],
"cilka": [],
"berta": ["sandra"],
"ana": ["berta", "cilka", "dani"]}'''
def omembe(tviti):
    slovar = {}
    for tvit in tviti:
        if avtor(tvit) not in slovar:
            slovar[avtor(tvit)] = se_zacne_z(tvit, "@")
        else:
            slovar[avtor(tvit)] += se_zacne_z(tvit, "@")
    return slovar

'''Funkcija neomembe(ime, omembe) prejme ime neke osebe in takšen slovar, kakršnega vrne gornja funkcija.
Vrniti mora seznam vseh ljudi, ki so avtorji kakega tvita, podana oseba (ime) pa jih ni omenjala. Če funkciji kot
argument podamo ime "Ana" in gornji slovar, mora vrniti ["sandra", "benjamin], saj Ana ni omenjala Sandre in Benjamina,
Cilko in Berto pa je. Iz seznama naj bo seveda izključena oseba sama (v tem primeru Ana). Vrstni red oseb
v seznamu je lahko poljuben.'''
def neomembe(ime, omembe):
    seznam = []
    for a in omembe.keys():
        if a not in omembe.get(ime) and ime != a:
            seznam.append(a)
    return seznam

'''Napišite funkcijo se_poznata(ime1, ime2, omembe), ki je podobna kot v prejšnji domači nalogi, le da kot argument
namesto tvitov dobi gornji slovar. Povedati mora, ali je prva oseba kdaj omenila drugo (ali obratno) ali ne.
Funkcija vrne True ali False.'''
def se_poznata(ime1, ime2, omembe):
    for oseba in omembe:
        omenjeni = omembe[oseba]
        if ime1 == oseba and ime2 in omenjeni or ime2 == oseba and ime1 in omenjeni:
            return True
    return False

'''Napišite funkcijo hashtagi(tviti), ki prejme seznam tvitov in vrne slovar, katerega ključi so hashtagi
(brez znaka #), pripadajoče vrednosti pa seznami avtorjev, ki so uporabili ta hashtagi. Avtorji naj bodo urejeni po abecedi.'''
def hashtagi(tviti):
    slovar = {}
    kljuc = vsi_hashtagi(tviti)
    for k in kljuc:
        for tvit in tviti:
            if k in tvit:
                if k not in slovar:
                    slovar[k] = [avtor(tvit)]
                else:
                    slovar[k] += [avtor(tvit)]
        slovar[k] = (sorted(slovar[k]))
    return slovar

import unittest

class TestObvezna(unittest.TestCase):
    maxDiff = 10000

    def test_1_besedilo(self):
        self.assertEqual(besedilo("sandra: Spet ta dež. #dougcajt"),
                         "Spet ta dež. #dougcajt")
        self.assertEqual(besedilo("ana: kdo so te: @berta, @cilka, @dani? #krneki"),
                         "kdo so te: @berta, @cilka, @dani? #krneki")

    def test_2_zadnji_tvit(self):
        self.assertDictEqual(
            zadnji_tvit([
                "sandra: Spet ta dež. #dougcajt",
                "berta: @sandra Delaj domačo za #programiranje1",
                "sandra: @berta Ne maram #programiranje1 #krneki",
                "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                "cilka: jst sm pa #luft",
                "benjamin: pogrešam ano #zalosten",
                "cilka: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"berta": "@sandra Delaj domačo za #programiranje1",
             "sandra": "@berta Ne maram #programiranje1 #krneki",
             "ana": "kdo so te: @berta, @cilka, @dani? #krneki",
             "benjamin": "pogrešam ano #zalosten",
             "cilka": "@benjamin @ana #split? po dvopičju, za začetek?"})

        self.assertDictEqual(
            zadnji_tvit([
                "sandra: Spet ta dež. #dougcajt",
                "sandra: @sandra Delaj domačo za #programiranje1",
                "sandra: @berta Ne maram #programiranje1 #krneki",
                "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                "sandra: jst sm pa #luft",
                "benjamin: pogrešam ano #zalosten",
                "sandra: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"ana": "kdo so te: @berta, @cilka, @dani? #krneki",
             "benjamin": "pogrešam ano #zalosten",
             "sandra": "@benjamin @ana #split? po dvopičju, za začetek?"})

        self.assertDictEqual(
            zadnji_tvit(["ana: kdo so te: @berta, @cilka, @dani? #krneki"]),
            {"ana": "kdo so te: @berta, @cilka, @dani? #krneki"})

        self.assertEqual(zadnji_tvit([]), {})

    def test_3_prvi_tvit(self):
        self.assertDictEqual(
            prvi_tvit([
                "sandra: Spet ta dež. #dougcajt",
                "berta: @sandra Delaj domačo za #programiranje1",
                "sandra: @berta Ne maram #programiranje1 #krneki",
                "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                "cilka: jst sm pa #luft",
                "benjamin: pogrešam ano #zalosten",
                "cilka: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"sandra": "Spet ta dež. #dougcajt",
             "berta": "@sandra Delaj domačo za #programiranje1",
             "ana": "kdo so te: @berta, @cilka, @dani? #krneki",
             "cilka": "jst sm pa #luft",
             "benjamin": "pogrešam ano #zalosten"})

        self.assertDictEqual(
            prvi_tvit([
                "sandra: Spet ta dež. #dougcajt",
                "sandra: @sandra Delaj domačo za #programiranje1",
                "sandra: @berta Ne maram #programiranje1 #krneki",
                "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                "sandra: jst sm pa #luft",
                "benjamin: pogrešam ano #zalosten",
                "sandra: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"sandra": "Spet ta dež. #dougcajt",
             "ana": "kdo so te: @berta, @cilka, @dani? #krneki",
             "benjamin": "pogrešam ano #zalosten"})

        self.assertDictEqual(
            prvi_tvit(["ana: kdo so te: @berta, @cilka, @dani? #krneki"]),
            {"ana": "kdo so te: @berta, @cilka, @dani? #krneki"})

        self.assertEqual(prvi_tvit([]), {})

    def test_4_prestej_tvite(self):
        self.assertDictEqual(
            prestej_tvite([
                "sandra: Spet ta dež. #dougcajt",
                "berta: @sandra Delaj domačo za #programiranje1",
                "sandra: @berta Ne maram #programiranje1 #krneki",
                "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                "cilka: jst sm pa #luft",
                "benjamin: pogrešam ano #zalosten",
                "cilka: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"sandra": 2, "berta": 1, "ana": 1, "cilka": 2, "benjamin": 1})

        self.assertDictEqual(
            prestej_tvite([
                    "sandra: Spet ta dež. #dougcajt",
                    "sandra: @sandra Delaj domačo za #programiranje1",
                    "sandra: @berta Ne maram #programiranje1 #krneki",
                    "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                    "sandra: jst sm pa #luft",
                    "benjamin: pogrešam ano #zalosten",
                    "sandra: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"sandra": 5, "ana": 1, "benjamin": 1})

        self.assertDictEqual(
            prestej_tvite(["ana: kdo so te: @berta, @cilka, @dani? #krneki"]),
            {"ana": 1})

        self.assertEqual(prestej_tvite([]), {})

    def test_5_omembe(self):
        self.assertDictEqual(
            omembe(["sandra: Spet ta dež. #dougcajt",
                    "berta: @sandra Delaj domačo za #programiranje1",
                    "sandra: @berta Ne maram #programiranje1 #krneki",
                    "ana: kdo so te: @berta, @cilka, @dani? #krneki",
                    "cilka: jst sm pa #luft",
                    "benjamin: pogrešam ano #zalosten",
                    "sandra: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {"sandra": ["berta", "benjamin", "ana"],
             "benjamin": [],
             "cilka": [],
             "berta": ["sandra"],
             "ana": ["berta", "cilka", "dani"]}
        )

    def test_6_neomembe(self):
        omembe = {"sandra": ["berta", "benjamin", "ana"],
                  "benjamin": [],
                  "cilka": [],
                  "berta": ["sandra"],
                  "ana": ["berta", "cilka", "dani", "benjamin", "sandra"]}

        self.assertEqual(neomembe("sandra", omembe), ["cilka"])
        self.assertEqual(neomembe("ana", omembe), [])
        self.assertEqual(set(neomembe("benjamin", omembe)), set(omembe) - {"benjamin"})

class TestDodatna(unittest.TestCase):
    def test_1_se_poznata(self):
        omembe = {"sandra": ["berta", "benjamin", "ana"],
                  "benjamin": [],
                  "cilka": [],
                  "berta": ["sandra"],
                  "ana": ["berta", "cilka", "dani"]}

        self.assertTrue(se_poznata("ana", "berta", omembe))
        self.assertTrue(se_poznata("berta", "ana", omembe))
        self.assertTrue(se_poznata("sandra", "benjamin", omembe))
        self.assertTrue(se_poznata("benjamin", "sandra", omembe))

        self.assertFalse(se_poznata("benjamin", "ana", omembe))
        self.assertFalse(se_poznata("ana", "benjamin", omembe))

        self.assertFalse(se_poznata("cilka", "dani", omembe))
        self.assertFalse(se_poznata("pavel", "peter", omembe))

    def test_2_hashtagi(self):
        self.assertDictEqual(
            hashtagi(["sandra: Spet ta dež. #dougcajt",
                      "berta: @sandra Delaj domačo za #programiranje1",
                      "sandra: @berta Ne maram #programiranje1 #krneki",
                      "ana: kdo so te @berta, @cilka, @dani? #krneki",
                      "cilka: jst sm pa #luft",
                      "benjamin: pogrešam ano #zalosten",
                      "ema: @benjamin @ana #split? po dvopičju, za začetek?"]),
            {'dougcajt': ['sandra'],
             'krneki': ['ana', 'sandra'],
             'luft': ['cilka'],
             'programiranje1': ['berta', 'sandra'],
             'split': ['ema'],
             'zalosten': ['benjamin']})

if __name__ == "__main__":
    unittest.main()

code/batch-2/dn6 - spet tviti/M-17115-2546.py


import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

import pickle
import numpy as np
import pandas as pd
from sklearn.neighbors import NearestNeighbors

from dnn import SCRM_Model
from variables import*
from util import*

class SCRM_Inference(object):
    def __init__(self):
        self.scrm = SCRM_Model()
        self.scrm.run()
        self.vocab = self.scrm.word2index

    def predict(self, embedding_concerns):
        output = []
        for embedding_concerns in embedding_concerns:
            vector = self.scrm.runTFliteInference(embedding_concerns, False)
            output.append(vector)

        outputs = np.array(output)
        return outputs

    def data_to_features(self):
        if not os.path.exists(data_feature_path):
            data = read_mongo()
            data = data.dropna(axis=0)

            student_concerns = data['Student_Concern'].values
            solutions = data['Solution'].values
            student_id = data['id'].values
            embedding_concerns = text_processing(student_concerns)[1]

            features = self.predict(embedding_concerns)
            np.savez(
                    data_feature_path,
                    name1=features,
                    name2=solutions,
                    name3=student_id
                    )
        else:
            data = np.load(data_feature_path, allow_pickle=True)
            features = data['name1']
            solutions = data['name2']
            student_id = data['name3']

        self.features = features
        self.solutions = solutions
        self.student_id = student_id

    def nearest_neighbor_model(self):
        if not os.path.exists(n_neighbour_weights):

            self.neighbor = NearestNeighbors(
                                        n_neighbors = n_neighbors,
                                        )
            self.features = self.features.reshape(self.features.shape[0], -1)
            self.neighbor.fit(self.features)

            with open(n_neighbour_weights, 'wb') as file:
                pickle.dump(self.neighbor, file)

        else:
            with open(n_neighbour_weights, 'rb') as file:
                self.neighbor = pickle.load(file)

    def process_inf_data(self, concern):
        preprocessed_concern = preprocess_one(concern)
        pad_concerns = sequence_and_padding_concerns([preprocessed_concern], self.vocab)
        embedding_concern = word_embeddings(pad_concerns, self.vocab)
        embedding_concern = embedding_concern.reshape(max_length, embedding_dim)
        return embedding_concern

    def predict_one(self, concern):
        embedding_concern = self.process_inf_data(concern)
        feature_vector = self.scrm.runTFliteInference(embedding_concern, False).squeeze()
        categories = self.scrm.runTFliteInference(embedding_concern).squeeze()
        return feature_vector, categories

    @staticmethod
    def create_df_from_categories(categories):
        categories = categories.reshape(1, -1)
        df_pred = pd.DataFrame(
                        data = categories,
                        columns=['Department', 'Sub_Section', 'Concern_Type']
                        )
        return df_pred

    def apply_inverse_transform(self, categories):
        df_pred = SCRM_Inference.create_df_from_categories(categories)
        with open(encoder_dict_path, 'rb') as handle:
            encoder_dict = pickle.load(handle)
        df_pred = df_pred.apply(lambda x: encoder_dict[x.name].inverse_transform(x))
        output = df_pred.values.squeeze().tolist()
        return output

    def predict_best_solution(self, concern):
        feature_vector, categories = self.predict_one(concern)

        neighbor = self.neighbor.kneighbors([feature_vector], 1)[1]
        neighbor = neighbor.squeeze()

        categories = self.apply_inverse_transform(categories)
        return self.solutions[neighbor], categories

    def make_response(self, request):
        concern = request['concern']
        solution, categories = self.predict_best_solution(concern)

        response = {
            'concern':concern,
            'solution': solution,
            'Department' : categories[0],
            'Sub_Section' : categories[1],
            'Concern_Type' : categories[2]
                }

        return response

inf = SCRM_Inference()
inf.data_to_features()
inf.nearest_neighbor_model()

request = {
    'concern': 'Can I join to mulitiple sports teams? '
          }

response = inf.make_response(request)
print(response)


import os
from selenium import webdriver
import pandas as pd

os.environ['PATH'] += r'C:/chromedriver'
driver = webdriver.Chrome()

url = 'https://www.youtube.com/c/JohnWatsonRooney/videos'
driver.get(url)

vidoes = driver.find_elements_by_class_name('style-scope ytd-grid-video-renderer')            ## scroll down must be used with mouse
you_list =[]                                                                                #  Dynamic website!!
for data in vidoes:
    title = data.find_element_by_id('video-title').text
    views = data.find_element_by_xpath('.//*[@id="metadata-line"]/span[1]').text
    posted = data.find_element_by_xpath('.//*[@id="metadata-line"]/span[2]').text
    #print(title, views, posted)

    youtube_dict={
        "Title" : [title],
        "Views" : [views],
        "Posted" : [posted]
    }
    you_list.append(youtube_dict)

DataFrame = pd.DataFrame(you_list)
#print(DataFrame)
DataFrame.to_csv('youtube.csv')


import calendar
import pymongo
import pdb
import datetime
from copy import deepcopy
import json
import locale
locale.setlocale(locale.LC_ALL, 'es_ES.utf8')
month_name = [month for month in calendar.month_name]

def get_db(settings, drop):
    connection = pymongo.MongoClient(
        settings['MONGODB_SERVER'], settings['MONGODB_PORT'])
    db_name = settings['MONGODB_DB']
    return connection[db_name]

def get_collection(db, collection_name):
    return db[collection_name]

def insert_many(collection, items_list):
    try:
        collection.insert_many(items_list)
    except pymongo.errors.DuplicateKeyError:
        return False
    return True

def _process_result(result):
    result["genre"] = ", ".join(result["genre"])
    result["platforms"] = ", ".join(result["platforms"])
    result["release_date"] = str(result["release_date"]).split(' ')[0]
    result["score"] = int(result["score"])
    return result

def list_reviews(collection, filter_dict, sort_by="release_date", offset=0, page_size=1):
    cursor = collection.find(filter_dict).sort(sort_by, pymongo.DESCENDING)
    if offset > 0:
        cursor = cursor.skip(offset)
    cursor = cursor.limit(page_size+1)
    results = [_process_result(result) for result in cursor]
    has_next = len(results) > page_size
    if has_next:
        return results[:-1], has_next
    return results, has_next

def search_by_name(collection, name, max_number_results=5):
    query = {"game_name": {"$regex": name, "$options": 'i'}}
    cursor = collection.find(query).limit(max_number_results)
    return [_process_result(result) for result in cursor]

def build_query(eq_filters, range_filters):
    filter_dict = {}

    and_cond = []
    for field, eq_conds in eq_filters.items():
        if len(eq_conds) == 1:
            filter_dict[field] = eq_conds[0]
        else:
            and_cond += [{field: value} for value in eq_conds]
    if and_cond:
        filter_dict["$and"] = and_cond

    for range_field, (inf_limit, sup_limit) in range_filters.items():
        _range_filter = {range_field: {}}
        if inf_limit:
            _range_filter[range_field]["$gt"] = inf_limit
        if sup_limit:
            _range_filter[range_field]["$lt"] = sup_limit
        if _range_filter[range_field]:
            filter_dict.update(_range_filter)
    return filter_dict


__author__ = 'KKharitonov'

import datetime
import logging

import pony.orm as pny
import torrent_list.orm.transform as transform

logging.basicConfig(level=logging.INFO)

clear_db_on_startup = False
sql_debug_flag = True

db = pny.Database()

class User(db.Entity):
    name = pny.Required(str)
    email = pny.Required(str)
    hubs = pny.Set('Hub')
    removed_movies = pny.Set('RemovedMovies', lazy=True)
    # movies = pny.Set('Movie', lazy=True)

class Hub(db.Entity):
    url = pny.Required(str)
    module = pny.Required(str)
    description = pny.Optional(str)
    torrents = pny.Set('Torrent')
    users = pny.Set(User)
    removed_movies = pny.Set('RemovedMovies', lazy=True)

class Movie(db.Entity):
    description = pny.Required(str)
    found_date = pny.Required(datetime.datetime)
    full_name = pny.Required(str)
    name_rus = pny.Required(str)
    name_eng = pny.Optional(str)
    actors = pny.Optional(str)
    genre = pny.Optional(str)
    imdb_id = pny.Optional(str)
    imdb_rating = pny.Optional(float)
    kinopoisk_id = pny.Optional(str)
    kinopoisk_rating = pny.Optional(str)
    poster_url = pny.Optional(str)
    year = pny.Optional(str)
    torrents = pny.Set('Torrent')
    removed_movies = pny.Set('RemovedMovies', lazy=True)

class Torrent(db.Entity):
    nnm_id = pny.PrimaryKey(int, size=32)
    title = pny.Required(str)
    torrent_url = pny.Required(str, unique=True)
    url = pny.Required(str, unique=True)
    hub = pny.Required(Hub)
    movie = pny.Optional(lambda: Movie)
    size = pny.Optional(str)
    seeders = pny.Optional(int)
    leechers = pny.Optional(int)
    translation = pny.Optional(str)
    # users = pny.Set(User)

class RemovedMovies(db.Entity):
    movie = pny.Required(Movie)
    hub = pny.Required(Hub)
    user = pny.Required(User)
    pny.PrimaryKey(movie, hub, user)

def init_db():
    if sql_debug_flag:
        pny.sql_debug(True)

    db.bind("sqlite", "torrents.sqlite", create_db=True)
    db.generate_mapping(create_tables=True)
    if clear_db_on_startup:
        db.drop_all_tables(with_all_data=True)
        db.create_tables()
        init_data()

@pny.db_session
def get_current_user():
    # FIXME Mock implementation
    return User[1]

def get_current_user_id():
    # FIXME Mock implementation
    return 1

@pny.db_session
def save_movie(hub_id, movie):
    query = "SELECT * FROM Movie WHERE full_name = $movie.full_name"
    if movie.imdb_id:
        query += " OR imdb_id = $movie.imdb_id"
    if movie.kinopoisk_id:
        query += " OR kinopoisk_id = $movie.kinopoisk_id"
    db_movie = Movie.get_by_sql(query)
    if db_movie:
        logging.info("Movie already exist in DB. Add new torrent to movie")
        db_torrent = transform.torrent_sc_to_db(movie.torrent, hub_id)
        db_movie.torrents.add(db_torrent)
    else:
        db_movie, db_torrent = transform.movie_sc_to_db(movie, hub_id)
        # add_movie_to_all_users(db_movie)

# def add_movie_to_all_users(movie_id, hub_id):
#     # for u in pny.selects(u for u in User for hub in u.hubs if db_torrent.hub == hub):
#     #     u.torrents.add(db_torrent)
#     for u in pny.selects(u for u in User for hub in u.hubs if hub == hub_id):
#         UserMoviesHub(user=u, hub=hub_id, movie=movie_id)

@pny.db_session
def filter_exist_torrents(url_list):
    ids = {url.split('=')[-1] for url in url_list}
    exist = pny.select(t.url for t in Torrent if t.nnm_id in ids)
    return url_list.difference(exist)

@pny.db_session
def get_all_movies(hub_id):
    user = get_current_user()
    if hub_id:
        movies = pny.select(m for m in Movie
                            for t in m.torrents
                            if t.hub.id == hub_id and m not in user.removed_movies.movie)
    else:
        movies = pny.select(m for m in Movie
                            if m not in user.removed_movies.movie)

    return transform.movies_db_to_json(movies)

# class RemovedMovies(db.Entity):
#     movie = pny.Required(Movie)
#     hub = pny.Required(Hub)
#     pny.PrimaryKey(movie, hub)
#     user = pny.Required(User)

@pny.db_session
def remove_movies_from_user(toRemove):
    user = get_current_user_id()
    for item in toRemove:
        for hub_id in item['hubIds']:
            RemovedMovies(movie=item['id'], hub=hub_id, user=user)

@pny.db_session
def init_data():
    user = User(name='Test Uset', email='kest01@yandex.ru')

    hub = Hub(url='https://nnm-club.me/forum/viewforum.php?f=218', module='nnm_scraping',
              description='NNM: Зарубежные новинки DVDRip')
    # hub2 = Hub(url='http://nnm-club.me/forum/viewforum.php?f=270', module='nnm_scraping', description='NNM: Отечественные новинки DVDRip')
    hub3 = Hub(url='https://nnm-club.me/forum/viewforum.php?f=888', module='nnm_scraping',
               description='NNM: Новинки (3D)')
    # hub4 = Hub(url='http://nnm-club.me/forum/viewforum.php?f=954', module='nnm_scraping', description='NNM: Новинки (HD)')
    # hub5 = Hub(url='http://nnm-club.me/forum/viewforum.php?f=217', module='nnm_scraping', description='NNM: Экранки')

    user.hubs.add(hub)
    # user.hubs.add(hub2)
    user.hubs.add(hub3)
    # user.hubs.add(hub4)
    # user.hubs.add(hub5)

@pny.db_session
def get_hubs():
    hubs = Hub.select()
    return hubs[:]

def get_habs_and_new():
    return transform.hubs_db_to_json(get_hubs())

if __name__ == "__main__":
    # @db_session

    clear_db_on_startup = True

    init_db()


print("Input:")
ll=[]
l2=[]
for j in range(3):
    for i in range(2):
        l = list(map(str, input().split()))

    def sq(x):
        return (int(l[0])/int((l[1])))

    m=list(map(sq, l))
    l2=l2+m
l2.sort()
print(l2)

B-JET_10th Batch V 1.0.0/0b3 prev ans.py


import os
import cv2
import numpy as np
from numpy.fft import fft2, ifft2
from scipy.signal.windows import gaussian
import matplotlib.pyplot as plt

RESULT_FILENAME_KEY = "{folder}/result_{{quality}}.jpg"
REGION_SIZE = 3

def best_cmp_fn(a, b):
    return a < b

def worse_cmp_fn(a, b):
    return best_cmp_fn(b, a)

class Noiser():
    def blur(self, img, sigma_blur):
        """
        :param img: cv2 image instance
        :param sigma_blur: int indicating blur quantity
        :return: image with gaussian blur
        """
        return cv2.GaussianBlur(img, (REGION_SIZE, REGION_SIZE), sigma_blur)

    def add_gaussian_noise(self, img, sigma_noise):
        """

        :param img: cv2 image instance
        :param sigma_noise: int indicating blur quantity
        :return: image with gaussian noise
        """
        gauss = np.random.normal(0, sigma_noise, np.shape(img))
        noisy_img = img + gauss
        noisy_img[noisy_img < 0] = 0
        noisy_img[noisy_img > 255] = 255
        return noisy_img

    def run(self, filename, sigma_noise, sigma_blur):
        """
        :param filename: image filename
        :param sigma_noise: int indicating gaussian noise quantity
        :param sigma_blur: int indicating gaussian blur quantity
        :return: noised image and folder location where it saved the modified image
        """
        img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
        blur_img = self.blur(img, sigma_blur)
        noise_img = self.add_gaussian_noise(blur_img, sigma_noise)

        _folder = 'results_{sigma_noise}_{sigma_blur}'.format(sigma_noise=sigma_noise, sigma_blur=sigma_blur)
        self._create_folder(_folder)
        cv2.imwrite('{folder}/image_with_noise.png'.format(folder=_folder), noise_img)
        return noise_img, _folder

    def _create_folder(self, folder):
        try:
            os.mkdir(folder)
        except:
            pass

class Wiener():

    def degradation_function(self, sigma_noise, region_size=REGION_SIZE):
        """

        :param sigma_noise: noise added to the img
        :param region_size: size of the window where noise was added
        :return:
        """
        h = gaussian(region_size, sigma_noise).reshape(region_size, 1)
        h = np.dot(h, h.transpose())
        h /= np.sum(h)
        return h

    def run(self, img, sigma_noise, output_filename):
        """
        The function finds best results and output the image
        :param img: cv2 image instance
        :param sigma_noise: int indicating gaussian noise quantity
        :param output_filename: str indicating output filename

        """
        H = self.degradation_function(sigma_noise, region_size=REGION_SIZE)
        H /= np.sum(H)
        G = fft2(img)
        H = fft2(H, s=G.shape)
        H_star = np.conj(H)
        H_2 = np.abs(H) ** 2

        self._calculate_best_k_and_output_image(G, H_2, H_star, output_filename, img, cmp_fn=best_cmp_fn, quality="best")
        self._calculate_best_k_and_output_image(G, H_2, H_star, output_filename, img, cmp_fn=worse_cmp_fn, quality="worse")

    def _calculate_best_k_and_output_image(self, G, H_2, H_star, filename, img, cmp_fn, quality):
        """
        The method gets the best K and outputs the image
        """
        best_k, F_hat = self._find_K_by_function(G, H_2, H_star, img, cmp_fn, key=quality)
        plt.imshow(F_hat, cmap='gray', interpolation='nearest')
        plt.axis('off')
        plt.title("{} K={}".format(quality, best_k))
        plt.savefig(filename.format(quality=quality), bbox_inches='tight')

    def _find_best_K_by_function(self, G, H_2, H_star, img, cmp_fn, key):
        """
        Iterates over every possible K, calculates the error and chooses the best one
        """
        best_error = -1
        best_k = -1
        start = 10
        best_F_hat = None
        for _k in range(start, 2000):
            k = _k / 1000
            F_hat = self._get_F_hat(H_2, H_star, G, k)
            error = ((img - F_hat) ** 2).mean()
            if _k == start:
                best_error = error
                best_k = k
            best_error, best_k, best_F_hat = (error, k, F_hat) if cmp_fn(error, best_error) else (
                best_error, best_k, best_F_hat)
        print("{}_error={}".format(key, best_error))
        print("{}_k={}".format(key, best_k))
        return best_k, best_F_hat

    def _get_F_hat(self, H_2, H_star, G, k):
        """

        :param H_2: square of is the magnitude of the Fourier transform of H
        :param H_star: complex conjugate of the Fourier transform of H
        :param G: Fourier transform of g
        :param k: constant related to the noise,
        :return: F_Hat based on the wiener formula
        """
        H = H_star / (H_2 + k)
        G = G * H
        inverse_fourier = np.abs(ifft2(G))
        return inverse_fourier

if __name__ == "__main__":
    noiser = Noiser()
    wiener = Wiener()

    filename = "lena.png"
    cases = [{
        "sigma_noise": 1,
        "sigma_blur": 1.5,
    }, {
        "sigma_noise": 5,
        "sigma_blur": 1.5,
    }, {
        "sigma_noise": 15,
        "sigma_blur": 1.5,
    }]

    for case in cases:
        image_with_noise, folder = noiser.run(filename, **case)
        wiener.run(image_with_noise, sigma_noise=case['sigma_noise'],
                   output_filename=RESULT_FILENAME_KEY.format(folder=folder))