import os
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required

from .forms import TaskForm

from .models import Task

@login_required
def list_tasks(request):
    if request.method == 'GET':
        context = {}
        return render(request, os.path.join('asana', 'tasks', 'index.html'), context)

    if request.method == 'POST':
        form = TaskForm(request.POST)

        if form.is_valid():
            task = form.save()
            return redirect('asana:tasks:view', task_id=task.id)

        context = {'form': form}
        return render(request, os.path.join('asana', 'tasks', 'create.html'), context)

@login_required
def create_task(request):
    if request.method == 'GET':
        context = {
            'form': TaskForm()
        }
        return render(request, os.path.join('asana', 'tasks', 'create.html'), context)

@login_required
def view_task(request, task_id):
    if request.method == 'GET':
        context = {
            'task': get_object_or_404(Task, pk=task_id)
        }
        return render(request, os.path.join('asana', 'tasks', 'view.html'), context)

    if request.method == 'PUT':
        context = {}
        return render(request, os.path.join('asana', 'tasks', 'view.html'), context)


import numpy as np
import tensorflow as tf
import tqdm

from flearn.utils.model_utils import batch_data, batch_data_multiple_iters
from flearn.utils.tf_utils import graph_size
from flearn.utils.tf_utils import process_grad
from flearn.models.base_model import BaseModel

class Model(BaseModel):
    '''
    Assumes that images are 28px by 28px
    '''

    def __init__(self, num_classes, optimizer, options, seed=1):
        # params
        self.num_classes = num_classes
        super(Model, self).__init__(optimizer=optimizer, seed=seed, options=options)

    def create_model(self):
        """Model function for Logistic Regression."""
        features = tf.placeholder(tf.float32, shape=[None, 784], name='features')
        labels = tf.placeholder(tf.int64, shape=[None,], name='labels')
        logits = tf.layers.dense(inputs=features, units=self.num_classes, kernel_regularizer=tf.contrib.layers.l2_regularizer(0.001))
        predictions = {
            "classes": tf.argmax(input=logits, axis=1),
            "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
            }
        loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

        grads_and_vars = self.optimizer.compute_gradients(loss)
        grads, _ = zip(*grads_and_vars)
        train_op = self.optimizer.apply_gradients(grads_and_vars, global_step=tf.train.get_global_step())
        eval_metric_ops = tf.count_nonzero(tf.equal(labels, predictions["classes"]))
        return features, labels, train_op, grads, eval_metric_ops, loss


from django import forms
from crispy_forms.helper import FormHelper
from .models import SuscripcionUsuario, Suscripcion

# Register your models here.

class SuscripcionUsuarioIngresoForm(forms.ModelForm):

    nombre = forms.CharField(label='nombre',widget=forms.TextInput(
        attrs={'class':'form-control', 'placeholder': 'Nombre'}
    ))

    apellido = forms.CharField(label='nombre',widget=forms.TextInput(
        attrs={'class':'form-control', 'placeholder': 'Apellido'}
    ))

    email = forms.EmailField(widget=forms.EmailInput(
        attrs={'class':'form-control', 'placeholder': ' Email'}
    ))

    telefono = forms.CharField(label='nombre',widget=forms.TextInput(
        attrs={'class':'form-control', 'placeholder': 'Teléfono'}
    ))

    ciudad = forms.CharField(label='nombre',widget=forms.TextInput(
        attrs={'class':'form-control', 'placeholder': 'Ciudad'}
    ))

    helper = FormHelper()
    helper.form_show_labels = False

    class Meta:
        model = SuscripcionUsuario
        fields = ['nombre', 'apellido','email','telefono','f_nacimiento','ciudad']
        widgets = {
            'f_nacimiento': forms.DateInput(attrs={'class': 'datepicker', 'placeholder': 'Fecha de Nacimiento'}),
        }

        def clean_email(self):
            email = self.clean_data.get('email')

            return email

class SuscripcionCreacionForm(forms.ModelForm):
    class Meta:
        model = Suscripcion
        fields = ['subject','body','email', 'status']


#!/usr/bin/env python3

import rospy
import mavros
from geometry_msgs.msg import PoseStamped
from mavros_msgs.msg import *
from mavros_msgs.srv import *

import pprint
import networkx as nx
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
from ayush.second_step_on_vertex_visit import second_step_on_vertex_visit
from ayush.initialize_graph import Robot,Vertex, build_graph, find_shortest_path
from ayush.first_step_on_vertex_visit import Id,what_to_do_if_next_node_known,first_step_on_arriving_at_vertex
from ayush.get_incidence_matrix import get_incidence_matrix
from ayush.order_matrix import completed,out,unexplored
pp = pprint.PrettyPrinter(indent=8)

spawn_location = [-24.1095,284.1490,8.63479,
                  -22.5968,284.1330,8.63479,
                  -21.0750,283.9410,8.63479,
                  -24.1239,282.6820,8.63479,
                  -23.0024,282.5940,8.63479,
                  -22.1617,282.5870,8.63479,
                  -21.0457,282.5580,8.63479,
                  -24.1631,281.1710,8.63479,
                  -22.5350,281.0980,8.63479,
                  -20.9154,281.1750,8.63479
                  ]
# callback method for state sub
current_state = State()
offb_set_mode = SetMode
new_pose = PoseStamped()

def state_cb(state):
    global current_state
    current_state = state

def position_cb(Pose):
    global new_pose
    new_pose = Pose

local_pos_pub = rospy.Publisher('uav5/mavros/setpoint_position/local', PoseStamped, queue_size=1)

rospy.Subscriber('uav5/mavros/state', State, state_cb)
rospy.Subscriber('uav5/mavros/local_position/pose', PoseStamped, position_cb)

#state_sub = rospy.Subscriber(mavros.get_topic('uav1','state'), State, state_cb)
arming_client = rospy.ServiceProxy('uav5/mavros/cmd/arming', mavros_msgs.srv.CommandBool)
set_mode_client = rospy.ServiceProxy('uav5/mavros/set_mode', mavros_msgs.srv.SetMode)

pose = PoseStamped()
#Leaf node cordinates with elevation
pose.pose.position.x = spawn_location[15]             #CHANGE TODO # Hover over spawn location # personal
pose.pose.position.y = spawn_location[16]
pose.pose.position.z = spawn_location[17] + 6

threshold = 0.1

# ANIMATION FUNCTION
def func(num, dataSet, line, redDots):
    # NOTE: there is no .set_data() for 3 dim data...
    line.set_data(dataSet[0:2, :num])
    line.set_3d_properties(dataSet[2, :num])
    redDots.set_data(dataSet[0:2, :num])
    redDots.set_3d_properties(dataSet[2, :num])
    return line

def algorithm():
    #Topography
    K = 10
    J = 24
    count = 0
    vertex = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X"]
    edges = ["AC","BC","CD","DE","EF","EK","FG","GH","HI","HJ","KL","KO","LM","LN","OP","PQ","PS","QR","ST","SU","UV","VW","VX"]
    robo_vertex = ["A","B","I","J","M","N","R","T","W","X"]
    XData = [2.50, 3.50,3,3,3,1.50,1.50,1.50,1,2,3.50,3,2.50,3.50,4.50,4.50,3.50,3.50,5,4.50,5.50,5.50,5,6]
    YData = [1,1,2,3,4,5,6,7,8,8,5,6,7,7,6,7,8,9,8,9,9,10,11,11] # Got from MATLAB
    [graph,edges_decomp] = build_graph(edges)
    global spawn_location
    G = nx.Graph()
    # --------------------------------------------------------------
    for i in range(J):
        G.add_node(chr(i+65))
        #print('LAMBA')

    for ed in edges_decomp:
        # print(*ed)
        G.add_edge(*ed)
    # nx.draw(G,with_labels = True, font_weight = 'bold')
    #--------------------------------------------------------------

    #plt.show
    #print(G.nodes)
    #print(G.edges)

    incidence_matrix = get_incidence_matrix(XData,YData,G)
    #pp.pprint(incidence_matrix)

    R = []
    for j in range(K):
        R.append(Robot(j,robo_vertex,incidence_matrix))

    #initializing of V : list of Vertex objects
    V = []
    for j in range(J):
        V.append(Vertex(vertex[j],edges,incidence_matrix))#asdf

    #print("The first mandatory push:")
    #print('')

    for k in range(K):
        R[k].setpoint_list.append(spawn_location[3*k])
        R[k].setpoint_list.append(spawn_location[3*k + 1])
        R[k].setpoint_list.append(spawn_location[3*k +2] + k+1)
        #print(R[k].present_location)
        start = R[k].present_location
        #print(V[ord(R[k].present_location) - 65].neighbors[0])
        end = V[ord(R[k].present_location) - 65].neighbors[0]
        #print(-1*incidence_matrix[ord(start) - 65,ord(end)-65])
        top = np.array([-1*incidence_matrix[ord(start) - 65,ord(end)-65]])
        bottom = np.array([-1*incidence_matrix[ord(end) - 65,ord(start)-65]])
        col_vector = np.vstack((top,bottom))
        #Setpoint - 1 as the leaf node location while the height is kept constant
        R[k].setpoint_list.append(XData[ord(R[k].present_location) - 65]*25)
        R[k].setpoint_list.append(YData[ord(R[k].present_location) - 65]*25)
        R[k].setpoint_list.append(spawn_location[3*k +2] + k+1)

        #print("The {e} robot is currently at {f}".format(e=k,f=R[k].present_location))
        #print("The next node chosen is {}".format(V[ord(R[k].present_location) - 65].neighbors[0]))

        R[k].setpoint_list.append(XData[ord(V[ord(R[k].present_location) - 65].neighbors[0]) - 65]*25)
        R[k].setpoint_list.append(YData[ord(V[ord(R[k].present_location) - 65].neighbors[0]) - 65]*25)
        R[k].setpoint_list.append(spawn_location[3*k +2] + k+1)
        rospy.loginfo('Setpoint Addded!')
        id,R,V = what_to_do_if_next_node_known(R,k,V,1,R[k].present_location,V[ord(R[k].present_location) - 65].neighbors[0],incidence_matrix=incidence_matrix)
        #flying_function(XData[ord(V[ord(R[k].present_location) - 65].neighbors[0]) - 65],YData[ord(V[ord(R[k].present_location) - 65].neighbors[0]) - 65],k+1)
        R[k].next_edge_decided,count = second_step_on_vertex_visit(graph, V,R,k,count)

        #print('The next edge selected by - ' + str(k) + '- robot is' + str(R[k].next_edge_decided))
        R[k].setpoint_list.append(XData[ord(R[k].next_edge_decided.replace(R[k].present_location,'')) - 65]*25)
        R[k].setpoint_list.append(YData[ord(R[k].next_edge_decided.replace(R[k].present_location,'')) - 65]*25)
        R[k].setpoint_list.append(spawn_location[3*k +2] + k+1)
        rospy.loginfo('Setpoint Addded!')
        #print('')

        #rospy.sleep(6)

    #print("This is the loop part which continues till the declaration of completion")
    while(count != K):
        for z in range(K):
            if R[z].count != 1:
                #print("{z} robot Travelling to the selected edge :{e}".format(z = z , e = R[z].next_edge_decided) )
                if R[z].next_edge_decided !=0:
                    id,R,V = what_to_do_if_next_node_known(R,z,V,2,R[z].present_location, R[z].next_edge_decided.replace(R[z].present_location,''),incidence_matrix = incidence_matrix)
                    #flying_function(XData[ord(R[z].next_edge_decided.replace(R[z].present_location,'')) - 65], YData[ord(R[z].next_edge_decided.replace(R[z].present_location,'')) - 65], z+1)
                    R[z].next_edge_decided,count = second_step_on_vertex_visit(graph, V,R,z,count)
                    if R[z].next_edge_decided !=0:
                        R[z].setpoint_list.append(XData[ord(R[z].next_edge_decided.replace(R[z].present_location,'')) - 65]*25)
                        R[z].setpoint_list.append(YData[ord(R[z].next_edge_decided.replace(R[z].present_location,'')) - 65]*25)
                        R[z].setpoint_list.append(spawn_location[3*z +2] + z+1)
                        rospy.loginfo('Setpoint Addded!')
                        #print('The next edge selected by : ' + str(z) + ' : robot is :' + str(R[z].next_edge_decided))
                        #print('')
    for k in range(K):
        R[k].setpoint_list.append(spawn_location[3*k])
        R[k].setpoint_list.append(spawn_location[3*k + 1])
        R[k].setpoint_list.append(spawn_location[3*k + 2] +k+1)

    return R[0].setpoint_list,R[1].setpoint_list,R[2].setpoint_list, R[3].setpoint_list,R[4].setpoint_list,R[5].setpoint_list,R[6].setpoint_list,R[7].setpoint_list,R[8].setpoint_list,R[9].setpoint_list
#still need to append the base station as last setpoint and spawn location as the first setpoint
def drone_reached(xdata, ydata, zdata):
    if abs(new_pose.pose.position.x - xdata) <= threshold and abs(new_pose.pose.position.y - ydata) <= threshold and abs(new_pose.pose.position.z - zdata) <= threshold:
        return True

def position_control():

    global spawn_location
    _,_,_,_,_, list_of_setpoints5,_,_,_,_ = algorithm()
    print(list_of_setpoints5)
    num_of_points = len(list_of_setpoints5)//3
    # print(list_of_setpoints1)
    rospy.init_node('offb_node5', anonymous=True)
    prev_state = current_state
    rate = rospy.Rate(20.0) # MUST be more then 2Hz

    dataSet = np.array(list_of_setpoints5)
    numDataPoints = len(list_of_setpoints5)//3
    dataSet = np.reshape(dataSet,(numDataPoints,3))
    dataSet = np.transpose(dataSet)
    print(dataSet)
    # GET SOME MATPLOTLIB OBJECTS
    fig = plt.figure()
    ax = Axes3D(fig)
    redDots = plt.plot(dataSet[0], dataSet[1], dataSet[2], lw=2, c='r', marker='o')[0] # For scatter plot
    # NOTE: Can't pass empty arrays into 3d version of plot()
    line = plt.plot(dataSet[0], dataSet[1], dataSet[2], lw=2, c='g')[0] # For line plot

    # AXES PROPERTIES]
    # ax.set_xlim3d([limit0, limit1])
    ax.set_xlabel('X(t)')
    ax.set_ylabel('Y(t)')
    ax.set_zlabel('Z(t)')
    ax.set_title('Trajectory of 5th UAV')

    # Creating the Animation object
    line_ani = animation.FuncAnimation(fig, func, frames=numDataPoints + 1, fargs=(dataSet,line,redDots), interval=1000, blit= False)
    line_ani.save(r'5_th_UAV_animation.gif')

    # send a few setpoints before starting
    for i in range(100):
        local_pos_pub.publish(pose)
        rate.sleep()

    # wait for FCU connection
    while not current_state.connected:
        rate.sleep()
    # print(num_of_points)
    for i in range(num_of_points):
        print(i)
        last_request = rospy.get_rostime()
        if i ==2:
            ayushtrial = input()
        else:
            ayushtrial = 1
        #substract personal
        while not rospy.is_shutdown() and not drone_reached(list_of_setpoints5[3*i] - spawn_location[15],list_of_setpoints5[3*i+1] - spawn_location[16],list_of_setpoints5[3*i+2] - spawn_location[17]):
            now = rospy.get_rostime()
            if current_state.mode != "OFFBOARD" and (now - last_request > rospy.Duration(4.)):
                set_mode_client(base_mode=0, custom_mode="OFFBOARD")
                last_request = now
            else:
                if not current_state.armed and (now - last_request > rospy.Duration(4.)):
                    arming_client(True)
                    last_request = now

            # older versions of PX4 always return success==True, so better to check Status instead
            if prev_state.armed != current_state.armed:
                rospy.loginfo("Vehicle armed: %r" % current_state.armed)
            if prev_state.mode != current_state.mode:
                rospy.loginfo("Current mode: %s" % current_state.mode)
            prev_state = current_state

            # new_x,new_y,new_z =
            # Update timestamp and publish pose
            #pose.header.stamp = rospy.Time.now()
            pose.pose.position.x = list_of_setpoints5[3*i] - spawn_location[15] #initial x #personal
            pose.pose.position.y = list_of_setpoints5[3*i+1] - spawn_location[16]#initial y
            pose.pose.position.z = list_of_setpoints5[3*i+2]  - spawn_location[17]#initial_height
            local_pos_pub.publish(pose)
            #print('here!!')
            # plt.scatter(new_pose.pose.position.x/50 , new_pose.pose.position.y/50, marker = '_', color='red')
            # plt.draw()
            rate.sleep()

if __name__ == '__main__':
    try:
        #print('D')
        position_control()
        # plt.savefig("5_city_uav_route_yo_final_run.png")
    except rospy.ROSInterruptException:
        pass


#want to say nothing

LAST, NEXT, KEY, VAL, FREQ = 0, 1, 2, 3, 4
class LFUCache:

    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.dic = {} #key -> [LAST, NEXT, KEY, VAL, FREQ]
        self.freq_dic = {} #freq -> root: [LAST, NEXT, None, None, FREQ]
        self.least_freq = 1
        self.cap = capacity

    def get(self, key):
        """
        :type key: int
        :rtype: int
        """
        dic, freq_dic, cap = self.dic, self.freq_dic, self.cap
        if key not in dic:
            return -1
        node = dic[key]
        node[NEXT][LAST], node[LAST][NEXT] = node[LAST], node[NEXT]
        freq = node[FREQ]
        if freq == self.least_freq and freq_dic[freq][NEXT] is freq_dic[freq]:
            self.least_freq += 1

        node[FREQ] += 1
        freq = node[FREQ]
        if freq not in freq_dic:
            root = []
            root[:] = [root, root, None, None, freq]
            freq_dic[freq] = root
        root = freq_dic[freq]
        root[LAST][NEXT], root[LAST], node[NEXT], node[LAST] = node, node, root, root[LAST]
        return node[VAL]

    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: void
        """
        dic, freq_dic, cap = self.dic, self.freq_dic, self.cap
        if cap == 0:
            return
        if key in dic:
            self.get(key)
            dic[key][VAL] = value
            return

        if cap == len(dic):
            evict = freq_dic[self.least_freq][NEXT]
            evict[NEXT][LAST], evict[LAST][NEXT] = evict[LAST], evict[NEXT]
            del dic[evict[KEY]]
        self.least_freq = 1
        if 1 not in self.freq_dic:
            root = []
            root[:] = [root, root, None, None, 1]
            freq_dic[1] = root

        root = freq_dic[1]
        node = [None, None, key, value, 1]
        root[LAST][NEXT], root[LAST], node[NEXT], node[LAST] = node, node, root, root[LAST]
        dic[key] = node

# Your LFUCache object will be instantiated and called as such:
# obj = LFUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""tests for embeddings"""

import unittest
from sknetwork.embedding.gsvd import GSVDEmbedding
from sknetwork.embedding.spectral import SpectralEmbedding
from scipy import sparse
import numpy as np

class TestClusteringMetrics(unittest.TestCase):

    def setUp(self):
        self.graph = sparse.csr_matrix(np.array([[0, 1, 1, 1],
                                                 [1, 0, 0, 0],
                                                 [1, 0, 0, 1],
                                                 [1, 0, 1, 0]]))
        self.bipartite = sparse.csr_matrix(np.array([[1, 0, 1],
                                                     [1, 0, 0],
                                                     [1, 1, 1],
                                                     [0, 1, 1]]))

    def test_gsvd(self):
        gsvd = GSVDEmbedding(2)
        gsvd.fit(self.graph)
        self.assertTrue(gsvd.embedding_.shape == (4, 2))
        self.assertTrue(gsvd.features_.shape == (4, 2))
        self.assertTrue(type(gsvd.singular_values_) == np.ndarray and len(gsvd.singular_values_) == 2)

        gsvd.fit(self.bipartite)
        self.assertTrue(gsvd.embedding_.shape == (4, 2))
        self.assertTrue(gsvd.features_.shape == (3, 2))
        self.assertTrue(type(gsvd.singular_values_) == np.ndarray and len(gsvd.singular_values_) == 2)

    def test_spectral(self):
        sp = SpectralEmbedding(2)
        sp.fit(self.graph)
        self.assertTrue(sp.embedding_.shape == (4, 2))
        self.assertTrue(type(sp.eigenvalues_) == np.ndarray and len(sp.eigenvalues_) == 2)


import tweepy as tw
import pandas as pd
import json

# App Auth
consumer_key = 'XXX'
consumer_secret = 'XXX'
access_key = 'XXX'
access_secret = 'XXX'

# Initialize API
auth = tw.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tw.API(auth, wait_on_rate_limit=True)

# Search terms
search_words = ["#coronavirus", "#COVID19", "#CoronavirusOutbreak"]
date_since = "2020-02-01"

# Collect tweets
tweets = tw.Cursor(api.search,
              q=search_words,
              lang="en",
              since=date_since, tweet_mode='extended',
              include_rts=True).items(1000)

tweets_arr = []

# Iterate and print tweets
for tweet in tweets:
    tweets_arr.append(tweet._json)
print("Done")

with open("data.json", "w+") as output:
    output.write(json.dumps(tweets_arr))


# example Yurobot Easy Module shield v1 on top of Metro Express
# URL:
# 2017-0624 PePo test buttons SW1 and SW2
import digitalio
import board
import time
import pulseio

# SETUP
print('Start buzzer demo...')

# Configure PWM buzzer and other state:
BUZZER_PIN = board.D5
# Duty cycle of tone when turned on, a square wave.
TONE_ON_DUTY  = 2**15
# Duty cycle of tone when turned off, 0 or no signal.
TONE_OFF_DUTY = 0
# tones
NOTE_FREQS = [ 261,  # Input 0 = 261 hz = middle C
               294,  # Input 1 = middle D
               329,  # Input 2 = middle E
               349,  # Input 3 = middle F
               392,  # Input 4 = middle G
               440,  # Input 5 = middle A
               493,  # Input 6 = middle B
               0]    # Input 7 = 0, no tune

# Setup buzzer PWM output.
buzzer = pulseio.PWMOut(BUZZER_PIN, duty_cycle=TONE_OFF_DUTY, frequency=440,variable_frequency=True)

# Setup two buttons SW1, SW2 on D2, D3
sw1 = digitalio.DigitalInOut(board.D2)
sw2 = digitalio.DigitalInOut(board.D3)
sw1.switch_to_input(pull=digitalio.Pull.UP) #input UP
sw2.switch_to_input(pull=digitalio.Pull.UP) #input UP

# Setup RGB-led on D9-D11
rgbled = [ digitalio.DigitalInOut(board.D9),
        digitalio.DigitalInOut(board.D10),
        digitalio.DigitalInOut(board.D11)]
# leds are output
for led in rgbled:
    led.direction = digitalio.Direction.OUTPUT

#LOOP: wait for button press, then light on RGB and buzzer
import math
while True:
    for led in rgbled:
        led.value = False
    buzzer.duty_cycle = TONE_OFF_DUTY

    if not sw1.value:
        print("sw1 pressed")
        rgbled[0].value = True
        freq = NOTE_FREQS[0] # grab note
    elif not sw2.value:
        print("sw2 pressed")
        rgbled[2].value = True
        freq = NOTE_FREQS[1] # grab note
    else:
        rgbled[1].value = True
        freq = NOTE_FREQS[7] # nothing

    if freq != 0:
        buzzer.frequency = freq
        buzzer.duty_cycle = TONE_ON_DUTY

    time.sleep(0.1)
    #time.sleep(0.01)


# This is the Hangman game. The purpose of this program is to mimick the Hangman
# game. User will guess the letters in the word, and they have no more than 6
# tries or the computer wins.

import random
words=["Paper","Blanket","Vaseline","White","Pink","Candle"]

def Welcome():
    response=input ("WELCOME TO HANGMAN!\nWOULD YOU LIKE TO PLAY? YES/NO: ")
    return response

def play():
    YesOrNo=Welcome()
    if YesOrNo == "Yes":
        Hangman(words)
    else:
        print ("You chose NO, come back again, Bye!")

def Hangman(words):
    word=random.choice(words)
    soloLetters=list(word)
    hang=list("-" * len(word))
    i=1
    print ("THIS WORD HAS ", len(word), " LETTERS")
    while i <= 6 and hang != list(word):
        print("\nThis is your",i,"of 6th tries")
        letter=input("\nGuess a letter!: ")
        if letter in soloLetters:
            position=soloLetters.index(letter)
            hang[position]=letter
            print()
            print(hang)
            soloLetters[position]= "-"
        else:
            i+=1
    if i > 6:
        print ("GAME OVER! Sorry you used all your tries")
    elif hang==list(word):
        print ("YOU WIN! Your word was ", word.upper(), "!")

play()


# -*- coding: utf-8 -*-
from django.shortcuts import render, get_object_or_404
from django.http import *
from django.template import loader, Context
from .models import Category, Post
# Create your views here.
template = loader.get_template('template.html')

def home(request):

    data = Context({
    	'categories' : Category.objects.all(),
    	'posts' : Post.objects.all(),
        'title':'Django Öğreniyorum',
        'text':'Merhaba Dünya, my blog',
    })

    return render(request,"home.html",data)
    #return HttpResponse("Home")

def category(request,slug):

	get_kategori = Category.objects.get(slug=slug)

	data = Context({
    	'slug' : slug,
    	'categories' : Category.objects.all(),
    	'posts' : Post.objects.all().filter(category_id=get_kategori.id),
    })

	return render(request,"category.html",data)

def get_post(request,slug):

    return HttpResponse(slug)


# Parser class -a custom set of expressions gets converted to regex expressions using following (assumed)input rules:
# 1. (REQUIRED) C|W|S|L ?- C-searching for chars (added to enable subbing to replace characters as well as whole words)
#                          W-searching for whole words
#                          S-searching for sentences (from '.' to '.', returning only the trailing dot)
#                          L-searching for whole lines (^ to $ in multiline mode)
#
# 2. (OPTIONAL) R ?- enable subbing mode, the following expression rules require only 2 words, separated by a comma
#                    first word being the expression to be searched for, the second, what that expression is replaced w\
#
# 3. (OPTIONAL)n-m(numeric) ?- minimum and maximum values of C,W - letters or S,L - words
#
# 4. (REQUIRED 1 OF) word expressions ?- word expressions allow char sequences in double quotemarks ("abc")
#                                        word expressions are separated by commas ","
#                                        special characters: \N ?- a number exists in the word\sentence\line
#                                                            \U ?- several uppercase only letters in a sequence
#                                                            \L ?- several lowercase only letters in a sequence
#                                                            \u ?- one uppercase letter
#                                                            \l ?- one lowercase letter
#                                                            + ?- adding several symbols without ordering
#                                                            - ?- negation of next symbol

import re

class parser:

    # dict -substitute assigned mods with python re regex mods
    def __identifyMod(self, mod):
        return {
            'N':'(?=.*?[0-9]+)',
            'U':'[A-Z]+',
            'u':'[A-Z]',
            'L':'[a-z]+',
            'l':'[a-z]',
            r'-u':'[^A-Z]',
            r'-U':'[^A-Z]+',
            r'-L':'[^a-z]+',
            r'-N':'(?![0-9])',
            r'-l':'[^a-z]'
        }[mod]

    # dict -identify search mode, returns the front and the back of final regex pattern
    def __idMode(self, mode):
        return{
            'W':['\\b','\\w*?\\b'],
            'S':['(?:[.]|^).*?','.*?[.]'],
            'L':['^','.*?$'],
            'C':['',''],
            'R':'R'
        }[mode]

    # subbing mode, ran instead of searching when 'R' is present in input string
    def __sub(self,regex,sub,text):
        x= re.compile(regex,re.MULTILINE|re.DOTALL)
        r = x.sub(sub["word"], text)
        return r

    #searches the supplied text using last input, returns all matched strings
    def search(self,text):
        matches = []
        crit = ['{','}']
        if self.sub != None:
            return self.__sub(self.inputExpression,self.sub,text)
        regex = re.compile(self.inputExpression,re.MULTILINE|re.DOTALL)

        mList = regex.findall(text)
        if self.mode == self.__idMode('W'):
            crit = ['.{','}\\b']

        elif self.mode == self.__idMode('S') or self.__idMode('L'):
            crit =['^(\\b\w+\\b\W*){','}$']

        for i in mList:
            if self.min==-1:
                matches.append(i)
            elif self.max==-1:
                x =re.match(crit[0]+self.min +','+crit[1] ,i)
                if x is not None: matches.append(x.group(0))
            else:
                x =re.match(crit[0]+self.min +','+self.max+crit[1],i)
                if x is not None: matches.append(x.group(0))
        self.lastMatches = matches
        return matches

    # splits word expressions into actual words, separating them with empty strings on plus signs,
    # clears slashes, assigns group numbers to words to identify whether order matters
    def __wordCleanup(self, words):

        for nr,i in enumerate(words):
            i["word"] = re.sub(r',', '', i["word"])
            i["word"] = re.sub('\\\\','',i['word'])
            i["word"] = re.sub('\\\\','',i['word'])
            if r'+' in i["word"]:
                i["word"] = re.split(r'\+',i['word'])
                self.permutable = True
                for w,un in enumerate(i["word"]):
                    i['word'][w] = [un,nr]
        return words

    # regex is not very useful with searching for permutations of strings, initially for each permutation of words
    # was created, and then matched separately, this has been replaced with a less accurate solution of just searching
    # to see whether all of the words to be permuted exist past certain point, in any order. this was done to save on
    # computing time, as for every permutation program time increases twofold
    def __createPermutations(self, rExpressions):
        orGroups = []
        for n, i in enumerate(rExpressions):
            if rExpressions[n - 1][1] == i[1] or rExpressions[n + 1][1] == i[1]:
                orGroups.append(i[1])
        for i in set(orGroups):
            for j in rExpressions:
                if j[1]==i:
                    if j[0][0:2] == '.*?':
                        j[0] = '(?=' + j[0] + ')'
                    elif j[0][0:4]!='(?!.':
                        j[0] = '(?=.*?' + j[0] + ')'

        return rExpressions

    # concatenates all regex expressions
    def __createSearch(self, rExpressions):
        regex = ''
        if self.permutable == True :
            rExpressions= self.__createPermutations(rExpressions)
        for i in rExpressions:
            regex = regex + i[0]
        regex = self.mode[0] +regex + self.mode[1]
        self.inputExpression = regex

    # translates input into python regex expressions
    def __toRegexExpression(self, exp):
        retString = ''
        cont = 0
        for i in range(0,len(exp)):
            if i<cont: continue
            if exp[i]=='"':
                for j in range(i+1,len(exp)):
                    if exp[j]=='"':
                        retString = retString +exp[i+1:j]
                        cont = j+1
                        break
                continue
            if exp[i] == '-' :
                i = i + 1
                if exp[i]== '"':
                    for j in range(i + 1, len(exp)):
                        if exp[j] == '"':
                            retString = retString +'(?!.*?'+exp[i + 1:j]+')'
                            cont = j
                            break
                    continue
                retString = retString + self.__identifyMod('-' + exp[i])
                cont = i+1
            else :
                retString = retString + self.__identifyMod(exp[i])
        return retString

    # input processing function, calls everything needed to go from user input to searchable regex expression
    # the expression is returned and saved inside class variable
    def inputPattern(self,text):
        modeMinMax = re.compile("(?P<mode>[WSLC])" #get mode value
                        "(?P<replace>[R])?"
                        "(?P<minimum>\d+)?" # get minimum value if any
                        "-?"
                        "(?P<maximum>\d+)?") # get maximum value if any
        match = modeMinMax.match(text)

        self.mode = self.__idMode(match.group('mode'))
        self.sub = match.group("replace")

        if match.group('minimum') is not None:
            self.min = match.group('minimum')
            if match.group('maximum') is not None:
                self.max = match.group('maximum')
        text = text[match.span(0)[1]-1:]

        separateIntoWords = re.compile(r'(?:[WSLCR0-9]*)(?P<word>.+?(?:,|$))') #assume words are divided by ','
        match = [m.groupdict() for m in separateIntoWords.finditer(text)]

        if self.sub != None:
            self.sub = match[1]
            match = [match[0]]

        self.__wordCleanup(match)
        for n,i in enumerate(match):
            if isinstance(i['word'],list):
                for j in i['word']:
                    self.regexList.append([self.__toRegexExpression(j[0]), n])
            else :self.regexList.append([self.__toRegexExpression(i['word']), n])

        self.__createSearch(self.regexList)

    def __init__(self):
        self.permutable = False
        self.inputText = ''
        self.min = -1
        self.max = -1
        self.mode = 'W'
        self.wordMatches = []
        self.regexList = []
        self.lastMatches = []
        self.sub = None

#CLASSEND###############################################################################################################

if __name__ =='__main__':
    #fi = open(os.path.join(os.path.expanduser('~'), 'Documents', 'b.txt'))
    ini = parser()
    ini.inputPattern(r'') #passing raw strings required
    print(ini.search(''))


# Copyright 2020, New York University and the TUF contributors
# SPDX-License-Identifier: MIT OR Apache-2.0

"""TUF module that implements the client update workflow.

This module contains the Updater class that provides an implementation of the
`TUF client workflow
<https://theupdateframework.github.io/specification/latest/#detailed-client-workflow>`_.
Updater provides an API to query available targets and to download them in a
secure manner: All downloaded files are verified by signed metadata.

High-level description of Updater functionality:
  * Initializing an :class:`~tuf.ngclient.updater.Updater` loads and validates
    the trusted local root metadata: This root metadata is used as the source
    of trust for all other metadata.
  * Calling :func:`~tuf.ngclient.updater.Updater.refresh()` will update root
    metadata and load all other top-level metadata as described in the
    specification, using both locally cached metadata and metadata downloaded
    from the remote repository.
  * When metadata is up-to-date, targets can be dowloaded. The repository
    snapshot is consistent so multiple targets can be downloaded without
    fear of repository content changing. For each target:
      * :func:`~tuf.ngclient.updater.Updater.get_one_valid_targetinfo()` is
        used to find information about a specific target. This will load new
        targets metadata as needed (from local cache or remote repository).
      * :func:`~tuf.ngclient.updater.Updater.updated_targets()` can be used to
        check if target files are already locally cached.
      * :func:`~tuf.ngclient.updater.Updater.download_target()` downloads a
        target file and ensures it is verified correct by the metadata.

Below is a simple example of using the Updater to download and verify
"file.txt" from a remote repository. The required environment for this example
is:
    * A webserver running on http://localhost:8000, serving TUF repository
      metadata at "/tuf-repo/" and targets at "/targets/"
    * Local metadata directory "~/tufclient/metadata/" is writable and contains
      a root metadata version for the remote repository
    * Download directory "~/target-downloads/" is writable

Example::

    from tuf.ngclient import Updater

    # Load trusted local root metadata from client metadata cache. Define the
    # remote repository metadata URL prefix and target URL prefix.
    updater = Updater(
        repository_dir="~/tufclient/metadata/",
        metadata_base_url="http://localhost:8000/tuf-repo/",
        target_base_url="http://localhost:8000/targets/",
    )

    # Update top-level metadata from remote
    updater.refresh()

    # Securely download a target:
    # Update target metadata, then download and verify target
    targetinfo = updater.get_one_valid_targetinfo("file.txt")
    updater.download_target(targetinfo, "~/tufclient/downloads/")
"""

import fnmatch
import logging
import os
from typing import Any, Dict, List, Optional
from urllib import parse

from securesystemslib import hash as sslib_hash
from securesystemslib import util as sslib_util

from tuf import exceptions
from tuf.ngclient._internal import requests_fetcher, trusted_metadata_set
from tuf.ngclient.config import UpdaterConfig
from tuf.ngclient.fetcher import FetcherInterface

logger = logging.getLogger(__name__)

class Updater:
    """Implementation of the TUF client workflow."""

    def __init__(
        self,
        repository_dir: str,
        metadata_base_url: str,
        target_base_url: Optional[str] = None,
        fetcher: Optional[FetcherInterface] = None,
        config: Optional[UpdaterConfig] = None,
    ):
        """Creates a new Updater instance and loads trusted root metadata.

        Args:
            repository_dir: Local metadata directory. Directory must be
                writable and it must contain a trusted root.json file.
            metadata_base_url: Base URL for all remote metadata downloads
            target_base_url: Optional; Default base URL for all remote target
                downloads. Can be individually set in download_target()
            fetcher: Optional; FetcherInterface implementation used to download
                both metadata and targets. Default is RequestsFetcher

        Raises:
            OSError: Local root.json cannot be read
            RepositoryError: Local root.json is invalid
        """
        self._dir = repository_dir
        self._metadata_base_url = _ensure_trailing_slash(metadata_base_url)
        if target_base_url is None:
            self._target_base_url = None
        else:
            self._target_base_url = _ensure_trailing_slash(target_base_url)

        # Read trusted local root metadata
        data = self._load_local_metadata("root")
        self._trusted_set = trusted_metadata_set.TrustedMetadataSet(data)

        if fetcher is None:
            self._fetcher = requests_fetcher.RequestsFetcher()
        else:
            self._fetcher = fetcher

        self.config = config or UpdaterConfig()

    def refresh(self) -> None:
        """Refreshes top-level metadata.

        Downloads, verifies, and loads metadata for the top-level roles in the
        specified order (root -> timestamp -> snapshot -> targets) implementing
        all the checks required in the TUF client workflow.

        The metadata for delegated roles are not refreshed by this method as
        that happens on demand during get_one_valid_targetinfo().

        The refresh() method should be called by the client before any other
        method calls.

        Raises:
            OSError: New metadata could not be written to disk
            RepositoryError: Metadata failed to verify in some way
            TODO: download-related errors
        """

        self._load_root()
        self._load_timestamp()
        self._load_snapshot()
        self._load_targets("targets", "root")

    def get_one_valid_targetinfo(self, target_path: str) -> Dict:
        """Returns target information for 'target_path'.

        The return value can be used as an argument to
        :func:`download_target()` and :func:`updated_targets()`.

        :func:`refresh()` must be called before calling
        `get_one_valid_targetinfo()`. Subsequent calls to
        `get_one_valid_targetinfo()` will use the same consistent repository
        state: Changes that happen in the repository between calling
        :func:`refresh()` and `get_one_valid_targetinfo()` will not be
        seen by the updater.

        As a side-effect this method downloads all the additional (delegated
        targets) metadata it needs to return the target information.

        Args:
            target_path: A target identifier that is a path-relative-URL string
                (https://url.spec.whatwg.org/#path-relative-url-string).
                Typically this is also the unix file path of the eventually
                downloaded file.

        Raises:
            OSError: New metadata could not be written to disk
            RepositoryError: Metadata failed to verify in some way
            TODO: download-related errors
        """
        return self._preorder_depth_first_walk(target_path)

    @staticmethod
    def updated_targets(
        targets: List[Dict[str, Any]], destination_directory: str
    ) -> List[Dict[str, Any]]:
        """Checks whether local cached target files are up to date

        After retrieving the target information for the targets that should be
        updated, updated_targets() can be called to determine which targets
        have changed compared to locally stored versions.

        All the targets that are not up-to-date in destination_directory are
        returned in a list. The list items can be downloaded with
        'download_target()'.
        """
        # Keep track of the target objects and filepaths of updated targets.
        # Return 'updated_targets' and use 'updated_targetpaths' to avoid
        # duplicates.
        updated_targets = []
        updated_targetpaths = []

        for target in targets:
            # Prepend 'destination_directory' to the target's relative filepath
            # (as stored in metadata.)  Verify the hash of 'target_filepath'
            # against each hash listed for its fileinfo.  Note: join() discards
            # 'destination_directory' if 'filepath' contains a leading path
            # separator (i.e., is treated as an absolute path).
            filepath = target["filepath"]
            target_fileinfo: "TargetFile" = target["fileinfo"]

            target_filepath = os.path.join(destination_directory, filepath)

            if target_filepath in updated_targetpaths:
                continue

            try:
                with open(target_filepath, "rb") as target_file:
                    target_fileinfo.verify_length_and_hashes(target_file)
            # If the file does not exist locally or length and hashes
            # do not match, append to updated targets.
            except (OSError, exceptions.LengthOrHashMismatchError):
                updated_targets.append(target)
                updated_targetpaths.append(target_filepath)

        return updated_targets

    def download_target(
        self,
        targetinfo: Dict,
        destination_directory: str,
        target_base_url: Optional[str] = None,
    ):
        """Downloads the target file specified by 'targetinfo'.

        Args:
            targetinfo: data received from get_one_valid_targetinfo() or
                updated_targets().
            destination_directory: existing local directory to download into.
                Note that new directories may be created inside
                destination_directory as required.
            target_base_url: Optional; Base URL used to form the final target
                download URL. Default is the value provided in Updater()

        Raises:
            TODO: download-related errors
            TODO: file write errors
        """
        if target_base_url is None and self._target_base_url is None:
            raise ValueError(
                "target_base_url must be set in either download_target() or "
                "constructor"
            )
        if target_base_url is None:
            target_base_url = self._target_base_url
        else:
            target_base_url = _ensure_trailing_slash(target_base_url)

        target_filepath = targetinfo["filepath"]
        target_fileinfo: "TargetFile" = targetinfo["fileinfo"]
        full_url = parse.urljoin(target_base_url, target_filepath)

        with self._fetcher.download_file(
            full_url, target_fileinfo.length
        ) as target_file:
            try:
                target_fileinfo.verify_length_and_hashes(target_file)
            except exceptions.LengthOrHashMismatchError as e:
                raise exceptions.RepositoryError(
                    f"{target_filepath} length or hashes do not match"
                ) from e

            filepath = os.path.join(destination_directory, target_filepath)
            sslib_util.persist_temp_file(target_file, filepath)

    def _download_metadata(
        self, rolename: str, length: int, version: Optional[int] = None
    ) -> bytes:
        """Download a metadata file and return it as bytes"""
        if version is None:
            filename = f"{rolename}.json"
        else:
            filename = f"{version}.{rolename}.json"
        url = parse.urljoin(self._metadata_base_url, filename)
        return self._fetcher.download_bytes(url, length)

    def _load_local_metadata(self, rolename: str) -> bytes:
        with open(os.path.join(self._dir, f"{rolename}.json"), "rb") as f:
            return f.read()

    def _persist_metadata(self, rolename: str, data: bytes):
        with open(os.path.join(self._dir, f"{rolename}.json"), "wb") as f:
            f.write(data)

    def _load_root(self) -> None:
        """Load remote root metadata.

        Sequentially load and persist on local disk every newer root metadata
        version available on the remote.
        """

        # Update the root role
        lower_bound = self._trusted_set.root.signed.version + 1
        upper_bound = lower_bound + self.config.max_root_rotations

        for next_version in range(lower_bound, upper_bound):
            try:
                data = self._download_metadata(
                    "root", self.config.root_max_length, next_version
                )
                self._trusted_set.update_root(data)
                self._persist_metadata("root", data)

            except exceptions.FetcherHTTPError as exception:
                if exception.status_code not in {403, 404}:
                    raise
                # 404/403 means current root is newest available
                break

        # Verify final root
        self._trusted_set.root_update_finished()

    def _load_timestamp(self) -> None:
        """Load local and remote timestamp metadata"""
        try:
            data = self._load_local_metadata("timestamp")
            self._trusted_set.update_timestamp(data)
        except (OSError, exceptions.RepositoryError) as e:
            # Local timestamp does not exist or is invalid
            logger.debug("Failed to load local timestamp %s", e)

        # Load from remote (whether local load succeeded or not)
        data = self._download_metadata(
            "timestamp", self.config.timestamp_max_length
        )
        self._trusted_set.update_timestamp(data)
        self._persist_metadata("timestamp", data)

    def _load_snapshot(self) -> None:
        """Load local (and if needed remote) snapshot metadata"""
        try:
            data = self._load_local_metadata("snapshot")
            self._trusted_set.update_snapshot(data)
            logger.debug("Local snapshot is valid: not downloading new one")
        except (OSError, exceptions.RepositoryError) as e:
            # Local snapshot does not exist or is invalid: update from remote
            logger.debug("Failed to load local snapshot %s", e)

            metainfo = self._trusted_set.timestamp.signed.meta["snapshot.json"]
            length = metainfo.length or self.config.snapshot_max_length
            version = None
            if self._trusted_set.root.signed.consistent_snapshot:
                version = metainfo.version

            data = self._download_metadata("snapshot", length, version)
            self._trusted_set.update_snapshot(data)
            self._persist_metadata("snapshot", data)

    def _load_targets(self, role: str, parent_role: str) -> None:
        """Load local (and if needed remote) metadata for 'role'."""
        try:
            data = self._load_local_metadata(role)
            self._trusted_set.update_delegated_targets(data, role, parent_role)
            logger.debug("Local %s is valid: not downloading new one", role)
        except (OSError, exceptions.RepositoryError) as e:
            # Local 'role' does not exist or is invalid: update from remote
            logger.debug("Failed to load local %s: %s", role, e)

            metainfo = self._trusted_set.snapshot.signed.meta[f"{role}.json"]
            length = metainfo.length or self.config.targets_max_length
            version = None
            if self._trusted_set.root.signed.consistent_snapshot:
                version = metainfo.version

            data = self._download_metadata(role, length, version)
            self._trusted_set.update_delegated_targets(data, role, parent_role)
            self._persist_metadata(role, data)

    def _preorder_depth_first_walk(self, target_filepath) -> Dict:
        """
        Interrogates the tree of target delegations in order of appearance
        (which implicitly order trustworthiness), and returns the matching
        target found in the most trusted role.
        """

        target = None
        role_names = [("targets", "root")]
        visited_role_names = set()
        number_of_delegations = self.config.max_delegations

        # Preorder depth-first traversal of the graph of target delegations.
        while (
            target is None and number_of_delegations > 0 and len(role_names) > 0
        ):

            # Pop the role name from the top of the stack.
            role_name, parent_role = role_names.pop(-1)
            self._load_targets(role_name, parent_role)
            # Skip any visited current role to prevent cycles.
            if (role_name, parent_role) in visited_role_names:
                logger.debug("Skipping visited current role %s", role_name)
                continue

            # The metadata for 'role_name' must be downloaded/updated before
            # its targets, delegations, and child roles can be inspected.

            role_metadata = self._trusted_set[role_name].signed
            target = role_metadata.targets.get(target_filepath)

            # After preorder check, add current role to set of visited roles.
            visited_role_names.add((role_name, parent_role))

            # And also decrement number of visited roles.
            number_of_delegations -= 1
            child_roles = []
            if role_metadata.delegations is not None:
                child_roles = role_metadata.delegations.roles

            if target is None:

                child_roles_to_visit = []
                # NOTE: This may be a slow operation if there are many
                # delegated roles.
                for child_role in child_roles:
                    child_role_name = _visit_child_role(
                        child_role, target_filepath
                    )

                    if child_role.terminating and child_role_name is not None:
                        logger.debug(
                            "Adding child role %s.\n"
                            "Not backtracking to other roles.",
                            child_role_name,
                        )
                        role_names = []
                        child_roles_to_visit.append(
                            (child_role_name, role_name)
                        )
                        break

                    if child_role_name is None:
                        logger.debug("Skipping child role %s", child_role_name)

                    else:
                        logger.debug("Adding child role %s", child_role_name)
                        child_roles_to_visit.append(
                            (child_role_name, role_name)
                        )

                # Push 'child_roles_to_visit' in reverse order of appearance
                # onto 'role_names'.  Roles are popped from the end of
                # the 'role_names' list.
                child_roles_to_visit.reverse()
                role_names.extend(child_roles_to_visit)

            else:
                logger.debug("Found target in current role %s", role_name)

        if (
            target is None
            and number_of_delegations == 0
            and len(role_names) > 0
        ):
            logger.debug(
                "%d roles left to visit, but allowed to "
                "visit at most %d delegations.",
                len(role_names),
                self.config.max_delegations,
            )

        return {"filepath": target_filepath, "fileinfo": target}

def _visit_child_role(child_role: Dict, target_filepath: str) -> str:
    """
    <Purpose>
      Non-public method that determines whether the given 'target_filepath'
      is an allowed path of 'child_role'.

      Ensure that we explore only delegated roles trusted with the target.  The
      metadata for 'child_role' should have been refreshed prior to this point,
      however, the paths/targets that 'child_role' signs for have not been
      verified (as intended).  The paths/targets that 'child_role' is allowed
      to specify in its metadata depends on the delegating role, and thus is
      left to the caller to verify.  We verify here that 'target_filepath'
      is an allowed path according to the delegated 'child_role'.

      TODO: Should the TUF spec restrict the repository to one particular
      algorithm?  Should we allow the repository to specify in the role
      dictionary the algorithm used for these generated hashed paths?

    <Arguments>
      child_role:
        The delegation targets role object of 'child_role', containing its
        paths, path_hash_prefixes, keys, and so on.

      target_filepath:
        The path to the target file on the repository. This will be relative to
        the 'targets' (or equivalent) directory on a given mirror.

    <Exceptions>
      None.

    <Side Effects>
      None.

    <Returns>
      If 'child_role' has been delegated the target with the name
      'target_filepath', then we return the role name of 'child_role'.

      Otherwise, we return None.
    """

    child_role_name = child_role.name
    child_role_paths = child_role.paths
    child_role_path_hash_prefixes = child_role.path_hash_prefixes

    if child_role_path_hash_prefixes is not None:
        target_filepath_hash = _get_filepath_hash(target_filepath)
        for child_role_path_hash_prefix in child_role_path_hash_prefixes:
            if not target_filepath_hash.startswith(child_role_path_hash_prefix):
                continue

            return child_role_name

    elif child_role_paths is not None:
        # Is 'child_role_name' allowed to sign for 'target_filepath'?
        for child_role_path in child_role_paths:
            # A child role path may be an explicit path or glob pattern (Unix
            # shell-style wildcards).  The child role 'child_role_name' is
            # returned if 'target_filepath' is equal to or matches
            # 'child_role_path'. Explicit filepaths are also considered
            # matches. A repo maintainer might delegate a glob pattern with a
            # leading path separator, while the client requests a matching
            # target without a leading path separator - make sure to strip any
            # leading path separators so that a match is made.
            # Example: "foo.tgz" should match with "/*.tgz".
            if fnmatch.fnmatch(
                target_filepath.lstrip(os.sep), child_role_path.lstrip(os.sep)
            ):
                logger.debug(
                    "Child role %s is allowed to sign for %s",
                    repr(child_role_name),
                    repr(target_filepath),
                )

                return child_role_name

            logger.debug(
                "The given target path %s "
                "does not match the trusted path or glob pattern: %s",
                repr(target_filepath),
                repr(child_role_path),
            )
            continue

    else:
        # 'role_name' should have been validated when it was downloaded.
        # The 'paths' or 'path_hash_prefixes' fields should not be missing,
        # so we raise a format error here in case they are both missing.
        raise exceptions.FormatError(
            repr(child_role_name) + " "
            'has neither a "paths" nor "path_hash_prefixes".  At least'
            " one of these attributes must be present."
        )

    return None

def _get_filepath_hash(target_filepath, hash_function="sha256"):
    """
    Calculate the hash of the filepath to determine which bin to find the
    target.
    """
    # The client currently assumes the repository (i.e., repository
    # tool) uses 'hash_function' to generate hashes and UTF-8.
    digest_object = sslib_hash.digest(hash_function)
    encoded_target_filepath = target_filepath.encode("utf-8")
    digest_object.update(encoded_target_filepath)
    target_filepath_hash = digest_object.hexdigest()

    return target_filepath_hash

def _ensure_trailing_slash(url: str):
    """Return url guaranteed to end in a slash"""
    return url if url.endswith("/") else f"{url}/"


import asyncio
import time

async def greetings():
    """ ... """
    print("Welcome")
    await asyncio.sleep(1)
    print("Good by")

async def main():
    await asyncio.gather(greetings(), greetings())

def say_greet():
    start = time.perf_counter()
    asyncio.get_event_loop().run_until_complete(main())
    elapsed = time.perf_counter() - start
    print(f"total time elapsed: {elapsed}")

asyncio.get_event_loop().run_until_complete(say_greet())


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

# !/usr/bin/python

import requests
import re
import time
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.disable(logging.DEBUG)

def getMode(url):
    requests.adapters.DEFAULT_RETRIES = 3

    response = requests.get(url)
    response.raise_for_status()

    # print(response.text)

    mode = re.search( r"This Org CacheMode -> \[(.*?)\]",response.text).group(1)

    return mode

if __name__ == '__main__' :

    logging.debug('start...')

    thread = []

    # orgname = ['perf01', 'perf01jetty', 'perf02', 'perf03', 'acm01vegas', 'acm01vegasjetty']
    orgname = ['acm01vegasjetty']

    for org in orgname:
        urlstr = "https://anperf01.active.com/" + org + "/servlet/ignitemetrics.sdi"
        print("Current ignie mode of " + org +" is " + str(getMode(urlstr,)) )

    logging.debug('end.')


# coding=utf-8
from framework.robotwrappers.Asserts import Asserts
from project.web.pages.ResultPage import ResultPage
from project.web.pages.MainPage import MainPage

class PageSteps:

    @staticmethod
    def main_page_is_opened():
        """Method assert is Main page opened"""
        is_page_opened = MainPage().is_opened()
        Asserts.should_be_true(is_page_opened, 'Main page has not been opened')

    @staticmethod
    def result_page_is_opened():
        """Method assert is Result page opened"""
        is_page_opened = ResultPage().is_opened()
        Asserts.should_be_true(is_page_opened, 'Result page has not been opened')


import csv
import os
from array import *
#Rollcall object that contains a vote matrix
class Rollcall:
    def __init__(self,votesRollcallFilepath, voteOptions):
        votesRollcallFile = open(votesRollcallFilepath,"r")
        voteIndex = 0
        mpIndex = 0
        lastVote = 0
        #For practical use, a 2D array is far superior to a dict, so we need new indexes for MPs and vote numbers
        #1 is For, 2 is Against, 3 is Abstain
        self.votes = [[]]
        #Matches the vote number in the csv file to the column index in rollCall 2D array
        self.voteToId = {}
        #Matches the MP number in the csv file to the line index in rollCall 2D array
        self.mpToId = {}
        #Matches the column index to the vote ID
        self.idToVote = []
        #Matches the line index to the MP ID
        self.idToMp = []
        try:
            reader = csv.reader(votesRollcallFile, delimiter='\t')
            next(reader)
            for row in reader:
                if row[2] == voteOptions[0]:
                    vote = 1
                elif row[2] == voteOptions[1]:
                    vote = 2
                elif row[2] == voteOptions[2]:
                    vote = 3
                if int(row[0]) != lastVote:
                    self.voteToId[row[0]] = voteIndex
                    self.idToVote.append(int(row[0]))
                    lastVote = int(row[0])
                    voteIndex += 1
                try:
                    mpIndex = self.mpToId[row[1]]
                except KeyError:
                    self.mpToId[row[1]] = mpIndex
                    self.idToMp.append(int(row[1]))
                    mpIndex += 1
                try:
                    self.votes[mpIndex].append(vote)
                except IndexError:
                    self.votes.append([vote])
        finally:
            votesRollcallFile.close()

    def writeOrd(self, ordFilepath):
        ordFile = open(ordFilepath,"w")
        for legisId in range(len(self.mpToId)):
            lId = str(legisId)
            ordFile.write("   ")
            for i  in range(0,(4-len(lId))):
                ordFile.write(" ")
            ordFile.write(lId)
            for i in range(1, 26):
                ordFile.write(" ")
            choices = [0] * len(self.voteToId)
            for i in range (1, len(self.voteToId)):
                try:
                    curr = self.votes[legisId][i]
                    if (curr == 1) :
                        ordFile.write(str(1))
                    elif (curr == 2):
                        ordFile.write(str(6))
                    elif (curr == 3):
                        ordFile.write(str(0))
                except IndexError:
                        ordFile.write(str(0))
            ordFile.write(os.linesep)

    def writeResult(self,coord1D,coord2D,userFilePath,updatedUserFilePath):
        updatedUserFile = open(updatedUserFilePath,"w")
        userFile = open(userFilePath,"r")
        try:
            reader = csv.reader(userFile, delimiter='\t')
            row1 = next(reader)
            for cat in row1:
                updatedUserFile.write(cat)
                updatedUserFile.write("\t")
            updatedUserFile.write("COORD1\tCOORD2")
            for row in reader:
                updatedUserFile.write(os.linesep)
                for cell in row:
                    updatedUserFile.write(cell)
                    updatedUserFile.write("\t")
                try:
                    #updatedUserFile.write(row[0])
                    updatedUserFile.write(str(coord1D[self.mpToId[row[0]]]))
                    updatedUserFile.write("\t")
                    #updatedUserFile.write(str(self.idToMp[self.mpToId[row[0]]]))
                    updatedUserFile.write(str(coord2D[self.mpToId[row[0]]]))
                except KeyError:
                    updatedUserFile.write("Not Computed")
                    updatedUserFile.write("\tNot Computed")
                except IndexError:
                    updatedUserFile.write("Not Voting")
                    updatedUserFile.write("\tNot Voting")
        finally:
            userFile.close()

def parse(votesRollcallFilepath, voteOptions):
    return Rollcall(votesRollcallFilepath, voteOptions)


from typing import Optional,List
from fastapi import FastAPI,Query
from pydantic import BaseModel,Field, EmailStr
from pymongo import MongoClient, UpdateOne
from passlib.context import CryptContext
import requests
from bs4 import BeautifulSoup
from string import punctuation
from bson import ObjectId
import re

#filtering library
import nltk
nltk.download('punkt')
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer

porter=PorterStemmer()

def increase_word_count(word_list):
    wordcount={}
    for word in word_list:
        if(word in wordcount):
            wordcount[word]=wordcount[word]+1
        else:
            wordcount[word]=1
    for word in wordcount.keys():
        result=db.words_count.find_one({'word':word})
        if(result):
            db.words_count.update_one({'word':word},{"$inc":{'count':wordcount[word]}})
        else:
            db.words_count.insert_one({'word':word, 'count':wordcount[word]})

def filter_sentence(input_str):
    stop_words = set(stopwords.words('english'))
    word_tokens = nltk.word_tokenize(input_str)
    word_tokens=[porter.stem(w) for w in word_tokens if not w in punctuation]
    filtered_sentence = [w for w in word_tokens if not w in stop_words]
    increase_word_count(filtered_sentence)
    filtered_sentence=set(filtered_sentence)
    return ' '.join(filtered_sentence)

URL="https://thehackernews.com/"

app = FastAPI()

client = MongoClient("mongodb-server", 27017)
db = client.assignment

page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
for post in soup.find_all(class_='story-link'):
    TB=post.find(class_='home-title')
    DB=post.find(class_='home-desc')
    UB=post
    IB=post.find(class_='home-img-src')
    if TB and DB and UB and IB:
        if(db.meta_data.find_one({'URL':UB['href']})):
            continue
        filtered_text=filter_sentence(DB.text.lower())
        metaData=db.meta_data.insert_one({
            'URL':UB['href'],
            'Description': DB.text,
            'Image':IB['data-src'],
            'Filtered_description': filtered_text
        })
        db.post.insert_one({
            'URL':UB['href'],
            'Title': TB.text,
            'Meta_data': ObjectId(metaData.inserted_id)
        })

# @app.get("/hackernews")
# def get_news():
#     allpost=[]
#     for post in db.post.find():
#         metadata=db.meta_data.find_one({"_id":post['Meta_data']})
#         allpost.append({
#             'URL':post['URL'],
#             'Title':post['Title'],
#             'Meta_data':{
#                 'Description':metadata['Description'],
#                 'Image':metadata['Image']
#             }
#         })
#     return allpost

@app.get("/hackernews")
def get_news(searchstr:str=Query("")):
    soln=set([])
    for data in db.meta_data.find():
        soln.add(data['URL'])
    for word in searchstr.split():
        if word in punctuation:
            continue
        tempSoln=set([])
        regx = re.compile(word, re.IGNORECASE)
        for data in db.meta_data.find({"Description":regx}):
            tempSoln.add(data['URL'])
        soln.intersection_update(tempSoln)
    return list(soln)


from bs4 import BeautifulSoup
from .interfaceparser import IParser

class MixmagParser(IParser):
    RATINGMAX = 5
    WEBPAGE_NAME = "http://www.mixmag.net"

    def __init__(self, document):
        self.document = document

    @staticmethod
    def fetch_url_reviews(html):
        document = BeautifulSoup(html)
        reviews_urls = []
        reviews_tags = document.findAll("h4")
        for review_tag in reviews_tags:
            reviews_urls.append(
                MixmagParser.WEBPAGE_NAME + review_tag.find("a")["href"])
        return reviews_urls

    @staticmethod
    def get_review_info(html):
        document = BeautifulSoup(html)
        parser = MixmagParser(document)

        artist = parser._get_artist_review()
        album = parser._get_album_review()
        rating = parser._get_rating_review()
        body_review = parser._get_body_review()
        information_review = {
            "artist": artist,
            "album": album,
            "rating": rating,
            "rating_max": MixmagParser.RATINGMAX,
            "body_review": body_review,
        }
        return information_review

    def _get_artist_review(self):
        return self.document.find(
            "h3", {"class": "article-title"}).\
            findAll(text=True)[0].title().strip()

    def _get_album_review(self):
        return self.document.find("span", {"class": "sub-info"}).text.title()

    def _get_rating_review(self):
        return len(self.document.find(
            "span", {"class": "rating type2"}).findAll("img"))

    def _get_body_review(self):
        body_review = ""
        # We observe that the last parragraph of the review is not relevant
        # for the body it is taken all except the last.
        review_parragraphs = \
            self.document.find("div", {"id": "cms-content"}).findAll("p")
        for i in range(len(review_parragraphs) - 1):
            body_review += review_parragraphs[i].text
        return body_review


import warnings

import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import LeaveOneOut
from sklearn.preprocessing import StandardScaler
import time
import scipy.io as scio
import numpy

from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

warnings.filterwarnings(action="ignore")

def cross_validate0(X, file_y, feaselect = False):

    # X = numpy.genfromtxt(file_x, delimiter=' ')
    y = numpy.genfromtxt(file_y, delimiter=' ')
    X = StandardScaler().fit_transform(X)
    d = []
    l = []
    for i,v in enumerate(X):
        if True in numpy.isnan(v):
            pass
            # print(i,v)
        else:
            l.append(y[i])
            d.append(v)
    X = numpy.array(d)
    y = numpy.array(l)
    # print(X.shape)
    # print(y.shape)
    if feaselect == True:
        X = fisher_idx(X, y)
        # print(X.shape, y.shape)
    models = []
    models.append(('LR', LogisticRegression(solver='liblinear')))
    models.append(('SVC', SVC()))
    models.append(('KNN', KNeighborsClassifier()))
    models.append(('DT', DecisionTreeClassifier()))
    # models.append(('RF', RandomForestClassifier(n_estimators=100, oob_score=True, random_state=123456, criterion='entropy')))
    scoring = 'accuracy'

    # Split the data into training/testing sets
    # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=43)

    numpy.random.seed(9)
    shuffle_indices = numpy.random.permutation(numpy.arange(len(y)))
    x_shuffled = X[shuffle_indices]  # 将样本和标签打乱
    y_shuffled = y[shuffle_indices]
    print(x_shuffled.shape, y_shuffled.shape)
    # Cross Validate
    results = []
    names = []
    timer = []
    # print('Model | Mean of CV | Std. Dev. of CV | Time')
    # for name, model in models:
    #     start_time = time.time()
    #     kfold = model_selection.KFold(n_splits=33, random_state=numpy.random.randint(1,100))
    #     cv_results = model_selection.cross_val_score(model, x_shuffled, y_shuffled, cv=kfold, scoring=scoring)
    #     t = (time.time() - start_time)
    #     timer.append(t)
    #     results.append(cv_results)
    #     names.append(name)
    #     msg = "%s: %f (%f) %f s" % (name, cv_results.mean(), cv_results.std(), t)
    #     print(msg)

    #留一法验证
    loo=LeaveOneOut()
    for name, model in models:
        start_time = time.time()
        # [:,(25, 90, 91)]
        cv_results = model_selection.cross_val_score(model, x_shuffled, y_shuffled, cv=loo, scoring=scoring)
        names.append(name)
        t = (time.time() - start_time)
        msg = "%s: %f (%f) %f s" % (name, cv_results.mean(), cv_results.std(), t)
        print(msg)

def run():
    dataFile = './data/matlab.mat'
    data = scio.loadmat(dataFile)

    features = data['features']

    # print(features.shape)
    EEG_fea = features[0][0][2].reshape(-1)
    for i in range(32):
        for j in range(40):
            if i is 0 and j is 0:
                continue
            # print(EEG_fea.shape)
            # print(features[i][j][2].reshape(-1).shape)
            EEG_fea = numpy.vstack((EEG_fea, features[i][j][2].reshape(-1)))
    print("EEG_fea.shape:" + str(EEG_fea.shape))

    EMG_fea = features[0][0][0].reshape(-1)
    for i in range(32):
        for j in range(40):
            if i is 0 and j is 0:
                continue
            # print(EEG_fea.shape)
            # print(features[i][j][0].reshape(-1).shape)
            EMG_fea = numpy.vstack((EMG_fea, features[i][j][0].reshape(-1)))
    print("EMG_fea.shape:" + str(EMG_fea.shape))

    GSR_fea = features[0][0][4].reshape(-1)
    for i in range(32):
        for j in range(40):
            if i is 0 and j is 0:
                continue
            # print(EEG_fea.shape)
            # print(features[i][j][0].reshape(-1).shape)
            GSR_fea = numpy.vstack((GSR_fea, features[i][j][4].reshape(-1)))
    print("GSR_fea.shape:" + str(GSR_fea.shape))

    BVP_fea = features[0][0][6].reshape(-1)
    for i in range(32):
        for j in range(40):
            if i is 0 and j is 0:
                continue
            # print(EEG_fea.shape)
            # print(features[i][j][0].reshape(-1).shape)
            BVP_fea = numpy.vstack((BVP_fea, features[i][j][6].reshape(-1)))
    print("BVP_fea.shape:" + str(BVP_fea.shape))

    RES_fea = features[0][0][8].reshape(-1)
    for i in range(32):
        for j in range(40):
            if i is 0 and j is 0:
                continue
            RES_fea = numpy.vstack((RES_fea, features[i][j][8].reshape(-1)))
    print("RES_fea.shape:" + str(RES_fea.shape))

    peripheral_fea = numpy.hstack((EMG_fea, RES_fea, BVP_fea[:,:-4], GSR_fea))
    print("peripheral_fea.shape:" + str(peripheral_fea.shape))
    all_fea = numpy.hstack((EEG_fea, peripheral_fea))
    print("all_fea.shape:" + str(all_fea.shape))
    # print("BVP_fea")
    # run_fea(BVP_fea[:,:-4])
    # print("GSR_fea")
    # run_fea(GSR_fea)
    # print("RES_fea")
    # run_fea(RES_fea)
    # print("EMG_fea")
    # run_fea(EMG_fea)
    print("EEG_fea")
    run_fea(EEG_fea, feaselect=True)
    # print("peripheral_fea")
    # run_fea(peripheral_fea)
    # print("all_fea")
    # run_fea(all_fea, feaselect=True)

def fisher_idx(features, labels):
    ''' Get idx sorted by fisher linear discriminant '''
    labels = np.array(labels)
    labels0 = np.where(labels < 1)
    labels1 = np.where(labels > 0)
    labels0 = np.array(labels0).flatten()
    labels1 = np.array(labels1).flatten()
    features0 = np.delete(features, labels1, axis=0)
    features1 = np.delete(features, labels0, axis=0)
    mean_features0 = np.mean(features0, axis=0)
    mean_features1 = np.mean(features1, axis=0)
    std_features0 = np.std(features0, axis=0)
    std_features1 = np.std(features1, axis=0)
    std_sum = std_features1**2 + std_features0**2
    fisher = (abs(mean_features0 - mean_features1)) / std_sum
    fisher_sorted = np.argsort(np.array(fisher))  # sort the fisher from small to large
    sorted_feature_idx = fisher_sorted[::-1]  # arrange from large to small
    #select fisher larger than 0.3
    fisher_threshold = 0.3
    feature_idx = np.where(fisher>fisher_threshold)
    if(features[:,feature_idx].shape[2] < 3):
        print(features[:,sorted_feature_idx].shape)
        return features[:,sorted_feature_idx[:3]]
    return features[:,feature_idx].reshape((features.shape[0], -1))

def run_fea(file_x, feaselect = False):

    print("2class:")
    file_y1 = './data/label_class_0.dat'
    file_y2 = './data/label_class_1.dat'

    print("valence")
    cross_validate0(file_x, file_y1, feaselect = feaselect)
    print("Arousal")
    cross_validate0(file_x, file_y2, feaselect = feaselect)
if __name__ == '__main__':
    run()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 24 19:28:38 2017

@author: kumar
"""
import random
import numpy as np
import matplotlib.pyplot as plt
#from scipy.stats import norm
import ucb
def gaussian_dist(no_arms):
    x = np.random.normal(1 ,1 ,no_arms) #calculating the mean value for normal distribution of each arm

    return x
'''
def stochastic_dist(no_arms):
    x= np.array([[]])
    flag =0
    for i in range(no_arms):
        if flag==0:
            x = np.random.dirichlet(np.ones(10), size=1) #making dirichlet distribution
            flag=1
        else:

            y =np.random.dirichlet(np.ones(10), size=1).ravel()
            x = np.vstack([x ,y])
    return x
'''
class EpsilonGreedy():
    def __init__(self , epsilon , counts , values ): #dist is distribution of probability distribution for each arm
        self.epsilon = epsilon
        self.counts = counts  #vector that counts the number of times an arm is pulled
        self.values = values #vector for avg value recieved when the arm is pulled.
        self.itr = 1
        self.netreward = []
        self.actualmean = []
        self.optarray= []
        self.target_itr = 0
        self.opt_count =0
        return
    #initialization
    def initialize(self , no_arms, mean_of_dist ,itrs):
        self.counts = [0 for i in range(no_arms)]
        self.values = [0.0 for i in range(no_arms)]
        self.actualmean = mean_of_dist
        self.target_itr = itrs
        return
	#gives the index of the best arm

    def best_arm(self ,val):
        temp = max(val)
        return val.index(temp)

    #selects on the basis of epsilon value whether to explore or exploit
    def select_arm(self):
        test = random.uniform(0.0 , 1.0)
       # print ("Random value ->" ,test )
        if test > self.epsilon :

            return self.best_arm(self.values)
        else:
            x =np.random.randint(len(self.counts))
            return x

    def update(self , chosen_arm ):
        self.counts[chosen_arm]=self.counts[chosen_arm]+1 ;

        #generate random  number between 1 to 10

       # rd = random.randint(0, 9)
        if chosen_arm == np.argmax(self.actualmean):
            self.opt_count = self.opt_count +1
        self.optarray = self.optarray + [self.opt_count]
        reward=np.random.normal(self.actualmean[chosen_arm], 1 ,1)

        n = self.counts[chosen_arm]
        value = self.values[chosen_arm]
        if self.itr==1:
            self.netreward = np.append(self.netreward , reward)
            print ("hello")
        else :
            #print (len(self.netreward))
           # print (self.netreward)
           # print (self.itr)
            t = self.netreward[self.itr-2] + reward
            self.netreward = np.append(self.netreward , t )

        new_value = ((n-1)/float(n) * value )+ (1/float(n)) *reward
        self.values[chosen_arm] = new_value
        self.itr = self.itr +1
        return

    def iterations(self ):
        for i in range(self.target_itr):
            temp = self.select_arm()
            self.update(temp)
        return

print ("Enter the epsilon value")
x = float(input())
print ("Enter the number of arms")
no_arms = int(input())
print ("Enter the value of C(for ucb)")
c= int(input())
print ("Enter the number of iterations")
no_of_itr= int(input())
mean_dist = gaussian_dist(no_arms)
'''
examp1 = EpsilonGreedy(0.01 ,[],[] )
examp1.initialize(no_arms , mean_dist, no_of_itr)
examp1.iterations()

examp2 = EpsilonGreedy(0 ,[],[] )
examp2.initialize(no_arms , mean_dist, no_of_itr)
examp2.iterations()
'''
c=2
examp = EpsilonGreedy(x , [] , [] )
examp.initialize( no_arms ,mean_dist,no_of_itr)
examp.iterations()
ucb_exam = ucb.Ucb(c, [], [])
ucb_exam.initialize(no_arms, mean_dist, no_of_itr)
ucb_exam.iterations(no_arms)

print (examp.counts)
print (examp.values)
print (ucb_exam.counts)
print (ucb_exam.values)
'''
print(examp1.counts)
print (examp1.values)
print(examp2.counts)
print (examp2.values)
'''
#print (examp.netreward)
for i in range(no_of_itr):
    examp.netreward[i] = examp.netreward[i] / (i+1)
    examp.optarray[i] = (examp.optarray[i] /(i+1))*100
    '''
    examp1.netreward[i] = examp1.netreward[i]/(i+1)
    examp1.optarray[i] = (examp1.optarray[i] /(i+1))*100
    examp2.netreward[i] = examp2.netreward[i]/(i+1)
    examp2.optarray[i] = (examp2.optarray[i] /(i+1))*100
    '''
    ucb_exam.netreward[i] = ucb_exam.netreward[i]/(i+1)
    ucb_exam.optarray[i]= (ucb_exam.optarray[i]/(i+1))*100
plt.figure(1)
plt.subplot(211)
plt.plot(list(range(no_of_itr)), examp.netreward ,'b', list(range(no_of_itr)), ucb_exam.netreward ,'k')
plt.ylabel('average reward')
plt.subplot(212)
plt.plot(list(range(no_of_itr)), examp.optarray ,'b', list(range(no_of_itr)), ucb_exam.optarray ,'k')
plt.ylabel('optimal %')
plt.show()


from CvPythonExtensions import *
import CvUtil
import ScreenInput
import CvScreenEnums
gc = CyGlobalContext()

class CvPediaBuilding:
	def __init__(self, main):
		self.iBuilding = -1
		self.top = main

	def interfaceScreen(self, iBuilding):
		self.iBuilding = iBuilding
		self.top.deleteAllWidgets()
		screen = self.top.getScreen()
		if not screen.isActive():
			self.top.setPediaCommonWidgets()

		self.H_ICON = 150
		self.W_MAIN_PANE = screen.getXResolution() * 2/5
		self.H_MAIN_PANE = 210
		self.X_ICON = self.top.X_ITEMS_PANE + 30
		self.Y_ICON = (self.H_MAIN_PANE - self.H_ICON)/2 + self.top.Y_ITEMS_PANE

		self.X_STATS_PANE = self.X_ICON + self.H_ICON
		self.Y_STATS_PANE = self.Y_ICON + self.H_ICON /4
		self.W_STATS_PANE = self.W_MAIN_PANE - self.H_ICON - self.top.W_BORDER * 2
		self.H_STATS_PANE = self.H_MAIN_PANE - self.Y_STATS_PANE + self.top.Y_ITEMS_PANE

		self.X_ANIMATION = self.top.X_ITEMS_PANE + self.W_MAIN_PANE + self.top.W_BORDER
		self.Y_ANIMATION = self.top.Y_ITEMS_PANE + 8
		self.W_ANIMATION = self.top.W_ITEMS_PANE - self.top.W_BORDER - self.W_MAIN_PANE
		self.H_ANIMATION = self.H_MAIN_PANE - 10
		self.X_ROTATION_ANIMATION = -20
		self.Z_ROTATION_ANIMATION = 30
		self.SCALE_ANIMATION = 1.0

		self.Y_PREREQ_PANE = self.top.Y_ITEMS_PANE + self.H_MAIN_PANE + 10
		self.H_PREREQ_PANE = 110
		self.Y_SPECIAL_PANE = self.Y_PREREQ_PANE + self.H_PREREQ_PANE + 10
		self.H_SPECIAL_PANE = screen.getYResolution() - self.Y_SPECIAL_PANE - self.top.Y_ITEMS_PANE
		self.H_HISTORY_PANE = screen.getYResolution() - self.Y_PREREQ_PANE - self.top.Y_ITEMS_PANE

		link = self.top.PLATYPEDIA_BUILDING
		sIcon = self.top.sBuildingIcon
		if isLimitedWonderClass(gc.getBuildingInfo(iBuilding).getBuildingClassType()):
			link = self.top.PLATYPEDIA_WONDER
			sIcon = self.top.sWonderIcon

		szHeader = gc.getBuildingInfo(self.iBuilding).getDescription().upper()
		szHeader = u"" + self.top.color4 + CyTranslator().getText(sIcon, ()) + szHeader + " " + CyTranslator().getText(sIcon, ()) + "</color>"
		screen.setLabel(self.top.getNextWidgetName(), "Background", szHeader, CvUtil.FONT_CENTER_JUSTIFY, screen.getXResolution()/2, self.top.Y_TITLE, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)

		screen.setText(self.top.getNextWidgetName(), "Background", self.top.MENU_TEXT, CvUtil.FONT_CENTER_JUSTIFY, screen.getXResolution()/2, screen.getYResolution() - 42, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_PEDIA_MAIN, link, -1)
		screen.addPanel( self.top.getNextWidgetName(), "", "", False, False, self.top.X_ITEMS_PANE, self.top.Y_ITEMS_PANE, self.W_MAIN_PANE, self.H_MAIN_PANE, PanelStyles.PANEL_STYLE_BLUE50)
		screen.addPanel(self.top.getNextWidgetName(), "", "", false, false, self.X_ICON, self.Y_ICON, self.H_ICON, self.H_ICON, PanelStyles.PANEL_STYLE_MAIN)
		screen.addDDSGFC(self.top.getNextWidgetName(), gc.getBuildingInfo(self.iBuilding).getButton(), self.X_ICON + self.H_ICON/2 - 64/2, self.Y_ICON + self.H_ICON/2 - 64/2, 64, 64, WidgetTypes.WIDGET_GENERAL, -1, -1 )
		screen.addBuildingGraphicGFC(self.top.getNextWidgetName(), self.iBuilding, self.X_ANIMATION, self.Y_ANIMATION, self.W_ANIMATION, self.H_ANIMATION, WidgetTypes.WIDGET_GENERAL, -1, -1, self.X_ROTATION_ANIMATION, self.Z_ROTATION_ANIMATION, self.SCALE_ANIMATION, True)

		self.placeStats()
		self.placeRequires()
		self.placeSpecial()
		self.placeHistory()
		self.placeLinks(self.top.iLastScreen == CvScreenEnums.PEDIA_BUILDING and screen.isActive())
		self.top.iLastScreen = CvScreenEnums.PEDIA_BUILDING

	def placeStats(self):
		screen = self.top.getScreen()
		buildingInfo = gc.getBuildingInfo(self.iBuilding)

		if isWorldWonderClass(gc.getBuildingInfo(self.iBuilding).getBuildingClassType()):
			iMaxInstances = gc.getBuildingClassInfo(gc.getBuildingInfo(self.iBuilding).getBuildingClassType()).getMaxGlobalInstances()
			szType = CyTranslator().getText("TXT_KEY_PEDIA_WORLD_WONDER", ())
			if iMaxInstances > 1:
				szType += " " + CyTranslator().getText("TXT_KEY_PEDIA_WONDER_INSTANCES", (iMaxInstances,))
			screen.setLabel(self.top.getNextWidgetName(), "", u"" + szType + u"", CvUtil.FONT_LEFT_JUSTIFY, self.X_STATS_PANE + 8,  self.Y_STATS_PANE - 28, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)
		elif isTeamWonderClass(gc.getBuildingInfo(self.iBuilding).getBuildingClassType()):
			iMaxInstances = gc.getBuildingClassInfo(gc.getBuildingInfo(self.iBuilding).getBuildingClassType()).getMaxTeamInstances()
			szType = CyTranslator().getText("TXT_KEY_PEDIA_TEAM_WONDER", ())
			if iMaxInstances > 1:
				szType += " " + CyTranslator().getText("TXT_KEY_PEDIA_WONDER_INSTANCES", (iMaxInstances,))
			screen.setLabel(self.top.getNextWidgetName(), "", u"" + szType + u"", CvUtil.FONT_LEFT_JUSTIFY, self.X_STATS_PANE + 8,  self.Y_STATS_PANE - 28, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)
		elif isNationalWonderClass(gc.getBuildingInfo(self.iBuilding).getBuildingClassType()):
			iMaxInstances = gc.getBuildingClassInfo(gc.getBuildingInfo(self.iBuilding).getBuildingClassType()).getMaxPlayerInstances()
			szType = CyTranslator().getText("TXT_KEY_PEDIA_NATIONAL_WONDER", ())
			if iMaxInstances > 1:
				szType += " " + CyTranslator().getText("TXT_KEY_PEDIA_WONDER_INSTANCES", (iMaxInstances,))
			screen.setLabel(self.top.getNextWidgetName(), "", u"" + szType + u"", CvUtil.FONT_LEFT_JUSTIFY, self.X_STATS_PANE + 8,  self.Y_STATS_PANE - 28, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)

		panelName = self.top.getNextWidgetName()
		screen.addListBoxGFC(panelName, "", self.X_STATS_PANE, self.Y_STATS_PANE, self.W_STATS_PANE, self.H_STATS_PANE, TableStyles.TABLE_STYLE_EMPTY)
		screen.enableSelect(panelName, False)
		if buildingInfo.getProductionCost() > 0:
			if self.top.iActivePlayer == -1:
				sText = CyTranslator().getText("TXT_KEY_PEDIA_COST", ((buildingInfo.getProductionCost() * gc.getDefineINT("BUILDING_PRODUCTION_PERCENT"))/100,))
			else:
				sText = CyTranslator().getText("TXT_KEY_PEDIA_COST", (gc.getPlayer(self.top.iActivePlayer).getBuildingProductionNeeded(self.iBuilding),))
			sText += u"%c" % gc.getYieldInfo(YieldTypes.YIELD_PRODUCTION).getChar()
			screen.appendListBoxString(panelName, "" + sText + u"", WidgetTypes.WIDGET_GENERAL, 0, 0, CvUtil.FONT_LEFT_JUSTIFY)

		sText = ""
		for k in xrange(YieldTypes.NUM_YIELD_TYPES):
			if buildingInfo.getYieldChange(k) != 0:
				sText += u"%+d%c" % (buildingInfo.getYieldChange(k), gc.getYieldInfo(k).getChar())
		if len(sText):
			sText = "" + CyTranslator().getText("TXT_KEY_PEDIA_YIELDS", ()) + ": " + sText + ""
			screen.appendListBoxString(panelName, sText, WidgetTypes.WIDGET_GENERAL, 0, 0, CvUtil.FONT_LEFT_JUSTIFY)

		sText = ""
		for k in xrange(CommerceTypes.NUM_COMMERCE_TYPES):
			iTotalCommerce = buildingInfo.getObsoleteSafeCommerceChange(k) + buildingInfo.getCommerceChange(k)
			if iTotalCommerce != 0:
				sText += u"%+d%c" % (iTotalCommerce, gc.getCommerceInfo(k).getChar())
		if len(sText):
			sText = "" + CyTranslator().getText("TXT_KEY_CONCEPT_COMMERCE", ()) + ": " + sText + ""
			screen.appendListBoxString(panelName, sText, WidgetTypes.WIDGET_GENERAL, 0, 0, CvUtil.FONT_LEFT_JUSTIFY)

		sText = ""
		iHappiness = buildingInfo.getHappiness()
		if self.top.iActivePlayer != -1:
			if (self.iBuilding == gc.getCivilizationInfo(gc.getPlayer(self.top.iActivePlayer).getCivilizationType()).getCivilizationBuildings(buildingInfo.getBuildingClassType())):
				iHappiness += gc.getPlayer(self.top.iActivePlayer).getExtraBuildingHappiness(self.iBuilding)
		if iHappiness > 0:
			sText += u"%+d%c" % (iHappiness, CyGame().getSymbolID(FontSymbols.HAPPY_CHAR))
		elif iHappiness < 0:
			sText += u"%+d%c" % (- iHappiness, CyGame().getSymbolID(FontSymbols.UNHAPPY_CHAR))

		iHealth = buildingInfo.getHealth()
		if self.top.iActivePlayer != -1:
			if (self.iBuilding == gc.getCivilizationInfo(gc.getPlayer(self.top.iActivePlayer).getCivilizationType()).getCivilizationBuildings(buildingInfo.getBuildingClassType())):
				iHealth += gc.getPlayer(self.top.iActivePlayer).getExtraBuildingHealth(self.iBuilding)
		if iHealth > 0:
			sText += u"%+d%c" % (iHealth, CyGame().getSymbolID(FontSymbols.HEALTHY_CHAR))
		elif iHealth < 0:
			sText += u"%+d%c" % (-iHealth, CyGame().getSymbolID(FontSymbols.UNHEALTHY_CHAR))

		iGreat = buildingInfo.getGreatPeopleRateChange()
		if iGreat != 0:
			sText += u"%+d%c" % (iGreat, CyGame().getSymbolID(FontSymbols.GREAT_PEOPLE_CHAR))
		if len(sText):
			sText = "" + CyTranslator().getText("TXT_KEY_PEDIA_EFFECTS", ()) + ": " + sText + ""
			screen.appendListBoxString(panelName, sText, WidgetTypes.WIDGET_GENERAL, 0, 0, CvUtil.FONT_LEFT_JUSTIFY)

	def placeRequires(self):
		screen = self.top.getScreen()
		panelName = self.top.getNextWidgetName()
		screen.addPanel( panelName, CyTranslator().getText("TXT_KEY_PEDIA_REQUIRES", ()), "", false, true, self.top.X_ITEMS_PANE, self.Y_PREREQ_PANE, self.W_MAIN_PANE, self.H_PREREQ_PANE, PanelStyles.PANEL_STYLE_BLUE50 )

		Info = gc.getBuildingInfo(self.iBuilding)
		for iPrereq in xrange(gc.getNumTechInfos()):
			if isTechRequiredForBuilding(iPrereq, self.iBuilding):
				screen.attachImageButton( panelName, "", gc.getTechInfo(iPrereq).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_TECH, iPrereq, 1, False )

		iPrereq = Info.getPrereqAndBonus()
		if iPrereq > -1:
			screen.attachImageButton( panelName, "", gc.getBonusInfo(iPrereq).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, iPrereq, -1, False )

		for k in xrange(gc.getNUM_BUILDING_PREREQ_OR_BONUSES()):
			iPrereq = Info.getPrereqOrBonuses(k)
			if iPrereq > -1:
				screen.attachImageButton( panelName, "", gc.getBonusInfo(iPrereq).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, iPrereq, -1, False )

		iCorporation = Info.getFoundsCorporation()
		bFirst = true
		if iCorporation > -1:
			for k in xrange(gc.getNUM_CORPORATION_PREREQ_BONUSES()):
				iPrereq = gc.getCorporationInfo(iCorporation).getPrereqBonus(k)
				if iPrereq > -1:
					if not bFirst:
						screen.attachLabel(panelName, "", CyTranslator().getText("TXT_KEY_OR", ()))
					else:
						bFirst = false
					screen.attachImageButton( panelName, "", gc.getBonusInfo(iPrereq).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, iPrereq, -1, False )

		iPrereq = Info.getPrereqReligion()
		if iPrereq > -1:
			screen.attachImageButton( panelName, "", gc.getReligionInfo(iPrereq).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_RELIGION, iPrereq, -1, False )

		iPrereq = Info.getPrereqCorporation()
		if iPrereq > -1:
			screen.attachImageButton( panelName, "", gc.getCorporationInfo(iPrereq).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_CORPORATION, iPrereq, -1, False )
## Coastal and Rivers ##
		if Info.isRiver():
			screen.attachImageButton(panelName, "", CyArtFileMgr().getInterfaceArtInfo("WORLDBUILDER_RIVER_PLACEMENT").getPath(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PYTHON, 6783, -1, CvUtil.FONT_LEFT_JUSTIFY)
		if Info.isWater():
			item = gc.getInfoTypeForString("TERRAIN_COAST")
			screen.attachImageButton(panelName, "", gc.getTerrainInfo(item).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_TERRAIN, item, 1, False)

	def placeSpecial(self):
		screen = self.top.getScreen()
		panelName = self.top.getNextWidgetName()
		screen.addPanel( panelName, CyTranslator().getText("TXT_KEY_PEDIA_SPECIAL_ABILITIES", ()), "", true, false, self.top.X_ITEMS_PANE, self.Y_SPECIAL_PANE, self.W_MAIN_PANE, self.H_SPECIAL_PANE, PanelStyles.PANEL_STYLE_BLUE50 )
		listName = self.top.getNextWidgetName()

		szSpecialText = CyGameTextMgr().getBuildingHelp(self.iBuilding, True, False, False, None)[1:]
## Vote Effects ##
		BuildingInfo = gc.getBuildingInfo(self.iBuilding)
		iVoteSource = BuildingInfo.getVoteSourceType()
		if iVoteSource > -1:
			bFirst = True
			VoteSourceInfo = gc.getVoteSourceInfo(iVoteSource)
			for k in xrange(YieldTypes.NUM_YIELD_TYPES):
				iYieldChange = VoteSourceInfo.getReligionYield(k)
				if (iYieldChange != 0):
					if bFirst:
						szSpecialText += CyTranslator().getText("TXT_KEY_PEDIA_VOTESOURCE_RELIGION",())
						bFirst = False
					szSpecialText += (u"%i%c" % (iYieldChange, gc.getYieldInfo(k).getChar()))
			for k in xrange(CommerceTypes.NUM_COMMERCE_TYPES):
				iCommerceChange = VoteSourceInfo.getReligionCommerce(k)
				if (iCommerceChange != 0):
					if bFirst:
						szSpecialText += CyTranslator().getText("TXT_KEY_PEDIA_VOTESOURCE_RELIGION",())
						bFirst = False
					szSpecialText += (u"%i%c" % (iCommerceChange, gc.getCommerceInfo(k).getChar()))
## Vote Effects ##
## State Religion Requirement ##
		iStateReligion = BuildingInfo.getStateReligion()
		if iStateReligion > -1:
			szSpecialText += CyTranslator().getText("TXT_KEY_PEDIA_UNIT_STATE_RELIGION", (gc.getReligionInfo(iStateReligion).getDescription(),))
## State Religion Requirement ##
		screen.addMultilineText(listName, szSpecialText, self.top.X_ITEMS_PANE+5, self.Y_SPECIAL_PANE+30, self.W_MAIN_PANE-10, self.H_SPECIAL_PANE-30, WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)

	def placeHistory(self):
		screen = self.top.getScreen()
		screen.addPanel(self.top.getNextWidgetName(), CyTranslator().getText("TXT_KEY_CIVILOPEDIA_HISTORY", ()), "", True, True, self.X_ANIMATION, self.Y_PREREQ_PANE, self.W_ANIMATION, self.H_HISTORY_PANE, PanelStyles.PANEL_STYLE_BLUE50 )
		szText = ""
		sStrategy = gc.getBuildingInfo(self.iBuilding).getStrategy()
		if len(sStrategy) and sStrategy.find("TXT_KEY") == -1:
			szText += CyTranslator().getText("TXT_KEY_CIVILOPEDIA_STRATEGY", ())
			szText += sStrategy + "\n\n"
			szText += CyTranslator().getText("TXT_KEY_CIVILOPEDIA_BACKGROUND", ())
		sPedia = gc.getBuildingInfo(self.iBuilding).getCivilopedia()
		if sPedia.find("TXT_KEY") == -1:
			szText += sPedia
		screen.addMultilineText(self.top.getNextWidgetName(), szText, self.X_ANIMATION + 10, self.Y_PREREQ_PANE + 30, self.W_ANIMATION - 20, self.H_HISTORY_PANE - 30, WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)

	def placeLinks(self, bRedraw):
		screen = self.top.getScreen()
		if bRedraw:
			screen.show("PlatyTable")
			return
		screen.addTableControlGFC("PlatyTable", 1, self.top.X_PANEL, 55, self.top.W_PANEL, screen.getYResolution() - 110, False, False, 24, 24, TableStyles.TABLE_STYLE_STANDARD);
		screen.enableSelect("PlatyTable", True)
		screen.setTableColumnHeader("PlatyTable", 0, "", self.top.W_PANEL)

		if isLimitedWonderClass(gc.getBuildingInfo(self.iBuilding).getBuildingClassType()):
			listSorted = self.top.sortWonders(self.top.iSortWonders)
			sIcon = self.top.sWonderIcon
		else:
			listSorted = self.top.sortBuildings(self.top.iSortBuildings)
			sIcon = self.top.sBuildingIcon
		self.top.placePediaLinks(listSorted, CyTranslator().getText(sIcon, ()), self.iBuilding, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BUILDING, -1)

	def handleInput (self, inputClass):
		return 0