import random
from datetime import datetime
from typing import List

from termcolor import colored

from modeles import Match, Player, Round, Tournament
from persistance import DatabasesTinydb
from views.common import Usefull
from views.main import MainView
from views.player import PlayerView
from views.tournament import TournamentView

class TournamentController:
    opponents_by_player = {}
    list_of_matchs = []
    score_list_player = []
    players_score_sorted = []
    add_score_player = []
    score_players = []
    round_number = ""
    round_list = []
    players = []
    resultat = []

    def __init__(self):
        self.main_view = MainView()
        self.tournament_view = TournamentView()
        self.player_view = PlayerView()
        self.usefull = Usefull()
        self.persistance = DatabasesTinydb()

    def get_db_players(self):
        for index, player in enumerate(DatabasesTinydb().players):
            idx = index
            ident = player["ident"]
            surname = player["surname"]
            firstname = player["firstname"]
            date_of_birth = player["date_of_birth"]

            self.players.append(Player(idx,
                                       ident,
                                       surname,
                                       firstname,
                                       date_of_birth)
                                )

    def create_dico_player_playing(self, competitors):
        """Création du dictionnaire de joueurs/adversaires"""
        opponents_by_player = {}

        for player in competitors:
            list_players_playing = [i for i in competitors if i != player]
            opponents_by_player[player.ident] = list_players_playing

        return opponents_by_player

    def generate_pairs_randomly(self, selected_player: list) -> list:
        """Génération des pairs de joueurs aléatoirement pour le 1er round"""
        matchs_list = []
        list_1 = []
        list_2 = []
        random.shuffle(selected_player)
        nb_player = len(selected_player)

        for i in range(nb_player):
            if i % 2:
                list_1.append(selected_player[i])
            else:
                list_2.append(selected_player[i])
        nb_match = len(selected_player) // 2

        for i in range(0, nb_match):
            player_1 = list_1[i]
            player_2 = list_2[i]
            self.opponents_by_player[player_1.ident].remove(player_2)
            self.opponents_by_player[player_2.ident].remove(player_1)
            print(f"     {player_1} -vs- {player_2}")
            matchs_list.append([player_1, player_2])
        return matchs_list

    def generate_pairs_for_round(self, players: list):
        """Génération des pairs de joueurs pour les autres rounds"""

        players_to_pair = []
        for player in players:
            players_to_pair.append(player)
        pairs = []

        while players_to_pair:
            current_player = players_to_pair.pop()
            opponents = self.opponents_by_player[current_player.ident]
            for opponent in opponents:
                if (
                    opponent in players_to_pair
                    and opponent in
                        self.opponents_by_player[current_player.ident]
                ):
                    new_opponent = opponent
                    # Create pair
                    pairs.append([current_player, new_opponent])
                    players_to_pair.remove(opponent)
                    self.opponents_by_player[current_player.ident].remove(
                        opponent
                    )
                    self.opponents_by_player[opponent.ident].remove(
                        current_player
                    )
                    print(f"     {current_player} -vs- {new_opponent}")
                    break
        return pairs

    def create_matches(self, pairs) -> List[Match]:
        """Création de la liste des matchs depuis les pairs"""

        matches = []

        for pair in pairs:
            new_match = Match(*pair)
            matches.append(new_match)

        return matches

    def enter_scores_for_match(self, match):
        """Saisie et incrémentation des scores"""

        for player_element in match.players:
            # This should be part of function in the view layer
            player_obj = player_element[0]
            score_progress = False
            while score_progress is False:
                player_match_score = input(
                    f" Saisir le score du joueur" f" {player_obj}: "
                )
                try:
                    if (
                        (float(player_match_score) == 0)
                        or (float(player_match_score) == 0.5)
                        or (float(player_match_score) == 1)
                    ):
                        score_progress = True
                    else:
                        print(
                            colored(
                                "!!! Entrée non valide, saisir "
                                "0 (perdu), "
                                "1 (gagné) ou "
                                "0.5 (nul) !!!",
                                "red",
                                attrs=["bold"],
                            )
                        )
                except ValueError:
                    print(
                        colored(
                            "!!! Entrée non valide, saisir "
                            "0 (perdu), "
                            "1 (gagné) ou "
                            "0.5 (nul) !!!",
                            "red",
                            attrs=["bold"],
                        )
                    )

            player_element[1] = float(player_match_score)
            player_obj.score += float(player_match_score)

    def get_round_list(self, matches: list, rounds: int):
        current_round = Round(matches, rounds)
        self.round_list.append([current_round.name, current_round.matches])

        return self.round_list

    def start_tournament(self):
        self.get_db_players()
        print("")
        if not self.players:
            print(
                colored(
                    "La base de données des joueurs est vide ! ",
                    "red",
                    attrs=["bold"]
                )
            )
            return
        # Display view to get inputs for the new tournament
        tournament_data = self.tournament_view.get_tournament_data()
        current_tournament = Tournament(*tournament_data)

        # Presentation of tournament
        print("")
        print(
            "     Tournoi d'échec:",
            colored(current_tournament.name,
                    "blue",
                    attrs=["bold"]),
        )
        print(
            "     Lieu:", colored(current_tournament.location,
                                  "blue",
                                  attrs=["bold"])
        )
        print(
            "     Nombre de rounds:",
            colored(current_tournament.nb_round,
                    "blue",
                    attrs=["bold"]),
        )
        print(
            "     Date du tournoi :",
            colored(current_tournament.date_start,
                    "blue",
                    attrs=["bold"]),
        )
        print("")
        # Display view to get players playing the tournament
        current_tournament.players = \
            self.tournament_view.add_players_tournament(self.players)

        # Create dictionary to store who played with who
        self.opponents_by_player = self.create_dico_player_playing(
            current_tournament.players
        )

        # For round in rounds:

        for self.round_number in range(1, current_tournament.nb_round + 1):
            if self.round_number == 1:
                print("                     *********************")
                print(
                    f"                     * Matchs du Round"
                    f" {self.round_number} *"
                )
                print("                     *********************")
                print("")

                # round_date_start = datetime.today().strftime("%d%m%Y-%H%M")
                # print("---round_date_start---->", round_date_start)
                pairs = self.generate_pairs_randomly(
                    current_tournament.players
                )

            else:
                print("                     *********************")
                print(
                    f"                     * Matchs du Round"
                    f" {self.round_number} *"
                )
                print("                     *********************")
                print("")

                # round_date_start = datetime.today().strftime("%d%m%Y-%H%M")
                # print("---round_date_start---->", round_date_start)
                players_sorted_by_score = sorted(
                    current_tournament.players,
                    key=lambda p: p.score,
                    reverse=True
                )
                pairs = self.generate_pairs_for_round(players_sorted_by_score)

            # Create matches from pairs
            matches = self.create_matches(pairs)

            # For match in matches:
            for i, match in enumerate(matches, 1):
                # Enter result for match
                print("")
                print(
                    colored(
                        f"Match {i}:"
                        f" {match.players[0][0]}"
                        f" -vs-"
                        f" {match.players[1][0]}",
                        "blue",
                        attrs=["bold"],
                    )
                )

                self.enter_scores_for_match(match)

                for player in match.players:
                    print(
                        f"   Score de {player[0].firstname}"
                        f" {player[0].surname}:",
                        colored(player[0].score,
                                "green",
                                attrs=["bold"]
                                )
                    )
                    self.resultat.append(
                        [
                            f"{player[0].surname}" f" {player[0].firstname}",
                            player[0].score,
                        ]
                    )

            # rounds list
            current_tournament.rounds.append(Round(matches,
                                                   str(self.round_number)
                                                   )
                                             )

            # round_date_end = datetime.today().strftime("%d%m%Y-%H%M")
            # print("---round_date_end---->", round_date_end)
            print("")

        current_tournament.date_end = datetime.today().strftime("%d-%m-%Y")
        current_tournament.description = input("Remarques générales"
                                               " du tournoi: ")
        print("")
        print(
            f"******************* "
            f"Fin du tournoi ({current_tournament.date_end}) "
            f"******************* "
        )

        # put tournament data in database
        self.persistance.put_current_tournament_in_database(
            current_tournament, self.round_number
        )

        return current_tournament


import csv, os,numpy
# Parse the csv file into precip and temp
tile = 'SP'
runtype = 'FC'
scenario='a2'
nhru=371

if runtype == 'CC':
    run = ''
    thisdir=os.getcwd()+"\\BCCA\\"+tile+"\\"+tile+"_"+runtype
    os.chdir(thisdir)
else:
    run = scenario
    thisdir=os.getcwd()+"\\BCCA\\"+tile+"\\"+tile+"_"+runtype+"\\"+scenario
    os.chdir(thisdir)

# set directories

#os.chdir(thisdir+'\\BCCA\\SP\\SP_FC\\'+run)
#CC
#dataset= ['cccma_cgmc3'+run,'cnrm_cm3'+run,'gfdl_cm2_1'+run,'ipsl_cm4'+run,'miroc3_2_medres'+run,'miub_echo_g'+run,'mri_cgcm2_3_2a'+run]
dataset=['mri_cgcm2_3_2a'+run]

for data in dataset:
    os.makedirs(data)
    #dataType = ['pr','tasmax','tasmin']
    varfile = [data+'-gregorian-20c3m-run1-pr-BCCA_0-125deg-monthly',\
        data+'-gregorian-20c3m-run1-tasmax-BCCA_0-125deg-monthly',\
        data+'-gregorian-20c3m-run1-tasmin-BCCA_0-125deg-monthly']
    varlist=['pr','tasmax','tasmin']
    index = 0

##    PORcount = 0
##    for var in varlist:
##        outputfile = thisdir+'\\'+data+'\\'+var+"_month.txt"
##        #inputfile=open(thisdir+'\\'+var+".csv", 'r')
##        #inputfile=open(thisdir+'\\'+data+'-gregorian-20c3m-run1-'+varlist+'-BCCA_0-125deg-monthly.csv', 'r')
##        inputfile=open(thisdir+"\\"+data+'-gregorian-20c3m-run1-'+var+'-BCCA_0-125deg-monthly.csv', 'r')
##        filelines = inputfile.readlines()
##        outputfile = open (outputfile, 'a')
##        PORfile = open(thisdir+"\\"+data+'\\POR.txt','a')
##        for line in filelines[2:]:
##            #print line[0:20]
##            splitline = line.split(',')
##            timestamp = splitline[0].split('T')
##            yrmoday = timestamp[0].split('-')
##            year = yrmoday[0]
##            month = int(yrmoday[1])
##            newline = year+' '+str(month)+' '
##            print year,month
##            for i in range(1,len(splitline)):
##                if var != 'pr':
##                    newline = newline +str((float(splitline[i].rstrip())*1.8)+32)+' ' # Celsius to Fahrenheit
##                if var == 'pr':
##                    newline = newline +str(float(splitline[i].rstrip())*.0393)+' '# mm to inches
##                # K to C
##                # K - 273.15 - deg C
##                # Celsius to Fahrenheit
##                #if var != 'ppt':
##                    #newline = newline +str((float(splitline[i].rstrip())*1.8)+32)+' '
##                # K to F
##                #K * 1.8 - 459.67
##                #newline = newline +str((float(splitline[i].rstrip())*1.8)-459.67)+' '
##                # kg m-2 s-1 to mm/day
##                # (kg m-2 s-1)*8640 to in/day
##                #newline = newline +str(float(splitline[i].rstrip())*8640*.3937)+' '
##                # mm to inches
####                if var == 'ppt':
####                    newline = newline +str(float(splitline[i].rstrip())*.0393)+' '
##            if var == 'pr':
##                PORline = str(year)+'-'+str(month)+'-01 \n'
##                PORfile.writelines(PORline)
##                PORcount = PORcount+1
##            newline = newline + '\n'
##            outputfile.writelines(newline)
##        inputfile.close()
##        outputfile.close()
##        print var+'.txt is finished formatting'
##    PORfile.close()
##    #*************************************************************
##        # write and format final temp file
##    tmaxfile = thisdir+'\\'+data+'\\tasmax_month.txt'
##    tminfile = thisdir+'\\'+data+'\\tasmin_month.txt'
##    tavefile = 'TAVE_month.txt'
##    outputfile = open (thisdir+'\\'+data+'\\'+tavefile, 'a')
##    files = [tmaxfile,tminfile]
##
##    tmax = numpy.zeros(shape = (PORcount,nhru))
##    tmin = numpy.zeros(shape = (PORcount,nhru))
##
##    dateList=[]
##    for i in range (0,len(files)):
##        count = 0
##        infile = open(files[i], 'r')
##        filelines = infile.readlines()
##        for lines in filelines[0:tmax.shape[0]]:
##            items = lines.split()
##            if i == 0:
##                tmax[count,...]=items[2:]
##            if i == 1:
##                tmin[count,...]=items[2:]
##            newstring = items[0]+' '+items[1]+' '
##            dateList.append(newstring)
##            count = count+1
##    infile.close()
##
##    temp_sum = numpy.add(tmax,tmin)
##    tave = temp_sum/2
##
##    for i in range(0,tave.shape[0]):
##        newstring = dateList[i]
##        for j in range(0,tave.shape[1]):
##            newstring = newstring+str(tave[i][j])+' '
##        newstring = newstring+'\n'
##        outputfile.writelines(newstring)
##    print 'done converting files for use in WBM'
##    outputfile.close()


from pathlib import Path
import pandas as pd
from nilearn.masking import compute_epi_mask
from nilearn.image import load_img, mean_img
from nilearn.masking import apply_mask
import nibabel as nib
from path_to_have import DATA_PATH, CACHE_PATH

class Subjects():
    """
    Class to get information from subjects
    """
    def __init__(self, lang = 'EN', path=DATA_PATH, cache=CACHE_PATH):
        """

        :param lang: EN (english) FR (french) or CN (Chinese)
        :param path: path to dataset
        :param cache: where the mask will be saved
        """
        path = Path(path)
        self.path = Path(path)
        self.cache = Path(cache)
        self.language = lang
        subjects = (path / 'derivatives').iterdir()
        files = list()
        for subject in subjects:
            if 'sub-' not in subject.name:
                continue

            runs = (subject / 'func').iterdir()
            language = subject.name.split('-')[1][:2]
            if language != self.language:
                continue
            for run_file in runs:
                #print(run_file.name)
                if not run_file.name.endswith('.nii.gz'):
                    continue
                run_id = int(run_file.name.split('-')[3][:2])
                file = dict(subject=subject.name,
                            run=int(run_id),
                            language=language,
                            file=run_file)
                files.append(file)
        self.files = pd.DataFrame(files)
        #print(self.files)

    def __call__(self, subject_id, run_nb):
        """ Gets the fmri masked for one specific run """
        files = self.files[self.files['subject'] == subject_id]
        files = files.sort_values(by = 'run')
        #print(files)
        files = files.iloc[int(run_nb - 1)]
        #for file in files.file:
        return self._read_fmri(str(files.file))

    @property
    def mask(self):
        """ Computes mask for language group """
        if not (self.cache / 'mask.nii').exists():
            img = mean_img([str(f) for f in self.files.file])
            mask = compute_epi_mask(img)
            nib.save(mask, self.cache / 'mask.nii')
        return nib.load(self.cache / 'mask.nii')

    def _read_fmri(self, file):
        """ Read fmri from file """
        imgs = load_img(str(file))
        masked_imgs = apply_mask(imgs, self.mask)
        return masked_imgs


"""
Contains tools for performing permutation tests.
"""

import numpy as np

def permute_subset(x: np.ndarrray, to_permute_subset: np.ndarray, inplace: bool=False):
    """
    Takes array x and a list of elements to permute in that array.
    Permutes only those elements, leaving the rest alone.

    Parameters
    ----------
    x : array-like, shape (n,)
        array to be permuted
    to_permute_subset : array-like, shape (c,) where c is number of elements to permute
        elements within x to permute, leaving other elements alone
    Example:
        x = np.asarray([0, 1, 2, 3, 4, 0, 1, 2, 3, 4])
        to_permute_subset = np.asarray([1, 3])
        permute_subset(x, to_permute_subset, inplace=False) # -> array([0, 1, 2, 1, 4, 0, 3, 2, 3, 4])

    Returns
    -------
    x : array-like, shape (n,)
        If inplace, modifies x inplace.
    """
    x = np.squeeze(np.asarray(x))
    assert x.ndim == 1
    if not inplace: x = np.copy(x)
    permute_flag = np.isin(x, to_permute_subset)
    per_array = x[permute_flag]
    x[permute_flag] = np.random.permutation(per_array)
    return x


import numpy as np
import torch
import torch.nn as nn
import math
import torch.nn.functional as F

class BaseNetwork(nn.Module):
    def __init__(self):
        super(BaseNetwork, self).__init__()

    def init_weights(self, init_type='normal', gain=0.02):
        '''
        initialize network's weights
        init_type: normal | xavier | kaiming | orthogonal
        https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/9451e70673400885567d08a9e97ade2524c700d0/models/networks.py#L39
        '''

        def init_func(m):
            classname = m.__class__.__name__
            if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
                if init_type == 'normal':
                    nn.init.normal_(m.weight.data, 0.0, gain)
                elif init_type == 'xavier':
                    nn.init.xavier_normal_(m.weight.data, gain=gain)
                elif init_type == 'kaiming':
                    nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
                elif init_type == 'orthogonal':
                    nn.init.orthogonal_(m.weight.data, gain=gain)

                if hasattr(m, 'bias') and m.bias is not None:
                    nn.init.constant_(m.bias.data, 0.0)

            elif classname.find('BatchNorm2d') != -1:
                nn.init.normal_(m.weight.data, 1.0, gain)
                nn.init.constant_(m.bias.data, 0.0)

        self.apply(init_func)

class InpaintGenerator(BaseNetwork):
    def __init__(self, residual_blocks=7, init_weights=True):
        super(InpaintGenerator, self).__init__()

        self.encoder1 = nn.Sequential(
            nn.ReflectionPad2d(3),
            GateConv(in_channels=3, out_channels=64, kernel_size=7, padding=0),
            nn.InstanceNorm2d(64, track_running_stats=False),
            nn.ReLU(True))

        self.encoder2 = nn.Sequential(
            GateConv(in_channels=64, out_channels=128, kernel_size=4, stride=2, padding=1),
            nn.InstanceNorm2d(128, track_running_stats=False),
            nn.ReLU(True),
        )

        self.encoder3 = nn.Sequential(
            GateConv(in_channels=128, out_channels=256, kernel_size=4, stride=2, padding=1),
            nn.InstanceNorm2d(256, track_running_stats=False),
            nn.ReLU(True)
        )

        self.fushion1 = nn.Sequential(
            nn.Conv2d(in_channels=256,out_channels=256,kernel_size=1),
            nn.InstanceNorm2d(256,track_running_stats=False),
            nn.ReLU(True)
        )
        self.fushion1_1 = nn.Sequential(
            nn.Conv2d(in_channels=256+68,out_channels=256,kernel_size=1),
            nn.InstanceNorm2d(256,track_running_stats=False),
            nn.ReLU(True)
        )

        self.fushion2 = nn.Sequential(
            nn.Conv2d(in_channels=128,out_channels=128,kernel_size=1),
            nn.InstanceNorm2d(128,track_running_stats=False),
            nn.ReLU(True)
        )

        self.decoder1 = nn.Sequential(
            GateConv(in_channels=256, out_channels=128, kernel_size=4, stride=2, padding=1, transpose=True),
            nn.InstanceNorm2d(128, track_running_stats=False),
            nn.ReLU(True),
        )

        self.decoder2 = nn.Sequential(
            GateConv(in_channels=256, out_channels=64, kernel_size=4, stride=2, padding=1, transpose=True),
            nn.InstanceNorm2d(64, track_running_stats=False),
            nn.ReLU(True),
        )

        self.decoder3 = nn.Sequential(
            nn.ReflectionPad2d(3),
            nn.Conv2d(in_channels=128, out_channels=3, kernel_size=7, padding=0),
        )

        blocks = []
        for _ in range(residual_blocks):
            block = ResnetBlock(256, 2)
            blocks.append(block)

        self.middle = nn.Sequential(*blocks)

        self.auto_attn = Auto_Attn(input_nc=256, norm_layer=None)

        ## Landmark Pridictor Setting

        points_num = 68
        self.prelu = nn.PReLU()
        self.fc_landmark = nn.Linear(256, points_num * 2)
        self.conv_afteratt_first = conv_1x1_bn(256, 1280)
        self.conv_afteratt_node1 = nn.Conv2d(256, 64, (1, 1))
        self.conv_afteratt_node2 = nn.Conv2d(1280, 64, (1, 1))
        self.conv_afterarr_node3 = nn.Conv2d(1280,128, (1,1))
        self.before_share1 = nn.Sequential(
            nn.ConvTranspose2d(in_channels=256, out_channels=128, kernel_size=4, stride=2, padding=1),
        )

        self.landmark_gamma = nn.Parameter(torch.zeros(1))

        if init_weights:
            self.init_weights()

    def forward(self, x, mask_whole, mask_half, mask_quarter):

        f_e1 = self.encoder1(x)
        f_e2 = self.encoder2(f_e1)
        f_e3 = self.encoder3(f_e2)
        x = self.middle(f_e3)
        x, _ = self.auto_attn(x, f_e3, mask_quarter)

        ##### landmark branch, extraction step
        x_lmk = self.conv_afteratt_first(x) ## 256 -> 1280
        node1 = self.conv_afteratt_node1(x)
        node2 = self.conv_afteratt_node2(x_lmk)

        node1 = node1.mean(3).mean(2)
        node2 = node2.mean(3).mean(2)

        x_lmk = self.conv_afterarr_node3(x_lmk)
        x_lmk = x_lmk.mean(3).mean(2)

        final = self.prelu(x_lmk)

        ############# Inpainting branch, parameter share
        x = self.decoder1(x)
        x = self.fushion1(torch.cat((f_e2*(1-mask_half),x),dim=1))
        x_share = x.clone()
        x_share = x_share.mean(3).mean(2)
        ############# Landmark Predictor branch
        end = torch.cat([node1,node2,final],dim=1)
        end += self.landmark_gamma * x_share
        landmark = self.fc_landmark(end)

        landmark_share = landmark
        landmark_share = landmark_share.reshape((-1, 68, 2))
        landmark_share = landmark_share * 128
        landmark_share[landmark_share >= 127] = 127
        landmark_share[landmark_share < 0] = 0
        landmark_map = torch.zeros((landmark_share.shape[0],68,128,128)).cuda()

        for i in range(landmark_share.shape[0]):
            for p in range(landmark_share.shape[1]):

                landmark_map[i,:,landmark_share[i,0:68,1].int()[p],landmark_share[i,0:68,0].int()[p]]=1

        ######### inpainting branch
        x = self.fushion1_1(torch.cat((landmark_map,x),dim=1))

        x = self.decoder2(x)
        x = self.fushion2(torch.cat((f_e1*(1-mask_whole),x),dim=1))
        x = self.decoder3(x)
        x = (torch.tanh(x) + 1) / 2

        return x, landmark

class Discriminator(BaseNetwork):
    def __init__(self, in_channels, use_sigmoid=True, use_spectral_norm=True, init_weights=True):
        super(Discriminator, self).__init__()
        self.use_sigmoid = use_sigmoid

        self.conv1 = self.features = nn.Sequential(
            spectral_norm(nn.Conv2d(in_channels=in_channels, out_channels=64, kernel_size=4, stride=2, padding=1, bias=not use_spectral_norm), use_spectral_norm),
            nn.LeakyReLU(0.2, inplace=True),
        )

        self.conv2 = nn.Sequential(
            spectral_norm(nn.Conv2d(in_channels=64, out_channels=128, kernel_size=4, stride=2, padding=1, bias=not use_spectral_norm), use_spectral_norm),
            nn.LeakyReLU(0.2, inplace=True),
        )

        self.conv3 = nn.Sequential(
            spectral_norm(nn.Conv2d(in_channels=128, out_channels=256, kernel_size=4, stride=2, padding=1, bias=not use_spectral_norm), use_spectral_norm),
            nn.LeakyReLU(0.2, inplace=True),
        )

        self.conv4 = nn.Sequential(
            spectral_norm(nn.Conv2d(in_channels=256, out_channels=512, kernel_size=4, stride=1, padding=1, bias=not use_spectral_norm), use_spectral_norm),
            nn.LeakyReLU(0.2, inplace=True),
        )

        self.conv5 = nn.Sequential(
            spectral_norm(nn.Conv2d(in_channels=512, out_channels=1, kernel_size=4, stride=1, padding=1, bias=not use_spectral_norm), use_spectral_norm),
        )

        self.auto_attn = Auto_Attn(input_nc=128,norm_layer=None)
        if init_weights:
            self.init_weights()

    def forward(self, x):
        conv1 = self.conv1(x)
        conv2 = self.conv2(conv1)
        conv2, _ = self.auto_attn(conv2, None)
        conv3 = self.conv3(conv2)
        conv4 = self.conv4(conv3)
        conv5 = self.conv5(conv4)

        outputs = conv5
        if self.use_sigmoid:
            outputs = torch.sigmoid(conv5)

        return outputs, [conv1, conv2, conv3, conv4, conv5]

class ResnetBlock(nn.Module):
    def __init__(self, dim, dilation=1, use_spectral_norm=False):
        super(ResnetBlock, self).__init__()
        self.conv_block = nn.Sequential(
            nn.ReflectionPad2d(dilation),
            spectral_norm(nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=3, padding=0, dilation=dilation, bias=not use_spectral_norm), use_spectral_norm),
            nn.InstanceNorm2d(dim, track_running_stats=False),
            nn.ReLU(True),

            nn.ReflectionPad2d(1),
            spectral_norm(nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=3, padding=0, dilation=1, bias=not use_spectral_norm), use_spectral_norm),
            nn.InstanceNorm2d(dim, track_running_stats=False),
        )

    def forward(self, x):
        out = x + self.conv_block(x)
        return out

def spectral_norm(module, mode=True):
    if mode:
        return nn.utils.spectral_norm(module)

    return module

def conv_bn(inp, oup, stride):
    return nn.Sequential(
        nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
        nn.BatchNorm2d(oup),
        nn.ReLU6(inplace=True)
    )

def conv_1x1_bn(inp, oup):
    return nn.Sequential(
        nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
        nn.BatchNorm2d(oup),
        nn.ReLU6(inplace=True)
    )

class AddCoords(nn.Module):
    """
    Add Coords to a tensor
    """
    def __init__(self, with_r=False):
        super(AddCoords, self).__init__()
        self.with_r = with_r

    def forward(self, x):
        """
        :param x: shape (batch, channel, x_dim, y_dim)
        :return: shape (batch, channel+2, x_dim, y_dim)
        """
        B, _, x_dim, y_dim = x.size()

        # coord calculate
        xx_channel = torch.arange(x_dim).repeat(B, 1, y_dim, 1).type_as(x)
        yy_cahnnel = torch.arange(y_dim).repeat(B, 1, x_dim, 1).permute(0, 1, 3, 2).type_as(x)
        # normalization
        xx_channel = xx_channel.float() / (x_dim-1)
        yy_cahnnel = yy_cahnnel.float() / (y_dim-1)
        xx_channel = xx_channel * 2 - 1
        yy_cahnnel = yy_cahnnel * 2 - 1

        ret = torch.cat([x, xx_channel, yy_cahnnel], dim=1)

        if self.with_r:
            rr = torch.sqrt(xx_channel ** 2 + yy_cahnnel ** 2)
            ret = torch.cat([ret, rr], dim=1)

        return ret

class CoordConv(nn.Module):
    """
    CoordConv operation
    """
    def __init__(self, input_nc, output_nc, with_r=False, use_spect=False, **kwargs):
        super(CoordConv, self).__init__()
        self.addcoords = AddCoords(with_r=with_r)
        input_nc = input_nc + 2
        if with_r:
            input_nc = input_nc + 1
        self.conv = spectral_norm(nn.Conv2d(input_nc, output_nc, **kwargs), use_spect)

    def forward(self, x):
        ret = self.addcoords(x)
        ret = self.conv(ret)

        return ret

def coord_conv(input_nc, output_nc, use_spect=False, use_coord=False, with_r=False, **kwargs):

    if use_coord:
        return CoordConv(input_nc, output_nc, with_r, use_spect, **kwargs)
    else:
        return spectral_norm(nn.Conv2d(input_nc, output_nc, **kwargs), use_spect)

class ResBlock(nn.Module):

    def __init__(self, input_nc, output_nc, hidden_nc=None, norm_layer=nn.BatchNorm2d, nonlinearity= nn.LeakyReLU(),
                 sample_type='none', use_spect=False, use_coord=False):
        super(ResBlock, self).__init__()

        hidden_nc = output_nc if hidden_nc is None else hidden_nc
        self.sample = True
        if sample_type == 'none':
            self.sample = False
        elif sample_type == 'up':
            output_nc = output_nc * 4
            self.pool = nn.PixelShuffle(upscale_factor=2)
        elif sample_type == 'down':
            self.pool = nn.AvgPool2d(kernel_size=2, stride=2)
        else:
            raise NotImplementedError('sample type [%s] is not found' % sample_type)

        kwargs = {'kernel_size': 3, 'stride': 1, 'padding': 1}
        kwargs_short = {'kernel_size': 1, 'stride': 1, 'padding': 0}

        self.conv1 = coord_conv(input_nc, hidden_nc, use_spect, use_coord, **kwargs)
        self.conv2 = coord_conv(hidden_nc, output_nc, use_spect, use_coord, **kwargs)
        self.bypass = coord_conv(input_nc, output_nc, use_spect, use_coord, **kwargs_short)

        if type(norm_layer) == type(None):
            self.model = nn.Sequential(nonlinearity, self.conv1, nonlinearity, self.conv2,)
        else:
            self.model = nn.Sequential(norm_layer(input_nc), nonlinearity, self.conv1, norm_layer(hidden_nc), nonlinearity, self.conv2,)

        self.shortcut = nn.Sequential(self.bypass,)

    def forward(self, x):
        if self.sample:
            out = self.pool(self.model(x)) + self.pool(self.shortcut(x))
        else:
            out = self.model(x) + self.shortcut(x)

        return out

class Auto_Attn(nn.Module):
    """ Short+Long attention Layer"""

    def __init__(self, input_nc, norm_layer = nn.InstanceNorm2d):
        super(Auto_Attn, self).__init__()
        self.input_nc = input_nc

        self.query_conv = nn.Conv2d(input_nc, input_nc // 4, kernel_size=1)
        self.gamma = nn.Parameter(torch.zeros(1))
        self.alpha = nn.Parameter(torch.zeros(1))

        self.softmax = nn.Softmax(dim=-1)

        self.model = ResBlock(int(input_nc*2), input_nc, input_nc, norm_layer=norm_layer, use_spect=True)

    def forward(self, x, pre=None, mask=None):
        """
        inputs :
            x : input feature maps( B X C X W X H)
        returns :
            out : self attention value + input feature
            attention: B X N X N (N is Width*Height)
        """
        B, C, W, H = x.size()
        proj_query = self.query_conv(x).view(B, -1, W * H)  # B X (N)X C
        proj_key = proj_query  # B X C x (N)

        energy = torch.bmm(proj_query.permute(0, 2, 1), proj_key)  # transpose check
        attention = self.softmax(energy)  # BX (N) X (N)
        proj_value = x.view(B, -1, W * H)  # B X C X N

        out = torch.bmm(proj_value, attention.permute(0, 2, 1))
        out = out.view(B, C, W, H)

        out = self.gamma * out + x

        if type(pre) != type(None):
            # using long distance attention layer to copy information from valid regions
            context_flow = torch.bmm(pre.view(B, -1, W*H), attention.permute(0, 2, 1)).view(B, -1, W, H)
            context_flow = self.alpha * (mask) * context_flow + (1-mask) * pre
            out = self.model(torch.cat([out, context_flow], dim=1))

        return out, attention

class GateConv(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, transpose=False):
        super(GateConv, self).__init__()
        self.out_channels = out_channels
        if transpose:
            self.gate_conv = nn.ConvTranspose2d(in_channels, out_channels * 2,
                                                kernel_size=kernel_size,
                                                stride=stride, padding=padding)
        else:
            self.gate_conv = nn.Conv2d(in_channels, out_channels * 2,
                                       kernel_size=kernel_size,
                                       stride=stride, padding=padding)

    def forward(self, x):
        x = self.gate_conv(x)
        (x, g) = torch.split(x, self.out_channels, dim=1)
        return x * torch.sigmoid(g)


import pandas as pd
from api_access import APIAccess
from crfm_access import CRFMAccess
from metric_wrangler import MetricWrangler
from prompt import Prompt

class QueryPipeline:
    """
    To test generating prompts, and querying the API, and parsing the output

    Attributes:
        construction_type (str): the type of examples to generate: one of {subject_location, religious_pronoun, propn_negation}
        shots (int): the number of shots to query the API with for each prompt
        model (str): the OpenAI model to query with the prompts
        construction_format (str): format of examples to generate: one of {qa, arrow}
        crfm (bool): True if running tests on Stanford CRFM, False otherwise
    """
    def __init__(self, construction_type, shots, model, construction_format, crfm):
        self.construction_type = construction_type
        self.shots = shots
        self.model = model
        self.construction_format = construction_format
        self.crfm = crfm

    def run_pipeline(self, queries, needs_instruction, verbose, needs_informative, include_ambiguous_examples, prob_of_ambiguous, togethercomputer, for_finetuning, finetuning_control, salient_task=None):
        """
        Creates a sample test pipeline with which to generate prompts, query the API, and parse the output
        Args:
            queries (str): the number of prompts to query the API with
            needs_instruction (bool): True if Prompt requires instruction, False otherwise
            verbose (bool): True to provide printed output, False otherwise
            needs_informative (bool): True if requires informative instruction, False otherwise
            include_ambiguous_examaples (bool): True if wish to include ambiguous examples and False otherwise
            prob_of_ambiguous (float): Number from 0.0 to 1.0 indicating the probability of each example generated being an ambigous example
            togethercomputer (bool): True if for t0pp example generation, False otherwise
            for_finetuning (bool): True if generating examples with withheld salient tasks for finetuning
            finetuning_control (bool): True if running tests for finetuning control and False otherwise
            salient_task (str): salient task for which to make examples (not required to generate examples)

        Returns:
            complete_test_df (pd.DataFrame): a DataFrame containing all of the information from the set of Prompts for the current construction_type + format_type
        """
        wrangler = MetricWrangler()
        examples = []
        test_examples_output_df = pd.DataFrame()

        for i in range(queries):
            prompt = Prompt(construction_type=self.construction_type, shots=self.shots, format_type=self.construction_format, needs_instruction=needs_instruction, needs_informative=needs_informative, include_ambiguous_examples=include_ambiguous_examples, salient_task=salient_task, prob_of_ambiguous=prob_of_ambiguous, for_finetuning=for_finetuning, finetuning_control=finetuning_control)

            examples.extend(prompt.get_examples())

            if verbose: prompt.print()

            api_access = CRFMAccess(prompt) if self.crfm else APIAccess(prompt)

            if for_finetuning:
                api_access.generate_data_for_openai_finetuning(format=self.construction_format, needs_instruction=needs_instruction)

            elif togethercomputer:
                if self.construction_format == 'qa':
                    max_tokens = 2
                else:
                    max_tokens = 1
                api_access.to_togethercomputer(format=self.construction_format, request_type="language-model-inference", model="t0pp", needs_instruction=needs_instruction, max_tokens=max_tokens, logprobs=4)
            else:
                output = api_access.request(self.model, self.construction_format, needs_instruction)
                unpacked_df = api_access.to_numpy_dataframe(output)

                probs_df = api_access.isolate_probs(unpacked_df)

                if verbose: print("CURRENT PROMPT PROBS DF")

                labeled_df = wrangler.label_probs(probs_df, needs_instruction)

                if verbose: print(labeled_df)

                test_examples_output_df = test_examples_output_df.append(labeled_df, ignore_index=True)
                if verbose: print(test_examples_output_df)

        complete_test_df = wrangler.construct_test_example_df(test_examples=examples, test_examples_output_df=test_examples_output_df)

        print("TEST EXAMPLES DF\n" + str(complete_test_df))

        return complete_test_df


import random
user_point=0
computer_point=0
op=input("welome to rock/paper/scissor game. \n do you wanna play?\n YES/NO: ").lower()
if op!="yes":
    quit()
name=input("type your name...").upper()
options=["rock","paper","scissor"]
while True:
    user_guess=input("type rock/ paper/ scissor or Q to quit ").lower()
    if user_guess=="q":
        break
    if user_guess not in options:
        print("pls enter a valid entry.")
        continue
    ran_dom=random.randint(0,2)
    computer_pick=options[ran_dom]
    print("computer picked " + computer_pick + ".")
    if user_guess=="scissor" and computer_pick=="paper":
        print("you won!")
        user_point+=1
    elif user_guess=="paper" and computer_pick=="rock":
        print("you won!")
        user_point+=1
    elif user_guess=="rock" and computer_pick=="scissor":
        print("you won!")
        user_point+=1
    else:
        print("computer won!")
        computer_point+=1
print(name+ "you won " + str(user_point) + " times.")
print("computer won " + str(computer_point) + " times.")
print("GOOD BYE!")


# read animals.txt
# and write animals_new.txt

animal = open('animals.txt', 'r')
lst_animal = []
for el in animal:
    lst_animal.append(el.rstrip())
animal.close()
new_animal = open('animals_new.txt', 'w', encoding='utf-8')
new_animal.write(' '.join(lst_animal))
new_animal.close()


from tools import read
from math import prod
from itertools import product

class cube:
    def __init__(self, corners):
        self.corners = corners

    def __hash__(self):
        return hash(self.corners)

    def __eq__(self, other):
        return self.corners == other.corners

    def meets(self,point):
        for dim in range(3):
            if point[dim] <= self.corners[0][dim] or self.corners[1][dim] <=  point[dim]:
                return true
        return False

    def get_fences(self,dim):
        return (self.corners[0][dim], self.corners[1][dim])

    def bisect(self,split_dim,line):
        if line <= self.corners[0][split_dim] or self.corners[1][split_dim] <= line:
            return {self}
        pairs = [[[self.corners[0][dim],self.corners[1][dim]]] for dim in range(3)]
        pairs[split_dim] = [[self.corners[0][split_dim],line], [line, self.corners[1][split_dim]]]
        new_cubes = set()
        for p0 in pairs[0]:
            for p1 in pairs[1]:
                for p2 in pairs[2]:
                    new_cubes.add( cube( ((p0[0], p1[0], p2[0]), (p0[1], p1[1], p2[1])) ))
        return new_cubes

    def split(self,other):
        split_cubes = {self}
        for dim in range(3):
            for f in other.get_fences(dim):
                new_splits = set()
                for c in split_cubes:
                    new_splits |= c.bisect(dim,f)
                split_cubes = new_splits
        return split_cubes

    def split_and_remove(self,other):
        split_cubes = self.split(other)
        return { c for c in split_cubes if not c.intersects(other) }

    def intersects(cube1,cube2):
        for dim in range(3):
            if cube2.corners[1][dim] <= cube1.corners[0][dim] or cube1.corners[1][dim] <= cube2.corners[0][dim]:
                return False
        return True

    def is_contained_in(self,other):
        for dim in range(3):
            if self.corners[0][dim] < other.corners[0][dim] or other.corners[1][dim] < self.corners[1][dim]:
                return False
        return True

    def size(self):
        return prod([ self.corners[1][dim] - self.corners[0][dim] for dim in range(3)])

    def __str__(self):
        return str(self.corners)

# parsing

data = read("22.input.txt")

cubes = []
for line in data:
    switch, coordinates_text = line.split(" ")
    coordinates = [ [int(p) for p in axis[2:].split("..")] for axis in coordinates_text.split(",")]
    cubes.append([switch, coordinates])
#

# 1, baby solution

init_area = [[[0 for _ in range(101)] for _ in range(101)]  for _ in range(101)]
for c in cubes[:20]:
    switch, coordinates = c
    switch = 1 if switch == "on" else 0
    xs, ys, zs = [l.copy() for l in coordinates]
    xs[1] += 1
    ys[1] += 1
    zs[1] += 1
    for x, y, z in product(range(*xs),range(*ys),range(*zs)):
        init_area[x+50][y+50][z+50] = switch

print(sum(sum(sum(p) for p in l) for l in init_area))

# 2, proper solution

def reformat_input(coordinates):
    return ((coordinates[0][0],coordinates[1][0],coordinates[2][0]), (coordinates[0][1]+1,coordinates[1][1]+1,coordinates[2][1]+1))

cubes = [(c[0],reformat_input(c[1])) for c in cubes]
#
first_cube = cube(cubes[0][1])
processed_cubes = { first_cube }

for line in cubes[1:]:
    switch, coords = line
    added_cube = cube(coords)
    new_processed_cubes = set()
    for c in processed_cubes:
        if not c.is_contained_in(added_cube):
            if c.intersects(added_cube):
                new_processed_cubes |= c.split_and_remove(added_cube)
            else:
                new_processed_cubes |= {c}
    processed_cubes = new_processed_cubes
    if switch == "on":
        processed_cubes.add(added_cube)

print(sum(c.size() for c in processed_cubes))


# dump old large dataset into another directory
from config import *
from data_aug import *

from torch.utils.data import Subset, ConcatDataset
from PIL import Image
import os
from multiprocessing import Pool

img_shape = (256, 256)
transform = CircleCrop(img_shape)

dataset1 = BD_Dataset(OLD_TRAIN_CSV, OLD_TRAIN_DIR,
                      transform, True, False, False, True)
dataset2 = BD_Dataset(OLD_TEST_CSV, OLD_TEST_DIR,
                      transform, True, False, False, True)
dataset2.data = dataset2.data.drop(["Usage"], axis=1)
dataset = ConcatDataset([dataset1, dataset2])
# dataset = BD_Dataset(TRAIN_CSV, TRAIN_DIR, transform, True, False, True, True)

if not os.path.isdir(OLD_PREPROCESSED_DIR):
    os.mkdir(OLD_PREPROCESSED_DIR)

def dumpImage(ind):
    img, id = dataset[ind]
    img.save(OLD_PREPROCESSED_DIR+id+".jpeg")

p = Pool(16)
p.map(dumpImage, [i for i in range(len(dataset))])


# -*- coding: utf-8 -
#
# This file is part of qrurl released under the MIT license.
# See the NOTICE for more information.

from ImageOps import expand as img_expand
from Image import fromstring as img_fromstring
from qrurl.qrencode import encode, to_matrix

def encode_to_img(string, width=400, border=10):
    qrcode = encode(string)
    matrix = to_matrix(qrcode)

    dotsize = (width - (border * 2)) / qrcode['width']
    realwidth = qrcode['width'] * dotsize

    rawdata = ''
    for row in matrix:
        line = ''
        for col in row:
            line += dotsize * chr(col * 255)
        rawdata += dotsize * line

    img = img_fromstring('L', (realwidth, realwidth), rawdata)
    return img_expand(img, border, 255)


# It changes the colors of the letters of a text when you click the screen

import pygame
import pygame.font
import random
from pygame.locals import *

def GetGlyphs(surf, COLOR):
     """ Pull All Glyphs and Shapes of a certain color from a certain surface """
     print("Looking for glyphs and shapes...")
     TempGlyph = []
     GlyphList = []
     Active = []

     # Make a copy
     SurfCopy = pygame.Surface(surf.get_size())
     SurfCopy.blit(surf, (0,0))

     DONECOLOR = (random.randrange(10,250),random.randrange(10,250),random.randrange(10,250))
     if DONECOLOR == COLOR:
          DONECOLOR += 1

     for x in range(SurfCopy.get_width()):
          for y in range(SurfCopy.get_height()):
               if SurfCopy.get_at([x,y])[:3] == COLOR:
                    TempGlyph = []
                    Active = []
                    Active.append([x,y])
                    while len(Active):
                         CurrPoint = Active.pop(0)
                         Point = [CurrPoint[0],CurrPoint[1]]

                         try:
                              if SurfCopy.get_at(  [Point[0]+1, Point[1]]  )[:3] == COLOR:
                                   Active.append(  [Point[0]+1, Point[1]]    )
                                   SurfCopy.set_at([Point[0]+1, Point[1]], DONECOLOR)
                         except IndexError:
                              pass

                         try:
                              if SurfCopy.get_at(  [Point[0]-1, Point[1]]  )[:3] == COLOR:
                                   Active.append(  [Point[0]-1, Point[1]]    )
                                   SurfCopy.set_at([Point[0]-1, Point[1]], DONECOLOR)
                         except IndexError:
                              pass

                         try:
                              if SurfCopy.get_at(  [Point[0], Point[1]+1]  )[:3] == COLOR:
                                   Active.append(  [Point[0], Point[1]+1]    )
                                   SurfCopy.set_at([Point[0], Point[1]+1], DONECOLOR)
                         except IndexError:
                              pass

                         try:
                              if SurfCopy.get_at(  [Point[0], Point[1]-1]  )[:3] == COLOR:
                                   Active.append(  [Point[0], Point[1]-1]    )
                                   SurfCopy.set_at([Point[0], Point[1]-1], DONECOLOR)
                         except IndexError:
                              pass

                         TempGlyph.append(Point)
                    GlyphList.append(TempGlyph)
                    pygame.display.flip()

     print("There are " + str(len(GlyphList)) + " glyphs found altogether")
     return GlyphList

if __name__ == '__main__':

     pygame.init()

     FALSE = 0
     TRUE = 1

     ANTIALIAS = FALSE

     WHITE = (255,255,255)
     BLACK = (0,0,0)
     RED = (255,0,0)
     GRAY = (128,128,128)

     OLDCOLOR = BLACK
     NEWCOLOR = RED
     BACKGROUND = WHITE

     FONTSIZE = 50

     Messages = []
     Surfaces = []

     # Displaying message
     Messages.append("Hello there, how are you?")
     Messages.append("This program is dull...")
     Messages.append("But is pretty when you click?!")

     # Set a default font
     CurrentFont = pygame.font.Font(None, FONTSIZE)

     for x in Messages:
          Surfaces.append(CurrentFont.render(x, ANTIALIAS, OLDCOLOR, BACKGROUND))

     MaxWidth = []
     TotalHeight = 0
     CurrentHeight = 0

     for x in Surfaces:
          MaxWidth.append(x.get_width())

     for x in Surfaces:
          TotalHeight += x.get_height()

     screen = pygame.display.set_mode([max(MaxWidth),TotalHeight] )
     screen.fill(BACKGROUND)

     for x in Surfaces:
          screen.blit(x, (0,CurrentHeight))
          CurrentHeight += x.get_height()

     pygame.display.flip()

     # Finally, we are done with the test surface. Now to pull out the letters.

     Glyphs = GetGlyphs(screen, OLDCOLOR)

     # Color the letters
     for G in Glyphs:
          RANDCOLOR = (random.randrange(0,256),random.randrange(0,256),random.randrange(0,256))
          for Point in G:
               screen.set_at(Point, RANDCOLOR)

     while pygame.event.poll().type != QUIT:
          if pygame.mouse.get_pressed()[0]:
               for G in Glyphs:
                    RANDCOLOR = (random.randrange(0,256),random.randrange(0,256),random.randrange(0,256))
                    for Point in G:
                         screen.set_at(Point, RANDCOLOR)
          pygame.display.flip()

pygame.quit()


class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs or len(strs) == 0:
            return ""
        min_word = min(strs, key=len)
        for i, char in enumerate(min_word):
            for word in strs:
                if char != word[i]:
                    return word[:i]
        return min_word


import random
import numpy as np
import copy
import math
import timeit

def sigmoid(x):
    return 1.0 / (1.0 + math.exp(-x))

def sigmoid_derv(x):
    return np.multiply(x ,( 1.0 - x))

class neuron:
    def __init__(self,prev_neurons, weights = None, bias = None):
        self.inputs = []
        self.input = 0
        self.output = 0
        self.error = 0
        self.prev_neurons = prev_neurons
        self.weights = []

        if weights == None:
            for _ in range(self.prev_neurons):
                self.weights.append(random.uniform(0,1))
        else:
            self.weights = weights

        if bias == None:
            self.bias = random.uniform(0,1)
        else:
            self.bias = bias

    def feedforward(self,input_values):
        self.inputs = input_values
        self.input = np.dot(input_values,self.weights)
        self.input = self.input + self.bias
        self.output = sigmoid(self.input)
        return self.output

    def update(self,learn_rate):
        for i in range(len(self.weights)):
            self.weights[i] += learn_rate * self.error * self.inputs[i]
        self.bias += learn_rate * self.error

class  neural_network:
    def __init__(self,input_layer_size, output_layer_size, learn_rate=0.1):
        self.output_layer = []
        self.hidden_layer = []
        self.predicted_outputs = []
        self.learn_rate = learn_rate
        for i in range(input_layer_size):
            self.hidden_layer.append(neuron(input_layer_size))
        for i in range(output_layer_size):
            self.output_layer.append(neuron(len(self.hidden_layer)))

    def run_once(self,input_data):
        temp = []
        prev_layer_outputs =[]

        for neuron in self.hidden_layer:
            temp.append(neuron.feedforward(input_data))

        prev_layer_outputs = copy.deepcopy(temp)
        temp.clear()

        for neuron in self.output_layer:
            temp.append(neuron.feedforward(prev_layer_outputs))

        prev_layer_outputs = copy.deepcopy(temp)
        return prev_layer_outputs

    def backpropagation(self,actual_outputs):
        #calculate error in output layer
        for i in range(len(self.output_layer)):
            self.output_layer[i].error = (actual_outputs[i] - self.output_layer[i].output) * sigmoid_derv(self.output_layer[i].output)
        #calculate error in hidden layer dit nog fixen
        for n in range(len(self.hidden_layer)):
            self.hidden_layer[n].error = 0.0
            for i in range(len(self.output_layer)):
                self.hidden_layer[n].error += (self.output_layer[i].weights[n] * self.output_layer[i].error) * sigmoid_derv(self.hidden_layer[n].output)

    def update_neurons(self):
        for neuron in self.output_layer:
            neuron.update(self.learn_rate)
        for neuron in self.hidden_layer:
            neuron.update(self.learn_rate)

    def train(self,input_data_set,expected_outputs,itterations=10000):
        for itter in range(itterations):
            for item in range(len(input_data_set)):
                self.run_once(input_data_set[item])
                self.backpropagation(expected_outputs[item])
                self.update_neurons()

def load_data(file_name):
    return np.genfromtxt(file_name, delimiter=',', usecols=[0,1,2,3])

def load_labels(file_name):
    return np.genfromtxt(file_name, delimiter=',', usecols=[4],dtype=str)

def labels_to_NN_output(labels):
    outputs =[]
    for label in labels:
        output =[]
        if label == "Iris-setosa":
            output = [1,0,0]
        elif label == "Iris-versicolor":
            output = [0,1,0]
        elif label == "Iris-virginica":
            output = [0,0,1]
        outputs.append(output)
    return outputs

def split_data_set(outputs,data):
    train_data =[]
    train_outputs =[]
    test_data =[]
    test_outputs =[]
    for i in range(len(data)):
        if i %2 == 0:
            train_data.append(data[i])
            train_outputs.append(outputs[i])
        else:
            test_data.append(data[i])
            test_outputs.append(outputs[i])
    return [[train_data,train_outputs],[test_data,test_outputs]]

def compare(predicted,actual):
    one_index = predicted.index(max(predicted))
    for i in range(len(predicted)):
        if i == one_index:
            predicted[i]=1
        else:
            predicted[i]=0
    return predicted == actual

def test_iris_NN(NN, test_data, test_outpus):
    total = len(test_data)
    good = 0
    fault = 0
    for i in range(total):
        predicted = NN.run_once(test_data[i])
        if compare(predicted,test_outpus[i]):
            good += 1
        else:
            fault += 1
    # return (aantal in test_set,aantal goed, aantal fout, percentage goed)
    return [total,good,fault,round(good/total * 100,1)]

def run_iris():
    print("loading iris data")
    data = load_data("iris.data")
    labels = load_labels("iris.data")
    outputs = labels_to_NN_output(labels)
    print("splitting data set in 2 parts")
    split_sets = split_data_set(outputs,data)

    train_data = split_sets[0][0]
    train_outpus = split_sets[0][1]

    test_data = split_sets[1][0]
    test_outpus = split_sets[1][1]

    number_of_itterations = 10000
    iris_NN = neural_network(4,3)
    #the network consists of 4 input neurons, 1 hidden layer containing 4 neurons and a outputlayer containing 3 neurons
    #since there are 3 flower types the output should be 3 neurons
    #since each data point had 4 parameters the input should be 4 neurons

    print("train network with ", number_of_itterations, " using the train set")
    iris_NN.train(train_data,train_outpus,number_of_itterations)
    print("testing network with test data set")
    test_results = test_iris_NN(iris_NN,test_data,test_outpus)

    print("test results:")
    print("entry's         : ",test_results[0])
    print("good predictions: ",test_results[1])
    print("bad  predictions: ",test_results[2])
    print("good  Percentage: ",test_results[3],"%")

def run_XOR():
    print("XOR validation:")
    #having a higher learn rate make the set learn quicker
    test = neural_network(2,1,0.3)
    test_set = ([1,1],[1,0],[0,0],[0,1])
    output = ([0],[1],[0],[1])
    # the XOR needs a lot more itterations or a higher learn rate before it has learned correctly
    # this is a known problem with a sigmoid based small network that needs to learn this problem
    # sometimes even 100.000 itterations is not enough
    test.train(test_set,output,100000)
    print("input: 0,0  expected = 0  predicted: ",round(test.run_once([0,0])[0],2))
    print("input: 1,0  expected = 1  predicted: ",round(test.run_once([1,0])[0],2))
    print("input: 0,1  expected = 1  predicted: ",round(test.run_once([0,1])[0],2))
    print("input: 1,1  expected = 0  predicted: ",round(test.run_once([1,1])[0],2))

def main():
    start = timeit.default_timer()
    run_iris()
    end = timeit.default_timer()
    print("time needed     : ",round(end-start,1), " secconds")

    print()

    start = timeit.default_timer()
    run_XOR()
    end = timeit.default_timer()
    print("XOR time needed: ",round(end-start,1), " secconds")

if __name__ == "__main__":
    main()


import random
global pick
global randomrps
global rps
print("""To start the game enter correct letter.
  R - Rock
  P - Paper
  S - Scissors """)
while True:
  rps = ["r", "p", "s"]
  randomrps = random.choice(rps)
  pick = input("Your pick: ").lower()
  if pick == str("r") and randomrps == str("s"):
    print("Rock crushes scissors... You WON!")
  elif randomrps == str("r") and pick == str("s"):
    print("Rock crushes scissors... You Lost!")
  elif pick == str("p") and randomrps == str("r"):
    print("Paper covers rock... You WON!")
  elif randomrps == str("p") and pick == str("r"):
    print("Paper covers rock... You Lost!")
  elif pick == str("s") and randomrps == str("p"):
    print("Scissors cuts paper... You WON!")
  elif randomrps == str("s") and pick == str("p"):
    print("Scissors cuts paper... You Lost!")
  elif pick == randomrps:
    print("TIE!")


from db_models.models import Reports, Projects, ReportHistory
from db.db import session
from flask import Flask, jsonify, request
from flask_restful import Resource, fields, marshal_with, abort, reqparse
import json
import modules.report_data_refiner as data_refiner

report_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'data': fields.String,
    'project_id': fields.Integer

}
import jsonpickle
def encode(ob):
    try:
        jsonpickle.set_preferred_backend('json')
        jsonpickle.set_encoder_options('json', ensure_ascii=False)
        #jsonpickle.set_encoder_options('simplejson', sort_keys=True, indent=4)
        json_s = jsonpickle.encode(ob, unpicklable=True)
        return json_s
    except Exception as e:
        print(str(e))
        return ""
class ProjectReportResource(Resource):
    @marshal_with(report_fields)
    def get(self, id):
        report = session.query(Reports).filter(Reports.project_id == id).first()
        if not report:
            abort(404, message="Reports not found")
        return report

class ReportResource(Resource):
    @marshal_with(report_fields)
    def get(self, id):
        report = session.query(Reports).filter(Reports.id == id).first()
        if not report:
            abort(404, message="Report {} doesn't exist".format(id))
        return report

    def delete(self, id):
        report = session.query(Reports).filter(Reports.id == id).first()
        if not report:
            abort(404, message="Document {} doesn't exist".format(id))
        session.delete(report)
        session.commit()
        return {}, 204

    @marshal_with(report_fields)
    def put(self, id):

        json_data = request.get_json(force=True)
        report = session.query(Reports).filter(Reports.id == id).first()
        report.data = json_data["data"]
        report.name = json_data["name"]
        session.add(report)
        session.commit()
        return report, 201

class ReportListResource(Resource):
    @marshal_with(report_fields)
    def get(self):
        reports = session.query(Reports).all()
        return reports

    @marshal_with(report_fields)
    def post(self):
        try:

            json_data = request.get_json(force=True)
            json_data = json.loads(json_data)
            project_id = json_data["projectId"]
            report = session.query(Reports).filter(Reports.project_id == project_id).first()

            project_name = json_data["name"]

            if (len(project_name)>30):
                project_name = project_name[:30]
                project_name+="..."
            if (report==None):
                report = Reports(projectId=json_data["projectId"], name=project_name,
                                  analytic_rule_id=json_data["schemaId"], data=encode(json_data["data"]))
            else:
                report.data = encode(json_data["data"])

            session.add(report)
            compressed_data = data_refiner.compress_data(encode(json_data["data"]))
            report_history = ReportHistory(project_id=json_data["projectId"],
                                       data=compressed_data,
                                       user_id=None)

            session.add(report_history)

            session.commit()
            return report, 201
            #return "OK"
        except Exception as e:
            abort(400, message="Error while adding record Document")


import numpy as np
from scipy.integrate import cumtrapz, simps, trapz, odeint, solve_bvp
from scipy.optimize import least_squares #minimize
from scipy.interpolate import interp1d, UnivariateSpline

np.seterr(divide='ignore')

def integrate(y, x):
    return np.hstack((0., cumtrapz(y, x)))

def complement(y, x):
    return np.trapz(y, x) - integrate(y, x)

def load_fgong(filename, N=16):
    '''Given an FGONG file, returns a Python dictionary containing
    NumPy arrays that correspond to the structures in the
    specification of the FGONG format:

    https://www.astro.up.pt/corot/ntools/docs/CoRoT_ESTA_Files.pdf

    That is, the dictionary has arrays indexed by 'nn', 'iconst',
    'ivar', 'ivers', 'glob' and 'var'.'''
    f = open(filename, 'r')

    fgong = {'header':[]}
    for i in range(4):
        fgong['header'].append(f.readline())

    tmp = [int(i) for i in f.readline().split()]
    fgong['nn'] = tmp[0]
    fgong['iconst'] = tmp[1]
    fgong['ivars'] = tmp[2]
    fgong['ivers'] = tmp[3]

    lines = f.readlines()
    tmp = []
    for line in lines:
        for i in range(len(line)//N):
            s = line[i*N:i*N+N]
            if s[-9:] == '-Infinity':
                s = '-Inf'
            elif s[-9:] == ' Infinity':
                s = 'Inf'
            elif s[-4].lower() != 'e':
                s = s[:-4] + 'e' + s[-4:]

            tmp.append(float(s))

    fgong['glob'] = np.array(tmp[:fgong['iconst']])
    fgong['var'] = np.array(tmp[fgong['iconst']:]).reshape((-1,fgong['ivars']))

    f.close()

    return fgong

def kernel(ell, nu, eig, fgong):
    """Returns a dict of structural kernels.  I have tried to make this as
    notationally similar to Gough & Thompson (1991) as possible.

    Parameters
    ----------
    ell: int
        The angular degree of the mode.
    nu: float
        The cyclic frequency of the mode.
    eig: np.array, shape(N,7)
        Eigenfrequency data for the mode, as produced by ADIPLS.
    fgong: dict
        Stellar model data in a dictionary, as per load_fgong()
        above.

    Returns
    -------
    kernel: np.array, length N
        The density or sound speed structure kernel.
    """

    G = 6.67232e-8                           # gravitational constant
    M, R = fgong['glob'][:2]                 # mass and radius from FGONG

    ## unpack eigenfunction (c.f. page 7 of Notes on adi. osc. prog.)
    x = eig[:,0]                             # dimensionless radius (i.e. r/R)
    y1 = eig[:,1]                            # xi_r / R
    y2 = eig[:,2]                            # l(l+1)/R * xi_h
    y3 = eig[:,3]                            # -x * Phi' / (g * r)
  # y4 = eig[:,4]                            # x^2 * d/dx (y_3 / x)

    xi_r = y1*R                              # radial component of eigenfunction
    xi_h = y2*R/L2 if ell > 0 else 0. * xi_r # horiz. component of eigenfunction

    ## unpack fgong file (c.f. page 6 section 2.1.3 of above doc)
    r = fgong['var'][::-1,0]                 # radial co-ordinate
    m = M*np.exp(fgong['var'][::-1,1])       # mass co-ordinate
    P_0 = fgong['var'][::-1,3]               # pressure
    rho_0 = fgong['var'][::-1,4]             # density
    Gamma1 = fgong['var'][::-1,9]            # first adiabatic index
    c02 = Gamma1*P_0/rho_0                   # square of the sound speed
    Y = 1 - fgong['var'][::-1,5] - fgong['var'][::-1,16] # helium abundance
    # Gamma_1,Y = ( partial ln Gamma_1 / partial ln Y ) _ {P, rho} etc
    #Gamma_1rho = fgong['var'][::-1,25]
    #Gamma_1p = fgong['var'][::-1,26]
    #Gamma_1Y = fgong['var'][::-1,27]

    ## equilibrium model (c.f. ADIPLS - The Aarhus adi. osc. pack., section 2.1)
    #A = fgong['var'][::-1,14]    # 1/Gamma_1 (dln p / dln r) - (dln rho / dln r)
    #A1 = (m/M)/(r/R)**3                      # fractional volume
    #Vg = (G*m*rho_0)/(Gamma1*P_0*r)
    #drho_dr = -(Vg+A)*rho_0/r                # density gradient

    omega = 2.*np.pi*nu                      # convert to cyclic frequency
    sigma = np.sqrt(R**3/G/M)*omega          # dimensionless frequency

    L2 = ell*(ell+1)
    L = np.sqrt(L2)

    # eta = m_0 / r**3
    # m_0 = 4*pi*int_s=0^r p_0(s) s^2 ds
    m_0 = 4 * np.pi * integrate( P_0 * r**2 , r )
    eta = m_0 / r**3

    # chi ("dilatation") = (d(xi)/dr) + 2(xi)/r - l(l+1)*eta/r
    dxi_r_dr = np.hstack((0., np.diff(xi_r)/np.diff(r)))
    chi = dxi_r_dr + 2*xi_r/r - L2*eta/r
    chi[0] = 0.

    # rho = -(d(rho_0)/dr)*xi_r - p_0*chi)
    drho_0_dr = np.hstack((0., np.diff(rho_0)/np.diff(r)))
    rho = -drho_0_dr * xi_r - rho_0 * chi

    # psi = -4*pi*G / (2*l+1) * [ int_s=0^r p(s) s^(l+2)/r^(l+1) ds +
    #                         l * int_s=r^R rho(s) r^l / s^(l-1) ds ]
    psi = -4*np.pi*G / (2*ell+1) * \
           ( integrate( rho * r**(ell+2) / r[-1]**(ell+2), r ) + \
        L * complement( rho * r[0]**(ell) / r**(ell-1), r ) )
    dpsi_dr = np.hstack((0., np.diff(psi)/np.diff(r)))

    g_0 = G * m_0 / r**2

    # I = int_r=0^R rho_0(r) (xi_r**2 + l(l+1) eta^2) r^2 dr
    I = trapz( rho_0 * ( xi_r**2 + L2 * eta**2 ) * r**2 , r )

    #S = np.trapz((xi_r**2+L2*xi_h**2)*rho*x**2, x)

    ### Calculate c, rho pair
    K_c2_rho = rho_0 * c02 * chi**2 * r**2 / ( 2 * I * sigma**2 )
    K_rho_c2 = K_c2_rho

    return {
        #('c',      'rho'): (K_c_rho,      K_rho_c2),
        ('c2',     'rho'): (K_c2_rho,     K_rho_c2),
        #('Gamma1', 'rho'): (K_Gamma1_rho, K_rho_Gamma1)
        #('u',      'Y'):   (K_u_Y,        K_Y_u),
        #('psi', 'psi'):    (psi,          psi)
    }


# Another solution: https://www.youtube.com/watch?v=xMmceinGIa8

class Solution:

    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        # inorder BAC
        stack = []
        while root or stack:
            # !!!
            # 3/16 3/27 not "and"
            while root:
                stack.append(root)
                # 3/16 為何不是append(cur.val)?比較：Leetcode 102
                # 3/27 JM:這是append node，之後會使用到
                root = root.left
            # root左邊裝滿後，開始pop
            root = stack.pop()
            # 3/21 之後要往右走，亦得從每個node去走...
            k -= 1
            if k == 0:
                return root.val
            # 左邊跑完，K還沒完，才需要走右邊
            # 12/6 不是 stack[0]

            root = root.right
            # Go as far left as we can,adding value from the stack,and poping from the right when we need to


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from pyscada.visa.devices import GenericDevice
import numpy as np
import time
import logging
from pyvisa.errors import VisaIOError

logger = logging.getLogger(__name__)
# -*- coding: utf-8 -*-
"""Object based access to the robot Tergane 45 from Terel

Example::
from pyscada.laborem.scripts.Robot_Tergane45 import Tergane45
unit = Tergane45()
import pyvisa
import time
visa_backend = '@py'  # use PyVISA-py as backend
rm = pyvisa.ResourceManager(visa_backend)
inst = rm.open_resource('ASRL/dev/serial0::INSTR', baud_rate=9600, data_bits=8, parity=pyvisa.constants.Parity.none, stop_bits=pyvisa.constants.StopBits.one, write_termination='')
unit.connect(inst)
unit.init()
unit.pince(0)
time.sleep(1)
unit.pince(1)

"""
__author__ = "Camille Lavayssière"
__copyright__ = "Copyright 2020, UPPA"
__credits__ = []
__license__ = "GPLv3"
__version__ = "0.1.0"
__maintainer__ = "Camille Lavayssière"
__email__ = "clavayssiere@univ-pau.fr"
__status__ = "Beta"
__docformat__ = 'reStructuredText'

class Tergane45(object):

    def __init__(self):
        self.instr = None
        self.old_theta = 0

    def connect(self, instr):
        if self.instr is None and instr is None:
            return
        self.instr = instr

    def init(self):
        try:
            logger.debug(self.instr.read_raw())
        except:
            pass
        # on tourne le bras
        self.rotation_base(0)
        # on baisse le bras
        self.prepare_epaule_coude_poignet(17, 1, 2)
        # on ouvre la pince
        # self.pince(1)
        # self.pince(0)
        # self.pince(1)

    def query(self, write_sring):
        self.instr.timeout = 50
        i = 0
        while i < 10:
            while True:
                try:
                    self.instr.read_raw()
                except VisaIOError:
                    break
            self.instr.write(write_sring)
            r1 = str(self.instr.read_raw())
            r2 = str(self.instr.read_raw())
            if write_sring in r1 and 'MESSAGE CORRECT' in r2:
                #logger.debug(write_sring + ' ok')
                break
            else:
                i += 1
                logger.debug(write_sring + ' nok')
                logger.debug(r1)
                logger.debug(r2)
                time.sleep(1)

    def take_and_drop(self, to_take, to_drop):
        r_to_take = to_take.R
        theta_to_take = to_take.theta
        z_to_take = to_take.z
        r_to_drop = to_drop.R
        theta_to_drop = to_drop.theta
        z_to_drop = to_drop.z
        self._take_and_drop(r_to_take, theta_to_take, z_to_take, r_to_drop, theta_to_drop, z_to_drop)

    def _take_and_drop(self, r1, theta1, z1, r2, theta2, z2):
        # on ouvre la pince
        self.pince(1)
        # prepare_epaule_coude_poignet(20, 5, 3)
        # rotation_base(0)
        # on place le bras pour prendre en l'air
        self.prepare_epaule_coude_poignet(r1, z1, 1)
        # on tourne le bras pour prendre
        self.rotation_base(theta1)
        # on ferme la pince
        self.pince(0)
        # on leve le bras
        self.prepare_epaule_coude_poignet(r1, 4, 2)
        self.prepare_epaule_coude_poignet(r2, 4, 1)
        # on tourne le bras pour deposer
        self.rotation_base(theta2)
        # on place le bras pour deposer
        self.prepare_epaule_coude_poignet(r2, sum([z2], 0.8), 3)
        # on ouvre la pince
        self.pince(1)
        # on se releve
        self.prepare_epaule_coude_poignet(r2, 4, 2)
        # prepare_epaule_coude_poignet(20, 4, 3)
        self.rotation_base(0)
        return True

    def format_ascii(self, rot_ascii, axe):
        if rot_ascii < 0:
            ret = axe + '-' + str(int(rot_ascii))[1:].zfill(3)
            return ret
        else:
            ret = axe + '+' + str(int(rot_ascii)).zfill(3)
            return ret

    def deg_to_ascii(self, angle_deg, angle_max_deg):
        return int(min(max(angle_deg, -angle_max_deg), angle_max_deg) * 511 / angle_max_deg)

    def prepare_epaule_coude_poignet(self, r, z, mouvement):
        l_epaule = 11.5
        l_coude = 14.8
        l_poignet = 8.8
        l_base = 11

        angle_max_epaule = 43
        angle_max_coude = 125
        angle_max_poignet = 90

        correction_angle_poignet = 28.5

        temps_entre_cmd = 0.05

        xp = r
        yp = z - l_base + l_poignet

        r_alpha = (xp ** 2 + yp ** 2 - l_epaule ** 2 - l_coude ** 2) / (-2 * l_epaule * l_coude)
        alpha = np.arccos(r_alpha)
        theta_coude = -np.pi + alpha

        theta_5 = np.arctan2(yp, xp) + np.arcsin(l_coude * np.sin(alpha) / (xp ** 2 + yp ** 2) ** 0.5)
        theta_epaule = -np.pi / 4 + theta_5

        theta_poignet = -np.pi / 2 - np.pi / 4 - theta_epaule - theta_coude

        if mouvement == 1:
            self.query(self.format_ascii(self.deg_to_ascii(theta_poignet * 180 / np.pi + correction_angle_poignet,
                                                           angle_max_poignet), 'F'))
            time.sleep(temps_entre_cmd)
            self.query(self.format_ascii(self.deg_to_ascii(theta_coude * 180 / np.pi, angle_max_coude), 'C'))
            time.sleep(temps_entre_cmd)
            self.query(self.format_ascii(self.deg_to_ascii(theta_epaule * 180 / np.pi, angle_max_epaule), 'E'))
            time.sleep(1)
        elif mouvement == 2:
            self.query(self.format_ascii(self.deg_to_ascii(theta_epaule * 180 / np.pi, angle_max_epaule), 'E'))
            time.sleep(temps_entre_cmd)
            self.query(self.format_ascii(self.deg_to_ascii(theta_coude * 180 / np.pi, angle_max_coude), 'C'))
            time.sleep(temps_entre_cmd)
            self.query(self.format_ascii(self.deg_to_ascii(theta_poignet * 180 / np.pi + correction_angle_poignet,
                                                           angle_max_poignet), 'F'))
            time.sleep(1)
        elif mouvement == 3:
            self.query(self.format_ascii(self.deg_to_ascii(theta_coude * 180 / np.pi, angle_max_coude), 'C'))
            time.sleep(temps_entre_cmd)
            self.query(self.format_ascii(self.deg_to_ascii(theta_epaule * 180 / np.pi, angle_max_epaule), 'E'))
            time.sleep(temps_entre_cmd)
            self.query(self.format_ascii(self.deg_to_ascii(theta_poignet * 180 / np.pi + correction_angle_poignet,
                                                           angle_max_poignet), 'F'))
            time.sleep(1)
        elif mouvement == 4:
            self.query(self.format_ascii(self.deg_to_ascii(theta_coude * 180 / np.pi, angle_max_coude), 'C'))
            time.sleep(temps_entre_cmd)
            self.query(self.format_ascii(self.deg_to_ascii(theta_poignet * 180 / np.pi + correction_angle_poignet,
                                                           angle_max_poignet), 'F'))
            time.sleep(temps_entre_cmd)
            self.query(self.format_ascii(self.deg_to_ascii(theta_epaule * 180 / np.pi, angle_max_epaule), 'E'))
            time.sleep(1)
        elif mouvement == 5:
            self.query(self.format_ascii(self.deg_to_ascii(theta_epaule * 180 / np.pi, angle_max_epaule), 'E'))
            time.sleep(temps_entre_cmd)
            self.query(self.format_ascii(self.deg_to_ascii(theta_poignet * 180 / np.pi + correction_angle_poignet,
                                                           angle_max_poignet), 'F'))
            time.sleep(temps_entre_cmd)
            self.query(self.format_ascii(self.deg_to_ascii(theta_coude * 180 / np.pi, angle_max_coude), 'C'))
            time.sleep(1)
        return True

    def rotation_base(self, theta):
        angle_max_base = 130
        theta_base = theta * np.pi / 180
        self.query(self.format_ascii(self.deg_to_ascii(theta_base * 180 / np.pi, angle_max_base), 'B'))
        try:
            theta = 0.0 - self.old_theta
            tempo = abs(sum([self.deg_to_ascii(theta_base * 180 / np.pi, angle_max_base), theta])) * 5000 / 1024
            time.sleep(tempo / 1000)
            self.old_theta = self.deg_to_ascii(theta_base * 180 / np.pi, angle_max_base)
        except Exception as e:
            logger.warning(e)
            time.sleep(3)
        return True

    def pince(self, openclose):
        if openclose == 0:
            self.query('P+511')
            time.sleep(1.7)
        else:
            self.query('P-511')
            time.sleep(1.7)
        return True

    def set_bases(self, bases_dict):
        logger.debug("set_bases")
        temp_actions = dict()

        # Find moves between bases
        for i in bases_dict.keys():
            if bases_dict[i].requested_element is None:
                continue
            if bases_dict[i].requested_element == bases_dict[i].element:
                # Nothing to move
                logger.debug("Nothing to do")
                pass
            elif bases_dict[i].element is not None and \
                    bases_dict[i].requested_element.value == bases_dict[i].element.value and \
                    bases_dict[i].requested_element.unit == bases_dict[i].element.unit:
                # Replace requested element by is brother
                logger.debug("Replace req element by element")
                bases_dict[i].requested_element = bases_dict[i].element
                bases_dict[i].save()
                while bases_dict[i].requested_element != bases_dict[i].element:
                    bases_dict[i].refresh_from_db()
                    logger.debug("Waiting to replace req element by element...")
                    time.sleep(1)
            else:
                # Find requested element in other base
                for j in bases_dict.keys():
                    if i != j and bases_dict[j].element is not None \
                            and bases_dict[i].requested_element == bases_dict[j].element:
                        # Req element in other base
                        logger.debug("Req element in other base")
                        temp_actions[i] = bases_dict[j]
                        break
                if i not in temp_actions.keys():
                    logger.debug("Not in other base")
                    temp_actions[i] = None

        # Break loops
        for i in bases_dict.keys():
            stop = False
            k = i
            count = 0
            while not stop and len(temp_actions):
                if k in temp_actions.keys():
                    count += 1
                    if temp_actions[k] == bases_dict[i]:
                        if count == 1:
                            logger.debug("Something is strange !")
                            stop = True
                        else:
                            logger.debug("Temp actions is a loop")
                            stop = True
                            temp_actions[k] = None
                    elif temp_actions[k] is not None and temp_actions[k].id in temp_actions.keys():
                        k = temp_actions[k].id
                        logger.debug("Replacing k")
                    else:
                        logger.debug("Temp actions is not a loop")
                        stop = True
                else:
                    stop = True

        while len(temp_actions):
            actions = dict()
            logger.debug("loop temp actions")
            logger.debug(temp_actions.keys())
            logger.debug(temp_actions.values())
            for i in temp_actions.keys():
                if bases_dict[i] not in temp_actions.values():
                    logger.debug("First action" + str(i))
                    actions[i] = temp_actions[i]
                else:
                    logger.debug("base " + str(i) + ": " + str(bases_dict[i]) + " - in temp action : ")

            for i in actions.keys():
                del temp_actions[i]
                self.unset_base(bases_dict[i])
                if actions[i] is None:
                    self.set_base(bases_dict[i])
                else:
                    self.move_base(actions[i], bases_dict[i])

    def unset_base(self, base):
        logger.debug("unset_base")
        if base.element is not None:
            self.take_and_drop(base, base.element)
            base.element = None
            base.save()
            while base.element is not None:
                base.refresh_from_db()
                time.sleep(1)

    def set_base(self, base):
        logger.debug("set_base")
        self.take_and_drop(base.requested_element, base)
        base.element = base.requested_element
        base.save()
        while base.element != base.requested_element:
            base.refresh_from_db()
            time.sleep(1)

    def move_base(self, base1, base2):
        logger.debug("move_base")
        self.take_and_drop(base1, base2)
        e = base1.element
        base2.element = e
        base2.save()
        base1.element = None
        base1.save()
        while base2.element != e or base1.element is not None:
            base2.refresh_from_db()
            base1.refresh_from_db()
            time.sleep(1)

class Handler(GenericDevice):
    """
    Tergane 45 Robot from Terel
    """
    device = None

    def connect(self):
        super(Handler, self).connect()
        self.device = Tergane45()
        self.device.connect(self.inst)

    def read_data(self, variable_instance):
        """
        read values from the device
        """
        return None

    def write_data(self, variable_id, value, task):
        """
        write values to the device
        """
        return None

    def parse_value(self, value, **kwargs):
        """
        takes a string in the HP3456A format and returns a float value or None if not parseable
        """
        return None


import numpy as np
import matplotlib
import matplotlib.pyplot as plt

from gridlod import util
from gridlod.world import World
import build_coefficient, lod_periodic

np.random.seed(123)

#random checkerboard
Nepsilon = np.array([128,128])
NFine = np.array([256,256])
alpha=0.1
beta=1.
p=0.1
aPert = build_coefficient.build_randomcheckerboard(Nepsilon,NFine,alpha,beta,p)
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

apertGrid = aPert.reshape(NFine, order='C')
im1 = ax1.imshow(apertGrid, origin='lower_left', extent=(0, 1, 0, 1), cmap='Greys')
fig.colorbar(im1, ax=ax1)
plt.show()

#random defects -- intro picture
Nepsilon = np.array([64,64])
NFine = np.array([256,256])
alpha=0.1
beta=1.
p=0.1
incl_bl = np.array([0.25, 0.25])
incl_tr = np.array([0.75, 0.75])
aPert = build_coefficient.build_inclusions_defect_2d(NFine,Nepsilon,alpha,beta,incl_bl,incl_tr,p)
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

apertGrid = aPert.reshape(NFine, order='C')
im1 = ax1.imshow(apertGrid, origin='lower_left', extent=(0, 1, 0, 1), cmap='Greys')
fig.colorbar(im1, ax=ax1)
plt.show()

#random defects -- different possibilities in num experiments
Nepsilon = np.array([16,16])
NFine = np.array([256,256])
alpha=1.
beta=10.
p=0.1
incl_bl = np.array([0.25, 0.25])
incl_tr = np.array([0.75, 0.75])
Lshape_bl = np.array([0.5, 0.5])
Lshape_tr = np.array([0.75, 0.75])
shift_bl = np.array([0.75, 0.75])
shift_tr=np.array([1., 1.])
model1={'name': 'inclfill'}
model2={'name':'inclshift', 'def_bl': shift_bl, 'def_tr': shift_tr}
model3={'name':'inclLshape', 'def_bl': Lshape_bl, 'def_tr': Lshape_tr}

aPertList = []
aPertList.append(build_coefficient.build_inclusions_defect_2d(NFine,Nepsilon,alpha,beta,incl_bl,incl_tr,p))
aPertList.append(build_coefficient.build_inclusions_defect_2d(NFine,Nepsilon,alpha,beta,incl_bl,incl_tr,p, 0.5))
aPertList.append(build_coefficient.build_inclusions_defect_2d(NFine,Nepsilon,alpha,beta,incl_bl,incl_tr,p, 5.))
aPertList.append(build_coefficient.build_inclusions_change_2d(NFine,Nepsilon,alpha,beta,incl_bl,incl_tr,p, model1))
aPertList.append(build_coefficient.build_inclusions_change_2d(NFine,Nepsilon,alpha,beta,incl_bl,incl_tr,p, model2))
aPertList.append(build_coefficient.build_inclusions_change_2d(NFine,Nepsilon,alpha,beta,incl_bl,incl_tr,p, model3))
fig = plt.figure()

for ii in range(6):
    ax = fig.add_subplot(2, 3, ii+1)
    bounds = np.array([0.2, 0.8, 1.5, 5.5, 10.5])
    mycmap = plt.cm.get_cmap('Greys')
    norm = matplotlib.colors.BoundaryNorm(bounds, mycmap.N)
    apertGrid = aPertList[ii].reshape(NFine, order='C')
    im = ax.imshow(apertGrid, origin='lower_left', extent=(0, 1, 0, 1), cmap=mycmap, norm=norm)

plt.show()

#two examples of the offline coeffs
Nepsilon = np.array([64,64])
NFine = np.array([256,256])
NCoarse=np.array([32, 32])
k=2
alpha = 0.1
beta = 1.
incl_bl = np.array([0.25, 0.25])
incl_tr = np.array([0.75, 0.75])
NCoarseElement = NFine // NCoarse
world = World(NCoarse, NCoarseElement, None)
middle = world.NWorldCoarse[1] // 2 * world.NWorldCoarse[0] + world.NWorldCoarse[0] // 2
patch = lod_periodic.PatchPeriodic(world, k, middle)
xpFine = util.pCoordinates(world.NWorldCoarse, patch.iPatchWorldCoarse, patch.NPatchCoarse)

aRefList_rand = build_coefficient.build_checkerboardbasis(patch.NPatchCoarse, Nepsilon // NCoarse,
                                                             world.NCoarseElement, alpha, beta)

fig = plt.figure()
for ii in range(4):
    ax = fig.add_subplot(2, 2, ii+1)
    apertGrid = aRefList_rand[-1+ii].reshape(patch.NPatchFine, order='C')
    im = ax.imshow(apertGrid, origin='lower_left',
                    extent=(xpFine[:,0].min(), xpFine[:,0].max(), xpFine[:,1].min(), xpFine[:,1].max()), cmap='Greys')
plt.show()

aRefList_incl = build_coefficient.build_inclusionbasis_2d(patch.NPatchCoarse, Nepsilon // NCoarse, world.NCoarseElement,
                                                         alpha, beta, incl_bl, incl_tr)

fig = plt.figure()
for ii in range(4):
    ax = fig.add_subplot(2, 2, ii+1)
    apertGrid = aRefList_incl[-1+ii].reshape(patch.NPatchFine, order='C')
    im = ax.imshow(apertGrid, origin='lower_left',
                   extent=(xpFine[:,0].min(), xpFine[:,0].max(), xpFine[:,1].min(), xpFine[:,1].max()), cmap='Greys')
plt.show()


from homework07.hw1_utils import EASY_ITER_TYPE, PURE_TYPE
from homework07.hw1_utils import handle_dict as hd

def handle_iter(iterable, element):
    counter = 0
    for value in iterable:
        if isinstance(value, tuple(val for val in PURE_TYPE)):
            counter = (
                counter + 1
                if value == element and type(value) == type(element)
                else counter
            )
        if isinstance(value, tuple(val for val in EASY_ITER_TYPE)):
            counter += handle_iter(value, element)
        if isinstance(value, dict):
            counter += hd.handle_dict(value, element)
    return counter


import os
import warnings
import torch
import transformers

from transformers import LlamaForCausalLM
from utils.llama_wrapper import LLaMAClass
from utils.modelutils import find_layers
from utils.quant import make_quant

def load_llama(model_name, load_quant=True, config=None, checkpoint="", groupsize=-1):
    def skip(*args, **kwargs):
        pass

    torch.nn.init.kaiming_uniform_ = skip
    torch.nn.init.uniform_ = skip
    torch.nn.init.normal_ = skip
    torch.set_default_dtype(torch.half)
    transformers.modeling_utils._init_weights = False
    torch.set_default_dtype(torch.half)

    print("Loading model... ", end="")
    if not load_quant:
        model = LlamaForCausalLM.from_pretrained(model_name, torch_dtype="auto")
        model.seqlen = 2048
    else:
        assert os.path.exists(checkpoint), "loading low-bit model requires checkpoint"
        model = LLaMAClass(config)

    torch.set_default_dtype(torch.float)
    model.eval()

    if load_quant:
        layers = find_layers(model)
        for name in ["lm_head"]:
            if name in layers:
                del layers[name]
        ckpt = torch.load(checkpoint)
        if ckpt["hyper_parameters"]["groupsize"] != groupsize:
            warnings.warn("Quantization group-size not-set / mismatch detected.")
        make_quant(model, ckpt["layers_bit"], groupsize=groupsize)
        print("Loading Quant model ...")
        model.load_state_dict(ckpt["model"])
        model.seqlen = 2048
    print("done.")
    return model

def inference(args):
    DEV = torch.device("cuda:0")
    prompt = "Let me tell you a story:"
    # prompt = "why is the sky blue?"

    config = transformers.AutoConfig.from_pretrained(args.model_name)
    model = load_llama(
        args.model_name,
        load_quant=True,
        config=config,
        checkpoint=args.checkpoint,
        groupsize=args.groupsize,
    )
    model.single_device_mode = bool(args.single_device_mode)
    if not model.single_device_mode:
        model.to(DEV)

    tokenizer = transformers.AutoTokenizer.from_pretrained(args.model_name)
    import time

    inputs = tokenizer.encode(prompt, return_tensors="pt").to(DEV)
    start_time = time.time()
    outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)
    end_time = time.time()
    print("time = {} s.".format(end_time - start_time))
    print(tokenizer.decode(outputs[0]))

def main():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "model_name",
        type=str,
        help="LLaMA model to load; pass `decapoda-research/llama-7b/13b/30b/65b-hf`.",
    )
    parser.add_argument(
        "checkpoint",
        type=str,
        default="",
        help="a checkpoint path from local storage",
    )
    parser.add_argument(
        "--groupsize",
        type=int,
        default=-1,
        help="Groupsize to use for quantization; default uses full row.",
    )
    parser.add_argument(
        "--single_device_mode",
        default=False,
        action="store_true",
        help="run LLaMA large models with single device",
    )
    args = parser.parse_args()
    inference(args)

main()


import firebase_admin

from firebase_admin import db

import json

cred_obj = firebase_admin.credentials.Certificate('thatsbullish-15d47-firebase-adminsdk-a0q0p-09492f9905.json')
default_app = firebase_admin.initialize_app(cred_obj,{
    'databaseURL':'https://thatsbullish-15d47-default-rtdb.firebaseio.com'
})

ref = db.reference("stocks")

with open("addtest.json","r") as f:
    addtest = json.load(f)
ref.set(addtest)


import torch.nn as nn
from dgl.nn import GraphConv
import torch.nn.functional as F
import torch
import torch as th

from dgl.nn import SAGEConv

# ----------- 2. create model -------------- #
# build a two-layer GraphSAGE model
class GraphSAGELinkPrediction(nn.Module):
    def __init__(self, in_feats, h_feats):
        super(GraphSAGE, self).__init__()
        self.conv1 = SAGEConv(in_feats, h_feats, 'mean')
        self.conv2 = SAGEConv(h_feats, h_feats, 'mean')

    def forward(self, g, in_feat):
        h = self.conv1(g, in_feat)
        h = F.relu(h)
        h = self.conv2(g, h)
        return h
class GraphClassificationModelCrossEntropy(nn.Module):
    def __init__(self, in_dim, hidden_dim, out_dim):
        super(GraphClassificationModelCrossEntropy, self).__init__()
        self.conv1 = GraphConv(in_dim, out_dim, allow_zero_in_degree=True)
        #self.conv2 = GraphConv(hidden_dim, out_dim, allow_zero_in_degree=True)

    def forward(self, g, features):
        h = self.conv1(g, features)
        #h = F.relu(h)
        #h = self.conv2(g, h)
        return h

    def fit(self, epochs, graph, optimizer):
        train_mask = graph.ndata['train_mask']
        #val_mask = graph.ndata['val_mask']
        labels = graph.ndata['label']
        features = graph.ndata['feat'].float()
        for epoch in range(epochs):
            logits = self(graph, features)
            loss = F.cross_entropy(logits[train_mask].float(), labels[train_mask].float())
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            if epoch % 10 == 0:
                # Evaluation loop
                with torch.no_grad():
                    logits = self(graph, features)
                    pred = logits.argmax(1)
                    train_acc = (pred[train_mask] == labels[train_mask]).float().mean()
                    #val_acc = (logits[val_mask].argmax(1) == labels[val_mask]).float().mean().item()
                    val_acc = 0
                    print(f'Epoch {epoch}: loss={loss:.4f}, train_acc={train_acc:.4f}, val_acc={val_acc:.4f}')

class GraphClassificationModelBinaryCrossEntropy(nn.Module):
    def __init__(self, in_dim, hidden_dim, out_dim):
        super(GraphClassificationModelBinaryCrossEntropy, self).__init__()
        self.conv1 = GraphConv(in_dim, out_dim, allow_zero_in_degree=True)
        #self.conv2 = GraphConv(hidden_dim, hidden_dim, allow_zero_in_degree=True)
        #self.conv3 = GraphConv(hidden_dim, out_dim, allow_zero_in_degree=True)

    def forward(self, g, features):
        h = self.conv1(g, features)
        #h = F.relu(h)
        #h = self.conv2(g, h)
        #h = self.conv3(g, h)
        return h

    def fit(self, epochs, graph, optimizer):
        train_mask = graph.ndata['train_mask']
        #val_mask = graph.ndata['val_mask']
        labels = graph.ndata['label']
        features = graph.ndata['feat'].float()
        for epoch in range(epochs):
            logits = self(graph, features)
            loss = F.binary_cross_entropy_with_logits(logits[train_mask], labels[train_mask].float())
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            if epoch % 1 == 0:
                # Evaluation loop
                with torch.no_grad():
                    logits = self(graph, features)
                    train_acc_matches = []
                    for id, index in enumerate(torch.max(logits[train_mask], dim=1)[1]):
                        if labels[train_mask][id][index] == 1:
                            train_acc_matches.append(1)
                        else:
                            train_acc_matches.append(0)
                    train_acc = sum(train_acc_matches) / len(train_acc_matches)
                    """
                    val_acc_matches = []
                    for id, index in enumerate(torch.max(torch.softmax(logits[val_mask], dim=1), dim=1)[1]):
                        if labels[val_mask][id][index] == 1:
                            val_acc_matches.append(1)
                        else:
                            val_acc_matches.append(0)
                    val_acc = sum(val_acc_matches) / len(val_acc_matches)
                    """
                    val_acc = 0
                    print(f'Epoch {epoch}: loss={loss:.4f}, train_acc={train_acc:.4f}, val_acc={val_acc:.4f}')

    def predict(self, graph, nodes_mask):
        features = graph.ndata['feat'].float()
        with torch.no_grad():
            logits = self(graph, features)[nodes_mask]
            return torch.max(torch.softmax(logits, dim=1), dim=1)[1]