# importing modules
import itertools
from collections import Counter
from Progress_bar import *

# create a counter dictionary of letter frequencies
def getFrequency(_words):
    concatenation= ''.join(map(str, _words))
    return Counter(concatenation)

# average the letter frequency across the numbers of letters in the counter dictionary keys
def averageFrequency(_letter_scores):
    for key in _letter_scores.keys():
        _letter_scores[key] = _letter_scores[key]/len(_letter_scores.keys())
    return _letter_scores

# create a counter dictionary for letter frequencies per location in word:
def letterPositionFrequency(_words):
    concatenation = ["", "", "", "", ""]
    for _word in _words:
        for _letter, index in zip(_word, range(5)):
            concatenation[index]+=_letter
    return [Counter(concatenation[0]), Counter(concatenation[1]), Counter(concatenation[2]), Counter(concatenation[3]), Counter(concatenation[4])]

# average the letter positional frequency across the numbers of letters in the counter dictionary keys
def averagePositionalFrequency(_letter_positions):
    for position in _letter_positions:
        for key in position.keys():
            position[key] = position[key] / len(position.keys())
    return _letter_positions

# get the score of a word using the letter scores (by frequency) found earlier
def getFrequencyScore(_word, _letter_scores):
    score = 0
    for letter in _word:
        score += _letter_scores[letter]
    return score

# get the score of a word using the letter positional scores (by frequency) found earlier
def getPositionalScore(_word, _letter_positions):
    score = 0
    for letter, index in zip(_word, range(5)):
        score += _letter_positions[index][letter]
    return score

# creating a list of all possible permutations of received feedback for a guessed word
def possibleCombinations():
    N = 5  # number of objects (e.g. slots)
    possible_values = [-1, 0, 1]  # -1 wrong letter, 0 right letter wrong place, 1 right letter right place
    # using itertools to create the permutations in question
    result = list(itertools.product(possible_values, repeat=N))
    # removing the option to guess the word on the first try, not statistically significant or interesting
    result.remove((1, 1, 1, 1, 1))
    return result

# check the remaining words after playing the first word and comparing it with a combination of a given answer (received feedback for a guessed word)
def checkWordAndCombo(_combination, _word, _words):
    vowles = ['a','e','i','o','u']
    # -1 wrong letter, 0 right letter wrong place, 1 right letter right place
    words_to_check = _words.copy()
    misplaced_letters = []
    refreshed_list = []
    for slot, index in zip(_combination, range(5)):
        if slot == -1:
            if _word[index] == "_":
                continue
            # if the letter is not in the target word at all, clear the words with that letter at that location
            words_to_check = [x for x in words_to_check if ((_word[index] not in x or _word[index] in vowles) and _word[index] != x[index])]
        elif slot == 0:
            # if the letter is not in the target word at a specific location, clear the words with that letter at that location
            words_to_check = [x for x in words_to_check if x[index] != _word[index]]
            # add the letter to a collection of misplaced letters
            misplaced_letters.append(_word[index])
        elif slot == 1:
            # if the letter is in the target word at the correct location, clear the words with that don't have that letter at that location
            words_to_check = [x for x in words_to_check if x[index] == _word[index]]
        else:
            continue
    if misplaced_letters:
        # if there were misplaced letters, create a new list of words that contain all the misplaced letters
        for a_word in words_to_check:
            test_condition = all(letter in a_word for letter in misplaced_letters)
            if test_condition:
                refreshed_list.append(a_word)
        return refreshed_list
    return words_to_check

# check all the words against all the combinations of possible outcomes (242 possible outcomes against ~2300 words in the Wordle answer bank)
def rankStartingScore(_combinations, _words, _letter_scores, _letter_positions, showProgress=False):
    starting_rank = []
    # Initial call to print 0% progress
    if showProgress:
        printProgressBarPyCharm(0, len(_words), prefix='Progress:', suffix='Complete', length=50)
    # iterate over all the words in the word bank
    for a_word, progress in zip(_words, range(len(_words))):
        current_word = ["", 0]  # word and score combo
        current_word[0] = a_word
        NonZero = 0
        # for each word, iterate over all the possible received feedback
        for combination in _combinations:
            # add all possible next turns given the data (all remaining words given the answer received)
            current_word[1] += len(checkWordAndCombo(combination, a_word, _words))
            # count the number of times there was any possible future data - 0 options left means the word is either very unique,
            # therefore not providing a lot of data, or we were right on the first guess - low possibility with low statistical significance
            if len(checkWordAndCombo(combination, a_word, _words)) != 0:
                NonZero += 1
        # average the score of all possible next-turn words divided by iterations that provided data
        if NonZero > 0:
            current_word[1] = current_word[1]/NonZero
        else:
            current_word[1] = 1
        starting_rank.append([current_word[0], current_word[1], len(set(a_word)), getFrequencyScore(current_word[0], _letter_scores), getPositionalScore(current_word[0], _letter_positions)])
        # calculate the final score
        starting_rank[-1].append((1/starting_rank[-1][1])*starting_rank[-1][2]*starting_rank[-1][3]*starting_rank[-1][4])
        # Update Progress Bar
        if showProgress:
            printProgressBarPyCharm(progress, len(_words), prefix='Progress:', suffix='Complete', length=50)
    if showProgress:
        printProgressBarPyCharm(100, 100, prefix='Progress:', suffix='Complete', length=50)
    starting_rank.sort(key=lambda x: x[5], reverse=True)
    return starting_rank


'''
>> P
N*M 보드가 있고 빨간 구슬/ 파란 구슬/ 구멍/ 빈 칸/ 장애물이 있을 때
구슬을 굴려서 빨간 구슬만 구멍으로 빼내는데 소요되는 최소 횟수 구하라
    - 상/하/좌/우로 구슬이 움직이지 않을때까지 이동
    - 10번 이하로 빼낼 수 없다면 -1 출력
>> S
상하좌우 이동시 벽을 만날 때까지
    - board[x][y] == '#' 이면 중지 // 'B/R'이면 한 칸 나아가며 -1 // '.'이면 한 칸 나아가며 + 1
    -> R/B 모두 이동한 뒤 해당 좌표가 False면 dfs 재귀 True면 continue
좌표를 모두 False로 초기화하고 해당 좌표를 방문할 때마다 True로 바꿔놓을까?
    - visited[1 << 9][1 << 9][1 << 9][1 << 9] = False # [rx][ry][bx][by]
'''

def dfs(depth: int, rx: int, ry: int, bx: int, by: int):
    global ans, flag

    if flag:
        return

    if depth > 9:
        flag = True
        return

    # 4방향 장애물 나올 때까지 이동
    for dx, dy in move:
        move_r = 0
        move_b = 0
        goal_r = False
        goal_b = False
        # 함수호출해서 r/b 각각 다음 좌표랑 구멍 들어간 여부 리턴
        # 구멍 r만 들어갔으면 종료
        #
        while board[rx][ry] != '#':
            rx = rx + dx
            ry = rx + dy
            if board[rx][ry] in ('R', 'B'):
                continue
            if board[rx][ry] == 'O':
                goal_r = True
            move_r += 1

        while board[bx][by] != '#':
            bx = bx + dx
            by = bx + dy
            if board[bx][by] in ('R', 'B'):
                continue
            if board[bx][by] == 'O':
                goal_b = True
            move_b += 1

        if (rx+(dx*move_r), ry+(dx*move_r), bx+(dx*move_b), by+(dx*move_b)) not in visited:
            dfs(depth+1, rx+(dx*move_r), ry+(dx*move_r),
                bx+(dx*move_b), by+(dx*move_b))
        # while rx

    # red, blue 좌표가 기존에 있었던 곳이면 pass 아니면 재귀 호출

N, M = map(int, input().split())
board = []
visited = set()
red, blue = (), ()
move = [(-1, 0), (1, 0), (0, -1), (0, 1)]  # 상 / 하 / 좌 / 우

for i in range(N):
    row = input()
    board.append(row)
    for j in range(len(row)):
        if row[j] == 'R':
            red = (i, j)
        if row[j] == 'B':
            blue = (i, j)

ans = 1e9
flag = False    # ans 값 구했을 때
visited.add((red[0], red[1], blue[0], blue[1]))
dfs(0, red[0], red[1], blue[0], blue[1])

print(ans)
# print(red, blue)


# pylint: disable=C0111,R0903

"""Shows when a key is pressed

Parameters:
    * keys.keys: Comma-separated list of keys to monitor (defaults to "")
"""

import core.module
import core.widget
import core.decorators
import core.event

import util.format

from pynput.keyboard import Listener

NAMES = {
    "Key.cmd": "cmd",
    "Key.ctrl": "ctrl",
    "Key.shift": "shift",
    "Key.alt": "alt",
}

class Module(core.module.Module):
    @core.decorators.never
    def __init__(self, config, theme):
        super().__init__(config, theme, [])

        self._listener = Listener(on_press=self._key_press, on_release=self._key_release)

        self._keys = util.format.aslist(self.parameter("keys", "Key.cmd,Key.ctrl,Key.alt,Key.shift"))

        for k in self._keys:
            self.add_widget(name=k, full_text=self._display_name(k), hidden=True)
        self._listener.start()

    def _display_name(self, key):
        return NAMES.get(key, key)

    def _key_press(self, key):
        key = str(key)
        if not key in self._keys: return
        self.widget(key).hidden = False
        core.event.trigger("update", [self.id], redraw_only=False)

    def _key_release(self, key):
        key = str(key)
        if not key in self._keys: return
        self.widget(key).hidden = True
        core.event.trigger("update", [self.id], redraw_only=False)

    def state(self, widget):
        return widget.name

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4


#!/usr/bin/python
import sys
import re
from date_time import date_time
from subprocess import call
from subprocess import check_output
import subprocess

def download_from_swift(cont,obj):
    src_cmd=". /home/ubuntu/.novarc;"
    swift_cmd=src_cmd + "swift download " + cont + " --skip-identical --prefix " + obj
    sys.stderr.write(date_time() + swift_cmd + "\n")
    try:
        check=check_output(swift_cmd,shell=True,stderr=subprocess.PIPE)
    except:
        sys.stderr.write(date_time() + "Download of " + obj + " from " + cont + " failed\n")
        exit(1)
    return 0
if __name__ == "__main__":
    import argparse
    parser=argparse.ArgumentParser(description='Simple download module to get files from swift.  Can use prefix or whole object name')
    parser.add_argument('-c','--container',action='store',dest='cont',help='Swift container, i.e. PANCAN')
    parser.add_argument('-o','--object',action='store',dest='obj',help='Swift object name/prefix, i.e. RAW/2015-1234')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)

    inputs=parser.parse_args()
    (cont,obj)=(inputs.cont,inputs.obj)
    download_from_swift(cont,obj)


class Calculator:
    def __init__(self,n1,n2):
        self.n1=n1
        self.n2=n2
    def add(self):
        r=self.n1 +self.n2
        return r
    def sub(self):
        r=self.n1 -self.n2
        return r
    def mul(self):
        r=self.n1 *self.n2
        return r
    def div(self):
        r=self.n1 /self.n2
        return r
cal=Calculator(3,5)
res=cal.add()
print(f'{cal.n1} + {cal.n2} = {res}');
res=cal.sub()
print(f'{cal.n1} - {cal.n2} = {res}')
res=cal.mul()
print(f'{cal.n1} * {cal.n2} = {res}')
res=cal.div()
print(f'{cal.n1} / {cal.n2} = {res}')


"""Demo of shared c-types with numpy"""

import multiprocessing as mp

from multiprocessing import sharedctypes
from numpy import ctypeslib

def fill_array(arr, value):
    arr.fill(value)

if __name__ == '__main__':

    # Create an array of integers on c-level
    raw_array = sharedctypes.RawArray('i', 4)

    # Convert the raw array into a numpy c-object
    array = ctypeslib.as_array(raw_array)

    # Reshape in-place
    array.shape = (2, 2)

    # Create two processes which write on different rows of `array`
    process1 = mp.Process(target=fill_array, args=(array[0, :], 5))
    process2 = mp.Process(target=fill_array, args=(array[1, :], 7))

    # Start both processes and wait for them to finish
    process1.start()
    process2.start()
    process1.join()
    process2.join()

    print(array)  # [[5 5] \ [7 7]]


# global imports
import json
import random
import time
import os
import sys

# local imports
from experiences.quic_web_browse import launchTests

# global vars
TOPOS_FP = './../topos.json'
GRAPHS_FP = './../test_graphs.json'
TG_PAIRS = './../pairs_topos_graphs.json'
random.seed(42)

def getNetemToTuple(topo):
    '''in json -> tuple (0 0 loss 1.69%) is stored as [0, 0, loss 1.69%]
        revert it back to tuple, otherwise error is produced
    '''
    topo[0]['netem'][0] = (topo[0]['netem'][0][0], topo[0]['netem'][0][1], topo[0]['netem'][0][2])
    topo[0]['netem'][1] = (topo[0]['netem'][1][0], topo[0]['netem'][1][1], topo[0]['netem'][1][2])
    return topo

def load_or_generate_pairs():
    if not os.path.isfile(TG_PAIRS):
        with open(TOPOS_FP, 'r') as fp:
            topos = json.load(fp)
        with open(GRAPHS_FP, 'r') as fp:
            graphs = json.load(fp)

        tuple_list = []
        for i in range(len(topos)):
            for j in range(len(graphs)):
                tuple_list.append((i, j))

        pairs = random.sample(tuple_list, 100)
        output = []
        for (t, g) in pairs:
            pair = {
                'graph': graphs[g],
                'topo': topos[t]
            }
            output.append(pair)
        with open(TG_PAIRS, 'w') as fp:
            json.dump(output, fp, indent=4)
        return output
    else:
        with open(TG_PAIRS, 'r') as fp:
            pairs = json.load(fp)
        return pairs

def restart_nn_inference(bdw_path1, bdw_path2):
    PYTHON_NN_INFERENCE = 'python3.6'

    def send_cmd(cmd):
        import subprocess
        REMOTE_PORT = '22'
        REMOTE_HOST = 'mininet@192.168.122.157'
        ssh_cmd = ["ssh", "-p", REMOTE_PORT, REMOTE_HOST, cmd]
        subprocess.Popen(ssh_cmd,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE,
                        shell=False)

    send_cmd("killall {}".format(PYTHON_NN_INFERENCE))
    time.sleep(0.5)
    spawn_cmd = "{} {} {} {}".format("python3.6", "./git/nn_testing/nn_inference.py",str(bdw_path1), str(bdw_path2))
    send_cmd(spawn_cmd)

def main():
    if len(sys.argv[1:]) < 1:
        print ("Not enough arguments")
        exit(-1)

    graphs_to_execute = sys.argv[1:]
    graphs_to_execute = [(int(g)-1) for g in graphs_to_execute]
    pairs = load_or_generate_pairs()

    counter = 1
    for g in graphs_to_execute:
        p = pairs[g]
        print (p)

        graph = p['graph']['file']
        topo = getNetemToTuple([p['topo']])

        bdw_path1 = p['topo']['paths'][0]['bandwidth']
        bdw_path2 = p['topo']['paths'][1]['bandwidth']

        # fp.write("{},\t{},\t{}\n".format(counter, graph, p['topo']))
        counter += 1

        try:
            start = time.time()
            restart_nn_inference(bdw_path1, bdw_path2)
            launchTests(topo, graph)
            end = time.time()

            diff = int(start - end)
            print("runtime: {}s".format(diff))
        except Exception as ex:
            print (ex)

if __name__ == "__main__":
    main()


import pandas as pd
import numpy as np
from tqdm import tqdm

class Word2vec(object):
    def __init__(self, window_size, embedding_dimension) -> None:
        self.window_size = window_size
        self.embedding_dimension = embedding_dimension

        self.data = None
        self.word_to_id = None
        self.id_to_word = None
        self.vocab_size = None

    def fit(self, path_to_data):
        df = pd.read_csv(path_to_data, index_col=False)
        df.drop(['Unnamed: 0'], axis=1, inplace=True)
        data = df.unstack().values

        self.data = data
        self._generate_word_to_id()
        self._generate_id_to_word()
        self.vocab_size = len(self.word_to_id)

    def _generate_word_to_id(self):
        word_to_id = dict()
        cnt = 0
        for review in self.data:
            for char in review.split(' '):
                if char not in word_to_id:
                    word_to_id[char] = cnt
                    cnt += 1
        self.word_to_id = word_to_id

    def _generate_id_to_word(self):
        self.id_to_word = {str(v):k for k,v in self.word_to_id.items()}

    def _get_low_context(self, idx, review):
        low_idx = np.max([0, idx-self.window_size])
        return review[low_idx:idx]

    def _get_high_context(self, idx, review):
        high_idx = np.min([len(review), idx+self.window_size])
        return review[idx:high_idx]

    def _concat_context(self, low, high):
        return low + high

    def _one_hot_encode_word(self, word):
        encoded = np.zeros(self.vocab_size, dtype=np.int)
        word_id = self.word_to_id[word]
        encoded[word_id] = 1
        return encoded

    def _one_hot_encode_context(self, context):
        encoded_context = np.zeros(self.vocab_size, dtype=np.int)
        for word in context:
            encoded_context[self.word_to_id[word]] = 1
        return encoded_context

    def generate_training_data(self, n=-1):
        X = []
        y = []
        reviews = self.data
        for k, review in tqdm(enumerate(reviews), desc='Generating training set'):
            if k == n:
                break
            else:
                words_review = review.split(' ')
                if '' in words_review:
                    words_review.remove('')
                elif ' ' in words_review:
                    words_review.remove(' ')
                for i, word in enumerate(words_review):

                    mid_word = word

                    low_context = self._get_low_context(idx=i, review=words_review)
                    high_context = self._get_high_context(idx=i+1, review=words_review)
                    context = self._concat_context(low_context, high_context)

                    encoded_mid_word = self._one_hot_encode_word(word=mid_word)
                    encoded_context = self._one_hot_encode_context(context=context)

                    X.append(encoded_mid_word)
                    y.append(encoded_context)

        return np.array(X), np.array(y)

    def get_word_with_id(self, id):
        return self.id_to_word[str(id)]


class Graph:
    def __init__(self, nodeList):
        self.nodesDict = nodeList
        self.startNode = ""
        self.endNode = ""

    def addNode(self, node):
        self.nodesDict.append(node)

    def showNodes(self):
        print(self.nodesDict)

    def setStartNode(self, startnode):
        self.startNode = startnode

    def setEndNode(self, endNode):
        self.endNode = endNode

    def dijkstra2(self):
        visited = []
        notVisited = []
        pathDict = {}
        nodeDict = {}
        currNode = "A"

        for key, value in self.nodesDict.items():
            pathDict[key] = 1000
            notVisited.append(key)

        pathDict[self.startNode] = 0

        cont = True

        while cont:
            for key, value in self.nodesDict[currNode].items():
                if key not in visited:
                    if(pathDict[key] > pathDict[currNode] + value):
                        pathDict[key] = pathDict[currNode] + value
                        nodeDict[key] = currNode
            visited.append(currNode)
            notVisited.remove(currNode)

            temp = {}
            for el in notVisited:
                temp[el] = pathDict[el]

            if len(temp) == 0:
                break

            currNode = min(temp, key=temp.get)

            if currNode == self.endNode:
                break

        go = True
        returnNodeList = []
        nextNode = self.endNode

        while go:
            returnNodeList.append(nextNode)
            nextNode = nodeDict[nextNode]

            if nextNode == self.startNode:
                returnNodeList.append(self.startNode)
                go = False

        returnNodeList.reverse()

        return returnNodeList

    def dijkstra(self):
        S = {}
        i = 0

        for key, value in self.nodesDict.items():
            print(value)
            nextNode = min(self.nodesDict[self.startNode], key=self.nodesDict[self.startNode].get)
            i += 1
            S[nextNode] = i

        S[self.startNode] = 0

        print(S)

class Node:
    def __init__(self, name, conn):
        self.name = name
        self.connections = conn

    def addConnection(self, name, weight):
        self.connections[name] = weight

    def showConnections(self):
        print(self.connections)

nodeA = Node('A', {'C': 1, 'D': 2})
nodeB = Node('B', {'F': 3, 'C': 2})
nodeC = Node('C', {'A': 1, 'B': 2, 'D': 1, 'E': 3})
nodeD = Node('D', {'A': 2, 'C': 1, 'G': 1})
nodeE = Node('E', {'C': 3, 'F': 2})
nodeF = Node('F', {'E': 2, 'G': 1})
nodeG = Node('G', {'D': 1, 'F': 1})

nodeList = {}
nodeList['A'] = {'C': 1, 'D': 2}
nodeList['B'] = {'F': 3, 'C': 2}
nodeList['C'] = {'A': 1, 'B': 2, 'D': 1, 'E': 3}
nodeList['D'] = {'A': 2, 'C': 1, 'G': 1}
nodeList['E'] = {'C': 3, 'F': 2}
nodeList['F'] = {'E': 2, 'G': 1}
nodeList['G'] = {'D': 1, 'F': 1}

graph = Graph(nodeList)
# graph.showNodes()
graph.setStartNode('A')
graph.setEndNode('F')
path = graph.dijkstra2()
print(path)


from django.contrib import messages
from django.shortcuts import redirect, render
import bcrypt
from .decorators import login_required
from .models import User, Books, Reviews, Author
from django.db.models import Count
from django.db.utils import IntegrityError

@login_required
def index(request):

    context = {
        'saludo': 'Hola'
    }
    return render(request, 'index.html', context)

@login_required
def books(request):
    usuarios = User.objects.all()
    libros = Books.objects.all()
    resenas = Reviews.objects.all()
    last_three = Reviews.objects.all().order_by('-created_at')[:3]
    autores = Author.objects.all()

    context ={
        'User': usuarios,
        'Books': libros,
        'Reviews': resenas,
        'newest_three_reviews': last_three,
        'Authors':autores,

    }
    return render(request, 'books.html', context)

@login_required
def booksadd(request):
    if request.method == 'GET':
        resenas = Reviews.objects.all()
        libros = Books.objects.all()
        autores = Author.objects.all()
        #estrellas =[]

        context = {
            'books' : libros,
            'Authors': autores,
            'Reviews': resenas,
            #'Estrellas': estrellas,

        }
        return render(request,"booksadd.html", context)

    else:
        errors = Books.objects.basic_validator(request.POST)
        autornuevo = None
        if request.POST['author_id'] == 'other':
            # en este caso hay que crearla
            new_author_name = request.POST['newAuthor']
            old_authors = Author.objects.filter(name__iexact=new_author_name)

            if len(old_authors) > 0:
                messages.error(request,"This author already exists.")
                return redirect("/books/add")
            autornuevo = Author.objects.create(name = new_author_name)

        else:
            # en este caso hay que rescatarla de la DB
            author_id = int(request.POST['author_id'])
            autornuevo = Author.objects.get(id=author_id)

        # Ahora estamos 100% seguros que SI existe 'autornuevo'
        user_id = request.session['user']['id']
        usuario = User.objects.get(id= user_id)
        titulo = request.POST['title']
        resena = request.POST['review']
        score = int(request.POST['stars'])

        '''
        if score == 1:
            estrellas.add('★☆☆☆☆')
        elif rating == 2:
            estrellas.add('★★☆☆☆')
        elif rating == 3:
            estrellas.add('★★★☆☆')
        elif rating == 4:
            estrellas.add('★★★★☆')
        else:
            estrellas.add('★★★★★')
        '''

        if len(errors)> 0: #si el suscriptor lleno mal esta cuestion
            for key, error_message in errors.items():
                messages.error(request, error_message)
            return redirect(f'/books/add')

        old_books = Books.objects.filter(title__iexact=titulo)
        if len(old_books) > 0:
            messages.error(request,"This title already exists.")

        try:
            new_book = Books.objects.create(title = titulo, author= autornuevo)
            new_review = Reviews.objects.create(desc= resena, rating= score, user= usuario, book = new_book)
        except IntegrityError:
            messages.error(request,"This title already exists. You could write another review.")
            return redirect(f'/books/add')

        messages.success(request, 'Book successfully added and Author successfully linked to the book')
    return redirect('/books')

@login_required
def booksview(request, nom):
    if request.method =='GET':
        usuarios = User.objects.all()
        libros = Books.objects.all()
        resenas = Reviews.objects.all()
        autores = Author.objects.all()
        this_book = Books.objects.get(id = int(nom))
        this_book_reviews = this_book.review.all()

        bookids = []
        tot = 0
        for rev in this_book_reviews:
            bookids.append(rev.user_id)
            tot= rev.rating

        if len(bookids) == 0:
            tot_sum = 'No reviews yet'
        else:
            tot_sum = tot/len(bookids)

        #this_review_users = User.objects.filter(review__book= this_book)
        #this_forbidden_to_review_users = User.objects.get(review__book__User__id= you)
        context ={
            'User': usuarios,
            'Books': libros,
            'Reviews': resenas,
            'Author': autores,
            'this_book': this_book,
            'this_book_reviews': this_book_reviews,
            'bookids':bookids,
            'tot_sum': tot_sum,

        }
        return render(request, 'booksview.html', context)
    else:
        #lo que tengo que preguntar ahora es que si existen reseñas de este libro que sean de un user con el mismo id del sesion, entonces no puede agregar
        #una reseña nueva para ese libro. entonces if [user_id for user_id in this_book_reviews.user.id not in request.session.user.id]
        curr_user = request.session['user']
        fresh_resena = request.POST['new_review']
        nuevo_score = int(request.POST['new_stars'])
        new_resena = Reviews.objects.create(desc= fresh_resena, rating= nuevo_score, user= curr_user, book = this_book)
        messages.success(request, 'Review successfully linked to the book')
        return redirect(f'/books/{nom}')

@login_required
def userview(request, nem):
    usuarios = User.objects.all()
    libros = Books.objects.all()
    resenas = Reviews.objects.all()
    autores = Author.objects.all()
    this_user = User.objects.get(id= int(nem))
    this_user_revs = Reviews.objects.filter(user = this_user)
    this_user_total_reviews = []
    for rev in this_user_revs:
        this_user_total_reviews.append(rev)

    context ={
        'User': usuarios,
        'Books': libros,
        'Reviews': resenas,
        'Author': autores,
        'this_user': this_user,
        'this_user_total_reviews': len(this_user_total_reviews)
    }

    return render(request, 'userview.html', context)

@login_required
def deletereview(request, nim):
    this_review = Reviews.objects.get(id = int(nim))
    this_book_id = this_review.book.id
    this_user= this_review.user
    context ={
        'this_user': this_user
    }
    del this_review
    return redirect(f'/books/{this_book_id}')

def addreview(request, nam):
    this_book = Books.objects.get(id = int(nam))
    user_id = request.session['user']['id']
    usuario = User.objects.get(id= user_id)
    fresh_resena = request.POST['new_review']
    nuevo_score = int(request.POST['new_stars'])
    new_resena = Reviews.objects.create(desc= fresh_resena, rating= nuevo_score, user= usuario, book = this_book)
    messages.success(request, 'Review successfully linked to the book')
    return redirect(f'/books/{nam}')

#connected_user_id = request.session['user']['id']
#user_connected = request.session['user']
#got:reviewsonthisbookuser = User.filter.get(this_book__review__user__id= user_id)
#tengo


from django.urls import path
from django.contrib import admin
from . import views
"""from django.contrib.auth import as auth_views"""
urlpatterns = [
    path('',views.home,name='home'),
    path('otp/<uid>', views.otpVerify, name='otp'),
    path('signin/',views.signin,name='signin'),
    path('signup/',views.signup,name='signup'),
    path('logout/',views.logout_acc,name='logout'),
    path('profile/',views.profile,name='profile'),
    path('advice/',views.advice,name='advice'),
    path('doctors/',views.doctor,name='doctor'),
    path('payment/',views.payment,name='payment'),
    path('sucess/',views.sucess,name='sucess'),
]


# 题目：有一堆石头，重量为stone[i], 每次任意取两块，如果重量相等，则粉碎了，如果重量不等，剩下一块石头重量为二者差值，
# 求问剩下的石头最小可能的值

# 思路：此题能想到是01背包问题不太容易，从题意得我们想得到的是剩下石头的最小值(最值问题)，怎么会有最小值呢？
# 极限情况就是每次拿的石头重量一样，在放大一点就是把石头分两堆，重量为sum/2, 每次从两堆各取一块石头，肯定有一种取法得到剩下值为0，类似两两抵消
# 当然并不是sum/2一定能整除，但我们保证两堆石头最接近sum//2，就能获得最小的剩下值，说到这就和416挺像了
# 所以对齐背包问题：有一个容量为sum//2的背包，去装重量stone[i]，价值stone[i]的, 求dp[j]的最大值

# 解法：动态规划-01背包
class Solution:
    def lastStoneWeightII(self, stones: List[int]) -> int:
        # dp[j] 表示容量为j的背包能装的物品的最大价值
        target = sum(stones) // 2
        dp = [0] * (target + 1)
        # 初始化
        dp[0] = 0      # 也可以不写
        for i in range(len(stones)):
            for j in range(target, stones[i]-1, -1):  # 减一才能到stones[i]
                dp[j] = max(dp[j], dp[j-stones[i]] + stones[i])
        res = dp[target]
        # 我们得到了两堆相等石头的最大重量，用总的一减就是粉碎后剩下的了
        return sum(stones) - (2 * res)


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

def feature_normalize(samples):
    """
    Feature-normalize samples
    :param samples: samples.
    :return: normalized feature
    """
    sam = np.copy(samples)
    col = sam.shape[1]
    for i in range(col):
        std_mean = np.mean(sam[ : ,i])
        sam[ : ,i] = (sam[ : ,i] - std_mean) / np.std(sam[ : ,i])
    return sam

def get_usv(sample_norm):
    m  = sample_norm.shape[0]
    Cov = (1/m) * np.transpose(sample_norm).dot(sample_norm)
    u, s, v = np.linalg.svd(Cov)
    return u,s

def project_data(samples, U, K):
    """
    Computes the reduced data representation when
    projecting only on to the top "K" eigenvectors
    """
    # Reduced U is the first "K" columns in U
    reduced_U = U[:,0:K]
    res = samples.dot(reduced_U)
    return res

def recover_data(Z, U, K):
    U_inverse = np.linalg.inv(U)
    reduced_U = U_inverse[:K]
    output = np.dot(Z,reduced_U)
    return output

def main():
    datafile = 'data1.mat'
    mat = scipy.io.loadmat(datafile)
    samples = mat['X']

    plt.figure(figsize=(7, 7))
    plt.scatter(samples[:, 0], samples[:, 1], s=30, facecolors='none', edgecolors='b')
    plt.title("Example Dataset", fontsize=18)
    plt.grid(True)
    # Feature normalize

    samples_norm = feature_normalize(samples)

    # Run SVD

    U, S = get_usv(samples_norm)  # IMPLEMENT U.

    # output the top principal component (eigen- vector) found
    # should expect to see an output of about [-0.707 -0.707]"
    print('Top principal component is ', U[:, 0])

    plt.figure(figsize=(7, 7))
    plt.scatter(samples[:, 0], samples[:, 1], s=30, facecolors='none', edgecolors='b')
    plt.title("Example Dataset: PCA Eigenvectors Shown", fontsize=18)
    plt.xlabel('x1', fontsize=18)
    plt.ylabel('x2', fontsize=18)
    plt.grid(True)
    # To draw the principal component, you draw them starting
    # at the mean of the data
    x1_mean = np.mean(samples[ : ,0])
    x2_mean = np.mean(samples[ : ,1])

    arrow1 = plt.arrow(x1_mean,x2_mean,U[:,0][0]*S[0], U[:,0][1]*S[0], color ='r',
                       label = 'First Principle Component')
    arrow2 = plt.arrow(x1_mean,x2_mean,U[:,1][0]*S[1], U[:,1][1]*S[1], color ='g',
                       label = 'Second Principle Component')

    # IMPLEMENT PLOT

    plt.legend(handles = [arrow1, arrow2],loc=4)

    # project the first example onto the first dimension
    # should see a value of about 1.481"

    z = project_data(samples_norm, U, 1)
    print('Projection of the first example is %0.3f.' % float(z[0]))
    recovered_sample = recover_data(z, U, 1)
    print('Recovered approximation of the first example is ', recovered_sample[0])

    plt.figure(figsize=(7, 7))
    plt.scatter(samples_norm[:, 0], samples_norm[:, 1], s=30, facecolors='none',
                edgecolors='b', label='Original Data Points')
    plt.scatter(recovered_sample[:, 0], recovered_sample[:, 1], s=30, facecolors='none',
                edgecolors='r', label='PCA Reduced Data Points')

    plt.title("Example Dataset: Reduced Dimension Points Shown", fontsize=14)
    plt.xlabel('x1 [Feature Normalized]', fontsize=14)
    plt.ylabel('x2 [Feature Normalized]', fontsize=14)
    plt.grid(True)

    for x in range(samples_norm.shape[0]):
        plt.plot([samples_norm[x, 0], recovered_sample[x, 0]], [samples_norm[x, 1], recovered_sample[x, 1]], 'k--')

    plt.legend(loc=4)
    plt.xlim((-2.5, 2.5))
    plt.ylim((-2.5, 2.5))
    plt.show()

if __name__ == '__main__':
    main()


from flask_restful import Resource, reqparse
import requests
import json
import datetime, time

from execo_g5k import *
import config
from Packages.ResourceAlloc.helper import Helper
from Models import DeploymentModel, g5kHostsModel

parser = reqparse.RequestParser()
parser.add_argument('NbNodes', help = 'This field cannot be blank', required = False)
parser.add_argument('walltime', help = 'This field cannot be blank', required = False)
parser.add_argument('jobName', help = 'This field cannot be blank', required = False)

parser.add_argument('job_id', help = 'This field cannot be blank', required = False)
parser.add_argument('frontend', help = 'This field cannot be blank', required = False)

class NodeReservation(Resource):
    def post(self):
        data = parser.parse_args()
        print(data)
        # try :
        h = Helper()
            #print(h.SiteList())
        hosts,time,job_id,frontend = h.AllocDeployG5k(data['NbNodes'],data['walltime'],data['jobName'])
        #Model Creation
        deployment = DeploymentModel(
            job_name=data['jobName'],
            nb_nodes= data['NbNodes'],
            frontend = frontend,
            walltime= self.toSeconds(data['walltime']),
            job_id = job_id,
            deployment_time =self.toSeconds(str(time))
        )
        try:
            deployment.save_to_db()
            lastDep = int(DeploymentModel.getLastid())-1
            for host in hosts:
                hostBD = g5kHostsModel(
                   id_dep = lastDep,
                   hostName = str(host)
                )
                hostBD.save_to_db()

        except:
            return {'message': 'Something went wrong'}, 500
        return {
            "message" :"successfuly deployed",
            "frontend":str(frontend),
            "job_id" :str(job_id),
            "hosts": hosts,
            "deploymentTime":str(time)
        },200
        # except:
            #return {"message":"error !!"},400
    def toSeconds(self,date):
        Dtime = (datetime.datetime.strptime(date.partition('.')[0], "%H:%M:%S")).time()
        seconds = (Dtime.hour * 60 + Dtime.minute) * 60 + Dtime.second
        return seconds

class NodeDestroy(Resource):
    def post(self):
        data = parser.parse_args()
        print(data)
        h = Helper()
        h.removeResources(data['job_id'],data['frontend'])

class AllDeployments(Resource):
    def get(self):
        print(DeploymentModel.getNextId())
        return DeploymentModel.return_allDeployments()

class getLastJob(Resource):
    def get(self):
        lastDepID = int(DeploymentModel.getLastid())-1
        res,job_id_frontend,status =DeploymentModel.getLastDeployment(lastDepID)
        return res,status

class getJobG5kInfo(Resource):
    def get(self):
        lastDepID = int(DeploymentModel.getLastid())-1
        res,job_id,frontend,status =DeploymentModel.getLastDeployment(lastDepID)
        ansG5k = get_oar_job_info(oar_job_id=job_id, frontend=frontend)
        ansG5k = json.dumps(ansG5k)
        res =json.loads(ansG5k)
        now = datetime.datetime.now()
        unixTS =oar.oar_date_to_unixts(str(now))
        timeLeft = (res['start_date'] + res['walltime'])- unixTS
        print (timeLeft)
        res.update({'time_left': timeLeft})
        res.update({'id_deployment': lastDepID})
        print(res)
        return res


import time
from test_slowdb import test_slowdb
from test_init import test_cache_ports_registered
from test_get_key import test_get_non_existing_key, test_get_existing_key
from test_put_key import (
    test_put_non_existing_key,
    test_put_existing_key,
    test_put_cache_aside,
)
from test_lru_cache import test_lru_cache
from test_consistent_hashing import test_consistent_hashing
from test_ch_distribution import test_consistent_hashing_distribution
from test_replication import test_replication
from test_fault_tolerance import test_fault_tolerance
from test_concurrent_get import test_concurrency_get
from test_cache_communication import test_cache_communication
import threading
import os
import subprocess
import signal
import argparse

def kill_process_on_port(port):
    """
    Kill the process using the specified port
    :param port: port number
    :return: None
    """
    command = f"lsof -i :{port} -t"
    try:
        result = subprocess.check_output(command, shell=True, text=True)
        pids = result.strip().split("\n")
        for pid in pids:
            if pid:
                os.kill(int(pid), signal.SIGTERM)
    except subprocess.CalledProcessError:
        # No process found using the specified port
        pass

def main(kill_ports, stop_event=None):
    """
    Start the SlowDB server, the cache cluster and the cache servers
    :param stop_event: stop event
    :return: None
    """
    if kill_ports:
        print("Killing processes on ports")
        for port in [10000, 8001, 8002, 8010, 8000]:
            kill_process_on_port(port)

    cache_ports = [8001, 8002, 8010]

    # Start the SlowDB server
    slowdb_process = subprocess.Popen(["python3", "slowdb.py"])

    cluster_process = subprocess.Popen(["python3", "cache_proxy.py", "10000"])
    time.sleep(2)
    # Start the cache servers
    cache_processes = [
        subprocess.Popen(["python3", "cache_server.py", str(port), "10000"])
        for port in cache_ports
    ]

    if stop_event:
        stop_event.wait()
        slowdb_process.terminate()
        cluster_process.terminate()
        for process in cache_processes:
            process.terminate()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Run tests with optional kill_ports flag')
    parser.add_argument('--kill_ports', type=bool, default=False,
                        help='Set to True to kill processes on ports, default is False')

    args = parser.parse_args()
    score = 0
    main_thread = threading.Thread(target=main, args=(args.kill_ports,))
    main_thread.start()
    time.sleep(5)
    print("------------------start of test----------------------")
    tests = [
        test_lru_cache,
        test_consistent_hashing,
        test_slowdb,
        test_cache_ports_registered,
        test_get_non_existing_key,
        test_get_existing_key,
        test_put_non_existing_key,
        test_put_existing_key,
        test_cache_communication,
        test_put_cache_aside,
        test_consistent_hashing_distribution,
        test_replication,
        test_fault_tolerance,
        test_concurrency_get
    ]
    for test in tests:
        result = test()
        if result != 0:
            score += result
            print(f"{test.__name__}: PASS +{result}")
        else:
            print(f"{test.__name__}: FAIL")
    print("------------------end of test----------------------")
    print(f"Total Score: {score} / 200")
    main_thread.join()


# rankDataRequestServer.py

import sys
import blpapi
import datetime

import blpapi
import sys
import datetime
import os

# for additional DEBUG logging
#os.environ['BLPAPI_LOGLEVEL'] = 'DEBUG'

SESSION_STARTED                 = blpapi.Name("SessionStarted")
SESSION_STARTUP_FAILURE         = blpapi.Name("SessionStartupFailure")
SESSION_CONNECTION_UP           = blpapi.Name("SessionnConnectionUp")
SESSION_CONNECTION_DOWN         = blpapi.Name("SessionConnectionDown")
SESSION_TERMINATED              = blpapi.Name("SessionTerminated")

SERVICE_OPENED                  = blpapi.Name("ServiceOpened")
SERVICE_OPEN_FAILURE            = blpapi.Name("ServiceOpenFailure")
SERVICE_DOWN                    = blpapi.Name("ServiceDown")

AUTHORIZATION_SUCCESS           = blpapi.Name("AuthorizationSuccess")
AUTHORIZATION_FAILURE           = blpapi.Name("AuthorizationFailure")

SLOW_CONSUMER_WARNING           = blpapi.Name("SlowConsumerWarning")
SLOW_CONSUMER_WARNING_CLEARED   = blpapi.Name("SlowConsumerWarningCleared")

EXCEPTION                       = blpapi.Name("Exception")
REPORT                          = blpapi.Name("Report")

d_rank = "//blp/rankapi"
d_auth = "//blp/apiauth"
d_host = "10.137.23.19"             # IP address of the Trading API Server instance.
d_port = 8194
d_user = "RANKAPI\\SERVER_API"      # User name of the server-side user.
d_ip = "1.1.1.1"                    # Any IP address unique for this user.

bEnd=False

class SessionEventHandler():

    def sendAuthRequest(self,session):

        authService = session.getService(d_auth)
        authReq = authService.createAuthorizationRequest()
        authReq.set("emrsId",d_user)
        authReq.set("ipAddress", d_ip)
        self.identity = session.createIdentity()

        print ("Sending authorization request: %s" % (authReq))

        session.sendAuthorizationRequest(authReq, self.identity)

        print ("Authorization request sent.")

    def sendCreateOrder(self, session):

        service = session.getService(d_rank)

        # build request
        request = service.createRequest("Query")

        ### set date/time range
        request.set("start", datetime.datetime(2021, 3, 1, 0, 0, 0, 0))
        request.set("end", datetime.datetime(2021, 3, 2, 0, 0, 0, 0))

        ### group by 0=Broker , 1=Security
        #request.set("groupBy", "Broker")
        request.set("groupBy", "Security")

        ### exchanges or securities
        # exchanges can be set using Bloomberg exchange code
        #exchanges = request.getElement("securityCriteria").setChoice("exchanges")
        #exchange = exchanges.appendElement()
        #exchange.setElement("code", "US");

        ### securities can be set to either Bloomberg ticker or figi
        securities = request.getElement("securityCriteria").setChoice("securities")
        securities.appendElement().setElement("ticker", "AAPL US Equity")
        securities.appendElement().setElement("ticker", "MSFT US Equity")
        securities.appendElement().setElement("ticker", "VOD LN Equity")

        #security.setElement("figi", "BBG000B9XRY4"); # figi for AAPL US Equity

        ### specify broker by acronym or rank
        #broker = request.getElement("brokers").appendElement()
        #broker.setElement("acronym", "ABCD"); # acronym

        ### source enum 0=Broker Contributed
        request.set("source", "Broker Contributed")

        ### units enum 0=Shares, 1=Local, 2=USD, 3=EUR, 4=GBP
        request.set("units", "Shares")

        print ("Sending Request: %s" % request.toString())

        #self.requestID = session.sendRequest(request)

        self.requestID = blpapi.CorrelationId()
        session.sendRequest(request, identity=self.identity, correlationId=self.requestID)  #Note the addition of the identity object.

        print ("RANK data request sent.")

    def processAdminEvent(self,event):
        print("Processing ADMIN event")

        for msg in event:
            if msg.messageType() == SLOW_CONSUMER_WARNING:
                print("Warning: Entered Slow Consumer status")

            elif msg.messageType() == SLOW_CONSUMER_WARNING_CLEARED:
                print("Slow consumer status cleared")

            else:
                print(msg)

    def processSessionStatusEvent(self,event,session):
        print("Processing SESSION_STATUS event")

        for msg in event:
            if msg.messageType() == SESSION_STARTED:
                print("Session started...")
                session.openServiceAsync(d_auth)

            elif msg.messageType() == SESSION_STARTUP_FAILURE:
                print("Error: Session startup failed", file=sys.stderr)

            else:
                print(msg)

    def processServiceStatusEvent(self,event,session):
        print ("Processing SERVICE_STATUS event")

        for msg in event:

            if msg.messageType() == SERVICE_OPENED:

                serviceName = msg.asElement().getElementAsString("serviceName")

                print("Service opened [%s]" % (serviceName))

                if serviceName==d_auth:

                    print("Auth service opened... Opening EMSX service...")
                    session.openServiceAsync(d_rank)

                elif serviceName==d_rank:

                    print("RANK service opened... Sending authorization request...")

                    self.sendAuthRequest(session)

            elif msg.messageType() == SERVICE_OPEN_FAILURE:
                    print("Error: Service Failed to open", file=sys.stderr)

    def processAuthorizationStatusEvent(self,event):

        print ("Processing AUTHORIZATION_STATUS event")

        for msg in event:

            print("AUTHORIZATION_STATUS message: %s" % (msg))

    def processResponseEvent(self, event, session):
        print("Processing RESPONSE event")

        for msg in event:

            print("MESSAGE: %s" % msg.toString())
            print("CORRELATION ID: %d" % msg.correlationIds()[0].value())

            if msg.messageType() == AUTHORIZATION_SUCCESS:
                print("Authorization successful....")
                print ("SeatType: %s" % (self.identity.getSeatType()))
                self.sendCreateOrder(session)

            elif msg.messageType() == AUTHORIZATION_FAILURE:
                print("Authorization failed....", file=sys.stderr)
                # insert code here to automatically retry authorization...

            elif msg.correlationIds()[0].value() == self.requestID.value():
                print("MESSAGE TYPE: %s" % msg.messageType())

                if msg.messageType() == EXCEPTION:
                    print (msg)
                    print ("Exception occured")

                elif msg.messageType() == REPORT:
                    ts = msg.getElementAsDatetime("timestampUtc")
                    print ("Timestamp: ", ts)
                    print(msg)

                global bEnd
                bEnd = True
            else:
                print ("Unexpected message...")
                print (msg)

    def processMiscEvents(self, event):

        print("Processing " + event.eventType() + " event")

        for msg in event:

            print("MISC MESSAGE: %s" % (msg.tostring()))

    def processEvent(self, event, session):
        try:

            if event.eventType() == blpapi.Event.ADMIN:
                self.processAdminEvent(event)

            if event.eventType() == blpapi.Event.SESSION_STATUS:
                self.processSessionStatusEvent(event,session)

            elif event.eventType() == blpapi.Event.SERVICE_STATUS:
                self.processServiceStatusEvent(event,session)

            elif event.eventType() == blpapi.Event.AUTHORIZATION_STATUS:
                self.processAuthorizationStatusEvent(event)

            elif event.eventType() == blpapi.Event.RESPONSE:
                self.processResponseEvent(event,session)

            else:
                self.processMiscEvents(event)

        except:
            print("Exception:  %s" % sys.exc_info()[0])

        return False

def main():

    sessionOptions = blpapi.SessionOptions()
    sessionOptions.setServerHost(d_host)
    sessionOptions.setServerPort(d_port)

    print("Connecting to %s:%d" % (d_host,d_port))

    eventHandler = SessionEventHandler()

    session = blpapi.Session(sessionOptions, eventHandler.processEvent)

    if not session.startAsync():
        print("Failed to start session.", file=sys.stderr)
        return

    global bEnd
    while bEnd==False:
        pass

    print ("Terminating...")

    session.stop()

if __name__ == "__main__":
    print("Bloomberg - RANK API Example - Server - rankDataRequestServer")
    try:
        main()
    except KeyboardInterrupt:
        print("Ctrl+C pressed. Stopping...")

__copyright__ = """
Copyright 2022. Bloomberg Finance L.P.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:  The above
copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""


#! /usr/bin/env python3

''' Scraping Image '''

import requests
import bs4

res = requests.get('https://en.wikipedia.org/wiki/Cicada_3301')
soup = bs4.BeautifulSoup(res.text, 'lxml')

image_info = soup.select('.thumbimage')
print(type(image_info))
print(len(image_info))
print(image_info)
print(image_info[0])

cicada = image_info[0]

image_link = 'http:'+ cicada['src']
print(image_link)

cicada_image = requests.get(image_link, 'lxml')
with open('cicada_image.jpg', 'wb') as f:
    f.write(cicada_image.content)


#!/usr/bin/python3

# inverse.py by optixal
# Constructs private exponent (d) from 2 prime factors (p, q) and public exponent (e)
# Usage: python3 inverse.py [p] [q] [e=65537]

import sys

def checkreq():
    if len(sys.argv) < 3:
        print("[*] Usage:", sys.argv[0], "[p]", "[q]", "[e=65537]")
        sys.exit(1)

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception("Mod inverse not found!")
    else:
        return x % m

def main():
    checkreq()

    p = int(sys.argv[1])
    q = int(sys.argv[2])
    print("Prime Factor p:", p)
    print("Prime Factor q:", q)

    n = p * q
    print("Modulus n:", n)

    totient = (p - 1) * (q - 1)
    print("Totient:", totient)

    # Usually e = 3 or 65537
    if len(sys.argv) == 4:
        e = int(sys.argv[3])
    else:
        e = 65537
    print("Public Exponent e:", e)

    d = modinv(e, totient)
    print("Private Exponent d:", d)

if __name__ == "__main__":
    main()


from math import isqrt
def isPrime(n):
    for i in range(2, isqrt(n) + 1):
        if n % i == 0:
            return False
    return True

def isSquare(n):
    if n <= 0:
        return False
    s = isqrt(n)
    return s * s == n

def P2(A):
    n = len(A)
    ans = 0
    for i in range(2, n):
        if isSquare(A[i]) and isPrime(i):
            ans += A[i]
    return ans


# https://github.com/thiswillbeyourgithub/i3_search_anki_collection
# Work under GPL v3 license
import urllib.request
import json
import argparse

def ankiconnect(action, **params):
    def request_wrapper(action, **params):
        return {'action': action, 'params': params, 'version': 6}

    requestJson = json.dumps(request_wrapper(action, **params)
                             ).encode('utf-8')
    try:
        response = json.load(urllib.request.urlopen(
                                urllib.request.Request(
                                    'http://localhost:8765',
                                    requestJson)))
    except (ConnectionRefusedError, urllib.error.URLError) as e:
        print(f"{e}: is Anki open and ankiconnect enabled?")
        raise SystemExit()

    if len(response) != 2:
        raise Exception('response has an unexpected number of fields')
    if 'error' not in response:
        raise Exception('response is missing required error field')
    if 'result' not in response:
        raise Exception('response is missing required result field')
    if response['error'] is not None:
        raise Exception(response['error'])
    return response['result']

parser = argparse.ArgumentParser()
parser.add_argument("--query",
                    nargs=1,
                    metavar="QUERY",
                    dest='query',
                    type=str,
                    required=True,
                    help="Query to ask to anki")
args = parser.parse_args().__dict__

ankiconnect(action="guiBrowse", query=args["query"][0])


def solution(elements):
    answer = 0
    leng = len(elements)
    data = set()
    for i in range(1, len(elements)):
        # print("i", i)
        sum = 0
        for j in range(i):
            sum += elements[j]
        data.add(sum)
        for idx, element in enumerate(elements):
            sum -= element
            sum += elements[(idx + i)%leng]
            data.add(sum)
    sum = 0
    for element in elements:
        sum += element
    data.add(sum)
    return len(data)


import os,sys
import numpy as np
from mpi4py import MPI
import pickle
import random as rand

from py_mc.mc import *

def RX_MPI_init():
    args = sys.argv
    nreplicas = int(args[1] )
    nprocs_per_replica = int(args[2])
    commworld = MPI.COMM_WORLD
    worldrank = commworld.Get_rank()
    worldprocs = commworld.Get_size()
    rand_seeds = [rand.random() for i in range(worldprocs)]
    rand.seed(rand_seeds[worldrank])

    if worldprocs > nreplicas:
        if worldrank == 0:
            print("Setting number of replicas smaller than MPI processes; I hope you"
                  +" know what you're doing..."
            )
            sys.stdout.flush()
        if worldrank >= nreplicas:
            # belong to comm that does nothing
            comm = commworld.Split(color=1, key=worldrank)
            comm.Free()
            sys.exit() # Wait for MPI_finalize
        else:
            comm = commworld.Split(color=0, key=worldrank)
    else:
        comm = commworld
    return comm, nreplicas, nprocs_per_replica

class ParallelMC(object):
    def __init__(self, comm, MCalgo, model, configs, kTs, grid=None, subdirs=True):
        self.comm = comm
        self.rank = self.comm.Get_rank()
        self.procs = self.comm.Get_size()
        self.kTs = kTs
        self.model = model
        self.subdirs = subdirs
        self.nreplicas = len(configs)

        if not(self.procs == self.nreplicas == len(self.kTs)):
            if self.rank==0:
                print("ERROR: You have to set the number of replicas equal to the"
                      +"number of temperatures equal to the number of processes"
                )
            sys.exit(1)

        myconfig = configs[self.rank]
        mytemp = kTs[self.rank]
        self.mycalc = MCalgo(model, mytemp, myconfig, grid)

    def run(self, nsteps, sample_frequency, observer=observer_base()):
        if self.subdirs:
            # make working directory for this rank
            try:
                os.mkdir(str(self.rank))
            except FileExistsError:
                pass
            os.chdir(str(self.rank))
        observables = self.mycalc.run(nsteps, sample_frequency, observer)
        pickle.dump(self.mycalc.config, open("config.pickle","wb"))
        if self.subdirs: os.chdir("../")
        if sample_frequency:
            obs_buffer = np.empty([self.procs,len(observables)])
            self.comm.Allgather(observables, obs_buffer)
            return obs_buffer

class TemperatureRX_MPI(ParallelMC):
    def __init__(self, comm, MCalgo, model, configs, kTs, grid=None,  subdirs=True):
        super(TemperatureRX_MPI, self).__init__(comm, MCalgo, model, configs, kTs, grid, subdirs)
        self.betas = 1.0/np.array(kTs)
        self.rank_to_T = np.arange(0, self.procs, 1, dtype=np.int)
        self.float_buffer = np.array(0.0, dtype=np.float)
        self.int_buffer = np.array(0, dtype=np.int)
        self.obs_save = []
        self.Trank_hist = []
        self.kT_hist = []

    def reload(self):
        self.rank_to_T = pickle.load(open("rank_to_T.pickle","rb"))
        self.mycalc.kT = self.kTs[self.rank_to_T[self.rank]]
        self.mycalc.config = pickle.load(open(str(self.rank)+"/calc.pickle","rb"))
        self.obs_save0 = np.load(open(str(self.rank)+"/obs_save.npy","rb"))
        self.Trank_hist0 = np.load(open(str(self.rank)+"/Trank_hist.npy","rb"))
        self.kT_hist0 = np.load(open(str(self.rank)+"/kT_hist.npy","rb"))

    def find_procrank_from_Trank(self, Trank):
        i = np.argwhere(self.rank_to_T == Trank)
        if i == None:
            sys.exit("Internal error in TemperatureRX_MPI.find_procrank_from_Trank")
        else:
            return i

    def Xtrial(self, XCscheme=-1):
        # What is my temperature rank?
        myTrank = self.rank_to_T[self.rank]
        if (myTrank+XCscheme)%2 == 0 and myTrank == self.procs - 1:
            self.comm.Allgather(self.rank_to_T[self.rank], self.rank_to_T)
            return
        if XCscheme == 1 and myTrank == 0:
            self.comm.Allgather(self.rank_to_T[self.rank], self.rank_to_T)
            return
        if (myTrank+XCscheme)%2 == 0:
            myTrankp1 = myTrank + 1
            # Get the energy from the replica with higher temperature
            exchange_rank = self.find_procrank_from_Trank(myTrankp1)
            self.comm.Recv(self.float_buffer, source=exchange_rank, tag=1)
            delta = (self.betas[myTrankp1] - self.betas[myTrank]) \
                    * (self.mycalc.energy - self.float_buffer)
            if delta < 0.0:
                # Exchange temperatures!
                self.comm.Send([self.rank_to_T[self.rank],1,MPI.INT], dest=exchange_rank, tag=2)

                self.rank_to_T[self.rank] = myTrankp1
            else:
                accept_probability = exp(-delta)
                #print accept_probability, "accept prob"
                if random() <= accept_probability:
                    self.comm.Send([self.rank_to_T[self.rank],1,MPI.INT], dest=exchange_rank, tag=2)
                    self.rank_to_T[self.rank] = myTrankp1
                else:
                    #print("RXtrial rejected")
                    self.comm.Send([self.rank_to_T[exchange_rank],1,MPI.INT], dest=exchange_rank, tag=2)
        else:
            myTrankm1 = myTrank - 1
            exchange_rank = self.find_procrank_from_Trank(myTrankm1)
            self.comm.Send(self.mycalc.energy, dest=exchange_rank, tag=1)
            self.comm.Recv([self.int_buffer,1,MPI.INT],source=exchange_rank, tag=2)
            self.rank_to_T[self.rank] = self.int_buffer
        self.comm.Allgather(self.rank_to_T[self.rank], self.rank_to_T)
        self.mycalc.kT = self.kTs[self.rank_to_T[self.rank]]
        return

    def run(self, nsteps, RXtrial_frequency, sample_frequency=verylargeint,
            print_frequency=verylargeint,
            observer=observer_base(), subdirs=True, save_obs=True):
        if subdirs:
            try:
                os.mkdir(str(self.rank))
            except FileExistsError:
                pass
            os.chdir(str(self.rank))
        self.accept_count = 0
        self.mycalc.energy = self.mycalc.model.energy(self.mycalc.config)
        test_observe = observer.observe(self.mycalc,open(os.devnull,"w"),lprint=False)
        if hasattr(test_observe,"__iter__"):
            obs_len = len(test_observe)
            obs = np.zeros([len(self.kTs), obs_len])
        if hasattr(test_observe,'__add__'):
            observe = True
        else:
            observe = False
        nsample = 0
        XCscheme = 0
        output = open("obs.dat", "a")
        for i in range(1,nsteps+1):
            self.mycalc.MCstep()
            if i%RXtrial_frequency == 0:
                self.Xtrial(XCscheme)
                XCscheme = (XCscheme+1)%2
            if i%sample_frequency == 0 and observe:
                obs_step = observer.observe(self.mycalc, output,i%print_frequency==0)
                obs[self.rank_to_T[self.rank]] += obs_step
                if save_obs:
                    self.obs_save.append(obs_step)
                    self.Trank_hist.append(self.rank_to_T[self.rank])
                    self.kT_hist.append(self.mycalc.kT)
                nsample += 1

        pickle.dump(self.mycalc.config, open("calc.pickle","wb"))
        if save_obs:
            if hasattr(self, "obs_save0"):
                obs_save_ = np.concatenate((self.obs_save0, np.array(self.obs_save)))
                Trank_hist_ = np.concatenate((self.Trank_hist0, np.array(self.Trank_hist)))
                kT_hist_ = np.concatenate((self.kT_hist0, np.array(self.kT_hist)))
            else:
                obs_save_ = np.array(self.obs_save)
                Trank_hist_ = np.array(self.Trank_hist)
                kT_hist_ = np.array(self.kT_hist)

            np.save(open("obs_save.npy","wb"), obs_save_, False)
            np.save(open("Trank_hist.npy", "wb"), Trank_hist_, False)
            np.save(open("kT_hist.npy", "wb"), kT_hist_, False)

        if subdirs: os.chdir("../")

        if self.rank == 0:
            pickle.dump(self.rank_to_T, open("rank_to_T.pickle","wb"))
            np.save(open("kTs.npy", "wb"), self.kTs, False)

        if nsample != 0:
            obs = np.array(obs)
            obs_buffer = np.empty(obs.shape)
            obs /= nsample
            self.comm.Allreduce(obs, obs_buffer, op=MPI.SUM)
            obs_list = []
            args_info = observer.obs_info(self.mycalc)
            for i in range(len(self.kTs)):
                obs_list.append(obs_decode(args_info,obs_buffer[i]))
            return obs_list


from datetime import timedelta, datetime, timezone
from dateutil import parser

""" Used for testing.
"""
EVALUATION_TIME_OVERRIDE = None

class SunriseSunsetData(object):

    def __init__(self, results):
        self.sunrise = parser.isoparse(results['results']['sunrise'])
        self.sunset = parser.isoparse(results['results']['sunset'])
        self.civil_twilight_begin = parser.isoparse(results['results']['civil_twilight_begin'])
        self.civil_twilight_end = parser.isoparse(results['results']['civil_twilight_end'])
        self.nautical_twilight_begin = parser.isoparse(results['results']['nautical_twilight_begin'])
        self.nautical_twilight_end = parser.isoparse(results['results']['nautical_twilight_end'])
        self.astronomical_twilight_begin = parser.isoparse(results['results']['astronomical_twilight_begin'])
        self.astronomical_twilight_end = parser.isoparse(results['results']['astronomical_twilight_end'])

        self.sunrise_begin = self.civil_twilight_begin
        self.sunrise_length = self.sunrise - self.sunrise_begin
        self.sunrise_end = self.sunrise

        self.sunset_begin = self.sunset
        self.sunset_end = self.civil_twilight_end
        self.sunset_length = self.sunset_end - self.sunset
        self.avg_transition_time = timedelta(seconds=(self.sunrise_length.seconds + self.sunset_length.seconds) / 2)

    @property
    def utcnow(self):
        return EVALUATION_TIME_OVERRIDE or datetime.now(tz=timezone.utc)

    @property
    def is_daylight(self):
        """ True from the the begining of civil_twilight_begin until until sunset
        """
        return self.utcnow >= self.civil_twilight_begin and self.utcnow < self.sunset

    @property
    def is_nighttime(self):

        return self.utcnow >= self.sunset or self.utcnow < self.civil_twilight_begin

    @property
    def is_twilight(self):

        if (self.utcnow >= self.civil_twilight_begin and self.utcnow <= self.sunrise):
            return True

        if (self.utcnow >= self.sunset_begin and self.utcnow <= self.civil_twilight_end):
            return True

        return False

    @property
    def proportion(self):
        # civil_twilight_begin > sunrise > day > sunset > civil_twilight_end
        if (self.utcnow >= self.sunrise_begin and self.utcnow <= self.sunrise_end):
            time_left = self.sunrise_end - self.utcnow
            total_time = self.sunrise_length
            return 1 - (time_left / total_time)
        elif (self.utcnow >= self.sunset_begin and self.utcnow <= self.sunset_end):
            time_left = self.sunset_end - self.utcnow
            total_time = self.sunset_length
            return 1 - (time_left / total_time)
        else:
            return 1.0

    def __str__(self):
        return "utcnow={}, civil_twilight_begin={}, sunrise={}, sunset={}, sunset_end={}, is_daylight={}, is_nightlight={}, is_twilight={}, proportion={}".format(self.utcnow.strftime("%c"), self.civil_twilight_begin, self.sunrise, self.sunset, self.civil_twilight_end, self.is_daylight, self.is_nighttime, self.is_twilight, self.proportion)

    def to_json(self):
        return {'utcnow': self.utcnow,
                'civil_twilight_begin': self.civil_twilight_begin,
                'sunrise': self.sunrise,
                'sunset': self.sunset,
                'civil_twilight_end': self.civil_twilight_end,
                'is_daylight': self.is_daylight,
                'is_twilight': self.is_twilight,
                'is_nighttime': self.is_nighttime,
                'sunrise_length': self.sunrise_length,
                'sunset_length': self.sunset_length
                }


from decimal import Decimal

closeness_threshold = 1 ** -5

# * simpler rational numbers will be rated higher
# * value should be a between [0, 1]
# * returns value between [0, 1]
def score_simplicity(value: float) -> float:
    exact_value = Decimal(str(value))

    for denominator in range(1, 1000):
        if exact_value % Decimal(1 / denominator) < closeness_threshold:
            return 1 / denominator

    return -1


import re
import inspect

class Listened:

    def __init__(self):
        self.__listeners = {}

    def add_listener(self, listener, pattern='\w+'):
        regex = re.compile(pattern)
        if not regex in self.__listeners:
            self.__listeners[regex] = set()

        args_spec = inspect.getargspec(listener)
        group_names = regex.groupindex.keys()
        if set(args_spec.args).issuperset(set(group_names)) or args_spec.keywords:
            self.__listeners[regex].add(listener)
        else:
            raise ValueError(
                'Pattern group names and listener attributes do not match.')

    def discard_listener(self, pattern, listener):
        regex = re.compile(pattern)
        if regex in self.__listeners:
            self.__listeners[regex].discard(listener)

    def notify_listeners(self, text):
        for regex, listeners in self.__listeners.iteritems():
            match = regex.match(text)
            if match:
                for listener in listeners:
                    # raw mode
                    if regex.pattern == '\w+':
                        listener(text)
                    else:
                        listener(text, regex.pattern, **match.groupdict())


import json
from http import HTTPStatus
from json import JSONDecodeError
from threading import Thread

from django.db.models import F
from django.http import JsonResponse
from django.urls import reverse
from django.views import View

from onequiz.operations.featureFlagOperations import featureFlagOperations, FeatureFlagType
from onequiz.operations.generalOperations import (
    QuestionAndResponse, QuizAttemptAutomaticMarking, QuizAttemptManualMarking
)
from quiz.models import (
    EssayResponse, MultipleChoiceResponse, QuizAttempt, Topic, TrueOrFalseResponse, Result, Response, Quiz
)

class TopicObjectApiEventVersion1Component(View):
    def get(self, *args, **kwargs):
        topics = Topic.objects.filter(**self.request.GET.dict()).annotate(
            _id=F('id'), _name=F('name'), _description=F('description')
        ).values('id', 'name', 'description')

        response = {
            "success": True,
            "data": {
                "topics": list(topics)
            }
        }
        return JsonResponse(response, status=HTTPStatus.OK)

class QuizAttemptObjectApiEventVersion1Component(View):

    def createResponseModels(self, quizAttempt, questionList):
        responseList = []
        essayResponseList = []
        trueOrFalseQuestionList = []
        multipleChoiceQuestionList = []

        for question in questionList:
            response = Response(question_id=question.id)
            responseList.append(response)

            if hasattr(question, 'essayQuestion'):
                essayResponseList.append(
                    EssayResponse(response=response, answer='')
                )
            elif hasattr(question, 'trueOrFalseQuestion'):
                trueOrFalseQuestionList.append(
                    TrueOrFalseResponse(response=response, trueSelected=None)
                )
            elif hasattr(question, 'multipleChoiceQuestion'):
                choiceList = question.multipleChoiceQuestion.choices['choices']
                for item in choiceList:
                    item['isChecked'] = False
                    del item['isCorrect']
                multipleChoiceQuestionList.append(
                    MultipleChoiceResponse(response=response, answers={'answers': choiceList})
                )
            else:
                print('Unknown question type.')
                continue

        Response.objects.bulk_create(responseList)
        EssayResponse.objects.bulk_create(essayResponseList)
        TrueOrFalseResponse.objects.bulk_create(trueOrFalseQuestionList)
        MultipleChoiceResponse.objects.bulk_create(multipleChoiceQuestionList)
        quizAttempt.responses.add(*responseList)
        return

    def post(self, *args, **kwargs):
        quizId = self.request.GET.get('quizId')
        existingQuizAttempt = QuizAttempt.objects.filter(
            quiz_id=quizId, user=self.request.user, status=QuizAttempt.Status.IN_PROGRESS
        )
        if existingQuizAttempt.exists():
            response = {
                "success": True,
                "message": "You already have an attempt that is in progress.",
                "redirectUrl": reverse('quiz:quiz-attempt-view', kwargs={'attemptId': existingQuizAttempt[0].id})
            }
            return JsonResponse(response, status=HTTPStatus.OK)

        quiz = Quiz.objects.prefetch_related(
            'questions__essayQuestion', 'questions__trueOrFalseQuestion', 'questions__multipleChoiceQuestion'
        ).get(id=quizId)
        newQuizAttempt = QuizAttempt.objects.create(user=self.request.user, quiz_id=quiz.id)
        questionList = quiz.getQuestions()

        self.createResponseModels(newQuizAttempt, questionList)
        newQuizAttempt.status = QuizAttempt.Status.IN_PROGRESS
        newQuizAttempt.save()

        response = {
            "success": True,
            "redirectUrl": reverse('quiz:quiz-attempt-view', kwargs={'attemptId': newQuizAttempt.id})
        }
        return JsonResponse(response, status=HTTPStatus.OK)

class QuizMarkingOccurrenceApiEventVersion1Component(View):

    def put(self, *args, **kwargs):
        quizAttempt = QuizAttempt.objects.select_related('quiz').prefetch_related(
            'responses__question',
        ).get(id=kwargs.get('id'))
        try:
            put = json.loads(self.request.body)
        except JSONDecodeError:
            put = json.loads(self.request.body.decode().replace('"', "'").replace("'", '"'))

        questionList = quizAttempt.quiz.getQuestions()
        responseList = quizAttempt.responses.all()
        awardedMarks = put.get('response', [])
        quizAttemptManualMarking = QuizAttemptManualMarking(quizAttempt, questionList, responseList, awardedMarks)

        if quizAttemptManualMarking.mark():
            resultObject = quizAttemptManualMarking.result
            resultObject.versionNo = Result.objects.filter(quizAttempt=quizAttempt).count() + 1
            quizAttempt.status = QuizAttempt.Status.MARKED
            resultObject.save()
            quizAttempt.save()

        response = {
            "success": True,
            "redirectUrl": reverse('quiz:quiz-attempt-result-view', kwargs={'attemptId': quizAttempt.id})
        }
        return JsonResponse(response, status=HTTPStatus.OK)

class QuestionResponseUpdateApiEventVersion1Component(View):

    def put(self, *args, **kwargs):
        if not featureFlagOperations.isEnabled(FeatureFlagType.SAVE_QUIZ_ATTEMPT_RESPONSE_AS_DRAFT):
            response = {
                "success": False,
                "message": f'Feature flag {FeatureFlagType.SAVE_QUIZ_ATTEMPT_RESPONSE_AS_DRAFT.value} not enabled.'
            }
            return JsonResponse(response, status=HTTPStatus.OK)

        try:
            put = json.loads(self.request.body)
        except JSONDecodeError:
            put = json.loads(self.request.body.decode().replace('"', "'").replace("'", '"'))

        qaid = put.get('quizAttemptId')
        qid = put.get('question').get('id')
        rid = put.get('response').get('id')

        quizAttempt = QuizAttempt.objects.select_related().prefetch_related('responses__question').get(id=qaid)
        responseList = quizAttempt.responses.all()
        responseInstance = next((r for r in responseList if r.question.id == qid and r.id == rid), None)

        if put.get('question').get('type') == 'EssayQuestion':
            responseInstance.essayResponse.answer = put.get('response').get('text')
            responseInstance.essayResponse.save()
        elif put.get('question').get('type') == 'TrueOrFalseQuestion':
            responseInstance.trueOrFalseResponse.trueSelected = put.get('response').get('selectedOption')
            responseInstance.trueOrFalseResponse.save()
        elif put.get('question').get('type') == 'MultipleChoiceQuestion':
            responseInstance.multipleChoiceResponse.answers['answers'] = put.get('response').get('choices')
            responseInstance.multipleChoiceResponse.save()

        response = {
            "success": True
        }
        return JsonResponse(response, status=HTTPStatus.OK)

class QuizAttemptQuestionsApiEventVersion1Component(View):

    def get(self, *args, **kwargs):
        quizAttempt = QuizAttempt.objects.prefetch_related(
            'responses__essayResponse', 'responses__trueOrFalseResponse', 'responses__multipleChoiceResponse',
            'responses__question',
        ).get(id=kwargs.get('id'))
        questionList = quizAttempt.quiz.getQuestions(quizAttempt.quiz.inRandomOrder)
        responseList = quizAttempt.responses.all()
        computedResponseList = QuestionAndResponse(questionList, responseList)

        response = {
            "success": True,
            "data": {
                "questions": computedResponseList.getResponse(),
                "quiz": {
                    "canEdit": quizAttempt.status in [QuizAttempt.Status.NOT_ATTEMPTED, QuizAttempt.Status.IN_PROGRESS]
                }
            }
        }
        return JsonResponse(response, status=HTTPStatus.OK)

    def put(self, *args, **kwargs):
        quizAttempt = QuizAttempt.objects.select_related('quiz').prefetch_related(
            'responses__essayResponse', 'responses__trueOrFalseResponse', 'responses__multipleChoiceResponse'
        ).get(id=kwargs.get('id'))

        try:
            put = json.loads(self.request.body)
        except JSONDecodeError:
            put = json.loads(self.request.body.decode().replace('"', "'").replace("'", '"'))

        userResponse = put.get('response', [])
        responseList = quizAttempt.responses.all()

        essayResponseObjects = []
        trueOrFalseResponseObjects = []
        multipleChoiceResponseObjects = []

        for response in userResponse:
            if response['type'] == 'EssayQuestion':
                existingResponseObject = next((o for o in responseList if o.id == response['response']['id']))
                if existingResponseObject is not None:
                    existingResponseObject.essayResponse.answer = response['response']['text']
                    essayResponseObjects.append(existingResponseObject.essayResponse)
            elif response['type'] == 'TrueOrFalseQuestion':
                existingResponseObject = next((o for o in responseList if o.id == response['response']['id']))
                if existingResponseObject is not None:
                    existingResponseObject.trueOrFalseResponse.trueSelected = response['response']['selectedOption']
                    trueOrFalseResponseObjects.append(existingResponseObject.trueOrFalseResponse)
            elif response['type'] == 'MultipleChoiceQuestion':
                existingResponseObject = next((o for o in responseList if o.id == response['response']['id']))
                if existingResponseObject is not None:
                    existingResponseObject.multipleChoiceResponse.answers['answers'] = response['response']['choices']
                    multipleChoiceResponseObjects.append(existingResponseObject.multipleChoiceResponse)
            else:
                continue

        EssayResponse.objects.bulk_update(essayResponseObjects, ['answer'])
        TrueOrFalseResponse.objects.bulk_update(trueOrFalseResponseObjects, ['trueSelected'])
        MultipleChoiceResponse.objects.bulk_update(multipleChoiceResponseObjects, ['answers'])

        # TODO: Optimize when automatic marking is enabled.
        quizAttemptAutomaticMarking = QuizAttemptAutomaticMarking(quizAttempt, quizAttempt.quiz.getQuestions(), responseList)
        if quizAttemptAutomaticMarking.mark():
            quizAttempt.status = QuizAttempt.Status.MARKED
        else:
            quizAttempt.status = QuizAttempt.Status.SUBMITTED

        quizAttempt.save()

        response = {
            "success": True,
        }
        return JsonResponse(response, status=HTTPStatus.OK)


# a program that calculates factorials
# the factorial n! is 1*2*3*4 ... *n

def factorial(number):
    """Returns the factorial of the given number."""
    result = 1
    for i in range(1, number+1):
        result = result*i
    return result

x = int(input('Please enter an integer number: '))
y = factorial(x)
print ("Factorial: {}! = {}}".format(x, y))


# pylint: disable=invalid-name, no-member, too-many-locals, too-many-arguments
"""Non-maximum suppression operator"""
import tvm

from tvm import api

def nms_ir(data, sort_result, valid_count, out, nms_threshold, force_suppress, nms_topk):
    """Low level IR routing for transform location in multibox_detection operator.

    Parameters
    ----------
    data: Buffer
        Buffer of output boxes with class and score.

    sort_result : Buffer
        Buffer of output box indexes sorted by score.

    valid_count : Buffer
        Buffer of number of valid output boxes.

    out : Buffer
        Output buffer.

    nms_threshold : float
        Non-maximum suppression threshold.

    force_suppress : boolean
        Whether to suppress all detections regardless of class_id.

    nms_topk : int
        Keep maximum top k detections before nms, -1 for no limit.

    Returns
    -------
    stmt : Stmt
        The result IR statement.
    """
    def calculate_overlap(out_tensor, box_a_idx, box_b_idx):
        """Calculate overlap of two boxes.
        """
        w = tvm.make.Max(0.0, tvm.make.Min(out_tensor[box_a_idx + 2], out_tensor[box_b_idx + 2])
                         - tvm.make.Max(out_tensor[box_a_idx], out_tensor[box_b_idx]))
        h = tvm.make.Max(0.0, tvm.make.Min(out_tensor[box_a_idx + 3], out_tensor[box_b_idx + 3])
                         - tvm.make.Max(out_tensor[box_a_idx + 1], out_tensor[box_b_idx + 1]))
        i = w * h
        u = (out_tensor[box_a_idx + 2] - out_tensor[box_a_idx]) * \
            (out_tensor[box_a_idx + 3] - out_tensor[box_a_idx + 1]) + \
            (out_tensor[box_b_idx + 2] - out_tensor[box_b_idx]) * \
            (out_tensor[box_b_idx + 3] - out_tensor[box_b_idx + 1]) - i
        return tvm.select(u <= 0.0, 0.0, i / u)

    ib = tvm.ir_builder.create()
    p_data = ib.buffer_ptr(data)
    p_sort_result = ib.buffer_ptr(sort_result)
    p_valid_count = ib.buffer_ptr(valid_count)
    p_out = ib.buffer_ptr(out)
    batch_size = out.shape[0]
    num_anchors = out.shape[1]

    nms_threshold_node = tvm.make.node("FloatImm", dtype="float32", value=nms_threshold)
    nms_topk_node = tvm.make.node("IntImm", dtype="int32", value=nms_topk)
    force_suppress_node = tvm.make.node("IntImm", dtype="int32", value=1 if force_suppress else 0)
    with ib.for_range(0, batch_size, for_type="parallel", name="n") as n:
        with ib.if_scope(tvm.all(nms_threshold_node > 0, nms_threshold_node < 1,
                                 p_valid_count[0] > 0)):
            # Reorder output
            nkeep = tvm.select(tvm.all(nms_topk_node > 0, nms_topk < p_valid_count[n]),
                               nms_topk, p_valid_count[n])
            with ib.for_range(0, nkeep, name="l") as l:
                with ib.for_range(0, 6, name="m") as m:
                    p_out[(n * num_anchors * 6
                           + l * 6 + m)] = p_data[(n * num_anchors * 6
                                                   + p_sort_result[n * num_anchors + l] * 6 + m)]
            with ib.if_scope(tvm.all(nms_topk_node > 0, nms_topk < p_valid_count[n])):
                with ib.for_range(0, p_valid_count[n] - nkeep, name="l") as l:
                    with ib.for_range(0, 6, name="m") as m:
                        p_out[(n * num_anchors * 6
                               + (l + nkeep) * 6 + m)] = p_data[(n * num_anchors * 6
                                                                 + (l + nkeep) * 6 + m)]
            # Apply nms
            with ib.for_range(0, p_valid_count[n], name="l") as l:
                offset_l = l * 6
                with ib.if_scope(p_out[n * num_anchors * 6 + offset_l] >= 0):
                    with ib.for_range(0, p_valid_count[n], name="m") as m:
                        offset_m = m * 6
                        with ib.if_scope(tvm.all(m > l, p_out[n * num_anchors * 6
                                                              + offset_m] >= 0)):
                            with ib.if_scope(tvm.any(force_suppress_node > 0,
                                                     p_out[n * num_anchors * 6 + offset_l] ==
                                                     p_out[n * num_anchors * 6 + offset_m])):
                                # When force_suppress == True or class_id equals
                                iou = calculate_overlap(p_out, n * num_anchors * 6 + offset_l + 2,
                                                        n * num_anchors * 6 + offset_m + 2)
                                with ib.if_scope(iou >= nms_threshold):
                                    p_out[n * num_anchors * 6 + offset_m] = -1.0
        with ib.else_scope():
            with ib.for_range(0, p_valid_count[n], name="l") as l:
                with ib.for_range(0, 6, name="m") as m:
                    p_out[(n * num_anchors * 6
                           + l * 6 + m)] = p_data[n * num_anchors * 6 + l * 6 + m]
        # Set invalid entry to be -1
        with ib.for_range(0, num_anchors - p_valid_count[n], name="l") as l:
            with ib.for_range(0, 6, name="m") as m:
                p_out[n * num_anchors * 6 + (l + p_valid_count[n]) * 6 + m] = -1.0
    return ib.get()

@tvm.target.generic_func
def nms(data, valid_count, nms_threshold=0.5, force_suppress=False, nms_topk=-1):
    """Non-maximum suppression operator for object detection.

    Parameters
    ----------
    data: tvm.Tensor
        3-D tensor with shape [batch_size, num_anchors, 6].
        The last dimension should be in format of
        [class_id, score, box_left, box_top, box_right, box_bottom].

    valid_count : tvm.Tensor
        1-D tensor for valid number of boxes.

    nms_threshold : float
        Non-maximum suppression threshold.

    force_suppress : boolean
        Whether to suppress all detections regardless of class_id.

    nms_topk : int
        Keep maximum top k detections before nms, -1 for no limit.

    Returns
    -------
    out : tvm.Tensor
        3-D tensor with shape [batch_size, num_anchors, 6].

    Example
    --------
    .. code-block:: python

        # An example to use nms
        dshape = (1, 5, 6)
        data = tvm.placeholder(dshape, name="data")
        valid_count = tvm.placeholder((dshape[0],), dtype="int32", name="valid_count")
        nms_threshold = 0.7
        force_suppress = True
        nms_topk = -1
        out = nms(data, valid_count, nms_threshold, force_suppress, nms_topk)
        np_data = np.random.uniform(dshape)
        np_valid_count = np.array([4])
        s = topi.generic.schedule_nms(out)
        f = tvm.build(s, [data, valid_count, out], "llvm")
        ctx = tvm.cpu()
        tvm_data = tvm.nd.array(np_data, ctx)
        tvm_valid_count = tvm.nd.array(np_valid_count, ctx)
        tvm_out = tvm.nd.array(np.zeros(dshape, dtype=data.dtype), ctx)
        f(tvm_data, tvm_valid_count, tvm_out)
    """
    batch_size = data.shape[0]
    num_anchors = data.shape[1]
    valid_count_dtype = "int32"
    valid_count_buf = api.decl_buffer(valid_count.shape, valid_count_dtype,
                                      "valid_count_buf", data_alignment=4)
    data_buf = api.decl_buffer(data.shape, data.dtype, "data_buf", data_alignment=8)
    score_axis = 1
    score_shape = (batch_size, num_anchors)
    score_tensor = tvm.compute(score_shape, lambda i, j: data[i, j, score_axis])
    score_tensor_buf = api.decl_buffer(score_tensor.shape, data.dtype,
                                       "score_tensor_buf", data_alignment=8)
    sort_tensor_dtype = "int32"
    sort_tensor_buf = api.decl_buffer(score_shape, sort_tensor_dtype,
                                      "sort_tensor_buf", data_alignment=8)
    sort_tensor = \
        tvm.extern(score_shape,
                   [score_tensor, valid_count],
                   lambda ins, outs: tvm.call_packed(
                       "tvm.contrib.sort.argsort", ins[0], ins[1],
                       outs[0], score_axis, True),
                   dtype=sort_tensor_dtype,
                   in_buffers=[score_tensor_buf, valid_count_buf],
                   out_buffers=sort_tensor_buf,
                   name="nms_sort")
    out = \
        tvm.extern(data.shape,
                   [data, sort_tensor, valid_count],
                   lambda ins, outs: nms_ir(
                       ins[0], ins[1], ins[2], outs[0], nms_threshold,
                       force_suppress, nms_topk),
                   dtype="float32",
                   in_buffers=[data_buf, sort_tensor_buf, valid_count_buf],
                   tag="nms")
    return out


class Settings():

  def __init__(self):
    """ constant setings """
    self.screen_width = 1200
    self.screen_height = 800
    self.bg_color = (135, 206, 250)

    # Bullet Settings:
    self.bullet_width = 3
    self.bullet_height = 15
    self.bullet_color = 60, 60, 60
    self.bullets_allowed = 3
    self.bullet_limit = 2

    # Rectangular Settings
    self.rectangular_width, self.rectangular_height = 100, 100
    self.rectangular_color = 255, 255, 51

    self.speedup_scale = 1.1
    self.init_dynamic_settings()

  def init_dynamic_settings(self):
    """ dynamic settings """
    self.ship_speed = 1.5
    self.bullet_speed_factor = 1
    self.rectangular_speed_factor = 0.1
    # rect_direction: 1 represents down; -1 represents up
    self.rect_direction = 1

  def increase_speed(self):
    self.ship_speed *= self.speedup_scale
    self.bullet_speed_factor *= self.speedup_scale
    self.rectangular_speed_factor *= self.speedup_scale


import json
from operator import methodcaller
from unittest import result
from sqlalchemy import column
import tabula
import pandas as pd
from flask import Flask, request,send_file,jsonify
from flask_cors import CORS
from insertTables import pushTablesToExcel
from pandasql import sqldf
from pdfmerge import combinePdf
import base64
import string
import io
import random
import os
import shutil

app = Flask(__name__)
CORS(app)

# db_connection = connectToDB()
# cursor = db_connection[0]
# my_conn = db_connection[1]

@app.route('/')
def mainPage():
    return "Server started...."

@app.route('/uploadFileName',methods = ['GET'])
def uploadFileName():
    global filename
    filename = request.args.getlist('filename')[0]
    return "GET filename"

@app.route('/upload',methods =['POST'])
def upload():
    str = request.files['file']
    str.save('C:/project/files/{}'.format(filename))
    #pushTablesToDB(my_conn)
    dfs = pushTablesToExcel(filename)
    return "POST hitted..."

@app.route('/search',methods = ['GET'])
def search():
        args = request.args
        hs_code = args.getlist('code')
        print(hs_code[0])
        dfs = pd.read_excel('C:/project/files/DB.xlsx')
        column_names = dfs.columns.values.tolist()
        if(column_names.count('HS_Code') == 0):
            return "Not found"
        query1 = 'select * from dfs where HS_Code = \'{}\''.format(hs_code[0])
        ans = sqldf(query1)

        if(len(ans) == 0):
            return "Not found"
        # dic=ans.to_dict('dict')
        # print(dic)
        dic1 = ans.to_dict('records')
        print(dic1)
        # print(dict_temp)
        # cursor.execute(query)
        # records = cursor.fetchall()
        # print('total rows found : ',len(records))
        # if(len(records) == 0):
        #     print('No matches found')
        # else:
        #     for row in records:
        #         print(str(row))
        return json.dumps(dic1)

@app.route('/pdfviewer',methods = ['GET'])
def pdfviewer():
    args = request.args
    searchfilename = args.getlist('searchResfilename')[0]
    with open ("C:/project/files/{}".format(searchfilename),"rb") as pdf_file:
        img = base64.b64encode(pdf_file.read())
    return send_file(io.BytesIO(img),attachment_filename="hello.pdf",as_attachment=True)

@app.route('/mergeUpload',methods =['POST'])
def mergeUpload():
    str = request.files['pdfs']
    res = ''.join(random.choices(string.ascii_uppercase +
                             string.digits, k = 6))
    str.save('C:/project/mergedirectory/test{}.pdf'.format(res))
    # combinePdf()
    return "saved..."

@app.route('/combine',methods=['GET'])
def combine():
   combinePdf()
   dir = 'C:\project\mergedirectory'
   for f in os.listdir(dir):
        os.remove(os.path.join(dir,f))

   with open ("C:/project/backend-flask/final.pdf","rb") as pdf_file:
        img = base64.b64encode(pdf_file.read())
   return send_file(io.BytesIO(img),attachment_filename="hello.pdf",as_attachment=True)

app.run(debug=True)


# -*- coding: utf-8 -*-
from gcd import ext_gcd
from montgomery import exp_mod
import strconvert
import sympy
from prettytable import PrettyTable

#中國於是定理(兩式)
def crt (a1,a2,m1,m2):
    M = m1*m2
    M1 = M//m1
    M2 = M//m2
    M1_inv = ext_gcd(M1 , m1)[1]
    M2_inv = ext_gcd(M2 , m2)[1]

    if(M1_inv < 0):M1_inv = M1_inv+m1
    if(M2_inv < 0):M2_inv = M2_inv+m2

    n = (a1*M1*M1_inv+a2*M2*M2_inv)%M
    return n

def gen_key(p, q):
    n = p * q
    return (n), (p ,q)    #回傳公鑰<n>、私鑰<p,q>

# 將明文m加密成密文c
def encrypt(m, pubkey):
    n = pubkey
    c = exp_mod(m, 2, n)
    return c

# 將密文m解密成明文c
def decrypt(c, prikey):
    p = prikey[0]
    q = prikey[1]
    a1 = exp_mod(c, (p+1)//4 , p)
    a2 = p - a1
    b1 = exp_mod(c, (q+1)//4 , q)
    b2 = q - b1
    m = crt(a1,b1,p,q),crt(a1,b2,p,q),crt(a2,b1,p,q),crt(a2,b2,p,q)
    return m

if __name__ == "__main__":

    while(True):
        choose = int(input("請選擇Rabin模式\n=====================================\n1.加密\n2.解密\n3.離開\n=====================================\n"))

        if(choose == 1):

            #明文輸入
            text = input("請輸入預加密明文:\n")
            m = strconvert.str_con(text)

            #生成p、q
            while(True):

                print("請輸入p、q (p*q >",m,")")

                while(True):
                    p = int(input('請輸入p:\n'))
                    if(sympy.isprime(p) == False):
                        print(p,"不是質數")
                        continue
                    elif((p-3)%4 != 0): #p、q必須滿足4k+3
                        print("p(",p,")不滿足4k+3")
                    else:
                        break

                while(True):
                    q = int(input('請輸入q:\n'))
                    if(sympy.isprime(q) == False):
                        print(q,"不是質數")
                        continue
                    elif((q-3)%4 != 0): #p、q必須滿足4k+3
                        print("q(",q,")不滿足4k+3")
                        continue
                    else:
                        break

                if(p*q < m):
                        print("p*q < m，請重新輸入")
                        continue
                else:
                    break

            #生成公鑰<n>、私鑰<n,p,q>
            pubkey, prikey = gen_key(p, q)
            print(pubkey, prikey)

            #Rabin加密
            c = encrypt(m, pubkey)

            print("\n------------- 生成公鑰 ---------------\nn =",pubkey,"\n")
            print("------------- 生成私鑰 ---------------\np =",prikey[0],"\nq =",prikey[1],"\n")
            print("------------- 加密密文 ---------------\n",c,"\n")

        elif(choose == 2):

            c = int(input("請輸入預解密密文\n"))

            while(True):
                p = int(input('請輸入p\n'))
                if(sympy.isprime(p) == False):
                    print("p不是質數")
                    continue
                elif((p-3)%4 != 0): #p、q必須滿足4k+3
                    print("p(",p,")不滿足4k+3")
                else:
                    break

            while(True):
                q = int(input('請輸入q\n'))
                if(sympy.isprime(q) == False):
                    print("q不是質數")
                    continue
                elif((q-3)%4 != 0): #p、q必須滿足4k+3
                    print("q(",q,")不滿足4k+3")
                    continue
                else:
                    break

            prikey = (p,q,p*q)

            #Rabin解密
            d = decrypt(c, prikey)
            print("\n------------- 解密明文 ---------------")
            print("",d[0],"(",strconvert.str_re(d[0]),")")
            print("-------------------------------------\n",d[1],"(",strconvert.str_re(d[1]),")")
            print("-------------------------------------\n",d[2],"(",strconvert.str_re(d[2]),")")
            print("-------------------------------------\n",d[3],"(",strconvert.str_re(d[3]),")\n")

        elif(choose == 3):
            break


from datetime import date
atual=date.today().year
nac=int(input("digiti sua data de nacimento"))
idade = atual - nac
print("O atleta tem {}".format(idade))
if idade <= 9:
    print("mirim")
elif idade<=14:
    print("infantil")
elif  idade<19:
    print("junior")
elif idade<=20:
    print("senio")
elif idade>20:
    print("master")