import os
import datetime
import numpy as np
import tensorflow as tf
import mlp.data_providers as data_providers

from image_processing import *
from layers import *

os.environ['MLP_DATA_DIR'] = '/disk/scratch/mlp/data'
os.environ['OUTPUT_DIR'] = '$HOME/experiments'

# check necessary environment variables are defined
assert 'MLP_DATA_DIR' in os.environ, (
    'An environment variable MLP_DATA_DIR must be set to the path containing'
    ' MLP data before running script.')
assert 'OUTPUT_DIR' in os.environ, (
    'An environment variable OUTPUT_DIR must be set to the path to write'
    ' output to before running script.')

# load data
train_data = data_providers.CIFAR10DataProvider('train', batch_size=100)
valid_data = data_providers.CIFAR10DataProvider('valid', batch_size=100)
valid_inputs = valid_data.inputs
valid_targets = valid_data.to_one_of_k(valid_data.targets)

# Convolutional layer with non-linearity
def conv2d(x, w, b, activation=tf.nn.relu):
    conv = tf.nn.conv2d(x, w, strides=[1,1,1,1], padding='SAME')
    return activation(tf.nn.bias_add(conv, b))

# fully connected layer with non-linearity
def fc(x, w, b, activation=tf.nn.relu):
    y = tf.nn.bias_add (tf.matmul(x, w), b)
    if(activation != 'None'):
        y = activation(y)
    return y

with tf.name_scope('data'):
    inputs = tf.placeholder(tf.float32, [None, 3072], name='inputs')
    targets = tf.placeholder(tf.float32, [None, train_data.num_classes], name='targets')
with tf.name_scope('parameters'):
    weights = {
        'W_conv1':tf.Variable(tf.truncated_normal([3,3,3,32], stddev=2./(9*3+9*32)**0.5)),
        'W_conv2':tf.Variable(tf.truncated_normal([3,3,32,64], stddev=2./(9*32+9*64)**0.5)),
        'W_conv3':tf.Variable(tf.truncated_normal([3,3,64,128], stddev=2./(9*64+9*128)**0.5)),
        'W_conv4':tf.Variable(tf.truncated_normal([3,3,128,128], stddev=2./(9*128*2)**0.5)),
        'W_fc1':tf.Variable(tf.truncated_normal([8*8*128, 1024], stddev=2./(8*8*128+1024)**0.5)),
        'W_fc2':tf.Variable(tf.truncated_normal([1024, 512], stddev=2./(1024+512)**0.5)),
        'W_fc3':tf.Variable(tf.truncated_normal([512, train_data.num_classes], stddev=2./(train_data.num_classes+512)**0.5))
    }
    biases = {
        'b_conv1':tf.Variable(tf.zeros([32])),
        'b_conv2':tf.Variable(tf.zeros([64])),
        'b_conv3':tf.Variable(tf.zeros([128])),
        'b_conv4':tf.Variable(tf.zeros([128])),
        'b_fc1':tf.Variable(tf.zeros([1024])),
        'b_fc2':tf.Variable(tf.zeros([512])),
        'b_fc3':tf.Variable(tf.zeros([train_data.num_classes]))
    }
# specify if apply data augmentation to input
if_augmentation = True

with tf.name_scope('model'):
    if(if_augmentation):
        inputs = image_cropping(inputs)
    input_layer = tf.reshape(inputs, [-1,32,32,3])
    # Convolutional layer   #1 #2
    conv1 = conv2d(
        input_layer, weights['W_conv1'], biases['b_conv1'])
    conv2 = conv2d(
        conv1, weights['W_conv2'], biases['b_conv2'])
    # Pooling Layer #1
    #pool1 = tf.contrib.layers.max_pool2d(inputs=conv2, kernel_size=[2,2],stride=2, padding='VALID')
    #pool1 = tf.contrib.layers.avg_pool2d(inputs=conv2, kernel_size=[2, 2],stride=2, padding='VALID')
    alpha, pool1 = mixed_pooling(conv2, alpha=-1)
    #pool1 = gated_pooling(conv2, filter=64)
    #pool1 = gated_pooling(conv2, filter=64, learn_option='l')
    #pool1 = gated_pooling(conv2, filter=64, learn_option='l/r/c')

    # Convolutional layer   #3 #4
    conv3 = conv2d(
        pool1,weights['W_conv3'],biases['b_conv3'])
    conv4 = conv2d(
        conv3, weights['W_conv4'],biases['b_conv4'])
    # Pooling Lyaer #2
    #pool2 = tf.contrib.layers.max_pool2d(inputs=conv4,kernel_size=[2,2],stride=2, padding='VALID')
    #pool2 = tf.contrib.layers.avg_pool2d(inputs=conv4,kernel_size=[2,2],stride=2, padding='VALID')
    _, pool2 = mixed_pooling(conv4, alpha=alpha)
    #_, pool2 = mixed_pooling(conv4, alpha=-1)
    #pool2 = gated_pooling(conv4, filter=128)
    #pool2 = gated_pooling(conv4, filter=128, learn_option='l')
    #pool2 = gated_pooling(conv4, filter=128, learn_option='l/r/c')
    pool2_flat = tf.reshape(pool2, [-1, 8*8*128])

    fc1= fc(pool2_flat, weights['W_fc1'], biases['b_fc1'])
    dropout1 = tf.nn.dropout(fc1, 0.4)
    fc2= fc(dropout1,  weights['W_fc2'], biases['b_fc2'])
    fc3= fc(fc2,  weights['W_fc3'], biases['b_fc3'], activation = 'None')
    outputs = fc3

# Anneal to learning rate
global_step= tf.Variable(0, trainable=False)
boundaries = [20, 40, 60, 80]
values = [0.01, 0.005, 0.001, 0.0005, 0.0001]
learning_rate1 = tf.train.piecewise_constant(
    global_step,boundaries , values)
learning_rate2 = tf.train.exponential_decay(
        learning_rate=0.5, global_step=global_step,
        decay_steps=100, decay_rate=0.001)
weight_decay = tf.nn.l2_loss(weights['W_conv1'])+tf.nn.l2_loss(weights['W_conv2']) + tf.nn.l2_loss(weights['W_conv3'])\
               + tf.nn.l2_loss(weights['W_conv4'])+tf.nn.l2_loss(weights['W_fc1'])+tf.nn.l2_loss(weights['W_fc2'])+\
               tf.nn.l2_loss(weights['W_fc3'])

with tf.name_scope('error'):
    error = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(outputs, targets) + 0.001*weight_decay)
with tf.name_scope('accuracy'):
    accuracy = tf.reduce_mean(tf.cast(tf.equal(
        tf.argmax(outputs, 1), tf.argmax(targets, 1)), tf.float32))
with tf.name_scope('train'):
    #train_step = tf.train.AdagradOptimizer(learning_rate=0.01).minimize(error, global_step=global_step)
    train_step = tf.train.MomentumOptimizer(learning_rate=0.01, momentum=0.9).minimize(error, global_step=global_step)
    #train_step = tf.train.RMSPropOptimizer(learning_rate=0.001).minimize(error)

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

# add summary operations
tf.summary.scalar('error', error)
tf.summary.scalar('accuracy', accuracy)
summary_op = tf.summary.merge_all()
# create objects for writing summaries and checkpoints during training
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
exp_dir = os.path.join(os.environ['OUTPUT_DIR'], timestamp)
checkpoint_dir = os.path.join(exp_dir, 'checkpoints')
if not os.path.exists(exp_dir):
    os.makedirs(exp_dir)
if not os.path.exists(checkpoint_dir):
    os.makedirs(checkpoint_dir)
train_writer = tf.summary.FileWriter(os.path.join(exp_dir, 'train-summaries'))
valid_writer = tf.summary.FileWriter(os.path.join(exp_dir, 'valid-summaries'))
saver = tf.train.Saver()

# create arrays to store run train / valid set stats
num_epoch = 75
train_accuracy = np.zeros(num_epoch)
train_error = np.zeros(num_epoch)
valid_accuracy = np.zeros(num_epoch)
valid_error = np.zeros(num_epoch)

# create session and run training loop
#sess = tf.Session()
NUM_THREADS = 8
sess = tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=NUM_THREADS))
sess.run(tf.global_variables_initializer())
step = 0
print('starting....10+')
for e in range(num_epoch):
    for b, (input_batch, target_batch) in enumerate(train_data):
        # do train step with current batch
        _, summary, batch_error, batch_acc = sess.run(
            [train_step, summary_op, error, accuracy],
            feed_dict={
                inputs: input_batch,
                targets: target_batch
            })
        # add symmary and accumulate stats
        train_writer.add_summary(summary, step)
        train_error[e] += batch_error
        train_accuracy[e] += batch_acc
        step += 1
    # normalise running means by number of batches
    train_error[e] /= train_data.num_batches
    train_accuracy[e] /= train_data.num_batches
    # evaluate validation set performance
    valid_summary, valid_error[e], valid_accuracy[e] = sess.run(
        [summary_op, error, accuracy],
        feed_dict={inputs: valid_inputs, targets: valid_targets})
    valid_writer.add_summary(valid_summary, step)
    # checkpoint model variables
    saver.save(sess, os.path.join(checkpoint_dir, 'model.ckpt'), step)
    # write stats summary to stdout
    print('Epoch {0:02d}: err(train)={1:.2f} acc(train)={2:.2f}'
          .format(e + 1, train_error[e], train_accuracy[e]))
    print('          err(valid)={0:.4f} acc(valid)={1:.4f}'
          .format(valid_error[e], valid_accuracy[e]))

# close writer and session objects
train_writer.close()
valid_writer.close()
sess.close()


class LongestBitonicSubsequence:
    def __init__(self, li) -> None:
        self.LBSlist = li   #1차원 배열
        self.answer = 0
        self.calculating()

    def calculating(self):
        uplist = []
        downlist = []
        anslist = []
        reLBSlist = self.LBSlist.copy()
        reLBSlist.reverse()

        for i in range(0, len(self.LBSlist)):
            ans = 1
            for j in range(0,i):
                if self.LBSlist[i] <= self.LBSlist[j]:
                    continue
                if ans <= uplist[j]:
                    ans += 1

            uplist.append(ans)

        for i in range(0, len(reLBSlist)):
            ans = 1
            for j in range(0,i):
                if reLBSlist[i] <= reLBSlist[j]:
                    continue
                if ans <= downlist[j]:
                    ans += 1

            downlist.append(ans)

        downlist.reverse()

        for i in range(0, len(self.LBSlist)):
            anslist.append(uplist[i] + downlist[i] - 1)

        self.answer = max(anslist)

    def printAnswer(self):
        print(self.answer)

class InputClass:
    def __init__(self,num) -> None:
        self.li = []
        self.num = 1
        self.mainInput(1)

    def testInput(self,i):
        pass

    def caseInput(self,i):
        if i == 1:
            self.li = [1, 5, 2, 1, 4, 3, 4, 5, 2, 1]
        if i == 2:
            self.li = [1,2,3,9,4,5,6]

    def mainInput(self,i):
        self.num = int(input())
        a = input().split()
        for i in a:
            self.li.append(int(i))

    def returnli(self):
        return self.li

inp = InputClass(1)
li = inp.returnli()

r = LongestBitonicSubsequence(li)
r.printAnswer()


# This code uses scikit-learn to calculate bag-of-words
# (BOW). `CountVectorizer` implements both tokenization and occurrence
# counting in a single class.
from sklearn.feature_extraction.text import CountVectorizer
v = CountVectorizer(stop_words='english') # Vectorizer.
c = [                           # Minimal corpus for illustration.
    'This is the first document.',
    'This is the second document.',
    'And the third one.',
    'Is this the first document?',
]
# Learn the vocabulary dictionary and return the document-term
# matrix. Tokenize and count word occurrences.
bow = v.fit_transform(c)
# Each term found by the analyzer during the fit is assigned a unique
# integer index corresponding to a column in the resulting
# matrix. This interpretation of the columns can be retrieved as
# follows.
bow.toarray()                   # Print the document-term matrix.
bow.A                           # Same effect, shortcut command.
v.get_feature_names()           # Which term is in which column?
# Inverse mapping from feature name to column index.
v.vocabulary_.get('second')
# Mapping of documents to BOW. Words that were not seen in the
# training corpus are ignored.
v.transform(['Something completely new.']).toarray()
v.transform(['A second try.']).toarray()


import os, sys, glob
from PIL import Image

print('Deleting old crops...')
import os, glob
for filename in glob.glob('./crop_*'):
    os.remove(filename)

print('Cropping...')
prefix = 'crop_'
first = 4
last = 509
zfill = 3
width = 1050
height = 800
l_margin = 570
t_margin = 600
r_margin = 570
is_left = True

for i in range(first, last + 1):
    current_file = str(i).zfill(zfill) + '.jpg'
    im = Image.open(current_file)
    if is_left:
        left = l_margin
        top = t_margin
        right = l_margin + width
        bottom = t_margin + height
    else:
        left = im.size[0] - r_margin - width
        top = t_margin
        right = im.size[0] - r_margin
        bottom = t_margin + height
    is_left = not is_left
    new_im = im.crop((left, top, right, bottom))
    new_im.save(prefix + current_file)

print('Done.')


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

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """

        def preorder(node):
            if node:
                res.append(str(node.val))
                preorder(node.left)
                preorder(node.right)

        res = []
        preorder(root)
        return ' '.join(res)

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        if not data:
            return None
        preorder = list(map(int, data.split(" ")))
        inorder = sorted(preorder)
        return self.formTree(preorder, inorder)

    def formTree(self, preorder, inorder):
        if inorder:
            root = TreeNode(preorder[0])
            inPos = inorder.index(preorder[0])
            preorder.pop(0)
            root.left =  self.formTree(preorder, inorder[:inPos])
            root.right =  self.formTree(preorder, inorder[inPos + 1:])
            return root
        else:
            return None

str = "-";
seq = ("a", "b", "c") # 字符串序列
print(str.join( seq ))
# join only works for string concatenation
str = "12364"
map(int,str)
# list(map(int,str)) = [1,2,3,6,4]


#!/usr/bin/python
import sys

def lcs(S,T):
    m = len(S)
    n = len(T)
    counter = [[0]*(n+1) for x in range(m+1)]
    longest = 0
    lcs_set = set()
    for i in range(m):
        for j in range(n):
            if S[i] == T[j]:
                c = counter[i][j] + 1
                counter[i+1][j+1] = c
                if c > longest:
                    lcs_set = set()
                    longest = c
                    lcs_set.add(S[i-c+1:i+1])
                elif c == longest:
                    lcs_set.add(S[i-c+1:i+1])

 #   if len(list(lcs_set)[0])>10:
#        print(c1,c2)
 #       print(lcs_set)
    return max(lcs_set,key=len)

myarray=[]
theirarray=[]
f=open(sys.argv[1],"r")
lines=f.readlines()
f.close()
for line in lines:
    if line[0]!=">":
        myarray.append(line)

f=open(sys.argv[2],"r")
lines=f.readlines()
f.close()
for line in lines:
    if line[0]!=">":
        theirarray.append(line)

big=""
lenarray=[]
for my in myarray:
    for they in theirarray:
        seq=lcs(my,they)
        lenarray.append(len(seq))
        if len(seq)>len(big):
            big=seq
print(len(big),big)
print(sum(lenarray)/len(lenarray))


#!/bin/usr/python

import urllib2

with open('present.txt','r') as f:
	lines = f.readlines()

url = 'http://google.com'

for line in lines:
	header = {'User-agent':line}
	req = urllib2.Request(url,None,header)
	urllib2.urlopen(req).read()


import os
import uvicorn
import requests
from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/api/character")
def rick_and_morty_character():
    '''
    '''
    obj_lst = []
    # get the data from Rick and Morty API
    res = requests.get("https://rickandmortyapi.com/api/character")
    # case when the API is up
    if res.status_code == 200:
        results = res.json()["results"]
        # build the object list
        for result in results:
            obj_lst.append({"name": result["name"], "location": result["location"]["name"], "image": result["image"]})
        # return the response
        return JSONResponse(status_code=200, content={"message": "Data fetched successfully", "data": obj_lst})
    # case when the API is down
    else:
        return JSONResponse(status_code=400, content={"message": "Unable to fetch data from Rick and Morty API"})

@app.get("/healthcheck")
def healthcheck():
    '''
    '''
    return JSONResponse(status_code=200, content={"message": "Service is up and running"})

if __name__ == "__main__":
    uvicorn.run("app:app", host="0.0.0.0", port = int(os.environ.get("FAST_API_PORT", 8080)))


from django.contrib.auth.models import Group, User
from rest_auth.registration.serializers import RegisterSerializer
from rest_framework import serializers

from auction.auctions.serializers import AuctionShortSerializer, BidSerializer

from .models import UserProfile

class ShortUserProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = UserProfile
        fields = ("url", "id", "address", "phone_number", "approved_terms")
        read_only_fields = ("id",)

class ShortUserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = (
            "url",
            "id",
            "username",
            "first_name",
            "last_name",
            "email",
            "is_staff",
            "is_active",
        )
        read_only_fields = ("username", "id")

class DetailUserSerializer(serializers.HyperlinkedModelSerializer):
    profile = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            "url",
            "username",
            "email",
            "first_name",
            "last_name",
            "is_staff",
            "is_active",
            "date_joined",
            "profile",
        )
        read_only_fields = ("username", "date_joined", "is_staff", "is_active")

    def get_profile(self, obj):
        profile = obj.profile
        serialized = ShortUserProfileSerializer(
            profile, context={"request": self.context.get("request")}
        )
        return serialized.data

class DetailUserProfileSerializer(serializers.HyperlinkedModelSerializer):
    active_auctions = serializers.SerializerMethodField()
    inactive_auctions = serializers.SerializerMethodField()
    won_auctions = serializers.SerializerMethodField()
    bids = serializers.SerializerMethodField()
    user = ShortUserSerializer(read_only=True)

    class Meta:
        model = UserProfile
        fields = (
            "url",
            "id",
            "user",
            "address",
            "phone_number",
            "approved_terms",
            "won_auctions",
            "bids",
            "active_auctions",
            "inactive_auctions",
        )
        read_only_fields = ("id", "user")

    def get_active_auctions(self, obj):
        auctions = obj.active_auctions
        serialized = AuctionShortSerializer(
            auctions, many=True, context={"request": self.context.get("request")}
        )
        return serialized.data

    def get_inactive_auctions(self, obj):
        auctions = obj.inactive_auctions
        serialized = AuctionShortSerializer(
            auctions, many=True, context={"request": self.context.get("request")}
        )
        return serialized.data

    def get_won_auctions(self, obj):
        won_auctions = obj.won_auctions
        serialized = AuctionShortSerializer(
            won_auctions, many=True, context={"request": self.context.get("request")}
        )
        return serialized.data

    def get_bids(self, obj):
        bids = obj.bids
        serialized = BidSerializer(
            bids, many=True, context={"request": self.context.get("request")}
        )
        return serialized.data

class RegisterUserProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = UserProfile
        fields = ("url", "id", "address")
        read_only_fields = ("id", "url")

class UserRegisterSerializer(RegisterSerializer):
    first_name = serializers.CharField(max_length=30)
    last_name = serializers.CharField(max_length=150)
    address = serializers.CharField(max_length=100)
    phone_number = serializers.CharField(max_length=20)
    approved_terms = serializers.BooleanField()

    def get_cleaned_data(self):
        data_dict = super().get_cleaned_data()
        data_dict["first_name"] = self.validated_data.get("first_name", "")
        data_dict["last_name"] = self.validated_data.get("last_name", "")
        data_dict["address"] = self.validated_data.get("address", "")
        data_dict["phone_number"] = self.validated_data.get("phone_number", "")
        data_dict["approved_terms"] = self.validated_data.get("approved_terms", "")
        return data_dict

    def custom_signup(self, request, user):
        UserProfile.objects.create(
            user=user,
            address=self.cleaned_data["address"],
            phone_number=self.cleaned_data["phone_number"],
            approved_terms=self.cleaned_data["approved_terms"],
        )


import time
from turtle import Turtle, Screen
import random
import time

# screen = Screen()
# tim = Turtle()
# ''' Proj 1- Draw anything controled by keyboard and home in the end'''
# def fwd():
#     tim.forward(10)
#
# def bwd():
#     tim.backward(10)
#
# def ccw():
#     tim.right(5)
#
# def cw():
#     tim.left(5)
# def clr():
#     tim.clear()
#     tim.penup()
#     tim.home()
#     tim.pendown()
#
# tim.screen.listen()
# tim.screen.onkey(fun=fwd, key="w")
# tim.screen.onkey(fun=bwd, key="s")
# tim.screen.onkey(fun=ccw, key="a")
# tim.screen.onkey(fun=cw, key="d")
# tim.screen.onkey(fun=clr, key="c")

'''Proj-2 Turtle race'''
screen = Screen()
screen.setup(width=500,height=400)
user_bet = screen.textinput(title="Turtle Race", prompt="Which turtle will win the race: "
                                                        "red,green,yellow,black,orange,purple\n"
                                                        "Choose the color you bet: ")
print(user_bet)
colors = ["red","green","yellow","black","orange","purple"]
y_position = [-70, -40, -10, 20, 50, 80]
all_turtles = []
if user_bet:
    move_on = True

for i in range(0,6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.color(colors[i])
    new_turtle.penup()
    new_turtle.speed("slow")
    new_turtle.goto(x=-220, y=y_position[i])
    all_turtles.append(new_turtle)

while move_on:
    '''Below is my code, which works. But second versin from teacher is better'''
    # for i in range(6):
    #     random_dist = random.randint(0, 10)
    #     all_turtles[i].forward(random_dist)
    #     if all_turtles[i].xcor() > 200:
    #         winner = all_turtles[i].color()[0]
    #         if winner == user_bet:
    #             print("YOU WIN :)")
    #         else:
    #             print(f"YOU LOSE :( The winner is {winner}")
    #         move_on = False

    for turtle in all_turtles:
        random_dist = random.randint(0, 10)
        turtle.forward(random_dist)
        if turtle.xcor() > 200:
            move_on = False
            winner = turtle.pencolor()
            if user_bet == winner:
                print("YAYA, YOU WIN!")
            else:
                print(f"Sorry you lost. The winner is {winner}")

# t_r.penup()
# t_r.goto(x=-200,y=-50)
# t_r.color("red")
#
#
# t_b.penup()
# t_b.goto(x=-200,y=0)
# t_b.color("blue")
#
# t_g.penup()
# t_g.goto(x=-200,y=50)
# t_g.color("green")
#
#
# def race():
#     while t_r.pos()[0] < 200 and t_b.pos()[0] < 200 and t_g.pos()[0] < 200:
#         t_r.speed(random.choice(a))
#         print(t_r.speed(random.choice(a)))
#         t_r.penup()
#         t_r.forward(5)
#
#         t_b.speed(random.choice(a))
#         t_b.speed(random.choice(a))
#         t_b.penup()
#         t_b.forward(5)
#
#
#         t_g.speed(random.choice(a))
#         t_g.speed(random.choice(a))
#         t_g.penup()
#         t_g.forward(5)
#
#         print("=======\n")
#         time.sleep(0.5)
#         if t_r.pos()[0] == 199:
#             screen.textinput(title="Race", prompt="Red is winner!")
#             print('Red is winner!')
#             time.sleep(0.5)
#         elif t_g.pos()[0] == 199:
#             screen.textinput(title="Race", prompt="Green is winner!")
#             print('Green is winner!')
#             time.sleep(0.5)
#         elif t_b.pos()[0] == 199:
#             screen.textinput(title="Race", prompt="Blue is winner!")
#             print('Blue is winner!')
#
# race()

screen.exitonclick()


import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

pinMotorAON = 17
pinMotorAForwards = 27
pinMotorABackwards = 22

pinMotorBON = 24
pinMotorBForwards = 25
pinMotorBBackwards = 23

##set the GPIO Pin mode

GPIO.setup(pinMotorAON, GPIO.OUT)
GPIO.setup(pinMotorAForwards, GPIO.OUT)
GPIO.setup(pinMotorABackwards, GPIO.OUT)
GPIO.setup(pinMotorBON, GPIO.OUT)
GPIO.setup(pinMotorBForwards, GPIO.OUT)
GPIO.setup(pinMotorBBackwards, GPIO.OUT)

def StopMotors():
    GPIO.output(pinMotorAON, 0)
    GPIO.output(pinMotorAForwards, 0)
    GPIO.output(pinMotorABackwards, 0)
    GPIO.output(pinMotorBON, 0)
    GPIO.output(pinMotorBForwards, 0)
    GPIO.output(pinMotorBBackwards, 0)

def Forwards():
    GPIO.output(pinMotorAON, 1)
    GPIO.output(pinMotorAForwards, 1)
    GPIO.output(pinMotorBON, 1)
    GPIO.output(pinMotorBForwards, 1)
    print("Moving Wheels forward")

def Backwards():
    GPIO.output(pinMotorAON, 1)
    GPIO.output(pinMotorABackwards, 1)
    GPIO.output(pinMotorBON, 1)
    GPIO.output(pinMotorBBackwards, 1)
    print("Moving Backwards")

def Right():
    GPIO.output(pinMotorAON, 1)
    GPIO.output(pinMotorAForwards, 1)
    print("Turning Right")

def Left():
    GPIO.output(pinMotorBON, 1)
    GPIO.output(pinMotorBForwards, 1)
    print("Turning Left")

Forwards()
time.sleep(2)
StopMotors()

Left()
time.sleep(2)
StopMotors()

Right()
time.sleep(2)
StopMotors()

Backwards()
time.sleep(2)
StopMotors()

StopMotors()

GPIO.cleanup()


from django.db import transaction
from byrd_backend.apps.wms.models import OrderLine
from byrd_backend.apps.wms.serializers import OrderLineSerializer
from byrd_backend.libs.operations import OperationManager
from byrd_backend.libs.exceptions import ByrdException

class OrderLineOperations(OperationManager):

    def __init__(self):
        super().__init__(model=OrderLine, serializer=OrderLineSerializer)

    def get_list(self, order=None):
        if not order:
            message = 'Missing order.'
            raise ByrdException(message, [message])
        order = self.get_instance(order)
        return super().get_list(self.filter_by_kwargs(order=order.id))

    def get_create_update_lines_and_picks(self, lines_data):
        from byrd_backend.apps.wms.operations import StorageOperations
        """
        Would create lines and update stock under stock
        :param lines_data:
        :param prev_lines:
        :return: A Tuple with 1st item as lines and 2nd as picks
        """
        try:
            with transaction.atomic():
                stock_operations = StorageOperations()
                if self.is_valid(lines_data, True, True):
                    lines, picks = [], []
                    for line_data in lines_data:
                        line = self.create_or_update(line_data)
                        lines.append(line.id)
                        picks = picks + stock_operations.get_picks(line)
                    return lines, picks
        except Exception as ex:
            raise ex


#muncul menu
list = ["Selamat Datang!"," ", "--Menu--", "1. Daftar Kontak", "2. Tambah Kontak", "3. Keluar", " "]

for x in list:
    print(x)

a = int(input("Pilih Menu: "))
print()

if a == 1:                                                  #menu 1
    daftar = ["Daftar Kontak:", "Nama: Wahyu", "No Telepon: 08123456789", "Nama: Wardhana", "No Telepon: 08987654321"]
    for z in daftar:
        print(z)
else:
    if a == 2:                                             #menu 2
        nama = []
        telepon = []
        for y in range(1):
            nama.append(input("Nama: "))
            telepon.append(input("No Telepon: "))
        for y in range(1):
            print("Kontak Berhasil Ditambahkan")
    else:
        if a == 3:                                          #menu 3
            print("Program selesai, sampai jumpa!")
        else:
            if a < 1 or a > 3:                              #menu 4
                print("Menu tidak tersedia")


import torch
import os
import mmcv

from mmcv.runner import load_checkpoint
from mmcv.parallel import MMDistributedDataParallel, MMDataParallel
from .env import get_root_logger
import numpy as np
from sklearn.metrics.pairwise import cosine_distances
from ..datasets.dataloader import build_dataloader
import time
from .test import collect_results_cpu
from mmcv.runner import get_dist_info
from tqdm import tqdm

def multi_gpu_extract_features(model, data_loader, progress=True):
    """Extract and save features for train split, several clips per video."""
    model.eval()
    results = []
    labels = []
    indices = []
    dataset = data_loader.dataset

    rank, world_size = get_dist_info()
    if rank == 0 and progress:
        prog_bar = mmcv.ProgressBar(len(dataset))

    time.sleep(2)  # This line can prevent deadlock problem in some cases.
    for i, data in enumerate(data_loader):
        label = data["gt_labels"].data[0].cuda()
        imgs = data['imgs'].data[0].cuda()
        with torch.no_grad():
            feat = model(imgs=imgs, retrieve_mode=True)
        results.extend(feat.cpu().numpy().tolist())
        # labels.append(label.repeat(1, 10).cpu().numpy().tolist())
        labels.extend(label.flatten().cpu().numpy().tolist())
        indices.extend(data['index'].data[0].flatten().cpu().numpy().tolist())
        if rank == 0 and progress:
            batch_size = len(feat)
            for _ in range(batch_size * world_size):
                prog_bar.update()

    feats = collect_results_cpu(results, len(dataset), None)
    labels = collect_results_cpu(labels, len(dataset), None)
    indices = collect_results_cpu(indices, len(dataset), None)
    return feats, labels, indices

def single_gpu_extract_features(model, data_loader):
    """Extract and save features for train split, several clips per video."""
    model.eval()
    feats = []
    labels = []
    model = model.cuda()
    indices = []
    for i, data in enumerate(tqdm(data_loader)):
        label = data["gt_labels"].data[0].cuda()
        imgs = data['imgs'].data[0].cuda()
        with torch.no_grad():
            feat = model(imgs=imgs, retrieve_mode=True)
        feats.extend(feat.cpu().numpy().tolist())
        # labels.append(label.repeat(1, 10).cpu().numpy().tolist())
        labels.extend(label.flatten().cpu().numpy().tolist())
        indices.extend(data['index'].data[0].flatten().cpu().numpy().tolist())
        # if i == 10: break
    feats = np.array(feats)
    labels = np.array(labels)
    return feats, labels, np.array(indices)

def  topk_retrieval(X_train, y_train, X_test, y_test):
    ks = [1, 5, 10, 20, 50]
    topk_correct = {k:0 for k in ks}

    X_test = np.array(X_test)
    X_test = X_test.reshape(X_test.shape[0], -1)
    X_train = np.array(X_train)
    X_train = X_train.reshape(X_train.shape[0], -1)

    distances = cosine_distances(X_test, X_train)
    indices = np.argsort(distances)

    for k in ks:
        # print(k)
        top_k_indices = indices[:, :k]
        # print(top_k_indices.shape, y_test.shape)
        for ind, test_label in zip(top_k_indices, y_test):
            labels = y_train[ind]
            if test_label in labels:
                # print(test_label, labels)
                topk_correct[k] += 1

    for k in ks:
        correct = topk_correct[k]
        total = len(X_test)
        print('Top-{}, correct = {:.2f}, total = {}, acc = {:.3f}'.format(k, correct, total, correct/total))

    return topk_correct

def retrieve(model,
             dataset,
             test_dataset,
             cfg,
             distributed=False,
             logger=None):
    if logger is None:
        logger = get_root_logger(cfg.log_level)
    logger.info(f"Ckpt path: {cfg.checkpoint}")
    if cfg.checkpoint.endswith('.pth'):
        prefix = os.path.basename(cfg.checkpoint)[:-4]
    else:
        prefix = 'unspecified'

    out_name = f'retrieve_{dataset.__class__.__name__}_{dataset.name}'
    output_dir = os.path.join(cfg.work_dir, out_name)
    mmcv.mkdir_or_exist(output_dir)

    multiprocessing_context = None
    if cfg.get('numpy_seed_hook', True) and cfg.data.workers_per_gpu > 0:
        multiprocessing_context = 'spawn'
    test_data_loader = build_dataloader(
        test_dataset,
        imgs_per_gpu=cfg.data.videos_per_gpu, #1, cfg.data.videos_per_gpu
        workers_per_gpu=cfg.data.workers_per_gpu,
        dist=distributed,
        shuffle=False,
        multiprocessing_context=multiprocessing_context,
        drop_last=False
    )

    cache_path = os.path.join(output_dir, f'{prefix}_feats.pkl')
    label_cache_path = os.path.join(output_dir, f'{prefix}_labels.pkl')
    test_cache_path = os.path.join(output_dir, f'{prefix}_feats_test.pkl')
    test_label_cache_path = os.path.join(output_dir, f'{prefix}_labels_test.pkl')
    if os.path.isfile(cache_path):
        logger.info(f"Load features from {cache_path}")
        train_feats = mmcv.load(cache_path)
        train_labels = mmcv.load(label_cache_path)

        test_feats = mmcv.load(cache_path)
        test_labels = mmcv.load(label_cache_path)
    else:
        load_checkpoint(model, cfg.checkpoint, logger=logger)
        # save config in model
        model.cfg = cfg
        # build dataloader

        data_loader = build_dataloader(
            dataset,
            imgs_per_gpu=cfg.data.videos_per_gpu, # 1, cfg.data.videos_per_gpu
            workers_per_gpu=cfg.data.workers_per_gpu,
            dist=distributed,
            shuffle=False,
            multiprocessing_context=multiprocessing_context,
            drop_last=False
        )

        if distributed:
            if cfg.get('syncbn', False):
                model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)

            model = MMDistributedDataParallel(
                model.cuda(),
                device_ids=[torch.cuda.current_device()],
                broadcast_buffers=False
            )
            train_feats, train_labels, train_indices = multi_gpu_extract_features(model, data_loader)
            test_feats, test_label, test_indicess = multi_gpu_extract_features(model, test_data_loader)
        else:
            device_ids = list(range(cfg.gpus))
            model = MMDataParallel(model, device_ids=device_ids).cuda()
            train_feats, train_labels, train_indices = single_gpu_extract_features(model, data_loader)
            test_feats, test_labels, test_indices = single_gpu_extract_features(model, test_data_loader)

        mmcv.dump(train_feats, cache_path)
        mmcv.dump(train_labels, label_cache_path)

        mmcv.dump(train_indices, os.path.join(output_dir, f'{prefix}_indices.pkl'))

        mmcv.dump(test_feats, test_cache_path)
        mmcv.dump(train_labels, test_label_cache_path)
        mmcv.dump(test_indices, os.path.join(output_dir, f'{prefix}_indices_test.pkl'))

    # evaluate results
    retrieve_results = topk_retrieval(train_feats, train_labels, test_feats, test_labels)
    mmcv.dump(retrieve_results, os.path.join(output_dir,
                                         f'{prefix}_retrieve_results.json'))


#
#
#

from __future__ import absolute_import, division, print_function, \
    unicode_literals

from mock import Mock, call
from os.path import dirname, join
from requests import HTTPError
from requests_mock import ANY, mock as requests_mock
from six import text_type
from unittest import TestCase

from octodns.record import Record
from octodns.provider.dnsimple import DnsimpleClientNotFound, DnsimpleProvider
from octodns.provider.yaml import YamlProvider
from octodns.zone import Zone

class TestDnsimpleProvider(TestCase):
    expected = Zone('unit.tests.', [])
    source = YamlProvider('test', join(dirname(__file__), 'config'))
    source.populate(expected)

    # Our test suite differs a bit, add our NS and remove the simple one
    expected.add_record(Record.new(expected, 'under', {
        'ttl': 3600,
        'type': 'NS',
        'values': [
            'ns1.unit.tests.',
            'ns2.unit.tests.',
        ]
    }))
    for record in list(expected.records):
        if record.name == 'sub' and record._type == 'NS':
            expected._remove_record(record)
            break

    def test_populate(self):
        provider = DnsimpleProvider('test', 'token', 42)

        # Bad auth
        with requests_mock() as mock:
            mock.get(ANY, status_code=401,
                     text='{"message": "Authentication failed"}')

            with self.assertRaises(Exception) as ctx:
                zone = Zone('unit.tests.', [])
                provider.populate(zone)
            self.assertEquals('Unauthorized', text_type(ctx.exception))

        # General error
        with requests_mock() as mock:
            mock.get(ANY, status_code=502, text='Things caught fire')

            with self.assertRaises(HTTPError) as ctx:
                zone = Zone('unit.tests.', [])
                provider.populate(zone)
            self.assertEquals(502, ctx.exception.response.status_code)

        # Non-existent zone doesn't populate anything
        with requests_mock() as mock:
            mock.get(ANY, status_code=404,
                     text='{"message": "Domain `foo.bar` not found"}')

            zone = Zone('unit.tests.', [])
            provider.populate(zone)
            self.assertEquals(set(), zone.records)

        # No diffs == no changes
        with requests_mock() as mock:
            base = 'https://api.dnsimple.com/v2/42/zones/unit.tests/' \
                'records?page='
            with open('tests/fixtures/dnsimple-page-1.json') as fh:
                mock.get('{}{}'.format(base, 1), text=fh.read())
            with open('tests/fixtures/dnsimple-page-2.json') as fh:
                mock.get('{}{}'.format(base, 2), text=fh.read())

            zone = Zone('unit.tests.', [])
            provider.populate(zone)
            self.assertEquals(16, len(zone.records))
            changes = self.expected.changes(zone, provider)
            self.assertEquals(1, len(changes))

        # 2nd populate makes no network calls/all from cache
        again = Zone('unit.tests.', [])
        provider.populate(again)
        self.assertEquals(16, len(again.records))

        # bust the cache
        del provider._zone_records[zone.name]

        # test handling of invalid content
        with requests_mock() as mock:
            with open('tests/fixtures/dnsimple-invalid-content.json') as fh:
                mock.get(ANY, text=fh.read())

            zone = Zone('unit.tests.', [])
            provider.populate(zone, lenient=True)
            self.assertEquals(set([
                Record.new(zone, '', {
                    'ttl': 3600,
                    'type': 'SSHFP',
                    'values': []
                }, lenient=True),
                Record.new(zone, '_srv._tcp', {
                    'ttl': 600,
                    'type': 'SRV',
                    'values': []
                }, lenient=True),
                Record.new(zone, 'naptr', {
                    'ttl': 600,
                    'type': 'NAPTR',
                    'values': []
                }, lenient=True),
            ]), zone.records)

    def test_apply(self):
        provider = DnsimpleProvider('test', 'token', 42)

        resp = Mock()
        resp.json = Mock()
        provider._client._request = Mock(return_value=resp)

        # non-existent domain, create everything
        resp.json.side_effect = [
            DnsimpleClientNotFound,  # no zone in populate
            DnsimpleClientNotFound,  # no domain during apply
        ]
        plan = provider.plan(self.expected)

        # No root NS, no ignored, no excluded
        n = len(self.expected.records) - 3
        self.assertEquals(n, len(plan.changes))
        self.assertEquals(n, provider.apply(plan))
        self.assertFalse(plan.exists)

        provider._client._request.assert_has_calls([
            # created the domain
            call('POST', '/domains', data={'name': 'unit.tests'}),
            # created at least some of the record with expected data
            call('POST', '/zones/unit.tests/records', data={
                'content': '1.2.3.4',
                'type': 'A',
                'name': '',
                'ttl': 300}),
            call('POST', '/zones/unit.tests/records', data={
                'content': '1.2.3.5',
                'type': 'A',
                'name': '',
                'ttl': 300}),
            call('POST', '/zones/unit.tests/records', data={
                'content': '0 issue "ca.unit.tests"',
                'type': 'CAA',
                'name': '',
                'ttl': 3600}),
            call('POST', '/zones/unit.tests/records', data={
                'content': '1 1 7491973e5f8b39d5327cd4e08bc81b05f7710b49',
                'type': 'SSHFP',
                'name': '',
                'ttl': 3600}),
            call('POST', '/zones/unit.tests/records', data={
                'content': '1 1 bf6b6825d2977c511a475bbefb88aad54a92ac73',
                'type': 'SSHFP',
                'name': '',
                'ttl': 3600}),
            call('POST', '/zones/unit.tests/records', data={
                'content': '20 30 foo-1.unit.tests.',
                'priority': 10,
                'type': 'SRV',
                'name': '_srv._tcp',
                'ttl': 600
            }),
        ])
        # expected number of total calls
        self.assertEquals(28, provider._client._request.call_count)

        provider._client._request.reset_mock()

        # delete 1 and update 1
        provider._client.records = Mock(return_value=[
            {
                'id': 11189897,
                'name': 'www',
                'content': '1.2.3.4',
                'ttl': 300,
                'type': 'A',
            },
            {
                'id': 11189898,
                'name': 'www',
                'content': '2.2.3.4',
                'ttl': 300,
                'type': 'A',
            },
            {
                'id': 11189899,
                'name': 'ttl',
                'content': '3.2.3.4',
                'ttl': 600,
                'type': 'A',
            }
        ])
        # Domain exists, we don't care about return
        resp.json.side_effect = ['{}']

        wanted = Zone('unit.tests.', [])
        wanted.add_record(Record.new(wanted, 'ttl', {
            'ttl': 300,
            'type': 'A',
            'value': '3.2.3.4'
        }))

        plan = provider.plan(wanted)
        self.assertTrue(plan.exists)
        self.assertEquals(2, len(plan.changes))
        self.assertEquals(2, provider.apply(plan))
        # recreate for update, and deletes for the 2 parts of the other
        provider._client._request.assert_has_calls([
            call('POST', '/zones/unit.tests/records', data={
                'content': '3.2.3.4',
                'type': 'A',
                'name': 'ttl',
                'ttl': 300
            }),
            call('DELETE', '/zones/unit.tests/records/11189899'),
            call('DELETE', '/zones/unit.tests/records/11189897'),
            call('DELETE', '/zones/unit.tests/records/11189898')
        ], any_order=True)


'''27 - O departamento de Educação Física deseja informatizar este setor e
colocou à disposição os seguintes dados de 50 alunos:
Matrícula, sexo (M, F), altura (cm) e status físico (1–bom, 2–regular, 3–ruim). Estes dados deverão ser lidos através de uma unidade de entrada qualquer. Calcular e imprimir:
a) A quantidade de alunos do sexo feminino com altura superior a 170 cm.
b) A % de alunos do sexo masculino (em relação ao total de alunos do sexo
masculino) cujo status físico seja bom. '''

quantMulheres_altas = 0
quantAlunos_bom = 0
quantAlunos_masc_bom = 0

for i in range(50):
    matricula = int(input("Matrícula do aluno: "))
    sexo = input("Sexo do aluno (M/F): ")
    altura = float(input("Altura do aluno (em cm): "))
    status = int(input("Status físico do aluno (1-Bom, 2-Regular, 3-Ruim): "))

    if sexo == "F" and altura > 170:
        quantMulheres_altas += 1
    if status == 1:
        quantAlunos_bom+= 1
        if sexo == "M":
            quantAlunos_masc_bom += 1

porcentagem = (quantAlunos_masc_bom / (50 - quantMulheres_altas)) * 100

print(f"Quantidade de mulheres com altura superior a 170 cm: {quantMulheres_altas}")
print(f"Porcentagem de alunos do sexo masculino com status físico bom: {porcentagem:.2f}%")


#!/usr/bin/python3
"""
Runs accurate simulate taps on a given file with failrates from a matching context file. Expects failure
rate file to have format:

RANK failrate

Results are dumped to stdout

RANK RANK_MOST_FAILED PHRASE {Suggestion Count} True/False

Given phrase {A B C} with most common suggestion being D in place of C
RANK: rank of phrase in ngram data
RANK_MOST_FAILED: rank of phrase {A B D}
{}: suggestion list
True/False: is whether or not the reversed phrase passed the simulation. For example the
phrase {A B D} is typed with the expectation thatD will be changed to C

arg1 - failure rate file
arg2 - context file associated with failure rate
arg3 - language-country
arg4 - failure threshold
arg5 - number of cycles to run
"""

import sys, codecs, os, operator
import subprocess

user = os.getenv("USER")
exec = "/Users/" + user + "/Library/Developer/Xcode/DerivedData/FleksySDK-ddtdrokihvkvteeirffxtjnqxvhs/Build/Products/Release/SimAccurateTaps"

def readContext(filename):
    contextFile = codecs.open(filename, 'r', 'utf-8')
    phraseList  = []
    phraseFreqMap = {}
    rank = 0
    for phrases in contextFile:
        words = phrases.lower().split(' ')
        words.pop(len(words)-1)
        phraseList.append(words)

        if (len(words) > 1):
            subphrase = " ".join(words[0:len(words)-1])
            targ = words[len(words)-1]
            if (subphrase in phraseFreqMap):
                phraseFreqMap[subphrase][targ] = rank
            else:
                temp = {}
                temp[targ] = rank
                phraseFreqMap[subphrase] = temp

        rank += 1

    return phraseList, phraseFreqMap

def parseFailFileLine(line):
    line = line.strip('\n ')
    words = line.split(' ')
    failrate = 0
    index = -1
    if (len(words) == 2):
        try:
            failrate = float(words[1])
            index = int(words[0])
        except ValueError:
            print("error:", line)

    return failrate, index

def launchProc(jetLoc, cycles, phrase):
    p1 = subprocess.Popen([exec, jetLoc, str(cycles)] + phrase, stdout = subprocess.PIPE)
    p2 = subprocess.Popen(["tail", "-n 2"], stdin = p1.stdout, stdout = subprocess.PIPE)
    p1.stdout.close()
    return p2.communicate()[0].decode(encoding='utf-8').strip().split('\n')

def failedWordFreq(line):
    failedFreq = {}
    # alternates between word and count
    words = line.split(' ')
    for i in range(0, len(words)-1, 2):
        failedFreq[words[i]] = int(words[i+1])

    return failedFreq

def checkForFalseNegFailure(output, threshold):
    maxFailed = ""
    failed = len(output) == 2 and float(output[1]) >= threshold
    if (failed):
        failedFreq = failedWordFreq(output[0])
        maxFailed = max(failedFreq.items(), key=operator.itemgetter(1))[0]

    return maxFailed, failed

def checkIfReversedSucceeded(output, threshold):
    success = True
    if (len(output) == 2 and float(output[1]) < threshold):
        failedFreq = failedWordFreq(output[0])
        if (targ in failedFreq):
            cnt = float(failedFreq[targ])
            success = cnt/float(cycles) > threshold

    return success

if (len(sys.argv) < 6):
    exit()

phraseList, phraseFreqMap = readContext(sys.argv[2])
failFile = codecs.open(sys.argv[1], 'r', 'utf-8')
lang = sys.argv[3]
threshold = float(sys.argv[4])
cycles = int(sys.argv[5])
jetLoc = "../Android/FleksySDKResources/encrypted/resourceArchive-" + lang + ".jet"

fnegOrig = 0
fnegCur = 0
fnegExtraBad = 0
reversed = 0
for line in failFile:
    failrate, index = parseFailFileLine(line)
    if (failrate >= threshold and index >= 0):
        maxFailed = ""
        fnegOrig += 1
        try:
            phrase = phraseList[index]
            output = launchProc(jetLoc, cycles, phrase)
            maxFailed, failed = checkForFalseNegFailure(output, threshold)

            if (failed):
                fnegCur += 1
                targ = phrase.pop(len(phrase)-1)
                phrase.append(maxFailed)
                outputRev = launchProc(jetLoc, cycles, phrase)
                successRev = checkIfReversedSucceeded(outputRev, threshold)
                if (successRev):
                    reversed += 1

                    phrase[len(phrase)-1] = targ
                    freqDict = phraseFreqMap[" ".join(phrase[0:len(phrase)-1])]
                    suggRank = "NA"
                    if (maxFailed in freqDict):
                        suggRank = freqDict[maxFailed]
                        if (suggRank > index):
                            fnegExtraBad += 1

                print(index, suggRank, "_".join(phrase), output[0], successRev)
        except:
            fnegOrig -= 1

print("False negative:", fnegOrig, float(fnegOrig-fnegCur)/float(fnegOrig), float(fnegExtraBad)/float(fnegOrig))

revRate = 1.
if (fnegCur > 0):
    revRate = float(reversed)/float(fnegCur)
print("Reversed:", reversed, revRate);


import random
import os

class UserClass:
    def __init__(self, name = "John Doe" , score = 0):
        self.name = name
        self.score = score

    def userWin(self):
        self.score = self.score +1

def playNext():
    print("Do you want to continue the game.")
    playOption = input("Press x to quit: ")

    return playOption

def userName(nr):
    valid = False

    while(valid == False):
        userN = input("Player " + nr + " enter your name : ")

        if(userN != ''):
            valid = True
        else:
            print("You must enter a name.")

    return userN

def generateRand():
    return random.sample(range(0,3),3)

def asignItem():
    stringIt = ["rock", "papper", "scissors"]
    listIt = [' ', ' ', ' ']
    indexIt = generateRand()
    j = 0

    for i in indexIt:
        listIt[i] = stringIt[j]
        j +=1

    return listIt

def playerInput(name1, name2):

    getOut = False

    while(getOut == False):
        try:
            player1 = int(input(name1 + " : Select a number from 1 to 3: "))
            player2 = int(input(name2 + " : Select a number from 1 to 3: "))

            if((player1 <= 3 and player1 >= 1) and (player2 <= 3 and player2 >= 1)):
                getOut = True
            else:
                print("The selected number must be : 1, 2 or 3!")

        except:
            print("Error: Enter a number!")

    return player1 ,  player2

def theWinner(player1Name, player2Name, player1Opt, player2Opt):
    if(player1Opt == "rock" and player2Opt == "papper") or (player2Opt == "rock" and player1Opt == "papper"):
        if player1Opt == "papper":
            print("Papper beats Rock. " + player1Name + " Wins!")
            return player1Name
        else:
            print("Papper beats Rock. " + player2Name + " Wins!")
            return player2Name

    elif(player1Opt == "rock" and player2Opt == "scissors") or (player2Opt == "rock" and player1Opt == "scissors"):
        if player1Opt == "rock":
            print("Rock beats Scissors. " + player1Name + " Wins!")
            return player1Name
        else:
            print("Rock beats Scissors. " + player2Name + " Wins!")
            return player2Name

    elif(player1Opt == "papper" and player2Opt == "scissors") or (player2Opt == "papper" and player1Opt == "scissors"):
        if player1Opt == "scissors":
            print("Scissors beats Papper. " + player1Name + " Wins!")
            return player1Name
        else:
            print("Scissors beats Papper. " + player2Name + " Wins!")
            return player2Name

    elif(player1Opt == player2Opt):
        print("Draw, both Players have " + player1Opt)

        return 0

def toSaveGame(saveFile, saveNr, player1Name, player1Score, player2Name, player2Score):
    openSaveGameFile = open(saveFile, "a")
    saveGameName = input("Insert a title for the saved game:  ")

    openSaveGameFile.write(str(saveNr) + " ### " + saveGameName)
    openSaveGameFile.write(" " + player1Init.name + " has: " + str(player1Init.score) + " points")
    openSaveGameFile.write(" " + player2Init.name + " has: " + str(player2Init.score) + " points" + "\n")
    openSaveGameFile.write("")

    openSaveGameFile.close()

if __name__ == "__main__":

    saveGameNr = 1

    saveGameFile = 'C:/Users/Florentin/Documents/Python/MyPyWorld/RPS game/SavedGames.txt'

    if(os.stat(saveGameFile).st_size == 0):

        gamestatus = True

        player1 = userName('1')
        player2 = userName('2')

        player1Init = UserClass(player1)
        player2Init = UserClass(player2)

        while(gamestatus):

            opt1,opt2 = playerInput(player1Init.name, player2Init.name)

            opt1 = asignItem()[(opt1) - 1]
            print(player1Init.name + " has : " + opt1)

            opt2 = asignItem()[(opt2) - 1]
            print(player2Init.name + " has : " + opt2)

            winner = theWinner(player1Init.name, player2Init.name, opt1, opt2)

            if(winner == player1Init.name):
                player1Init.userWin()
            elif(winner == player2Init.name):
                player2Init.userWin()

            print("The score is: ")
            print(player1Init.name + " has: " + str(player1Init.score) + " points")
            print(player2Init.name + " has: " + str(player2Init.score) + " points")

            if('x' == playNext().lower()):
                print("Game Over!")
                saveGame = input("Do you want to save the game? Press 'y' if you want to save the game: ")

                if(saveGame.lower() == 'y'):

                    toSaveGame(saveGameFile, saveGameNr, player1Init.name, player1Init.score, player2Init.name, player2Init.score )

                gamestatus = False

    else:
        gamestatus = True

        openSaveGameFile = open(saveGameFile, "r")
        fileReadLine = openSaveGameFile.readlines()
        countLines = 0
        openSaveGameFile.close()

        for i in fileReadLine:
            print(i)
            countLines +=1

        ifOptOk = True

        while(ifOptOk):
            userOptSaveGame = (input("Enter the number of the Saved game: "))
            userOptSaveGame = int(userOptSaveGame) - 1
            if(userOptSaveGame > countLines):
                print("Select a valid number!")

            else:
                userOptLine = fileReadLine[userOptSaveGame].split()
                ifOptOk = False

        player1Init = UserClass(userOptLine[3], int(userOptLine[5]))
        player2Init = UserClass(userOptLine[7], int(userOptLine[9]))

        print("The score is: ")
        print(player1Init.name + " has: " + str(player1Init.score) + " points")
        print(player2Init.name + " has: " + str(player2Init.score) + " points")

        while(gamestatus):

            opt1,opt2 = playerInput(player1Init.name, player2Init.name)

            opt1 = asignItem()[(opt1) - 1]
            print(player1Init.name + " has : " + opt1)

            opt2 = asignItem()[(opt2) - 1]
            print(player2Init.name + " has : " + opt2)

            winner = theWinner(player1Init.name, player2Init.name, opt1, opt2)

            if(winner == player1Init.name):
                player1Init.userWin()
            elif(winner == player2Init.name):
                player2Init.userWin()

            print("The score is: ")
            print(player1Init.name + " has: " + str(player1Init.score) + " points")
            print(player2Init.name + " has: " + str(player2Init.score) + " points")

            if('x' == playNext().lower()):
                print("Game Over!")
                saveGame = input("Do you want to save the game? Press 'y' if you want to save the game: ")

                if(saveGame.lower() == 'y'):
                    countLines = countLines + 1
                    toSaveGame(saveGameFile, countLines, player1Init.name, player1Init.score, player2Init.name, player2Init.score  )

                gamestatus = False

        openSaveGameFile.close()


import numpy as np
import matplotlib.pyplot as plt

file_name = "explore_rewards_1to60_0.1x0.1.npy"
explore_freqs = list(range(1, 60)) + [100000000]

explore_rewards = np.load(file_name)
print(explore_rewards.shape)

means = explore_rewards.mean(axis=1)
stds = explore_rewards.std(axis=1)

print(means[-1])

plt.plot(explore_freqs[:-1], means[:-1])
plt.axhline(y=means[-1], color='r', linestyle='-', label="No exploration")
plt.title("Mean reward vs exploration frequency p=(0.9,0.1)")
plt.xlabel("Exploration frequency")
plt.ylabel("Mean reward (10k steps)")
plt.legend()


import instaloader,statistics

L = instaloader.Instaloader()
profiles=[]
profil=input("Pes mou to username tou instagram pou thes: ")
print(profil,type(profil))
profile = instaloader.Profile.from_username(L.context, profil)
print(profile.get_posts())
count=0
for post in profile.get_posts():
    if(count==100):
        break
    post_comments = post.get_comments()

    for comment in post_comments:
        profiles.append(comment.owner.username)
    count+=1
profiles.sort() #tin ekana sort gia na me diefkolini na kano elenxo an to apotelesma einai sosto sto telos
print(profiles) #kai afto to afino edo gia na deite oti einai sosto to apotelesma, an den to xreiazeste sbiste to
maxcommentprofile=statistics.mode(profiles)
print("O xrhsths tou instagram me onoma: ",maxcommentprofile,"exei kanei ta perisotera sxolia sto profil tou/ths: ",profil)


# -*- coding: utf-8 -*-
"""
    pymemcache.interactors
    ~~~~~~~~~~~~~~~~~~~~~~
    Interfaces for ingesting requests and returning responses.

"""
import logging

from pymemcache import request
from pymemcache import response

LOGGER = logging.getLogger(__name__)

def execute_request(raw_data, the_cache):
    """Parse and execute the given request, returning a response.

    :param raw_data: The raw request data
    :type raw_data: str or unicode
    :param the_cache: The in-memory cache for this process
    :type the_cache: mixed
    """
    command, body = request.parse_command(raw_data)
    LOGGER.debug('--> Command %r', command)

    if command.startswith('get'):
        key = command.split(' ')[1]
        result = the_cache.get(key)
        if not result:
            return response.NotFoundResponse()
        return response.GetResponse({key: result})

    if command.startswith('set'):
        key = command.split(' ')[1]
        the_cache.set(key, body[0])
        return response.StoredResponse()


import qm
import qm.extension

########################################################################
# Classes
########################################################################

class Suite(qm.extension.Extension):
    """A collection of tests.

     A test suite is a collection of tests.  The suite may contain other
    suites by reference as well; all tests contained in these contained
    suites are considered contained in the containing suite as well."""

    arguments = [
       ]

    kind = "suite"

    EXTRA_ID = "qmtest_id"
    """The name of the extra keyword argument to '__init__' that
    specifies the name of the test or resource."""

    EXTRA_DATABASE = "qmtest_database"
    """The name of the extra keyword argument to '__init__' that
    specifies the database containing the test or resource."""

    def __init__(self, arguments = None, **args):
        """Construct a new 'Runnable'.

        'arguments' -- As for 'Extension.__init__'.

        'args' -- As for 'Extension.__init__'."""

        self.__id = args.pop(self.EXTRA_ID)
        self.__database = args.pop(self.EXTRA_DATABASE)
        if arguments: args.update(arguments)
        super(Suite, self).__init__(**args)

    def GetDatabase(self):
        """Return the 'Database' that contains this suite.

        returns -- The 'Database' that contains this suite."""

        return self.__database

    def GetId(self):
        """Return the ID of this test suite."""

        return self.__id

    def GetTestIds(self):
        """Return the tests contained in this suite.

        returns -- A sequence of labels corresponding to the tests
        contained in this suite.  Tests that are contained in this suite
        only because they are contained in a suite which is itself
        contained in this suite are not returned."""

        return []

    def GetSuiteIds(self):
        """Return the suites contained in this suite.

        returns -- A sequence of labels corresponding to the suites
        contained in this suite.  Suites that are contained in this suite
        only because they are contained in a suite which is itself
        contained in this suite are not returned."""

        return []

    def IsImplicit(self):
        """Return true if this is an implicit test suite.

        Implicit test suites cannot be edited."""

        raise NotImplementedError

    def GetAllTestAndSuiteIds(self):
        """Return the tests/suites contained in this suite and its subsuites.

        returns -- A pair '(test_ids, suite_ids)'.  The 'test_ids' and
        'suite_ids' elements are both sequences of labels.  The values
        returned include all tests and suites that are contained in this
        suite and its subsuites, recursively."""

        suite = self

        test_ids = []
        suite_ids = []

        # Maintain a work list of suites to process.
        work_list = [suite]
        # Process until the work list is empty.
        while len(work_list) > 0:
            suite = work_list.pop(0)
            # Accumulate test and resource IDs in the suite.
            test_ids.extend(suite.GetTestIds())
            # Find sub suites in the suite.
            sub_suite_ids = suite.GetSuiteIds()
            # Accumulate them.
            suite_ids.extend(sub_suite_ids)
            # Retrieve the 'Suite' objects.
            sub_suites = map(self.GetDatabase().GetSuite, sub_suite_ids)
            # Don't expand ordinary suites contained in implicit suites.
            if suite.IsImplicit():
                sub_suites = filter(lambda s: s.IsImplicit(), sub_suites)
            # Add contained suites to the work list.
            work_list.extend(sub_suites)

        return test_ids, suite_ids


#coding=utf-8
import torch
import torch.nn as nn
from torchvision.models import vgg16,resnet18
import os
from torch.autograd import Variable
import numpy as np
from torch.nn.parameter import Parameter

class TripletLossModel(nn.Module):
    def __init__(self,embedding_size,num_classes,checkpoint):
        super(TripletLossModel, self).__init__()
        self.featuresvgg16 = vgg16(pretrained=False).features
        self.featuresLayer = nn.Sequential(
            nn.Linear(512 * 3 * 3, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, embedding_size),
        )
        self.classifier = nn.Sequential(
            nn.Linear(embedding_size, num_classes),
        )
        self.embedding_size = embedding_size

        if checkpoint is not None:
            # Check if there are the same number of classes
            if list(checkpoint['state_dict'].values())[-1].size(0) == num_classes:
                self.load_state_dict(checkpoint['state_dict'])
            else:
                own_state = self.state_dict()
                for name, param in checkpoint['state_dict'].items():
                    if "classifier" not in name:
                        if isinstance(param, Parameter):
                            param = param.data
                        own_state[name].copy_(param)

    def l2_norm(self,input):
        input_size = input.size()
        buffer = torch.pow(input, 2)
        normp = torch.sum(buffer, 1).add_(1e-10)
        norm = torch.sqrt(normp)
        _output = torch.div(input, norm.view(-1, 1).expand_as(input))
        output = _output.view(input_size)
        return output

    def forward_GetFeature(self, x):
        x = self.featuresvgg16(x)
        x = x.view(x.size(0), -1)
        x = self.featuresLayer(x) #512
        x=self.l2_norm(x)
        # Multiply by alpha = 10 as suggested in https://arxiv.org/pdf/1703.09507.pdf
        alpha = 10
        return x*alpha

    def forward(self,data):
        # the loss is special so couldn't put loss in there.
        return self.forward_GetFeature(data);

    def forward_classifier(self, x):
        features= self.forward_GetFeature(x)
        res = self.model.classifier(features)
        return res

##======================================================================================================================

class CenterLossModel(nn.Module):
    def __init__(self,embedding_size,num_classes,checkpoint):
        super(CenterLossModel, self).__init__()
        self.featuresvgg16 = vgg16(pretrained=False).features
        self.featuresLayer=nn.Sequential(
                nn.Linear(512*3*3, 4096),
                nn.ReLU(True),
                nn.Dropout(),
                nn.Linear(4096, embedding_size),
        )
        self.classifier=nn.Sequential(
                nn.Linear(embedding_size, num_classes),
        )
        self.centers = torch.zeros(num_classes, embedding_size).type(torch.FloatTensor)
        self.num_classes = num_classes

        if checkpoint is not None:
            # Check if there are the same number of classes
            if list(checkpoint['state_dict'].values())[-1].size(0) == num_classes:
                self.load_state_dict(checkpoint['state_dict'])
                assert checkpoint['centers'].shape[0]==num_classes;
                assert checkpoint['centers'].shape[1] == embedding_size;
                self.centers = checkpoint['centers']
            else:
                own_state = self.state_dict()
                for name, param in checkpoint['state_dict'].items():
                    if "classifier" not in name:
                        if isinstance(param, Parameter):
                            # backwards compatibility for serialized parameters
                            param = param.data
                        own_state[name].copy_(param)

    def get_center_loss(self,features,target,args):
        batch_size = target.size(0)
        features_dim = features.size(1)
        target_expand = target.view(batch_size,1).expand(batch_size,features_dim)
        if args.cuda:
            self.centers=self.centers.cuda()
        centers_var = Variable(self.centers)
        centers_batch = centers_var.gather(0,target_expand)
        criterion = nn.MSELoss()
        center_loss = criterion(features,  centers_batch)

        # next is update center with manual operation .it will be much easier if you put it in optimizer.the code like this:
        '''
        optimizer = optim.SGD([
                                {'params': model.parameters(),'lr':args.lr},
                                {'params': model.centers ,'lr':args.alpha}   # different learning rate
                              ],  momentum = conf.momentum)
        '''
        #numpy's computation must on cpu . if we can replace it by torch .the speed can improve
        diff = centers_batch - features
        unique_label, unique_reverse, unique_count = np.unique(target.cpu().data.numpy(), return_inverse=True, return_counts=True)
        appear_times = torch.from_numpy(unique_count).gather(0,torch.from_numpy(unique_reverse))
        appear_times_expand = appear_times.view(-1,1).expand(batch_size,features_dim).type(torch.FloatTensor)
        diff_cpu = diff.cpu().data / appear_times_expand.add(1e-6)  # 防止除数为0 加一个很小的数
        #∆c_j =(sum_i=1^m δ(yi = j)(c_j − x_i)) / (1 + sum_i=1^m δ(yi = j))
        diff_cpu = args.alpha * diff_cpu
        if args.cuda:
            diff_cpu.cuda()
        assert self.centers.shape[0] == args.num_classes;
        assert self.centers.shape[1] == args.embedding_size;
        for i in range(batch_size):
            #Update the parameters c_j for each j by c^(t+1)_j = c^t_j − α · ∆c^t_j
            self.centers[target.data[i]] -= diff_cpu[i].type(self.centers.type())

        return center_loss

    def l2_norm(self,input):
        input_size = input.size()
        buffer = torch.pow(input, 2)
        normp = torch.sum(buffer, 1).add_(1e-10)
        norm = torch.sqrt(normp)
        _output = torch.div(input, norm.view(-1, 1).expand_as(input))
        output = _output.view(input_size)
        return output

    def forward_GetFeature(self, x):
        x = self.featuresvgg16(x)
        x = x.view(x.size(0), -1)
        x = self.featuresLayer(x)
        x=self.l2_norm(x)
        return x

    '''
    put loss in forward function because if we put it outsise, computate cost function will occupy lots of memory of main GPU which result in out of memory
    however,the other gpus only occupy little memory. so we transfer this task(loss) from main GPU to each gpu, and we only need return loss result to main GPU
    this is a strategy of load balancing
    '''
    def forward(self,x,target_var,args):
        feature512=self.forward_GetFeature(x)
        if target_var is None:
            return feature512;
        classifyResult = self.classifier(feature512)
        center_loss = self.get_center_loss(feature512, target_var,args)
        criterion = nn.CrossEntropyLoss()
        cross_entropy_loss = criterion(classifyResult, target_var)
        #CrossEntropyLoss  contains softmax
        loss = args.center_loss_weight * center_loss + cross_entropy_loss
        prec = accuracy(classifyResult.data, target_var, topk=(1,))
        return prec[0],loss

def loadCheckpoint(args):
    '''
    the strategy to load chechpoint is choose the max index of all checkpoints in lod_dir
    '''
    checkpoint=None;
    checkpointList = os.listdir(args.log_dir)
    if (len(checkpointList) > 0):
        newest = "";
        numMax = 0;
        for fileName in checkpointList:
            if os.path.isdir(os.path.join(args.log_dir, fileName)):
                continue
            houzhui=fileName.split('pth');
            if  len(houzhui)==2:
                num = int(fileName.split('Acc')[-1].split(".")[0])
                if (num >= numMax):
                    newest = fileName;
                    numMax = num;
        checkpointPath = os.path.join(args.log_dir, newest)
        if not os.path.isdir(checkpointPath):
            print('=> loading checkpoint {}'.format(checkpointPath))
            checkpoint = torch.load(checkpointPath)
            args.start_epoch = checkpoint['epoch']
        else:
            print('=> no checkpoint found at {}'.format(args.log_dir))
    else:
        print('=> no checkpoint found at {}'.format(args.log_dir))
    return checkpoint;

def accuracy(output, target, topk=(1,)):
    """Computes the precision@k for the specified values of k"""
    batch_size = target.size(0)
    _,pred = output.topk(k=1,dim=1,largest=True, sorted=True)  #
    pred = pred.t()
    correct = pred.eq(target.view(1, -1).expand_as(pred.long()))
    res = []
    for k in topk:
        correct_k = correct[:k].view(-1).float().sum(0)
        res.append(correct_k.mul_(100.0 / batch_size))
    return res


# -*- coding:utf-8 -*-

from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

import os
from utils import parse_musescore
from pitchDetection.mfshs import MFSHS
from utils import parse_musescore, get_wav_and_json_file, save_files, draw_array
from utils import post_cnn_onset
from alignment import sw_alignment
from onset_predict import predictor_onset
from post_process import Evaluator, trans_onset_and_offset

import numpy as np

def get_files():
    test_dir = './data/test1'
    wav_files = [os.path.join(test_dir, x) for x in os.listdir(
        test_dir) if x.endswith('wav') or x.endswith('mp3')]

    txt_files = [os.path.join(x[0:-3] + 'txt') for x in wav_files]
    return wav_files, txt_files

def get_gound_score_notes(txt_files):
    ground_notes, score_notes = dict(), dict()
    for file in txt_files:
        ground_note, score_note = [], []
        with open(file, 'r') as fr:
            fr.readline()
            lines = fr.readlines()
            for line in lines:
                line = line.strip().split('\t')
                ground_note.append(float(line[0]))
                score_note.append(float(line[1]))

        file_id = os.path.basename(file)[0:-4]
        ground_notes[file_id] = ground_note
        score_notes[file_id] = score_note

    return ground_notes, score_notes

def is_octive(det_note, score_note):
    det_note = np.array(det_note)
    score_note = np.array(score_note)
    diff_note = det_note - score_note
    octive1 = np.where((diff_note > 10) & (diff_note < 14))[0]
    octive2 = np.where((diff_note > -14) & (diff_note < -10))[0]
    is_octive1 = (len(octive1) / len(diff_note)) > 0.8
    is_octive2 = (len(octive2) / len(diff_note)) > 0.8

    if is_octive1:
        det_note = det_note - 12
    elif is_octive2:
        det_note = det_note + 12
    return det_note

def cal_acc(det_note, score_note):
    det_note = np.array(det_note)
    det_note = is_octive(det_note, score_note)
    score_note = np.array(score_note)
    diff_note = abs(det_note - score_note)
    acc_index = np.where(diff_note <= 0.5)[0]
    accuracy = len(acc_index) / len(diff_note)
    return accuracy, diff_note

def print_save_acc(wav_files, ground_notes, score_notes):
    fwt = open('log/acc.txt', 'w')
    for index in range(len(wav_files)):
        json_path = '/home/data/lj/onset_detect/MUS/evaluate/'
        wav_file = wav_files[index]
        fid = os.path.basename(wav_file)[0:-4]
        # score_note = np.array(score_notes[fid]).astype(int)
        json_path = os.path.join(json_path, fid)
        score_file = [os.path.join(json_path, x) for x in os.listdir(
            json_path) if x.endswith('json')][0]

        mfshs = MFSHS(wav_file)
        mfshs.pitch_detector()
        pitches = mfshs.pitches
        zero_amp_frame = mfshs.zeroAmploc

        score_note, note_types, pauseLoc = parse_musescore(
            score_file)  # parse musescore
        predictor = predictor_onset()
        onset_time = predictor.predict(wav_file)

        onset_frame = predictor.onset_frame

        onset_frame = post_cnn_onset(pitches, onset_frame)

        match_loc_info = sw_alignment(pitches,
                                      onset_frame,
                                      score_note)

        onset_offset_pitches = trans_onset_and_offset(match_loc_info,
                                                      onset_frame,
                                                      pitches)
        filename_json = os.path.splitext(wav_file)[0] + ".json"
        evaluator = Evaluator(filename_json,
                              onset_offset_pitches,
                              zero_amp_frame,
                              score_note,
                              pauseLoc,
                              note_types)

        print(wav_file)
        sys_acc, sys_diff_note = cal_acc(evaluator.det_note, score_note)

        gnote = ground_notes[fid]
        snote = score_note
        ground_acc, ground_diff_note = cal_acc(gnote, snote)

        ground_sys_acc, ground_sys_diff_note = cal_acc(
            evaluator.det_note, gnote)

        strs = '{}\t{}\t{}'.format('ground', 'sys', 'ground_sys')
        print(strs)
        strs = '{:.3f}\t{:.3f}\t{:.3f}\n'.format(
            ground_acc, sys_acc, ground_sys_acc)
        print(strs)

        file_name = os.path.join('log', fid + '.txt')
        with open(file_name, 'w') as fw:
            fw.write('gnote\t\tsnote\t\tdnote\n')
            for index in xrange(len(gnote)):
                fw.write('{:.3f}\t\t{:.3f}\t\t{:.3f}\t\t'.format(
                    gnote[index], snote[index], evaluator.det_note[index]))

                fw.write('{:.3f}\t\t{:.3f}\t\t{:.3f}\n'.format(ground_diff_note[
                         index], sys_diff_note[index], ground_sys_diff_note[index]))

            fw.write('{:.3f}\t\t{:.3f}\t\t{:.3f}\n'.format(
                ground_acc, sys_acc, ground_sys_acc))

        fwt.write(wav_file + '\n')
        fwt.write(strs)
        fwt.write('\n')
        fwt.flush()
    fwt.close()

if __name__ == '__main__':
    wav_files, txt_files = get_files()
    ground_notes, score_notes = get_gound_score_notes(txt_files)
    print_save_acc(wav_files, ground_notes, score_notes)


import streamlit as st
import PyPDF2
import os

st.title("AI Model")
st.markdown("---")

# Function to split text into chunks
def split_text_into_chunks(text, chunk_size, chunk_overlap):
    chunks = []
    text_length = len(text)
    start = 0

    while start < text_length:
        end = min(start + chunk_size, text_length)
        chunk = text[start:end]
        chunks.append(chunk)
        start = end - chunk_overlap

    return chunks

# Function to process PDFs
def process_pdf(pdf_files, chunk_size=500, chunk_overlap=100):
    total_chunks = 0

    for pdf_file in pdf_files:
        pdf_reader = PyPDF2.PdfReader(pdf_file)
        total_pages = len(pdf_reader.pages)
        st.write(f"Total Pages: {total_pages}")

        for page_num, page in enumerate(pdf_reader.pages, 1):
            page_text = page.extract_text()

            # Split the page text into chunks
            document_chunks = split_text_into_chunks(page_text, chunk_size, chunk_overlap)
            total_chunks += len(document_chunks)

            for chunk_num, chunk in enumerate(document_chunks, 1):
                st.subheader(f"Page {page_num}, Chunk {chunk_num}")
                st.write(chunk)

    st.write(f"Total Chunks: {total_chunks}")

# Upload PDF files
pdf_docs = st.file_uploader("Upload your PDF Files", accept_multiple_files=True)

if st.button("Process"):
    if pdf_docs:
        with st.spinner("Processing"):
            process_pdf(pdf_docs)


import logging
import os
import warnings
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import List, Tuple, Union, Dict, Optional, Callable, Any

import numpy as np
import tensorflow as tf
from tqdm import tqdm

from nebullvm.api.utils import (
    ifnone,
    inspect_dynamic_size,
    QUANTIZATION_METRIC_MAP,
)
from nebullvm.base import (
    DeepLearningFramework,
    ModelParams,
    InputInfo,
    ModelCompiler,
    QuantizationType,
)
from nebullvm.converters import ONNXConverter
from nebullvm.inference_learners import TensorflowBaseInferenceLearner
from nebullvm.measure import compute_optimized_running_time
from nebullvm.optimizers import BaseOptimizer
from nebullvm.optimizers.tensorflow import TensorflowBackendOptimizer
from nebullvm.transformations.base import MultiStageTransformation
from nebullvm.utils.data import DataManager
from nebullvm.utils.feedback_collector import FEEDBACK_COLLECTOR
from nebullvm.utils.tf import (
    get_outputs_sizes_tf,
    create_model_inputs_tf,
    run_tf_model,
)
from nebullvm.optimizers.multi_compiler import MultiCompilerOptimizer

logging.basicConfig(
    format="%(asctime)s %(message)s", datefmt="%d/%m/%Y %I:%M:%S %p"
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

def _extract_dynamic_axis(
    tf_model: tf.Module,
    dataset: List[Tuple[Tuple[tf.Tensor, ...], Any]],
    input_sizes: List[Tuple[int, ...]],
    batch_size: int,
    max_data: int = 100,
) -> Optional[Dict]:
    dynamic_axis = {"inputs": [{}] * len(input_sizes), "outputs": []}
    output_sizes = []
    for i, (input_tensors, y) in enumerate(dataset):
        if i >= max_data:
            break
        inspect_dynamic_size(
            input_tensors, input_sizes, batch_size, dynamic_axis["inputs"]
        )
        outputs = tuple(run_tf_model(tf_model, input_tensors))
        if i == 0:
            dynamic_axis["outputs"] = [{}] * len(outputs)
            output_sizes = [tuple(output.shape[1:]) for output in outputs]
        inspect_dynamic_size(
            outputs, output_sizes, batch_size, dynamic_axis["outputs"]
        )
    if any(
        len(x) > 0 for x in (dynamic_axis["inputs"] + dynamic_axis["outputs"])
    ):
        return dynamic_axis
    return None

def extract_info_from_tf_data(
    tf_model: tf.Module,
    dataset: List[Tuple[Tuple[tf.Tensor, ...], Any]],
    batch_size: int,
    input_sizes: List[Tuple[int, ...]],
    input_types: List[str],
    dynamic_axis: Dict,
):
    input_row, _ = dataset[0]
    batch_size = ifnone(batch_size, int(input_row[0].shape[0]))
    input_sizes = ifnone(input_sizes, [tuple(x.shape[1:]) for x in input_row])
    input_types = ifnone(
        input_types, ["int" if x.dtype == int else "float" for x in input_row]
    )
    dynamic_axis = ifnone(
        dynamic_axis,
        _extract_dynamic_axis(tf_model, dataset, input_sizes, batch_size),
    )
    return batch_size, input_sizes, input_types, dynamic_axis

def optimize_tf_model(
    model: Union[tf.Module, tf.keras.Model],
    save_dir: str,
    dataset: List[Tuple[Tuple[tf.Tensor, ...], Any]] = None,
    batch_size: int = None,
    input_sizes: List[Tuple[int, ...]] = None,
    input_types: List[str] = None,
    extra_input_info: List[Dict] = None,
    dynamic_axis: Dict = None,
    perf_loss_ths: float = None,
    perf_metric: Union[str, Callable] = None,
    ignore_compilers: List[str] = None,
    custom_optimizers: List[BaseOptimizer] = None,
):
    """Basic function for optimizing a tensorflow model.

    This function saves the output model as well in a nebuly-readable format
    in order to avoid temporary-files corruptions which would prevent the model
    saving later in the process.

    Args:
        model (tf.Module or keras.Model): Model that needs optimization.
        save_dir (str): Path to the directory where saving the final model.
        dataset (List, optional):  Dataset containing data in the form of
            (xs, y) where xs are tuples of Tensors and ys can be whatever
            needed for computing the selected metric at quantization time.
            The data will be used for extracting all the data related
            information or completing the missing information in the case of
            partially given ones. If no data is given, both the `batch_size`
            and the `input_sizes` must be passed by the user.
        batch_size (int, optional): The model batch size.
        input_sizes (List[Tuple]], optional): List containing the size of all
            the input tensors of the model. Note that even just a single
            tensor is needed as model input, this field must be a list
            containing (in the exposed case) a single element). The tuple must
            contain all then input tensor dimensions excluding the batch size.
            This means that the final input tensor size will be considered as
            `(batch_size, *input_tensor_size)`, where `input_tensor_size` is
            one list element of `input_sizes`.
        input_types (List[str], optional): List of input types. If no value is
            given all the inputs will be considered as float type. The
            supported string values are "int" and "float".
        extra_input_info (List[Dict], optional): List of extra information
            needed for defining the input tensors, e.g. max_value and min_value
            the tensors can get.
        dynamic_axis (Dict, optional): Dictionary containing info about the
            dynamic axis. It should contain as keys both "inputs" and "outputs"
            and as values two lists of dictionaries where each dictionary
            represents the dynamic axis information for an input/output tensor.
            The inner dictionary should have as key an integer, i.e. the
            dynamic axis (considering also the batch size) and as value a
            string giving a "tag" to it, e.g. "batch_size".
        perf_loss_ths (float, optional): Tolerated relative error for
            performing approximation techniques before compiling the model.
            If no value is given, no optimization will be performed. Note that
            it will not be used for compilers using the torch API when
            `use_torch_api` is `True`. Just dynamic quantization will be
            performed, since no data is given as input.
        perf_metric (Union[Callable, str], optional): The metric to
            be used for accepting or refusing a precision-reduction
            optimization proposal. If none is given but a `metric_drop_ths` is
            received, the `nebullvm.measure.compute_relative_difference`
            metric will be used as default one. A user-defined metric can
            be passed as function accepting as inputs two tuples of tensors
            (produced by the baseline and the quantized model) and the related
            original labels.
            For more information see
            `nebullvm.measure.compute_relative_difference` and
            `nebullvm.measure.compute_accuracy_drop`. `metric`
            accepts as value also a string containing the metric name. At the
            current stage the supported metrics are `"numeric_precision"` and
            `"accuracy"`.
        ignore_compilers (List[str]): List of DL compilers we want to ignore
            while running the optimization. Compiler name should be one
            between "tvm", "tensor RT", "openvino" and "onnxruntime".
        custom_optimizers (List[BaseOptimizer], optional): List of optimizers
            which can be used for producing InferenceLearners, i.e. models
            optimized for inference. This list is useful when some compilers,
            not included in the base version of nebullvm or not used
            by default, which are specific for a particular tasks, need
            to be used.

    Returns:
        BaseInferenceLearner: Optimized model usable with the classical
            tensorflow interface. Note that as a torch model it takes as input
            and it gives as output `tf.Tensor` s.
    """
    warnings.warn(
        "Deprecated: The usage of the tensorflow api is deprecated. "
        "`optimize_tf_model`will be removed from the next release. "
        "Use `optimize_model` instead."
    )
    if dataset is not None:
        (
            batch_size,
            input_sizes,
            input_types,
            dynamic_axis,
        ) = extract_info_from_tf_data(
            model, dataset, batch_size, input_sizes, input_types, dynamic_axis
        )
        input_data = DataManager(dataset)
    else:
        input_data = None
    if isinstance(perf_metric, str):
        perf_metric = QUANTIZATION_METRIC_MAP.get(perf_metric)
    if input_types is None:
        input_types = ["float"] * len(input_sizes)
    if extra_input_info is None:
        extra_input_info = [{}] * len(input_sizes)
    if not len(input_sizes) == len(input_types) == len(extra_input_info):
        raise ValueError(
            f"Mismatch in the input list lengths. Given {len(input_sizes)} "
            f"sizes, {len(input_types)} input types and "
            f"{len(extra_input_info)} extra input infos."
        )
    input_infos = [
        InputInfo(size=input_size, dtype=input_type, **extra_info)
        for input_size, input_type, extra_info in zip(
            input_sizes, input_types, extra_input_info
        )
    ]
    dl_library = DeepLearningFramework.TENSORFLOW
    model_params = ModelParams(
        batch_size=batch_size,
        input_infos=input_infos,
        output_sizes=get_outputs_sizes_tf(
            model,
            input_tensors=create_model_inputs_tf(batch_size, input_infos),
        ),
        dynamic_info=dynamic_axis,
    )
    FEEDBACK_COLLECTOR.start_collection(model, framework=dl_library)
    ignore_compilers = (
        []
        if ignore_compilers is None
        else [ModelCompiler(compiler) for compiler in ignore_compilers]
    )
    input_tfms = MultiStageTransformation([])
    model_converter = ONNXConverter()
    model_optimizer = MultiCompilerOptimizer(
        ignore_compilers=ignore_compilers,
        extra_optimizers=custom_optimizers,
        debug_mode=int(os.environ.get("DEBUG_MODE", "0")) > 0,
        logger=logger,
    )
    with TemporaryDirectory() as tmp_dir:
        logger.info("Running Optimization using tensorflow interface (1/3)")
        if perf_loss_ths is not None:
            q_types = [
                None,
                QuantizationType.DYNAMIC,
                QuantizationType.HALF,
            ]
            if dataset is not None:
                q_types.append(QuantizationType.STATIC)
        else:
            q_types = [None]
        torch_res = [
            _torch_api_optimization(
                model,
                model_params,
                perf_loss_ths,
                q_type,
                input_tfms,
                False,
                input_data,
            )
            for q_type in tqdm(q_types)
        ]
        (tf_api_model, tf_api_latency, used_compilers,) = sorted(
            torch_res, key=lambda x: x[1]
        )[0]
        ignore_compilers.extend(used_compilers)
        logger.info("Running Optimization using ONNX interface (2/3)")
        onnx_path = model_converter.convert(
            model, model_params.input_sizes, Path(tmp_dir)
        )
        model_optimized = model_optimizer.optimize(
            model=str(onnx_path),
            output_library=dl_library,
            model_params=model_params,
            input_tfms=input_tfms,
            metric_drop_ths=perf_loss_ths,
            metric=perf_metric,
            input_data=input_data,
        )
        logger.info("Running comparison between optimized models (3/3).")
        model_optimized = _compare_optimized_models(
            model_optimized, tf_api_model, tf_api_latency
        )
        if model_optimized is None:
            raise RuntimeError(
                "No valid compiled model has been produced. "
                "Look at the logs for further information about the failure."
            )
        model_optimized.save(save_dir)
    FEEDBACK_COLLECTOR.send_feedback()
    return model_optimized.load(save_dir)

def _compare_optimized_models(
    new_model: TensorflowBaseInferenceLearner,
    previous_best_model: TensorflowBaseInferenceLearner,
    previous_latency: float,
) -> TensorflowBaseInferenceLearner:
    if new_model is not None:
        new_latency = compute_optimized_running_time(new_model)
        if new_latency < previous_latency:
            return new_model
    return previous_best_model

def _get_optimizers_supporting_tf_api(use_extra_compilers: bool):
    if use_extra_compilers:
        logger.warning(
            "No compiler found supporting the tensorflow interface."
        )
    return [(ModelCompiler.TFLITE, TensorflowBackendOptimizer(logger=logger))]

def _torch_api_optimization(
    model: tf.Module,
    model_params: ModelParams,
    quantization_ths: float,
    quantization_type: QuantizationType,
    input_tfms: MultiStageTransformation,
    use_extra_compilers: bool,
    input_data: DataManager,
) -> Tuple[Optional[TensorflowBaseInferenceLearner], float, List]:
    used_compilers = []
    best_tf_opt_model = None
    best_latency = np.inf
    for compiler, optimizer in tqdm(
        _get_optimizers_supporting_tf_api(use_extra_compilers)
    ):
        try:
            if hasattr(optimizer, "optimize_from_tf"):
                candidate_model = optimizer.optimize_from_tf(
                    torch_model=model,
                    model_params=model_params,
                    perf_loss_ths=quantization_ths
                    if quantization_type is not None
                    else None,
                    quantization_type=quantization_type,
                    input_tfms=input_tfms.copy(),
                    input_data=input_data,
                )
            else:
                candidate_model = optimizer.optimize(
                    model=model,
                    output_library=DeepLearningFramework.PYTORCH,
                    model_params=model_params,
                    metric_drop_ths=quantization_ths
                    if quantization_type is not None
                    else None,
                    quantization_type=quantization_type,
                    input_tfms=input_tfms.copy(),
                    input_data=input_data,
                )
            candidate_latency = compute_optimized_running_time(candidate_model)
            if candidate_latency < best_latency:
                best_latency = candidate_latency
                best_tf_opt_model = candidate_model
            FEEDBACK_COLLECTOR.store_compiler_result(
                compiler,
                quantization_type,
                quantization_ths,
                candidate_latency,
            )
            used_compilers.append(compiler)
        except Exception as ex:
            warnings.warn(
                f"Compilation failed with torch interface of {compiler}. "
                f"Got error {ex}. If possible the compilation will be "
                f"re-scheduled with the ONNX interface. Please consult the "
                f"documentation for further info or open an issue on GitHub "
                f"for receiving assistance."
            )
            FEEDBACK_COLLECTOR.store_compiler_result(
                compiler, quantization_type, quantization_ths, None
            )
    return best_tf_opt_model, best_latency, used_compilers


from Animal import Animal

class AnimalShelter(object):

    def __init__(self):
        self.first_cat = None
        self.last_cat = None
        self.first_dog = None
        self.last_dog = None
        self.pet_count = 0

    def __repr__(self):
        cat_counter = 0
        dog_counter = 0
        current_cat = self.first_cat
        current_dog = self.first_dog
        while current_cat is not None:
            current_cat = current_cat.next
            cat_counter += 1
        while current_dog is not None:
            current_dog = current_dog.next
            dog_counter += 1

        return "Total cats: {}; Total dogs: {}".format(cat_counter, dog_counter)

    def enqueue(self, name, species):
        self.pet_count += 1
        new_pet = Animal(name, species)
        new_pet.tracker_counter = self.pet_count

        if species == 'cat':
            if self.first_cat is None:
                self.first_cat = new_pet
            if self.last_cat is not None:
                self.last_cat.next = new_pet
            self.last_cat = new_pet

        elif species == 'dog':
            if self.first_dog is None:
                self.first_dog = new_pet
            if self.last_dog is not None:
                self.last_dog.next = new_pet
            self.last_dog = new_pet

    def dequeue_cat(self):
        if self.first_cat is not None:
            placeholder_cat = self.first_cat
            self.first_cat = placeholder_cat.next
            self.pet_count -= 1
            return ("Dequeued cat: ", str(placeholder_cat.name))
        else:
            return "No cats to dequeue"

    def dequeue_dog(self):
        if self.first_dog is not None:
            placeholder_dog = self.first_dog
            self.first_dog = placeholder_dog.next
            self.pet_count -= 1
            return ("Dequeued dog: ", str(placeholder_dog.name))
        else:
            return "No dogs to dequeue"

    def dequeue_any(self):
        if self.first_cat is not None and self.first_dog is None:
            return self.dequeue_cat()
        elif self.first_cat is None and self.first_dog is not None:
            return self.dequeue_dog()
        else:
            if self.first_cat.tracker_counter < self.first_dog.tracker_counter:
                return self.dequeue_cat()
            else:
                return self.dequeue_dog()


import cv2
from mnist import MNIST
import numpy as np
from skimage.feature import hog
from sklearn.decomposition import PCA ,FactorAnalysis
from sklearn.neighbors import KNeighborsClassifier
import time

start_time = time.time()

mndata = MNIST('data')
tr_imgs , tr_lbs = mndata.load_training()
test_imgs , test_lbs = mndata.load_testing()

new_tr_lbs = [item for item in tr_lbs]
new_test_label = [item for item in test_lbs]

def deskew(img):
    SZ= 20
    m = cv2.moments(img)
    if abs(m['mu02']) < 1e-2:
        # no deskewing needed.
        return img.copy()
    # Calculate skew based on central momemts.
    skew = m['mu11']/m['mu02']
    # Calculate affine transform to correct skewness.
    M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
    # Apply affine transform
    img = cv2.warpAffine(img, M, (SZ, SZ), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR)
    return img

new_train = []
for img in tr_imgs :
    pixels = np.array(img, dtype='uint8')
    pixels = pixels.reshape((28, 28))
    pixels = deskew(pixels)
    # print(np.shape(pixels))
    pixels = np.pad(pixels, ((4, 4), (4, 4)), mode='constant')
    img_hog = hog(pixels)
    new_train.append(img_hog)

new_test = []
for img in test_imgs :
    pixels = np.array(img, dtype='uint8')
    pixels = pixels.reshape((28, 28))
    pixels = deskew(pixels)
    # print(np.shape(pixels))
    pixels = np.pad(pixels, ((4, 4), (4, 4)), mode='constant')
    img_hog = hog(pixels)
    new_test.append(img_hog)

pca = FactorAnalysis(n_components=20)
# new_train = pca.fit_transform(new_train)
# new_test = pca.fit_transform(new_test)

neigh = KNeighborsClassifier(n_neighbors=100)
neigh.fit(new_train, new_tr_lbs)

print('hog  knn:100')
print(neigh.score(new_test,new_test_label))

print("--- %s seconds ---" % (time.time() - start_time))


file = open("chisla.dat", "r")
file_with_lines = file.readlines()
for line in file_with_lines:
    chisla = line.split(',')
    for k in range(0,len(chisla)-1):
        for i in range(0,len(chisla)-1):
            if int(chisla[i]) < int(chisla[i+1]):
                chisla[i] = chisla[i]
            else:
                t = chisla[i]
                chisla[i] = chisla[i+1]
                chisla[i+1] = t
print(chisla)

my_var = ['Ivan', 'Rinat', 'Olga', 'Kira']

# в новый список записываем элементы начального списка, измененные
# с помощью replace
new_list = [_.replace("i", "A", 1) for _ in my_var]
print(new_list)
# Вывод:

['Ivan', 'RAnat', 'Olga', 'KAra']