from collections import defaultdict

FILE_NAME = "input16.in"

fields = defaultdict(list)
your_ticket = []
other_tickets = defaultdict(list)

with open(FILE_NAME, 'r') as file:
    fieldos = True
    your = False
    other = False
    other_index = 0
    for line in file:
        if line == "\n":
            continue
        if "your" in line:
            fieldos = False
            your = True
            continue
        if "nearby" in line:
            other = True
            your = False
            continue
        if fieldos:
            value = line.strip().split(": ")
            key, ranges = value
            first_range, second_range = ranges.split(" or ")
            fields[key].append(first_range)
            fields[key].append(second_range)
        else:
            value = line.strip().split(",")
            if your:
                your_ticket = list(map(int, value))
            if other:
                other_tickets[other_index] = list(map(int, value))
                other_index += 1

invalids = 0
new_others = defaultdict(list)
bad = False

for key, value in other_tickets.items():   #PART 1
    bad = False
    for val in value:
        some_good = False
        for _, conditions in fields.items():
            if some_good:
                break
            for cond in conditions:
                lower, upper = map(int, cond.split("-"))
                if lower <= val <= upper:
                    some_good = True
                    break
        if not some_good:
            invalids += val
            bad = True
    if not bad:
        new_others[key] = value

print(invalids)

fields_options = [set() for _ in range(len(fields))]   #PART 2
help_index = -1
for key, value in new_others.items():    #create  array, each row index represents sets of possibilities of fields for ticket index (1-20)
    help_index += 1
    for index, val in enumerate(value):
        possible_conds = set()
        for condition, ranges in fields.items():
            good = False
            for rango in ranges:
                lower, upper = map(int, rango.split("-"))
                if lower <= val <= upper:
                    good = True
            if good:
                possible_conds.add(condition)
        if help_index == 0:
            fields_options[index] = possible_conds
        else:
            fields_options[index] &= possible_conds

real_positions = [None for _ in range(len(fields))]

while None in real_positions:    #determine position of each field
    to_be_deleted = set()
    for index, conds in enumerate(fields_options):
        if len(conds) == 0:
            continue
        if len(conds) == 1:
            what = next(iter(conds))
            real_positions[index] = what
            to_be_deleted.add(what)
    for val in to_be_deleted:
        for i in range(len(fields_options)):
            if val in fields_options[i]:
                fields_options[i].remove(val)

res = 1
for index, value in enumerate(real_positions):  #get result of 2.part
    if "departure" in value:
        res *= your_ticket[index]
print(res)


# save model not replace

import face_recognition
import cv2
import os
import pickle

print(cv2.__version__)

j=0

Encodings=[]
Names=[]

with open('train.pkl','rb') as f:
    Names=pickle.load(f)
    Encodings=pickle.load(f)

for root,dirs, files in os.walk(image_dir):
    for file in files:
        print(root)
        print(file)
        testImagePath=os.path.join(root,file)
        testImage=face_recognition.load_image_file(testImagePath)
        facePositions=face_recognition.face_locations(testImage)
        allEncodings=face_recognition.face_encodings(testImage,facePositions)
        testImage=cv2.cvtColor(testImage,cv2.COLOR_RGB2BGR)

        for (top,right,bottom,left),face_encoding in zip(facePositions,allEncodings):
            name='Unknown Person'
            matches=face_recognition.compare_faces(Encodings,face_encoding)

            if True in matches:
                first_match_index=matches.index(True)
                name=Names[first_match_index]

            cv2.rectangle(testImage,(left,top),(right,bottom),(0,0,255),2)
            cv2.putText(testImage,name,(left,top-6),font,.75,(0,255,255),2)

        cv2.imshow('Picture', testImage)
        cv2.moveWindow('Picture',0,0)

        if cv2.waitKey(0)==ord('q'):
            cv2.destroyAllWindows()

# เมื่อ run program จะทำการวนซ่้ำรูปภาพที่ recoginize in folder unknow


import keras
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Input, Dense, Activation
from keras.layers import Reshape, Lambda
from keras.models import Model, load_model
from keras.layers import Bidirectional
from keras.layers import LSTM
from keras.optimizers import Adam
from generate_data import TextImageGenerator

def ctc_lambda_func(args):
    y_pred, labels, input_length, label_length = args
    # the 2 is critical here since the first couple outputs of the RNN tend to be garbage:
    y_pred = y_pred[:, 2:, :]
    return keras.backend.ctc_batch_cost(labels, y_pred, input_length, label_length)

def train(img_w, load=False):
    # Input Parameters
    img_h = 64

    # Network parameters
    conv_filters = 16
    kernel_size = (3, 3)
    pool_size = 2
    time_dense_size = 32
    rnn_size = 512

    if keras.backend.image_data_format() == 'channels_first':
        input_shape = (1, img_w, img_h)
    else:
        input_shape = (img_w, img_h, 1)

    batch_size = 32
    downsample_factor = pool_size ** 2
    tiger_train = TextImageGenerator('./train/', img_w, img_h, batch_size, downsample_factor)
    tiger_train.build_data()
    tiger_test = TextImageGenerator('./test/', img_w, img_h, batch_size, downsample_factor)
    tiger_test.build_data()

    act = 'relu'
    input_data = Input(name='the_input', shape=input_shape, dtype='float32')
    inner = Conv2D(conv_filters, kernel_size, padding='same',
                   activation=act, kernel_initializer='he_normal',
                   name='conv1')(input_data)
    inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max1')(inner)
    inner = Conv2D(conv_filters, kernel_size, padding='same',
                   activation=act, kernel_initializer='he_normal',
                   name='conv2')(inner)
    inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max2')(inner)

    conv_to_rnn_dims = (img_w // (pool_size ** 2), (img_h // (pool_size ** 2)) * conv_filters)
    inner = Reshape(target_shape=conv_to_rnn_dims, name='reshape')(inner)

    # cuts down input size going into RNN:
    inner = Dense(time_dense_size, activation=act, name='dense1')(inner)

    gru_1 = LSTM(rnn_size, return_sequences=True, name='gru1')
    gru_1b = LSTM(rnn_size, return_sequences=True, go_backwards=True, name='gru1_b')
    gru1_merged = Bidirectional(gru_1, backward_layer=gru_1b)(inner)
    gru_2 = LSTM(rnn_size, return_sequences=True, kernel_initializer='he_normal', name='gru2')
    gru_2b = LSTM(rnn_size, return_sequences=True, go_backwards=True, kernel_initializer='he_normal', name='gru2_b')
    gru2_merged = Bidirectional(gru_2, backward_layer=gru_2b)(gru1_merged)
    # transforms RNN output to character activations:
    inner = Dense(tiger_train.get_output_size(), kernel_initializer='he_normal',
                  name='dense2')(gru2_merged)
    y_pred = Activation('softmax', name='softmax')(inner)
    Model(inputs=input_data, outputs=y_pred).summary()

    labels = Input(name='the_labels', shape=[tiger_train.max_text_len], dtype='float32')
    input_length = Input(name='input_length', shape=[1], dtype='int64')
    label_length = Input(name='label_length', shape=[1], dtype='int64')

    # Keras doesn't currently support loss funcs with extra parameters
    # so CTC loss is implemented in a lambda layer
    loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([y_pred, labels, input_length, label_length])

    sgd = Adam()
    if load:
        model = load_model('./tmp_model.h5', compile=False)
    else:
        model = Model(inputs=[input_data, labels, input_length, label_length], outputs=loss_out)

    # the loss calc occurs elsewhere, so use a dummy lambda func for the loss
    model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=sgd)
    model.summary()
    if not load:
        # captures output of softmax so we can decode the output during visualization
        #test_func = tf.keras.backend.function([input_data], [y_pred])

        model.fit_generator(generator=tiger_train.next_batch(),
                        steps_per_epoch=tiger_train.n,
                        epochs=1,
                        validation_data=tiger_test.next_batch(),
                        validation_steps=tiger_test.n)

    return model

model = train(128, load=False)
extracted_layers = model.layers[:-4]
new_model = keras.Sequential(extracted_layers)
new_model.save('ocr_model.h5', include_optimizer=False)


import matplotlib
import matplotlib.pyplot as plt
import dataset
import numpy as np
import tensorflow as tf
import os
import time
tf.compat.v1.reset_default_graph()
np.random.seed(42)
tf.compat.v1.set_random_seed(42)

###################################################################################
###################Uncomment this part to run capsulenetworks for artist classification
output_classes     = {0: 'Albrecht_Durer',
                     1: 'Boris_Kustodiev',
                     2: 'Camille_Pissarro',
                     3: 'Childe_Hassam',
                     4: 'Claude_Monet',
                     5: 'Edgar_Degas',
                     6: 'Eugene_Boudin',
                     7: 'Gustave_Dore',
                     8: 'Ilya_Repin',
                     9: 'Ivan_Aivazovsky',
                     10: 'Ivan_Shishkin',
                     11: 'John_Singer_Sargent',
                     12: 'Marc_Chagall',
                     13: 'Martiros_Saryan',
                     14: 'Nicholas_Roerich',
                     15: 'Pablo_Picasso',
                     16: 'Paul_Cezanne',
                     17: 'Pierre_Auguste_Renoir',
                     18: 'Pyotr_Konchalovsky',
                     19: 'Raphael_Kirchner',
                     20: 'Rembrandt',
                     21: 'Salvador_Dali',
                     22: 'Vincent_van_Gogh'}
train_path='./processed_Data/Artist/dataartisttrain_old'
val_path='./processed_Data/Artist/dataartistval_old'

###################################################################################
###################Uncomment this part to run capsulenetworks for genre classification
#output_classes     =  {0: 'abstract_painting',
#                        1: 'cityscape',
#                        2: 'genre_painting',
#                        3: 'illustration',
#                        4: 'landscape',
#                        5: 'nude_painting',
#                        6: 'portrait',
#                        7: 'religious_painting',
#                        8: 'sketch_and_study',
#                        9: 'still_life'}
# train_path='./processed_Data/Genre/datagenretrain_old'
# val_path='./processed_Data/Genre/datagenreval_old'
###################################################################################
###################Uncomment this part to run capsulenetworks for style classification
# output_classes = {0: 'Abstract_Expressionism',
#                   1: 'Action_painting',
#                   2: 'Analytical_Cubism',
#                   3: 'Art_Nouveau',
#                   4: 'Baroque',
#                   5: 'Color_Field_Painting',
#                   6: 'Contemporary_Realism',
#                   7: 'Cubism',
#                   8: 'Early_Renaissance',
#                   9: 'Expressionism',
#                   10: 'Fauvism',
#                   11: 'High_Renaissance',
#                   12: 'Impressionism',
#                   13: 'Mannerism_Late_Renaissance',
#                   14: 'Minimalism',
#                   15: 'Naive_Art_Primitivism',
#                   16: 'New_Realism',
#                   17: 'Northern_Renaissance',
#                   18: 'Pointillism',
#                   19: 'Pop_Art',
#                   20: 'Post_Impressionism',
#                   21: 'Realism',
#                   22: 'Rococo',
#                   23: 'Romanticism',
#                   24: 'Symbolism',
#                   25: 'Synthetic_Cubism',
#                   26: 'Ukiyo_e'}

# train_path='./processed_Data/Style/datastyletrain_old'
# val_path='./processed_Data/Style/datastyleval_old'
#######################################################################
#Parameterssss
batch_size = 128
num_epochs = 80
iterations = 1
#20% of the data will automatically be used for validation
test_size = 0.2
img_size = 28

start = time.time()
print('Starteddddd', start)

if not os.path.exists(train_path):
    print("No such directory")
    raise Exception
classes = os.listdir(train_path)
num_classes = len(classes)

# We shall load all the training and validation images and labels into memory using openCV and use that during training
data = dataset.read_train_sets(train_path, val_path, img_size, classes, test_size)

# Display the stats
print("Complete reading input data. Will Now print a snippet of it")
print("Number of files in Training-set:\t\t{}".format(len(data.train.labels)))
print("Number of files in Validation-set:\t{}".format(len(data.valid.labels)))
print("Number of files in Test-set:\t{}".format(len(data.test.labels)))

print('Doneeeee', time.time()-start)
X_train = data.train.images
y_train = data.train.labels

X_test = data.test.images
y_test = data.test.labels

X_valid = data.valid.images
y_valid = data.valid.labels

print('#training dataaaaa')
print(np.shape(X_train),np.shape(y_train))
print(type(y_train[1]), y_train[:10])

print('#testing dataaaaa')
print(np.shape(X_test),np.shape(y_test))
print(type(y_test[1]), y_test[:10])

print('#Validation dataaaaa')
print(np.shape(X_valid),np.shape(y_valid))
print(type(y_valid[1]), y_valid[:10])

n_samples = 5

print('And Corresponding Labelsssss')
print(y_train[:n_samples])

X = tf.compat.v1.placeholder(shape=[None, 28, 28, 1], dtype=tf.float32, name="X")

#primary capsuless

caps1_n_maps = 32
caps1_n_caps = caps1_n_maps * 6 * 6  # 1152 primary capsules
caps1_n_dims = 8

conv1_params = {
    "filters": 256,
    "kernel_size": 9,
    "strides": 1,
    "padding": "valid",
    "activation": tf.nn.relu,
}

conv2_params = {
    "filters": caps1_n_maps * caps1_n_dims, # 256 convolutional filters
    "kernel_size": 9,
    "strides": 2,
    "padding": "valid",
    "activation": tf.nn.relu
}

conv1 = tf.layers.conv2d(X, name="conv1", **conv1_params)
conv2 = tf.layers.conv2d(conv1, name="conv2", **conv2_params)

caps1_raw = tf.reshape(conv2, [-1, caps1_n_caps, caps1_n_dims],
                       name="caps1_raw")

def squash(s, axis=-1, epsilon=1e-7, name=None):
    with tf.name_scope(name, default_name="squash"):
        squared_norm = tf.reduce_sum(tf.square(s), axis=axis,
                                     keepdims=True)
        safe_norm = tf.sqrt(squared_norm + epsilon)
        squash_factor = squared_norm / (1. + squared_norm)
        unit_vector = s / safe_norm
        return squash_factor * unit_vector

caps1_output = squash(caps1_raw, name="caps1_output")

#Digital Capsules Now

caps2_n_caps = 10
caps2_n_dims = 16

init_sigma = 0.1

W_init = tf.random.normal(
    shape=(1, caps1_n_caps, caps2_n_caps, caps2_n_dims, caps1_n_dims),
    stddev=init_sigma, dtype=tf.float32, name="W_init")
W = tf.Variable(W_init, name="W")

batch_size = tf.shape(X)[0]
W_tiled = tf.tile(W, [batch_size, 1, 1, 1, 1], name="W_tiled")

caps1_output_expanded = tf.expand_dims(caps1_output, -1,
                                       name="caps1_output_expanded")
caps1_output_tile = tf.expand_dims(caps1_output_expanded, 2,
                                   name="caps1_output_tile")
caps1_output_tiled = tf.tile(caps1_output_tile, [1, 1, caps2_n_caps, 1, 1],
                             name="caps1_output_tiled")

caps2_predicted = tf.matmul(W_tiled, caps1_output_tiled,
                            name="caps2_predicted")

#Routing by agreement
#round 1
raw_weights = tf.zeros([batch_size, caps1_n_caps, caps2_n_caps, 1, 1],
                       dtype=np.float32, name="raw_weights")
routing_weights = tf.nn.softmax(raw_weights, axis=2, name="routing_weights")

weighted_predictions = tf.multiply(routing_weights, caps2_predicted,
                                   name="weighted_predictions")
weighted_sum = tf.reduce_sum(weighted_predictions, axis=1, keepdims=True,
                             name="weighted_sum")

caps2_output_round_1 = squash(weighted_sum, axis=-2,
                              name="caps2_output_round_1")

#round2

caps2_output_round_1_tiled = tf.tile(
    caps2_output_round_1, [1, caps1_n_caps, 1, 1, 1],
    name="caps2_output_round_1_tiled")

agreement = tf.matmul(caps2_predicted, caps2_output_round_1_tiled,
                      transpose_a=True, name="agreement")

raw_weights_round_2 = tf.add(raw_weights, agreement,
                             name="raw_weights_round_2")

routing_weights_round_2 = tf.nn.softmax(raw_weights_round_2,
                                        axis=2,
                                        name="routing_weights_round_2")
weighted_predictions_round_2 = tf.multiply(routing_weights_round_2,
                                           caps2_predicted,
                                           name="weighted_predictions_round_2")
weighted_sum_round_2 = tf.reduce_sum(weighted_predictions_round_2,
                                     axis=1, keepdims=True,
                                     name="weighted_sum_round_2")
caps2_output_round_2 = squash(weighted_sum_round_2,
                              axis=-2,
                              name="caps2_output_round_2")

caps2_output = caps2_output_round_2

#Estimating class probabilities

def safe_norm(s, axis=-1, epsilon=1e-7, keep_dims=False, name=None):
    with tf.name_scope(name, default_name="safe_norm"):
        squared_norm = tf.reduce_sum(tf.square(s), axis=axis,
                                     keepdims=keep_dims)
        return tf.sqrt(squared_norm + epsilon)

y_proba = safe_norm(caps2_output, axis=-2, name="y_proba")

y_proba_argmax = tf.argmax(y_proba, axis=2, name="y_proba")

y_pred = tf.squeeze(y_proba_argmax, axis=[1,2], name="y_pred")

#Labels

y = tf.compat.v1.placeholder(shape=[None], dtype=tf.int64, name="y")

#computing margin loss

m_plus = 0.9
m_minus = 0.1
lambda_ = 0.5

T = tf.one_hot(y, depth=caps2_n_caps, name="T")

caps2_output_norm = safe_norm(caps2_output, axis=-2, keep_dims=True,
                              name="caps2_output_norm")

present_error_raw = tf.square(tf.maximum(0., m_plus - caps2_output_norm),
                              name="present_error_raw")
present_error = tf.reshape(present_error_raw, shape=(-1, 10),
                           name="present_error")

absent_error_raw = tf.square(tf.maximum(0., caps2_output_norm - m_minus),
                             name="absent_error_raw")
absent_error = tf.reshape(absent_error_raw, shape=(-1, 10),
                          name="absent_error")

L = tf.add(T * present_error, lambda_ * (1.0 - T) * absent_error,
           name="L")

margin_loss = tf.reduce_mean(tf.reduce_sum(L, axis=1), name="margin_loss")

#Reconstruction

mask_with_labels = tf.placeholder_with_default(False, shape=(),
                                               name="mask_with_labels")

reconstruction_targets = tf.cond(mask_with_labels, # condition
                                 lambda: y,        # if True
                                 lambda: y_pred,   # if False
                                 name="reconstruction_targets")

reconstruction_mask = tf.one_hot(reconstruction_targets,
                                 depth=caps2_n_caps,
                                 name="reconstruction_mask")

reconstruction_mask_reshaped = tf.reshape(
    reconstruction_mask, [-1, 1, caps2_n_caps, 1, 1],
    name="reconstruction_mask_reshaped")

caps2_output_masked = tf.multiply(
    caps2_output, reconstruction_mask_reshaped,
    name="caps2_output_masked")

decoder_input = tf.reshape(caps2_output_masked,
                           [-1, caps2_n_caps * caps2_n_dims],
                           name="decoder_input")

#Decoder

n_hidden1 = 512
n_hidden2 = 1024
n_output = 28 * 28

with tf.name_scope("decoder"):
    hidden1 = tf.layers.dense(decoder_input, n_hidden1,
                              activation=tf.nn.relu,
                              name="hidden1")
    hidden2 = tf.layers.dense(hidden1, n_hidden2,
                              activation=tf.nn.relu,
                              name="hidden2")
    decoder_output = tf.layers.dense(hidden2, n_output,
                                     activation=tf.nn.sigmoid,
                                     name="decoder_output")

X_flat = tf.reshape(X, [-1, n_output], name="X_flat")
squared_difference = tf.square(X_flat - decoder_output,
                               name="squared_difference")
reconstruction_loss = tf.reduce_mean(squared_difference,
                                    name="reconstruction_loss")

alpha = 0.05

loss = tf.add(margin_loss, alpha * reconstruction_loss, name="loss")

#Computing accuracies and initializing paramters
correct = tf.equal(y, y_pred, name="correct")
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32), name="accuracy")

optimizer = tf.train.AdamOptimizer()
training_op = optimizer.minimize(loss, name="training_op")

init = tf.compat.v1.global_variables_initializer()
saver = tf.compat.v1.train.Saver()

train_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))
valid_dataset =  tf.data.Dataset.from_tensor_slices((X_valid, y_valid))
test_dataset = tf.data.Dataset.from_tensor_slices((X_test, y_test))

#Traininggggggggggggggggg

def next_batch(num, data, labels):
    '''
    Return a total of `num` random samples and labels.
    '''
    idx = np.arange(0 , len(data))
    np.random.shuffle(idx)
    idx = idx[:num]
    data_shuffle = [data[ i] for i in idx]
    labels_shuffle = [labels[ i] for i in idx]

    return np.asarray(data_shuffle), np.asarray(labels_shuffle)

n_epochs = 80
batch_size = 100
restore_checkpoint = True

n_iterations_per_epoch =  np.shape(X_train)[0] // batch_size
n_iterations_validation = np.shape(X_valid)[0] // batch_size
best_loss_val = np.infty
checkpoint_path = "./my_capsule_network"

def plot_train_val_test(train_acc, val_acc, train_loss, val_loss):
   fig, (ax1, ax2) = plt.subplots(1, 2)

   # Accuracy
   ax1.set_title('Model accuracy')
   ax1.plot(train_acc)
   ax1.plot(val_acc)
   ax1.set_xlabel('epoch')
   ax1.set_ylabel('accuracy')
   ax1.legend(['train', 'validation'], loc='upper left')

   # Loss
   ax2.set_title('Model loss')
   ax2.plot(train_loss)
   ax2.plot(val_loss)
   ax2.set_xlabel('epoch')
   ax2.set_ylabel('loss')
   ax2.legend(['train', 'validation',], loc='upper left')

   fig.set_size_inches(20, 5)
   plt.show()

train_acc = []
val_acc = []
train_loss = []
val_loss = []

with tf.Session() as sess:
    if restore_checkpoint and tf.train.checkpoint_exists(checkpoint_path):
        saver.restore(sess, checkpoint_path)
    else:
        init.run()

    for epoch in range(n_epochs):
        loss_trains = []
        acc_trains = []
        for iteration in range(1, n_iterations_per_epoch + 1):
            X_batch, y_batch = next_batch(batch_size, X_train, y_train)
            #print(train.shape)
            #X_batch, y_batch = train
            # Run the training operation and measure the loss:
            loss_train, acc_train = sess.run(
                [loss, accuracy],
                feed_dict={X: X_batch.reshape([-1, 28, 28, 1]),
                           y: y_batch,
                           mask_with_labels: True})

            print("\rIteration: {}/{} ({:.1f}%)  Loss: {:.5f}".format(
                      iteration, n_iterations_per_epoch,
                      iteration * 100 / n_iterations_per_epoch,
                      loss_train),
                  end="")
            loss_trains.append(loss_train)
            acc_trains.append(acc_train)
        loss_train = np.mean(loss_trains)
        acc_train = np.mean(acc_trains)
        # At the end of each epoch,
        # measure the validation loss and accuracy:
        loss_vals = []
        acc_vals = []
        for iteration in range(1, n_iterations_validation + 1):
            X_batch, y_batch = next_batch(batch_size, X_valid, y_valid)
            #X_batch, y_batch = valid
            loss_val, acc_val = sess.run(
                    [loss, accuracy],
                    feed_dict={X: X_batch.reshape([-1, 28, 28, 1]),
                               y: y_batch})
            loss_vals.append(loss_val)
            acc_vals.append(acc_val)
            print("\rEvaluating the model: {}/{} ({:.1f}%)".format(
                      iteration, n_iterations_validation,
                      iteration * 100 / n_iterations_validation),
                  end=" " * 10)
        loss_val = np.mean(loss_vals)
        acc_val = np.mean(acc_vals)

        print("\rEpoch: {}  Val accuracy: {:.4f}%  Loss: {:.6f}{}".format(
            epoch + 1, acc_val * 100, loss_val,
            " (improved)" if loss_val < best_loss_val else ""))
        train_acc.append(acc_train)
        val_acc.append(acc_val)
        train_loss.append(loss_train)
        val_loss.append(loss_val)
        # And save the model if it improved:
        if loss_val < best_loss_val:
            save_path = saver.save(sess, checkpoint_path)
            best_loss_val = loss_val

n_iterations_test = np.shape(X_test)[0] // batch_size

with tf.Session() as sess:
    saver.restore(sess, checkpoint_path)
    loss_tests = []
    acc_tests = []
    for iteration in range(1, n_iterations_test + 1):
        X_batch, y_batch = next_batch(batch_size, X_test, y_test)
        #[X_batch, y_batch] = test
        loss_test, acc_test = sess.run(
                [loss, accuracy],
                feed_dict={X: X_batch.reshape([-1, 28, 28, 1]),
                           y: y_batch})
        loss_tests.append(loss_test)
        acc_tests.append(acc_test)
        print("\rEvaluating the model: {}/{} ({:.1f}%)".format(
                  iteration, n_iterations_test,
                  iteration * 100 / n_iterations_test),
              end=" " * 10)
    loss_test = np.mean(loss_tests)
    acc_test = np.mean(acc_tests)
    print("\rFinal test accuracy: {:.4f}%  Loss: {:.6f}".format(
        acc_test * 100, loss_test))

#predictions = cnn.predict_classes(X_test, verbose=0)
#plot_confusion_matrix(confusion_matrix(y_test, predictions), list(output_classes.keys()))

#print(classification_report(y_test, predictions))

plot_train_val_test(train_acc, val_acc, train_loss, val_loss)


from django.conf import settings
from django.test import SimpleTestCase, override_settings

import responses

from ...records.api import get_records_client
from ...records.models import Record
from ..exceptions import ClientAPIError, DoesNotExist, MultipleObjectsReturned
from .factories import create_record, create_search_response

@override_settings(CLIENT_BASE_URL=f"{settings.CLIENT_BASE_URL}")
class ClientAPIExceptionTest(SimpleTestCase):
    def setUp(self):
        self.records_client = get_records_client()

    @responses.activate
    def test_raises_does_not_exist(self):
        responses.add(
            responses.GET,
            f"{settings.CLIENT_BASE_URL}/fetch",
            json={"hits": {"total": {"value": 0, "relation": "eq"}, "hits": []}},
        )

        with self.assertRaises(DoesNotExist):
            self.records_client.fetch(iaid="C140")

    @responses.activate
    def test_raises_multiple_objects_returned(self):
        responses.add(
            responses.GET,
            f"{settings.CLIENT_BASE_URL}/fetch",
            json={"hits": {"total": {"value": 2, "relation": "eq"}, "hits": [{}, {}]}},
        )

        with self.assertRaises(MultipleObjectsReturned):
            self.records_client.fetch(iaid="C140")

@override_settings(CLIENT_BASE_URL=f"{settings.CLIENT_BASE_URL}")
class ClientAPIFilterTest(SimpleTestCase):
    def setUp(self):
        self.records_client = get_records_client()

    @responses.activate
    def test_hits_returns_list(self):
        responses.add(
            responses.GET,
            f"{settings.CLIENT_BASE_URL}/search",
            json=create_search_response(
                total_count=2,
                records=[
                    create_record(iaid="C4122893"),
                    create_record(iaid="C4122894"),
                ],
            ),
        )

        result = self.records_client.search(web_reference="ADM 223/3")

        self.assertEqual(result.total_count, 2)
        self.assertEqual(len(result), 2)
        self.assertTrue(isinstance(result.hits[0], Record))
        self.assertTrue(isinstance(result.hits[1], Record))
        self.assertEqual(result.hits[0].iaid, "C4122893")
        self.assertEqual(result.hits[1].iaid, "C4122894")

    @responses.activate
    def test_fetch_for_record_out_of_bounds_raises_index_error(self):
        responses.add(
            responses.GET,
            f"{settings.CLIENT_BASE_URL}/search",
            json=create_search_response(records=[create_record()]),
        )

        result = self.records_client.search(web_reference="ADM 223/3")

        with self.assertRaises(IndexError):
            result.hits[1]

class ClientExceptionTest(SimpleTestCase):
    def setUp(self):
        self.records_client = get_records_client()

    @responses.activate
    def test_raises_invalid_iaid_match(self):
        responses.add(
            responses.GET,
            f"{settings.CLIENT_BASE_URL}/fetch",
            status=500,
        )

        with self.assertRaises(ClientAPIError):
            self.records_client.fetch(iaid="C140")


import datetime
from flask import Flask, Response, send_from_directory
import httpx
from os.path import exists

app = Flask(__name__)

now = datetime.datetime.now().strftime("%Y%m%d")

@app.route("/health")
def health():
  return "Ready"

@app.route("/")
def root():
  if not exists(f"/data/{now}.jpg"):
    print("Daily image missing. Fetching new image!")
    req = httpx.get("https://picsum.photos/300", follow_redirects=True)
    f = open(f"/data/{now}.jpg","wb")
    f.write(req.content)
  resp = f"""

<form method="post" action="/todos">
<input type="text" name="todo" maxlength="140">
<input type="submit" value="Create TODO">
</form>

"""
  req = httpx.get("http://backend-svc/todos")
  for todo in req.json():
    if todo["done"]:
      resp = resp + f"""
{todo["task"]}
"""
    else:
      resp = resp + f"""
<button onclick="done('/todos/{todo["id"]}')">Done</button> {todo["task"]}</form>
"""
  resp = resp + "
"
  return resp

@app.route("/pics/<string:pic>")
def picture(pic):
  return send_from_directory("/data", pic)


import numpy as np
from lightfm.datasets import fetch_movielens
from lightfm import LightFM

data = fetch_movielens(min_rating = 4.0)

print(repr(data['train']))
print(repr(data['test']))

#model with loss func.
model = LightFM(loss = 'warp')

model.fit(data['train'],epochs = 30,num_threads = 2)

def sample_rec(model, data, user_ids):

    n_users,n_items = data['train'].shape
    for i in user_ids:

        known_pos = data['item_labels'][data['train'].tocsr()[i].indices]
        scores = model.predict(i,np.arange(n_items))
        top_items = data['item_labels'][np.argsort(-scores)]

        #printing
        print("User  %s"% i)
        print(" Known positives:")
        for j in known_pos[:3]:     ##top 3
            print("     %s" % j)
        print(" Recommended:")
        for j in top_items[:3]:
            print("     %s" % j)

sample_rec(model,data,[3,45,250])


import bs4
import urllib.request
import smtplib
import time
prices_list=[]
def check_price():

    url = 'https://www.amazon.in/dp/B082MDMW3X/ref=s9_acsd_al_bw_c2_x_0_i?pf_rd_m=A1K21FY43GMZF8&pf_rd_s=merchandised-search-5&pf_rd_r=CF9JY0WX1GAAPBD3S9KW&pf_rd_t=101&pf_rd_p=8398f427-fbf5-4310-a31e-29a4be7a59bc&pf_rd_i=26297682031'
    sauce = urllib.request.urlopen(url).read()
    soup = bs4.BeautifulSoup(sauce,"html.parser")
    price = soup.find(id="priceblock_dealprice").get_text()
    p1 = float(price.replace(",","").replace("₹",""))
    print(price)
    print(p1)
    prices_list.append(p1)
    return p1
check_price()

def send_email(message):
    s=smtplib.SMTP('smtp.gmail.com',587)
    s.starttls()
    s.login("anshtestiing123@gmail.com","anshpratap013@")
    s.sendmail("anshtestiing123@gmail.com","anshpratap013@gmail.com",message)
    s.quit()

send_email("Hi Ansh")
def price_decrease_check(prices_list):
    if prices_list[-1]<prices_list[-2]:
        return True
    else:
        return False
count = 1
while True:

    current_price = check_price()
    if count>1:
        flag = price_decrease_check(prices_list)
        if flag>1:
            decrease = prices_list[-1]-prices_list[-2]
            message = "The price has decreased please check the item and it has decreased by {decrese} rupees"
            send_email(message)
    time.sleep(1)
    count+=1


import cv2
import numpy as np
import torch

class BaseTransform(object):
    def __init__(self, resize, rgb_means, swap=(2, 0, 1)):
        self.means = rgb_means
        self.resize = resize
        self.swap = swap

    def __call__(self, img):

        interp_methods = [cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_NEAREST, cv2.INTER_LANCZOS4]
        interp_method = interp_methods[0]
        img = cv2.resize(np.array(img), (self.resize,
                                         self.resize),interpolation = interp_method).astype(np.float32)
        img -= self.means
        img = img.transpose(self.swap)
        return torch.from_numpy(img)


#IMPORTING LIBRARIES
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# READING DATA FROM TRAIN DATASET
data_1 = pd.read_csv('iosdml1_train.csv')
x_train = data_1.iloc[:, :2].values
y_train = data_1.iloc[:, -1].values
# READING DATA FROM TEST DATASET
data_2 = pd.read_csv('iosdml1_test.csv')
x_test = data_1.iloc[:, :2].values
y_test = data_1.iloc[:, -1].values
# FEATURE SCALING
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)
# KNN
from sklearn.neighbors import KNeighborsClassifier
klf = KNeighborsClassifier(n_neighbors=25)
klf.fit(x_train, y_train)
# TESTING A SAMPLE
print(klf.predict(sc.transform([[8.480100064,58.5780145]])))
# ACCURACY OF MODEL
y_pred = klf.predict(x_test)
from sklearn.metrics import confusion_matrix, accuracy_score
print(confusion_matrix(y_test, y_pred))
print(accuracy_score(y_test, y_pred))


import concurrent
from concurrent import futures
import grpc
import json
import booking_pb2
import booking_pb2_grpc

class BookingServicer(booking_pb2_grpc.BookingServicer):
    def __init__(self):
        with open('{}/databases/bookings.json'.format("."), "r") as jsf:
            self.db = json.load(jsf)["bookings"]

    def GetAllBookings(self,request,context):
        for booking in self.db:
            yield booking_pb2.BookingMessage(date=booking['dates'],userid=booking['userid'])

    def GetBookingByUserId(self, request, context):
        for booking in self.db:
            if str(booking["userid"]) == str(request.id):
                print("hello")
                return booking_pb2.BookingMessage(
                    userid=booking["userid"],
                    date=[booking_pb2.Date(date=b.date,movies=b.movies) for b in booking]
                )
        return booking_pb2.BookingMessage(
            userid="",
            date=""
        )

    def CreateBooking(self, request, context):
        self.db.append({
            "userid":request.userid,
            "date":request.date
        })

def serve():
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  booking_pb2_grpc.add_BookingServicer_to_server(BookingServicer(),
                                                      server)
  server.add_insecure_port('[::]:' + "3005")
  server.start()
  server.wait_for_termination()

if __name__ == '__main__':
  serve()


# -*- coding: utf-8 -*-
"""
Author: [Yunting Chiu](https://www.linkedin.com/in/yuntingchiu/)
"""

import cv2
import matplotlib.pyplot as plt
import numpy as np
import time
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler # standardize features by removing the mean and scaling to unit variance.
from sklearn.metrics import confusion_matrix
#from sklearn.metrics import plot_confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.model_selection import GridSearchCV

# Exploratory Data Analysis
##Read the data (`.npz` file)

data_zipped = np.load("np_data_all.npz", allow_pickle=True)

for item in data_zipped.files:
    print(item)
    print(data_zipped[item])

#print(data_zipped[item].shape)
data = data_zipped[item]

"""## Check the length of $X$ and $y$"""

X = []
y = []
for i in data:
  X.append(i[0])
  y.append(i[1])
print("The length of X feature is", len(X[1]))

print("The length should be " + str((6984+7000)))
print("data dimension:",data.shape)

"""## Visualization"""

fake_cnt = 0
real_cnt = 0
for i in data:
  if i[1] == "fake":
    fake_cnt += 1
  else:
    real_cnt += 1

#print(fake_cnt)
#print(real_cnt)
df = [['fake', fake_cnt], ['real', real_cnt]]
df = pd.DataFrame(df, columns=['image_type', 'count'])
#ax = df.plot.bar(x='video_type', y='count', rot=0)
fig = plt.figure()
plt.bar(df['image_type'], df['count'])
plt.xlabel("Image Type")
plt.ylabel("Count")
plt.savefig('10.count_type.png')

"""# Machine Learning Task

"""## Random Forest Classifier"""

start_time = time.time()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42) # 80% for training, 20 for of testing

### Cross vaildation procedure and define a classifier
cv_inner = KFold(n_splits=5, shuffle=True, random_state=100)
rf_clf = RandomForestClassifier(random_state=42, bootstrap=True)

# define search space
# n_estimators: The number of trees in the forest.
space = {}
space['n_estimators'] = [100, 500, 1000, 2000]
space['max_depth'] = [0, 100, 500, 1000, 2000, None]
space['min_samples_leaf'] = [100, 500, 1000]
space['min_samples_split'] = [100, 500, 1000]

# define search
search = GridSearchCV(rf_clf, space, scoring='accuracy', n_jobs=1, cv=cv_inner)
result = search.fit(X_train, y_train)
print(search.best_params_)
best_model = result.best_estimator_
print("Best Model: {}".format(best_model))

# evaluate model on the hold out dataset
y_pred = best_model.predict(X_test)
print("--- %s seconds ---" % (time.time() - start_time))
print("----------Confusion Matrix----------------")
print(confusion_matrix(y_test, y_pred))

### RF Confusion Matrix

#plot_confusion_matrix(svm_clf, X_test, y_test, values_format = '.0f')
#plt.figure(figsize=(12,8))
#plt.show()
conf_matrix = confusion_matrix(y_true = y_test, y_pred = y_pred)

# Print the confusion matrix using Matplotlib

fig, ax = plt.subplots(figsize=(7.5, 7.5))
ax.matshow(conf_matrix, cmap=plt.cm.Blues, alpha=0.3)
for i in range(conf_matrix.shape[0]):
    for j in range(conf_matrix.shape[1]):
        ax.text(x=j, y=i,s=conf_matrix[i, j], va='center', ha='center', size='xx-large')

plt.xlabel('Predictions', fontsize=18)
plt.ylabel('Actuals', fontsize=18)
plt.title('Confusion Matrix', fontsize=18)
plt.show()
plt.savefig('10.confusion_matrix.png')

### RF Accuracy Score

print("----------Accuracy Score----------------")
print(accuracy_score(y_test, y_pred))

print("------------Classification Report----------")
target_names = ['fake', 'real']
print(classification_report(y_test, y_pred, target_names=target_names))

# References
# https://machinelearningmastery.com/nested-cross-validation-for-machine-learning-with-python/
# https://towardsdatascience.com/hyperparameter-tuning-the-random-forest-in-python-using-scikit-learn-28d2aa77dd74


import requests
import json
import os

def buscar_pokemon(nombre):
    url = f"https://pokeapi.co/api/v2/pokemon/{nombre.lower()}"
    response = requests.get(url)

    if response.status_code == 404:
        print("El Pokémon no fue encontrado.")
        return None

    data = response.json()
    imagen = data["sprites"]["front_default"]
    peso = data["weight"]
    altura = data["height"]
    movimientos = [movimiento["move"]["name"] for movimiento in data["moves"]]
    habilidades = [habilidad["ability"]["name"] for habilidad in data["abilities"]]
    tipos = [tipo["type"]["name"] for tipo in data["types"]]

    pokemon = {
        "nombre": nombre,
        "imagen": imagen,
        "peso": peso,
        "altura": altura,
        "movimientos": movimientos,
        "habilidades": habilidades,
        "tipos": tipos
    }

    return pokemon

def guardar_pokemon(pokemon):
    carpeta_pokedex = "pokedex"
    if not os.path.exists(carpeta_pokedex):
        os.makedirs(carpeta_pokedex)

    nombre_archivo = f"{carpeta_pokedex}/{pokemon['nombre']}.json"
    with open(nombre_archivo, "w") as archivo:
        json.dump(pokemon, archivo, indent=4)
    print(f"La información del Pokémon se ha guardado en {nombre_archivo}.")

def mostrar_info_pokemon(pokemon):
    print("Nombre:", pokemon["nombre"])
    print("Imagen:", pokemon["imagen"])
    print("Peso:", pokemon["peso"])
    print("Altura:", pokemon["altura"])
    print("Movimientos:", ", ".join(pokemon["movimientos"]))
    print("Habilidades:", ", ".join(pokemon["habilidades"]))
    print("Tipos:", ", ".join(pokemon["tipos"]))

# Ciclo principal del programa
while True:
    # Obtener el nombre del Pokémon desde el usuario
    nombre_pokemon = input("Ingrese el nombre de un Pokémon (o 'q' para salir): ")

    # Verificar si se quiere salir del programa
    if nombre_pokemon.lower() == "q":
        break

    # Buscar el Pokémon en la Pokédex
    pokemon = buscar_pokemon(nombre_pokemon)

    if pokemon:
        mostrar_info_pokemon(pokemon)
        guardar_pokemon(pokemon)


import datetime
import textwrap
from pathlib import Path

from slap import __version__
from slap.application import Application, Command, argument, option
from slap.plugins import ApplicationPlugin
from slap.util.external.licenses import get_spdx_license_details, wrap_license_text
from slap.util.vcs import get_git_author

TEMPLATES = {
    "poetry": {
        "pyproject.toml": """
            [build-system]
            requires = ["poetry-core"]
            build-backend = "poetry.core.masonry.api"

            [tool.poetry]
            name = "{name}"
            version = "0.1.0"
            description = ""
            authors = ["{author_name} <{author_email}>"]
            license = "{license}"
            readme = "readme.md"
            packages = [{{ include = "{path}", from = "src" }}]
            classifiers = []
            keywords = []

            [tool.poetry.urls]
            # "Bug Tracker" = ""
            # Documentation = ""
            # Homepage = ""
            # Repository = ""

            [tool.poetry.dependencies]
            python = "^3.6"

            [tool.poetry.dev-dependencies]
            black = "*"
            flake8 = "*"
            isort = "*"
            mypy = "*"
            pytest = "*"

            [tool.slap]
            typed = true

            [tool.slap.test]
            check = "slap check"
            mypy = "dmypy run src/"
            pytest = "pytest tests/ -vv"
            black = "black --check src/ tests/"
            isort = "isort --check-only src/ tests/"
            flake8 = "flake8 src/ tests/"

            [tool.slap.run]
            fmt = "black src/ tests/ && isort src/ tests/"

            [tool.mypy]
            python_version = "3.6"
            explicit_package_bases = true
            mypy_path = ["src"]
            namespace_packages = true
            pretty = true
            show_error_codes = true
            show_error_context = true
            strict = true
            warn_no_return = true
            warn_redundant_casts = true
            warn_unreachable = true
            warn_unused_ignores = true

            [tool.isort]
            profile = "black"
            line_length = 120
            combine_as_imports = true

            [tool.black]
            line-length = 120
        """,
        "LICENSE": "",
        "readme.md": """
            # {name}

        """,
        ".flake8": """
            [flake8]
            max-line-length = 120
        """,
        ".gitignore": """
            /.vscode
            /dist
            /build
            .venv/
            *.egg-info/
            __pycache__/
            poetry.lock
        """,
        "src/{path}/__init__.py": """
            __version__ = "0.1.0"
        """,
        "tests/test_import.py": """
            def test_import():
                exec("from {dotted_name} import *")
    """,
        "src/{path}/py.typed": "",
    },
    "github": {
        ".github/workflows/python-package.yml": """
            name: Python application

            on:
              push: {{ branches: [ develop ], tags: [ "*" ] }}
              pull_request: {{ branches: [ develop ] }}

            jobs:
              test:
                runs-on: ubuntu-latest
                strategy:
                  fail-fast: false
                  matrix:
                    python-version: [ "3.6", "3.7", "3.8", "3.9", "3.10", "3.x" ]
                steps:
                - uses: actions/checkout@v2
                - uses: python-slap/slap.cli@gha/install/v1
                - uses: actions/setup-python@v2
                  with: {{ python-version: "${{{{ matrix.python-version }}}}" }}
                - run: slap install -vv --no-venv-check
                - run: slap test

              update-changelog:
                runs-on: ubuntu-latest
                if: github.event_name == 'pull_request'
                steps:
                  - uses: actions/checkout@v2
                  - uses: python-slap/slap.cli@gha/changelog/update/v1
    """,
    },
}

class InitCommandPlugin(ApplicationPlugin, Command):
    """Bootstrap some files for a Python project.

    Currently available templates:

    1. <info>poetry</info>
    """

    app: Application

    name = "init"
    arguments = [
        argument(
            "directory",
            description="The directory in which to create the generated files. If not specified, a new directory with "
            "the name specified via the <opt>--name</opt> option is created.",
            optional=True,
        )
    ]
    options = [
        option(
            "--name",
            description="The name of the Python package.",
            flag=False,
        ),
        option(
            "--license",
            description="The package license.",
            flag=False,
            default="MIT",
        ),
        option(
            "--template",
            "-t",
            description="The template to use.",
            flag=False,
            default="poetry",
        ),
        option(
            "--overwrite",
            "-f",
            description="Overwrite files.",
        ),
        option(
            "--dry",
            "-d",
            description="Dont actually write files.",
        ),
        option(
            "--as-markdown",
            description="Render the content as Markdown (uses by the Slap docs)",
        ),
    ]

    def load_configuration(self, app: Application) -> None:
        return None

    def activate(self, app: Application, config: None) -> None:
        self.app = app
        app.cleo.add(self)

    def handle(self) -> int:
        from nr.util.optional import Optional

        template = self.option("template")
        if template not in TEMPLATES:
            self.line_error(f'error: template "{template}" does not exist', "error")
            return 1

        author = get_git_author()
        name = self.option("name")
        directory = (
            Optional(self.argument("directory"))
            .map(Path)
            .map(lambda v: v or (name.replace(".", "-") if name else None))
            .or_else_get(Path.cwd)
        )

        scope = {
            "license": self.option("license"),
            "year": datetime.date.today().year,
            "author_name": author.name if author and author.name else "Unknown",
            "author_email": author.email if author and author.email else "me@unknown.org",
        }
        if self.option("name"):
            scope.update(
                {
                    "name": self.option("name"),
                    "dotted_name": self.option("name").replace("-", "_"),
                    "path": self.option("name").replace(".", "/").replace("-", "_"),
                    "package": self.option("name").replace(".", "_").replace("-", "_"),
                }
            )
        for filename, content in TEMPLATES[template].items():
            if filename == "LICENSE":
                content = get_spdx_license_details(self.option("license")).license_text
                content = wrap_license_text(content).replace("<year>", str(scope["year"]))
                content = wrap_license_text(content).replace("<copyright holders>", scope["author_name"])
            else:
                filename = filename.format(**scope)
                content = textwrap.dedent(content.format(**scope)).strip()
                if content:
                    content += "\n"

            path = directory / filename

            if self.option("as-markdown"):
                print(f'```{path.suffix[1:]} title="{path}"')
                print(content, "    ")
                print(f"```\n\n")
                continue

            if path.exists() and not self.option("overwrite"):
                self.line(f"skip <info>{path}</info> (already exists)")
                continue

            if not self.option("dry") and not self.option("as-markdown"):
                path.parent.mkdir(parents=True, exist_ok=True)
                path.write_text(content)

            self.line(f"write <info>{path}</info>")

        return 0


import requests
import os
import sys

from physics import calculate

LINE_URL = 'https://api.line.me/v2/bot/message/reply'
token = os.environ.get('LINE_TOKEN')

VALID_VARIABLES = ['v', 'u', 'a', 't', 's']

class User:
    def __init__(self, userId):
        self.userId = userId
        self.reset()

    def reset(self):
        self.unknown_variable = None
        self.missing_variable = None
        self.variables_to_ask = VALID_VARIABLES.copy()

        # for calculation
        self.variables = {}

    def ask_for_unknown(self, replyToken):
        self.reply(replyToken, 'กรุณาใส่ตัวแปรที่ท่านต้องการหา', VALID_VARIABLES)

    def ask_for_missing(self, replyToken):
        self.reply(replyToken, 'กรุณาใส่ตัวแปรที่ไม่มีอยู่ในโจทย์', self.variables_to_ask)

    def converse(self, replyToken, text):
        if self.unknown_variable is None:
            if text in VALID_VARIABLES:
                self.unknown_variable = text
                self.variables_to_ask.remove(self.unknown_variable)
            else:
                self.ask_for_unknown(replyToken)
                return

        if self.missing_variable is None:
            if text in self.variables_to_ask:
                self.missing_variable = text
                self.variables_to_ask.remove(self.missing_variable)
            else:
                self.ask_for_missing(replyToken)
                return

        if len(self.variables_to_ask) != 0:
            variable = self.variables_to_ask[0]
            if text.isnumeric():
                value = float(text)
                self.variables_to_ask.remove(variable)
                self.variables[variable] = value

                if len(self.variables_to_ask) != 0:
                    self.reply(replyToken, self.variables_to_ask[0] + ' = ?')
                    return
            else:
                self.reply(replyToken, variable + ' = ?')
                return

        try:
            answer = calculate(self.unknown_variable, self.missing_variable, self.variables)
            reply = 'คำตอบของท่านคือ ' + self.unknown_variable + ' = ' + answer + '\n'
            link = 'https://fequalsma.herokuapp.com/graph?a={a}&u={u}&t={t}'.format(**self.variables)
            reply += link
            self.reply(replyToken, reply)
        except Exception as e:
            self.reply(replyToken, 'Something went wrong!')
        self.reset()

    def create_quickReply_item(self, option):
        return {\
            'type': 'action',\
            'action': {\
                'type': 'message',\
                'label': option,\
                'text': option\
            }\
        }

    def reply(self, replyToken, text, options=[]):
        body = {}
        body['replyToken'] = replyToken
        body['messages'] = [{ 'type': 'text', 'text': text }]

        if len(options) != 0:
            quickReply = { 'items': [] }

            for option in options:
                quickReply['items'].append(self.create_quickReply_item(option))

            body['messages'][0]['quickReply'] = quickReply

        headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token }
        req = requests.post(LINE_URL, json=body, headers=headers)


import ply.lex as lex

# List of token names.   This is always required
reserved = {
    'if': 'IF',
    'then': 'THEN',
    'else': 'ELSE',
    'while': 'WHILE',
    "switch": "SWITCH",
    'bool': "BOOL",
    'char': "CHAR",
    'byte': "BYTE",
    'short': "SHORT",
    'int': "INT",
    'long': "LONG",
    'double': "DOUBLE",
    'float': "FLOAT",
    'main': "MAIN",
    'class': "CLASS",
    'pub': "PUBLIC",
    'pri': "PRIVATE",
    'pro ': "PROTECTED",
    'static': "STATIC"
}

# (?i) - case insensitive

tokens = [
             'NUMBER',
             'PLUS',
             'MINUS',
             'TIMES',
             'DIVIDE',
             'ID',
             'COMMENT',
             'NEWLINE'
         ] + list(reserved.values())

# Regular expression rules for simple tokens

t_PLUS = r'\+'
t_MINUS = r'-'
t_TIMES = r'\*'
t_DIVIDE = r'/'

literals = [';', '=', '(', ')', '{', '}', ',']

# A regular expression rule with some action code
def t_NUMBER(t):
    r'\d+'
    t.value = int(t.value)
    return t

# Define a rule so we can track line numbers
def t_NEWLINE(t):
    r'\n+'
    t.lexer.lineno += len(t.value)

# A string containing ignored characters (spaces and tabs)
t_ignore = ' \t'

# Error handling rule
def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

def t_ID(t):
    r'[a-zA-Z_][a-zA-Z_0-9]*'
    t.type = reserved.get(t.value, 'ID')  # Check for reserved words
    return t

def t_COMMENT(t):
    r'\//.*'
    pass

# Build the lexer
lexer = lex.lex()

# Test it out
data = '''
3 + 4 * 10
  + -20 *2
  if
  //
'''

# Give the lexer some input
lexer.input(data)

# # Tokenize
# for tok in lexer:
#     print(tok.type, tok.value, tok.lineno, tok.lexpos)


#1 wala issue
import json
import pprint
import collections
import operator
import pandas as pd
import csv
import math
from collections import defaultdict
import networkx as nx

csv_file = open('article-ids.csv')
csv_reader = csv.reader(csv_file,delimiter = ',')
aid = {}

for row in csv_reader:
    if row[0] == "Article_Name":
        continue
    aid[row[0]] = row[1]

csv_file = open('category-ids.csv')
csv_reader = csv.reader(csv_file,delimiter = ',')
cid = {}
cid2 = {}

for row in csv_reader:
    if row[0] == "Category_Name":
        continue
    cid[row[0]] = row[1]
    cid2[row[1]] = row[0]

csv_file = open('article-categories.csv')
csv_reader = csv.reader(csv_file,delimiter = ',')
acid = {}
for row in csv_reader:
    if row[0] == "Article ID":
        continue
    lis = row[1].split(" ")
    acid[row[0]] = lis

G = nx.DiGraph()
csv_file = open('edges.csv')
csv_reader = csv.reader(csv_file,delimiter = ',')

for row in csv_reader:
    if row[0] == "From_ArticleID":
        continue
    x = (row[0],row[1])
    G.add_edge(*x)

sample = open('temp4','r')
lines = sample.readlines()

catnp = {}
catnt = {}
catsp = {}
catst = {}
catnp = defaultdict(lambda:0,catnp)
catnt = defaultdict(lambda:0,catnt)
catsp = defaultdict(lambda:0,catsp)
catst = defaultdict(lambda:0,catst)

for line in lines:
    done = []
    done2 = []
    a = line[:-1]
    lis = a.split(";")
    stack = []
    for key in lis:
        if key == '<' :
            stack.pop()
        else:
            stack.append(aid[key])
    f = stack[0]
    l = stack[-1]
    if f != l:
        try:
            short = nx.shortest_path(G,f,l)
        except:
            continue

        for key in stack:
            if key in acid:
                for cats in acid[key]:
                    a = cid2[cats]
                    n = a.count('.') +1
                    for i in range(1,n):
                        k = ".".join(a.split(".", i)[:i])
                        cat = cid[k]
                        if cat not in done:
                            catnp[cat] = catnp[cat] + 1
                            done.append(cat)
                        catnt[cat] = catnt[cat] + 1
                    if cats not in done:
                        catnp[cats] = catnp[cats] + 1
                        done.append(cats)
                    catnt[cats] = catnt[cats] + 1

        for key in short:
            if key in acid:
                for cats in acid[key]:
                    a = cid2[cats]
                    n = a.count('.') +1
                    for i in range(1,n):
                        k = ".".join(a.split(".", i)[:i])
                        cat = cid[k]
                        if cat not in done2:
                            catsp[cat] = catsp[cat] + 1
                            done2.append(cat)
                        catst[cat] = catst[cat] + 1
                    if cats not in done2:
                        catsp[cats] = catsp[cats] + 1
                        done2.append(cats)
                    catst[cats] = catst[cats] + 1

sd = open('category-subtree-paths.csv','w')
print('Category_ID,Number_of_human_paths_traversed,Number_of_human_times_traversed,Number_of_shortest_paths_traversed,Number_of_shortest_times_traversed',file=sd)

for i in range(1,147):
    key = "C" + "{:04n}".format(i)
    if key in catsp.keys():
        print(key,catnp[key],catnt[key],catsp[key],catst[key],sep=",",file =sd)
    else:
        print(key,0,0,0,0,sep=",",file =sd)


from PyQt5.QtCore import QSize, Qt
from PyQt5.QtWidgets import QLabel, QPushButton, QFrame, QWidget, QVBoxLayout, QHBoxLayout
from PyQt5.QtGui import *
from modules.codeeditor import CodeEditor

def add(self):
	# Creacion del tab
	tab = QFrame(self.ui.pages)
	tab.setObjectName(u"file_"+str(self.tab_number))
	tab.setMinimumHeight(45)
	tab.setMaximumHeight(45)
	tab.setFrameShape(QFrame.StyledPanel)
	tab.setFrameShadow(QFrame.Raised)
	tab.setToolTip("Nuevo archivo *")
	tab.mousePressEvent = lambda x: self.change_actual(None, tab)

	file_layout = QHBoxLayout(tab)
	file_layout.setSpacing(0)
	file_layout.setObjectName(u"file_layout_"+str(self.tab_number))
	file_layout.setContentsMargins(4, 0, 5, 0)

	title = QLabel("Nuevo archivo *", tab)
	title.setObjectName(u"title_"+str(self.tab_number))

	btn_close = QPushButton(tab)
	btn_close.setObjectName(u"btn_close_"+str(self.tab_number))
	btn_close.setMinimumSize(QSize(28, 28))
	btn_close.setMaximumSize(QSize(28, 28))
	btn_close.setCursor(QCursor(Qt.PointingHandCursor))
	btn_close.clicked.connect(lambda: remove(self))

	file_layout.addWidget(title)
	file_layout.addWidget(btn_close)
	self.ui.Layout_pages.addWidget(tab)

	self.stacked_tabs.append(tab)

	# Creacion del text box
	widget = QWidget()
	widget.setObjectName(u"page_"+str(self.tab_number))
	# creacion del layout
	widget_layout = QVBoxLayout(widget)
	widget_layout.setSpacing(0)
	widget_layout.setObjectName(u"widget_layout_"+str(self.tab_number))
	widget_layout.setContentsMargins(0, 0, 0, 0)
	# Creacion del textbox
	textbox = CodeEditor(widget)
	textbox.setObjectName(u"document_"+str(self.tab_number))
	textbox.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

	widget_layout.addWidget(textbox)

	self.ui.stackedWidget.addWidget(widget)

	self.tab_number += 1

def remove(self):
	#verificar si el archivo se ha guardado

	# obtengo el indice del tab a eliminar
	number_actual = self.sender().objectName().split("_")[-1]

	# Elimino el tab
	tab = self.ui.top.findChild(QFrame, "file_"+number_actual)
	tab.deleteLater()
	#elimino la pagina textbox
	page = self.ui.stackedWidget.findChild(QWidget, "page_"+number_actual)
	page.deleteLater()
	# remuevo el tab del stack
	self.stacked_tabs.remove(tab)

	# si mi stack se quedo sin tab debe cerrar la ventana
	if len(self.stacked_tabs) == 0:
		self.close()
		return

	# verifico si el ultimo tab seleccionado es el mismo al que se desea eliminar
	number_before = self.before_select.objectName().split("_")[-1]
	# si es asi, entonces elimino la referencia al tab
	if number_actual == number_before:
		# Cambiar el tab seleccionado
		self.change_actual(None, self.stacked_tabs[0])
		self.before_select = self.stacked_tabs[0]


from django.shortcuts import render, get_object_or_404, redirect
from recipes.models import Recipe
from recipes.forms import RecipeForm

# SHOW_RECIPE
def show_recipe(request, id):
    recipe = get_object_or_404(Recipe, id=id)
    context = {
        "recipe_object": recipe,
    }
    return render(request, "recipes/detail.html", context)

# RECIPE_LIST
def recipe_list(request):
    recipes = Recipe.objects.all()
    context = {
        "recipe_list": recipes,
    }
    return render(request, "recipes/list.html", context)

# CREATE_RECIPE
def create_recipe(request):
    if request.method == "POST":
        form = RecipeForm(request.POST)

        if form.is_valid():
            form.save()
            return redirect("recipe_list")
    else:
        form = RecipeForm()

    context = {
        "form": form,
    }

    return render(request, "recipes/create.html", context)

# EDIT_RECIPE
def edit_recipe(request, id):
    recipe = get_object_or_404(Recipe, id=id)

    if request.method == "POST":
        form = RecipeForm(request.POST, instance=recipe)
        if form.is_valid():
            form.save()

            return redirect("show_recipe", id=id)

    else:
        form = RecipeForm(instance=recipe)

    context = {
        "recipe_object": recipe,
        "form": form,
    }
    return render(request, "recipes/edit.html", context)


from __future__ import division
from __future__ import print_function
import tensorflow as tf

from tensorflow.keras.layers import Lambda, Dense, TimeDistributed, Input
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing import image
import tensorflow.keras.backend as K

from vgg16 import VGG16
from RoiPooling import RoiPooling
from get_regions import rmac_regions, get_size_vgg_feat_map

import scipy.io
import numpy as np
import utils

from dataset import generate_data
import time
import pandas as pd
import re
import os

from PIL import Image

flags = tf.compat.v1.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data', 'mnist', 'dataset')
flags.DEFINE_float('start', 0.0, 'starting file')
flags.DEFINE_float('end',  1.0, 'end_file')
flags.DEFINE_string('prefix', '/rds/general/user/emuller/home/emily/phd/', 'when using RDS')

start = np.float(FLAGS.start)
end = np.float(FLAGS.end)

def addition(x):
    sum = K.sum(x, axis=1)
    return sum

def weighting(input):
    x = input[0]
    w = input[1]
    w = K.repeat_elements(w, 512, axis=-1)
    out = x * w
    return out

def rmac(input_shape, num_rois):

    # Load VGG16
    model = tf.keras.applications.vgg16.VGG16(include_top = False, input_shape=input_shape)
    #img_input = Input(shape=input_shape)
    vgg16_model = tf.keras.models.Model(inputs=model.input, outputs=model.output)
    #vgg16_model = VGG16(utils.DATA_DIR + utils.WEIGHTS_FILE, input_shape)

    # Regions as input
    in_roi = Input(shape=(num_rois, 4), name='input_roi')

    # ROI pooling
    x = RoiPooling([1], num_rois)([vgg16_model.layers[-1].output, in_roi])

    # Normalization
    x = Lambda(lambda x: K.l2_normalize(x, axis=2), name='norm1')(x)

    # PCA
    x = TimeDistributed(Dense(512, name='pca',
                              kernel_initializer='identity',
                              bias_initializer='zeros'))(x)

    # Normalization
    x = Lambda(lambda x: K.l2_normalize(x, axis=2), name='pca_norm')(x)

    # Addition
    rmac = Lambda(addition, output_shape=(512,), name='rmac')(x)

    # # Normalization
    rmac_norm = Lambda(lambda x: K.l2_normalize(x, axis=1), name='rmac_norm')(rmac)

    # Define model
    model = Model([vgg16_model.input, in_roi], rmac_norm)
    print (model.summary())
    # Load PCA weights
    mat = scipy.io.loadmat(FLAGS.prefix + '003_image_matching/keras_rmac-master/' + utils.DATA_DIR + utils.PCA_FILE)
    b = np.squeeze(mat['bias'], axis=1)
    w = np.transpose(mat['weights'])
    model.layers[-4].set_weights([w, b])

    return model

def preprocess(img):
    (left, upper, right, lower) = (137, 132, 505, 500)
    # Here the image "im" is cropped and assigned to new variable im_crop
    img_crop = img.crop((left, upper, right, lower))
    img_crop = img_crop.resize((640,640),Image.BICUBIC)
    return img_crop
# if __name__ == "__main__":

    # # Load sample image
    # # file = utils.DATA_DIR + 'sample.jpg'
    # img = image.load_img(file)

#     # Resize
    # scale = utils.IMG_SIZE / max(img.size)
    # new_size = (int(np.ceil(scale * img.size[0])), int(np.ceil(scale * img.size[1])))
    # print('Original size: %s, Resized image: %s' %(str(img.size), str(new_size)))

    # img = img.resize(new_size)

    # # Mean substraction
    # x = image.img_to_array(img)
    # x = np.expand_dims(x, axis=0)
#     x = utils.preprocess_image(x)

#     # Load RMAC model
#     Wmap, Hmap = get_size_vgg_feat_map(x.shape[3], x.shape[2])
#     regions = rmac_regions(Wmap, Hmap, 3)
#     print('Loading RMAC model...')
#     model = rmac((x.shape[1], x.shape[2], x.shape[3]), len(regions))

#     # Compute RMAC vector
#     print('Extracting RMAC from image...')
#     RMAC = model.predict([x, np.expand_dims(regions, axis=0)])
#     print('RMAC size: %s' % RMAC.shape[1])
#     print('Done!')
path = FLAGS.data
files = os.listdir(path)
n = len(files)
corrupts = []

start_time = time.time()
if __name__ == "__main__":

    # Load sample image
    #dataset = FLAGS.data

    img_dim = 640
    K.set_image_data_format('channels_last')
    #ds, ds_test, img_dim_, files = generate_data(dataset, img_dim, 1, subset=(None, None), shuffle=False)
    K.set_image_data_format('channels_first')
    encoded_images = {}
    counter = 0
    for i in range(int(np.floor(n*start)), int(np.ceil(n*end))):
    #for img in ds:
        try:
            # for running with PIL
            img = Image.open(path + '/' + files[i])
            img = preprocess(img)
            name = files[i][:-4]
            img = np.array(img)
            img = np.expand_dims(img, axis=0)
            img = tf.transpose(img, [0, 3, 1, 2]).numpy()
            img = img.astype('float32')
            x = utils.preprocess_image(img)

            # Load RMAC model
            if counter == 0:
                Wmap, Hmap = get_size_vgg_feat_map(x.shape[3], x.shape[2])
                regions = rmac_regions(Wmap, Hmap, 3)
                model = rmac((x.shape[1], x.shape[2], x.shape[3]), len(regions))
            else:
                pass

            # Compute RMAC vector
            RMAC = model.predict([x, np.expand_dims(regions, axis=0)])

            encoded_images[name] = [RMAC]
        except:
            corrupts.append(files[i])
        counter += 1
        if counter % 10000 == 0:
            encoded = pd.DataFrame(encoded_images).T
            encoded.to_csv(FLAGS.prefix + '003_image_matching/keras_rmac-master/census2021outputs/census2011_zoom_rmac_feature_vector_zoom_%s.csv' % str(FLAGS.end))
            print('Completed image %s in %s seconds!' % (str(counter) + '_' + name, str(time.time() - start_time) ))
            print ('There are %s corrupt files' %len(corrupts))

encoded = pd.DataFrame(encoded_images).T
encoded.to_csv(FLAGS.prefix + '003_image_matching/keras_rmac-master/census2021outputs/census2011_zoom_rmac_feature_vector_zoom_%s.csv' % str(FLAGS.end))
print (corrupts)


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

import os

HERE = os.path.dirname(os.path.abspath(__file__))

# We setup the cache for Chameleon templates
template_cache = os.path.join(HERE, 'cache')
if not os.path.exists(template_cache):
    os.makedirs(template_cache)
os.environ["CHAMELEON_CACHE"] = template_cache

# Bootstrapping the Crom registry
from crom import monkey, implicit
monkey.incompat()
implicit.initialize()

# Read the ZCML
# This is not a mandatory stage.
# Actually, what the ZCML loading does is grok the packages
# This can be done manually, using `crom.configure`
from cromlech.configuration.utils import load_zcml
load_zcml(os.path.join(HERE, 'app.zcml'))

# Load translation
# This is needed only if we want internationalization
from cromlech.i18n import load_translations_directories
load_translations_directories()

# Adding the event dispatcher
# Use only if you have event handlers or plan to have some.
from cromlech.events import setup_dispatcher
setup_dispatcher()

def populate_db(db):
    """We create two leaves here.. We get the DB connection object.
    We need to open and to close it. It doesn't need to return anything.
    Make sure to use a transaction manager to have it correctly persisted.
    """
    import transaction
    from cromdemo.models import RootCategory, Category, Item
    from cromlech.zodb import Connection

    with Connection(db, transaction_manager=transaction.manager) as conn:
        conn = db.open()
        root = conn.root()
        if not hasattr(root,'appRoot'):
            appRoot=RootCategory()
            appRoot.__name__='root'
            root.appRoot=appRoot
            category = Category(title='Tree Leaves',
                        body='Tree Leaves go in this category')
            appRoot['Leaves'] =category
            category['greenLeaf'] = Item(title='Green Leaf',
                                        body='A summer leaf')
            category['redLeaf'] = Item(title='Red leaf',
                                      body='A fall leaf')

            category = Category(title='Cars',
                        body='Cars go in this category')
            appRoot['Cars'] =category
            category['Ford'] = Item(title='Ford Escort',
                                        body='A boring Ford')
            category['Ferrari'] = Item(title='Ferrari',
                                      body='An Exciting Ferari')
            transaction.manager.commit()

# We read the zodb conf and initialize it
from cromlech.zodb import init_db
with open('zodb.conf', 'r') as fd:
        zodb_config = fd.read()
        db = init_db(zodb_config)
        populate_db(db)

# Getting the crypto key and creating the JWT service
# We chose the JWT signed cookie for the demo
# `cromlech.sessions` proposed different backends.
# Or you can use the WSGI session middleware of your choice.
from cromlech.sessions.jwt import key_from_file
from cromlech.sessions.jwt import JWTCookieSession

key = key_from_file(os.path.join(HERE, 'jwt.key'))
session_wrapper = JWTCookieSession(key, 300)

# Create the application, including the middlewares.
from cromdemo.wsgi import demo_application
from cromlech.zodb.middleware import ZODBApp
from fanstatic import Fanstatic
zodb_application = ZODBApp(demo_application, db, key="zodb.connection")
fanstatic_app = Fanstatic(zodb_application)
application = session_wrapper(fanstatic_app)


import pathlib
import os
from setuptools import setup, find_packages

UPSTREAM_URLLIB3_FLAG = "--with-upstream-urllib3"

def get_requirements(raw=False):
    """Build the requirements list for this project"""
    requirements_list = []

    with open("requirements.txt") as reqs:
        for install in reqs:
            if install.startswith("# only telegram.ext:"):
                if raw:
                    break
                continue
            requirements_list.append(install.strip())

    return requirements_list

def get_packages_requirements(raw=False):
    """Build the package & requirements list for this project"""
    reqs = get_requirements(raw=raw)
    exclude = ["tests*"]
    packs = find_packages(exclude=exclude)
    return packs, reqs

packages, requirements = get_packages_requirements()
# The directory containing this file
HERE = pathlib.Path(__file__).parent

# The text of the README file
README = (HERE / "README.md").read_text()

def read(rel_path: str) -> str:
    here = os.path.abspath(os.path.dirname(__file__))
    # intentionally *not* adding an encoding option to open, See:
    #   https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690
    with open(os.path.join(here, rel_path)) as fp:
        return fp.read()

def get_version(rel_path):
    for line in read(rel_path).splitlines():
        if line.startswith("__version__"):
            delim = '"' if '"' in line else "'"
            return line.split(delim)[1]
    else:
        raise RuntimeError("Unable to find version string.")

# This call to setup() does all the work
# circle bracket and format in the download_url parameter to resolve linting issue
# of line too long
setup(
    name="polly-python",
    version=get_version("polly/__init__.py"),
    description="Polly SDK",
    long_description=README,
    long_description_content_type="text/markdown",
    packages=packages,
    include_package_data=True,
    setup_requires=["wheel"],
    install_requires=requirements,
    url="https://github.com/ElucidataInc/polly-python",
    download_url=(
        "https://elucidatainc.github.io/PublicAssets/builds/polly-python/"
        "polly_python-{a}-none-any.whl".format(a=get_version("polly/__init__.py"))
    ),
)


from unittest.mock import Mock, patch

import botocore.session
from botocore.exceptions import ParamValidationError
from moto import (  # pylint: disable=import-error
    mock_ec2,
    mock_kinesis,
    mock_kms,
    mock_lambda,
    mock_s3,
    mock_sqs,
)

from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.test.test_base import TestBase

def assert_span_http_status_code(span, code):
    """Assert on the span"s "http.status_code" tag"""
    tag = span.attributes["http.status_code"]
    assert tag == code, "%r != %r" % (tag, code)

class TestBotocoreInstrumentor(TestBase):
    """Botocore integration testsuite"""

    def setUp(self):
        super().setUp()
        BotocoreInstrumentor().instrument()

        self.session = botocore.session.get_session()
        self.session.set_credentials(
            access_key="access-key", secret_key="secret-key"
        )

    def tearDown(self):
        super().tearDown()
        BotocoreInstrumentor().uninstrument()

    @mock_ec2
    def test_traced_client(self):
        ec2 = self.session.create_client("ec2", region_name="us-west-2")

        ec2.describe_instances()

        spans = self.memory_exporter.get_finished_spans()
        assert spans
        span = spans[0]
        self.assertEqual(len(spans), 1)
        self.assertEqual(span.attributes["aws.agent"], "botocore")
        self.assertEqual(span.attributes["aws.region"], "us-west-2")
        self.assertEqual(span.attributes["aws.operation"], "DescribeInstances")
        assert_span_http_status_code(span, 200)
        self.assertEqual(
            span.resource,
            Resource(
                attributes={
                    "endpoint": "ec2",
                    "operation": "describeinstances",
                }
            ),
        )
        self.assertEqual(span.name, "ec2.command")

    @mock_ec2
    def test_not_recording(self):
        mock_tracer = Mock()
        mock_span = Mock()
        mock_span.is_recording.return_value = False
        mock_tracer.start_span.return_value = mock_span
        mock_tracer.use_span.return_value.__enter__ = mock_span
        mock_tracer.use_span.return_value.__exit__ = True
        with patch("opentelemetry.trace.get_tracer") as tracer:
            tracer.return_value = mock_tracer
            ec2 = self.session.create_client("ec2", region_name="us-west-2")
            ec2.describe_instances()
            self.assertFalse(mock_span.is_recording())
            self.assertTrue(mock_span.is_recording.called)
            self.assertFalse(mock_span.set_attribute.called)
            self.assertFalse(mock_span.set_status.called)

    @mock_ec2
    def test_traced_client_analytics(self):
        ec2 = self.session.create_client("ec2", region_name="us-west-2")
        ec2.describe_instances()

        spans = self.memory_exporter.get_finished_spans()
        assert spans

    @mock_s3
    def test_s3_client(self):
        s3 = self.session.create_client("s3", region_name="us-west-2")

        s3.list_buckets()
        s3.list_buckets()

        spans = self.memory_exporter.get_finished_spans()
        assert spans
        span = spans[0]
        self.assertEqual(len(spans), 2)
        self.assertEqual(span.attributes["aws.operation"], "ListBuckets")
        assert_span_http_status_code(span, 200)
        self.assertEqual(
            span.resource,
            Resource(
                attributes={"endpoint": "s3", "operation": "listbuckets"}
            ),
        )

        # testing for span error
        self.memory_exporter.get_finished_spans()
        with self.assertRaises(ParamValidationError):
            s3.list_objects(bucket="mybucket")
        spans = self.memory_exporter.get_finished_spans()
        assert spans
        span = spans[2]
        self.assertEqual(
            span.resource,
            Resource(
                attributes={"endpoint": "s3", "operation": "listobjects"}
            ),
        )

    # Comment test for issue 1088
    @mock_s3
    def test_s3_put(self):
        params = dict(Key="foo", Bucket="mybucket", Body=b"bar")
        s3 = self.session.create_client("s3", region_name="us-west-2")
        location = {"LocationConstraint": "us-west-2"}
        s3.create_bucket(Bucket="mybucket", CreateBucketConfiguration=location)
        s3.put_object(**params)

        spans = self.memory_exporter.get_finished_spans()
        assert spans
        span = spans[0]
        self.assertEqual(len(spans), 2)
        self.assertEqual(span.attributes["aws.operation"], "CreateBucket")
        assert_span_http_status_code(span, 200)
        self.assertEqual(
            span.resource,
            Resource(
                attributes={"endpoint": "s3", "operation": "createbucket"}
            ),
        )
        self.assertEqual(spans[1].attributes["aws.operation"], "PutObject")
        self.assertEqual(
            spans[1].resource,
            Resource(attributes={"endpoint": "s3", "operation": "putobject"}),
        )
        self.assertEqual(spans[1].attributes["params.Key"], str(params["Key"]))
        self.assertEqual(
            spans[1].attributes["params.Bucket"], str(params["Bucket"])
        )
        self.assertTrue("params.Body" not in spans[1].attributes.keys())

    @mock_sqs
    def test_sqs_client(self):
        sqs = self.session.create_client("sqs", region_name="us-east-1")

        sqs.list_queues()

        spans = self.memory_exporter.get_finished_spans()
        assert spans
        span = spans[0]
        self.assertEqual(len(spans), 1)
        self.assertEqual(span.attributes["aws.region"], "us-east-1")
        self.assertEqual(span.attributes["aws.operation"], "ListQueues")
        assert_span_http_status_code(span, 200)
        self.assertEqual(
            span.resource,
            Resource(
                attributes={"endpoint": "sqs", "operation": "listqueues"}
            ),
        )

    @mock_kinesis
    def test_kinesis_client(self):
        kinesis = self.session.create_client(
            "kinesis", region_name="us-east-1"
        )

        kinesis.list_streams()

        spans = self.memory_exporter.get_finished_spans()
        assert spans
        span = spans[0]
        self.assertEqual(len(spans), 1)
        self.assertEqual(span.attributes["aws.region"], "us-east-1")
        self.assertEqual(span.attributes["aws.operation"], "ListStreams")
        assert_span_http_status_code(span, 200)
        self.assertEqual(
            span.resource,
            Resource(
                attributes={"endpoint": "kinesis", "operation": "liststreams"}
            ),
        )

    @mock_kinesis
    def test_unpatch(self):
        kinesis = self.session.create_client(
            "kinesis", region_name="us-east-1"
        )

        BotocoreInstrumentor().uninstrument()

        kinesis.list_streams()
        spans = self.memory_exporter.get_finished_spans()
        assert not spans, spans

    @mock_sqs
    def test_double_patch(self):
        sqs = self.session.create_client("sqs", region_name="us-east-1")

        BotocoreInstrumentor().instrument()
        BotocoreInstrumentor().instrument()

        sqs.list_queues()

        spans = self.memory_exporter.get_finished_spans()
        assert spans
        self.assertEqual(len(spans), 1)

    @mock_lambda
    def test_lambda_client(self):
        lamb = self.session.create_client("lambda", region_name="us-east-1")

        lamb.list_functions()

        spans = self.memory_exporter.get_finished_spans()
        assert spans
        span = spans[0]
        self.assertEqual(len(spans), 1)
        self.assertEqual(span.attributes["aws.region"], "us-east-1")
        self.assertEqual(span.attributes["aws.operation"], "ListFunctions")
        assert_span_http_status_code(span, 200)
        self.assertEqual(
            span.resource,
            Resource(
                attributes={"endpoint": "lambda", "operation": "listfunctions"}
            ),
        )

    @mock_kms
    def test_kms_client(self):
        kms = self.session.create_client("kms", region_name="us-east-1")

        kms.list_keys(Limit=21)

        spans = self.memory_exporter.get_finished_spans()
        assert spans
        span = spans[0]
        self.assertEqual(len(spans), 1)
        self.assertEqual(span.attributes["aws.region"], "us-east-1")
        self.assertEqual(span.attributes["aws.operation"], "ListKeys")
        assert_span_http_status_code(span, 200)
        self.assertEqual(
            span.resource,
            Resource(attributes={"endpoint": "kms", "operation": "listkeys"}),
        )

        # checking for protection on sts against security leak
        self.assertTrue("params" not in span.attributes.keys())


import torch
import torchreid
import tensorrt as trt

# Load pre-trained OSNet model with x0.25 width multiplier
model_name = 'osnet_x0_25'
model = torchreid.models.build_model(
    name=model_name,
    num_classes=1000,
    pretrained=True
)

# Create example input tensor
data_shape = (3, 256, 128)
input_tensor = torch.randn(1, *data_shape)

# Build TensorRT engine
engine_file_path = f'{model_name}.engine'
with trt.Logger(trt.Logger.INFO) as logger:
    with trt.Builder(logger) as builder, builder.create_network() as network:
        # Configure builder
        config = builder.create_builder_config()
        config.max_workspace_size = 1 << 30  # 1 GB
        builder.max_batch_size = 1

        # Create input tensor
        input_tensor_trt = network.add_input(
            name='input',
            dtype=trt.float32,
            shape=(3, 256, 128)
        )

        # Convert PyTorch model to TensorRT engine
        model_trt = torchreid.engine.build_engine(
            model=model,
            data_shape=data_shape,
            fp16_mode=True,
            engine_file_path=engine_file_path,
            builder=builder,
            config=config
        )

        # Create output tensor
        output_tensor_trt = model_trt(input_tensor_trt)

        # Add output tensor to network
        network.mark_output(
            name='output',
            tensor=output_tensor_trt
        )

        # Build engine
        engine = builder.build_cuda_engine(network)

        # Save engine
        with open(engine_file_path, 'wb') as f:
            f.write(engine.serialize())