import random, copy, time, sys

def choose_ai_dif():
    print('Choose the difficulty of the computer')
    print('1. Easy\n2. Hard')
    while True:
        choice = input()
        if choice == '1':
            return 1
        elif choice == '2':
            return 2
        else:
            print('Please enter either 1 or 2')

def first():
    global player
    global computer
    #'X' always goes first
    print('Choose your marker: X or O')
    while True:
        marker = input()
        if marker.upper() == 'X':
            player = 'X'
            computer = 'O'
            break
        elif marker.upper() == 'O':
            player = 'O'
            computer = 'X'
            break
        else:
            print('Please enter either X or O')

def print_board(board):
    print(board['topL'] + '|' + board['topM'] + '|' + board['topR'])
    print('-+-+-')
    print(board['midL'] + '|' + board['midM'] + '|' + board['midR'])
    print('-+-+-')
    print(board['botL'] + '|' + board['botM'] + '|' + board['botR'])
    print('\n')

def win(board, turn):
    return ((board['topL']==turn and board['topM']==turn and board['topR']==turn) or
    (board['midL']==turn and board['midM']==turn and board['midR']==turn) or
    (board['botL']==turn and board['botM']==turn and board['botR']==turn) or
    (board['topL']==turn and board['midL']==turn and board['botL']==turn) or
    (board['topM']==turn and board['midM']==turn and board['botM']==turn) or
    (board['topR']==turn and board['midR']==turn and board['botR']==turn) or
    (board['topL']==turn and board['midM']==turn and board['botR']==turn) or
    (board['topR']==turn and board['midM']==turn and board['botL']==turn))

def get_empty(board):
    #gets all empty squares in the given board state
    empty = []
    for square in board:
        if board[square] == " ":
            empty.append(square)

    if len(empty) == 0:
        return 0
    else:
        return empty

def pos_moves(board,turn):
    empty = get_empty(board)
    pos_move =[]
    board_copy = copy.copy(board)
    if empty == 0:
        pos_move.append(board_copy)
        return pos_move
    else:
        for square in empty:
            board_copy[square] = turn
            board_pos = copy.copy(board_copy)
            pos_move.append(board_pos)
            board_copy[square] = " "

    return pos_move

#Minimax algorithm
def miniMax(cur_board,depth,isMax):
    maxScore= -2000
    minScore= 2000

    turn = ai_score[isMax][1]
    cur_board_copy = copy.copy(cur_board)#Copy board as to not modify the original board
    empty = get_empty(cur_board_copy)
    pos_move = pos_moves(cur_board_copy, turn)
    for i in pos_move:
        #Check if move wins
        isWin = win(i,ai_score[isMax][1])
        if isWin:
            #print('First win')
            return ai_score[isMax][0]
        elif empty == 0:
            return  0

        scr = miniMax(i,depth+1,not isMax)
        #print("SCORE")
        #print(scr)
        if isMax and (scr > maxScore):
            maxScore = scr

            #print('MAXSCORE')
            #print(maxScore)
        elif isMax == False and (scr < minScore):
            minScore = scr
            #print('MINSCORE')
            #print(minScore)

            #totalScore += scr
    if isMax:
        return maxScore
    else:
        return minScore

#RANDOM AI
def ticTacAI():
    print('ticTacAI\'s turn to move!')
    time.sleep(1)
    move = random.choice(list(emptySquare.keys()))
    emptySquare.pop(move)
    board[move] = computer

#Perfect AI
def ticTacAI_Perf():
    print('ticTacAI\'s turn to move!')
    bestScore = -1000
    bestMove = ''

    cur_board = copy.copy(board)
    cur_empty = copy.copy(emptySquare)
    used = copy.copy(emptySquare)

    numEmpty = len(emptySquare)

    for i in range(numEmpty):

        move = random.choice(list(used))
        cur_board[move] = computer
        used.pop(move)
        cur_empty.pop(move)

        #Check for win
        if win(cur_board,computer):
            bestMove = move
            break

        scr = miniMax(cur_board,0,False)#True=ai turn, False = Human turn
        cur_empty = copy.copy(emptySquare)
        cur_board[move] = ' '

        if scr > bestScore:
            bestScore = scr
            bestMove = move

    emptySquare.pop(bestMove)
    print(bestMove)
    board[bestMove] = computer

#############################################################################

#Global Vars
score=[0,0]
player = 'X'
computer = 'O'
turn = 'X'

print('Welcome to Tic-Tac-Toe Simulator! Try to beat the computer!\n')
print('When it\'s your turn to move, type one of the below options to make a move.')
print('Options are:')
print('''
    |    |
topL|topM|topR
----+----+----
midL|midM|midR
----+----+----
botL|botM|botR
    |    |\n\n''')

while True:
    board = {'topL':' ','topM':' ', 'topR':' ',
             'midL':' ','midM':' ', 'midR':' ',
             'botL':' ','botM':' ', 'botR':' '}
    emptySquare = copy.copy(board)

    choice = choose_ai_dif()
    first()
    print_board(board)
    ai_score = {True:[1,computer], False:[-1,player], 'tie':0}

    winner = ''

    for i in range(9):

        if turn == player:
            while True:
                print('Human\'s turn. Move on which square?')
                move = input()
                if move in emptySquare:
                    break
                else:
                    print('Not a legal move. Options are: topL,topM,topR,midL,midM,midR,botL,botM,botR')
            board[move] = turn
            emptySquare.pop(move)
        elif choice == 1:
            ticTacAI()
            print(1)
        else:
            ticTacAI_Perf()

        print_board(board)
        if win(board,turn):
            if turn == player:
                winner = 'Human'
                score[0] += 1
            else:
                winner = 'ticTacAI'
                score[1] += 1

            break

        if turn == 'X':
            turn = 'O'
        else:
            turn = 'X'

    if winner == '':
        winner = 'Nobody'

    print(winner +' wins!')
    print('Human:'+str(score[0])+' ticTacAI:'+str(score[1]))

    while True:
        print('play again?(y/n)')
        again = input()
        if again.lower() == 'y':
            turn = 'X'
            break
        elif again.lower() == 'n':
            print('Thanks for playing!')
            time.sleep(1)
            sys.exit()
        else:
            print('please enter \'y\' or \'n\'')


import importlib.util
import os
import re
spec = importlib.util.spec_from_file_location("opendbpy", "./OpenDB/build/src/swig/python/opendbpy.py")
odb = importlib.util.module_from_spec(spec)
spec.loader.exec_module(odb)
db = odb.dbDatabase.create()
chip = odb.odb_read_design(db, ["./OpenDB/tests/data/gscl45nm.lef"], ["./OpenDB/tests/data/design.def"])
tech = db.getTech()
block = chip.getBlock()

versions = [odb.defout.DEF_5_3, odb.defout.DEF_5_4, odb.defout.DEF_5_5, odb.defout.DEF_5_6]
#result = odb.odb_write_def(block, 'test_out.def', DEF_5_6)
version_dict = {0: 'DEF_5_3', 1: 'DEF_5_4', 2:'DEF_5_5', 3:'DEF_5_6'}

for i,version in enumerate(versions):
    print(version)
    result = odb.odb_write_def(block, 'test_out.def', version)
    if result == None:
        exit("DEF not written")
    db= odb.dbDatabase.create()
    def_parser = odb.defin(db)
    lef_parser = odb.lefin(db, True)
    tech_lib = lef_parser.createTechAndLib("./OpenDB/tests/data/gscl45nm.lib",
    "./OpenDB/tests/data/gscl45nm.lef")
    libs = db.getLibs()
    chip = def_parser.createChip(libs,"test_out.def")
    if chip == None:
        exit("Failed to read written DEF")
    f = open("test_out.def", "r")
    os.system("cat test_out.def")
    written_def = f.read()

    if re.match(r'VERSION\s+(\d+)\.(\d+)\s+?;',written_def):
        data = re.findall(r'VERSION\s+(\d+)\.(\d+)\s+?;', written_def)
    major = data[0][0]
    minor = data[0][1]
    version_str = str(version)
    if major == None or  minor == None or "DEF_"+ major + "_" + minor!=version_dict[i]:
        exit("Invalid written DEF for version")


import random
import requests
import os

class Rand():
    net_random = True
    main_url = 'https://api.random.org/json-rpc/2/invoke'

    def __init__(self):
        self.KEY = os.environ['RANDKEY']
        try:
            r = requests.post(self.main_url)
        except Exception:
            self.net_random = False
            print("Use local random")
        if r.status_code != 415:
            self.net_random = False
            print("Use local random")

    def get_random(self, min_num, max_num, amount, replacement=False):
        ans = []
        if self.net_random:
            payload = {
                'jsonrpc': '2.0',
                'method': "generateIntegers",
                'params': {
                    'apiKey': self.KEY,
                    'n': amount,
                    'min': min_num,
                    'max': max_num,
                    'replacement': replacement},
                'id': random.randint(1, 1000)}
            r = requests.post(self.main_url, json=payload).json()
            ans = r['result']['random']['data']
        else:
            while amount >= 0:
                ans.append(random.randint(min_num, max_num))
        return ans

    def Dice(self):
        ans = self.get_random(1, 6, 2, replacement=True)
        return ans[0], ans[1]

    def Flip(self):
        if random.randint(0, 1000) <= random.randint(0, 1000):
            ans = 'Орёл'
        else:
            ans = 'Решка'
        return ans

    def Roll(self, start, end, amount):
        return self.get_random(start, end, amount)


#!/bin/python3
import sys
import time
temp_file_format = "./.sublist"

def find_hash(val,mod,prime):
    calc_val , i = 0, 0
    len_val = len(val)
    while i < len_val:
        calc_val =(calc_val +(ord(val[i])*pow(prime,i+1)%mod)%mod)%mod
        i+=1
    return calc_val%mod

def open_files(inputR,inputS,M):
    sublist_map = {}
    size_sublist_r = [0 for i in range(M)]
    size_sublist_s = [0 for i in range(M)]

    for i in range(M):
        with open(temp_file_format+"R"+str(i)+".txt","w") as f:
            pass
        with open(temp_file_format+"S"+str(i)+".txt","w") as f:
            pass

    with open(inputR) as f1:
        while True:
            l1 = f1.readline()
            l1 = l1.strip("\n").strip()
            if not l1:
                break
            if l1:
                data = l1.split(" ")
                calc_hash = find_hash(data[1],M,19)
                if calc_hash in sublist_map:
                    sublist_map[calc_hash].append(l1+"\n")
                else:
                    sublist_map[calc_hash] = [l1+"\n"]

                if len(sublist_map[calc_hash])==100:
                    with open(temp_file_format+"R"+str(calc_hash)+".txt","a") as f:
                        f.writelines(sublist_map[calc_hash])
                        sublist_map[calc_hash].clear()
                        size_sublist_r[calc_hash]+=100

        for calc_hash in sublist_map:
            with open(temp_file_format+"R"+str(calc_hash)+".txt","a") as f:
                        f.writelines(sublist_map[calc_hash])
                        size_sublist_r[calc_hash]+=len(sublist_map[calc_hash])
                        sublist_map[calc_hash].clear()

        # print(sublist_map)

    with open(inputS) as f1:
        while True:
            l1 = f1.readline()
            l1 = l1.strip("\n").strip()
            if not l1:
                break
            if l1:
                data = l1.split(" ")
                calc_hash = find_hash(data[0],M,19)
                if calc_hash in sublist_map:
                    sublist_map[calc_hash].append(l1+"\n")
                else:
                    sublist_map[calc_hash] = [l1+"\n"]

                if len(sublist_map[calc_hash])==100:
                    with open(temp_file_format+"S"+str(calc_hash)+".txt","a") as f:
                        f.writelines(sublist_map[calc_hash])
                        size_sublist_s[calc_hash]+=100
                        sublist_map[calc_hash].clear()

        for calc_hash in sublist_map:
            with open(temp_file_format+"S"+str(calc_hash)+".txt","a") as f:
                        f.writelines(sublist_map[calc_hash])
                        size_sublist_s[calc_hash]+=len(sublist_map[calc_hash])
                        sublist_map[calc_hash].clear()

        return(size_sublist_r,size_sublist_s)

def get_next(size_sublist_r, size_sublist_s,outfile,M):
    out = open(outfile,"w")
    for i in range(M):
        if(min(size_sublist_r[i],size_sublist_s[i])>M*100):
            exit(0)

        if(size_sublist_r[i]<size_sublist_s[i]):
            with open(temp_file_format+"R"+str(i)+".txt") as f:
                rfile = f.readlines()
                rfile = [line.strip("\n").strip(" ").split(" ") for line in rfile]
                # print(rfile)
            with open(temp_file_format+"S"+str(i)+".txt") as f:
                for line in f:
                    line = line.strip("\n").strip()
                    if not line:
                        break
                    line = line.split(" ")
                    for rlines in rfile:
                        if(line[0]==rlines[1]):
                            out.write(rlines[0]+" "+rlines[1]+" "+line[1]+"\n")
        else:
            with open(temp_file_format+"S"+str(i)+".txt") as f:
                sfile = f.readlines()
                sfile = [line.strip("\n").strip(" ").split(" ") for line in sfile]
                # print(rfile)
            with open(temp_file_format+"R"+str(i)+".txt") as f:
                for line in f:
                    line = line.strip("\n").strip()
                    if not line:
                        break
                    line = line.split(" ")
                    for slines in sfile:
                        if(line[1]==slines[0]):
                            out.write(line[0]+" "+slines[0]+" "+slines[1]+"\n")

if __name__ == "__main__":
    inputR = sys.argv[1]
    # inputR = "inputR_"
    inputS = sys.argv[2]
    # inputS = "inputS_"
    output_file = "./"+ inputR.split("/")[-1] + "_" + inputS.split("/")[-1]+"_join.txt"
    # output_file = "output"
    M = int(sys.argv[3]) # in terms of blocks
    # M = 1# in terms of records
    # print(inputR,inputS,M)
    start = time.time()
    size_sublist_r, size_sublist_s = open_files(inputR,inputS,M)
    # print(size_sublist_r, size_sublist_s)
    get_next(size_sublist_r, size_sublist_s,output_file,M)
    # get_next(inputR,inputS,M)

    end = time.time()
    total_time_taken = end - start
    with open("observations_hash.txt","a") as ob:
        ob.write("\n"+str(M)+" "+str(total_time_taken))


def solution(N, number):

    if N == number:return 1

    arr=[set() for i in range(8)]

    for i,j in enumerate(arr,start=1):
        j.add(int(str(N) * i))

    for i in range(1,8):
        for j in range(i):
            for op1 in arr[j]:
                for op2 in arr[i-j-1]:
                    arr[i].add(op1 + op2)
                    arr[i].add(op1 - op2)
                    arr[i].add(op1 * op2)
                    if op2 != 0: arr[i].add(op1 // op2)

        if number in arr[i]:
            res=i+1
            break

    else:
        res=-1

    return res

if __name__ =="__main__":
    N=5
    number=12
    print(solution(N, number))


#!/usr/bin/env python3

# @author: Michel Anderson
# @github: MichelJr001
# @Twitter: _Michel_Jr_

# Criador de arquivos json 1.0

import json
import os

class cadastro():
    def __init__(self, nome, snome, idade, nascionalidade):
        self.nome = nome
        self.snome = snome
        self.idade = idade
        self.nascionalidade = nascionalidade

        new_json = {"Nome": nome, "Sobrenome": snome, "Idade": idade, "Nascionalidade": nascionalidade}

        # Tranforma o json new_json em string
        json_puro = json.dumps(new_json)

        # Tranforma a string json_puro em json
        json_filtrado = json.loads(json_puro)

        dados = open("dados.txt", "a")
        dados.write("\n--------------------------------------------------------------------------------")
        dados.write("\nNome: {}\nSobrenome: {}\nIdade: {}\nNascionalidade: {}\n".format(json_filtrado["Nome"], json_filtrado["Sobrenome"], json_filtrado["Idade"], json_filtrado["Nascionalidade"]))
        dados.close()

        dados_json = open("dados.json", "a")
        dados_json.write(json_puro)
        dados_json.write("\n")
        dados_json.close()

os.system('clear')
print("""
\033[32m
   ###    ##    ##    ###    ##       ##    ## ######## ########               ##  ######   #######  ##    ## v1.0
  ## ##   ###   ##   ## ##   ##        ##  ##       ##  ##                     ## ##    ## ##     ## ###   ##
 ##   ##  ####  ##  ##   ##  ##         ####       ##   ##                     ## ##       ##     ## ####  ##
##     ## ## ## ## ##     ## ##          ##       ##    ######                 ##  ######  ##     ## ## ## ##
######### ##  #### ######### ##          ##      ##     ##               ##    ##       ## ##     ## ##  ####
##     ## ##   ### ##     ## ##          ##     ##      ##               ##    ## ##    ## ##     ## ##   ###
##     ## ##    ## ##     ## ########    ##    ######## ######## #######  ######   ######   #######  ##    ##
\033[0m
 @author: Michel Anderson
 @github: MichelJr001
""")

while True:

        nome_cliente = str(input("[\033[32m NOME DO CLIENTE \033[0m]: "))
        snome_cliente = str(input("[\033[32m SOBRENOME DO CLIENTE \033[0m]: "))
        sexo_cliente = str(input("[\033[32m SEXO DO CLIENTE \033[0m]: "))
        idade_cliente = str(input("[\033[32m DATA DE NASCIMENTO DO CLIENTE \033[0m]: "))
        nacionalidade_cliente = str(input("[\033[32m NACIONALIDADE DO CLIENTE \033[0m]: "))

        try:
                cadastro(nome_cliente, snome_cliente, idade_cliente, nacionalidade_cliente)
                print("[\033[32m SUCESSO \033[0m]: Cadastrado com sucesso!\n")
        except:
                print("[\033[31m ERRO AO CADASTRAR \033[0m]: Algo de errado aconteceu!\n")

        esc = str(input("[\033[32m DESEJA CONTINUAR \033[0m][S/N]: ")).upper().strip()[0]

        if esc not in "SN":
                print("[\033[31m ERRO \033[0m]: Escolha invalida!")
        else:
                if esc == "S":
                        os.system(clear)
                else:
                        break


# import the necessary packages
from __future__ import print_function
from imutils.object_detection import non_max_suppression
from imutils import paths
import numpy as np
import imutils
import cv2

from camera import VideoCamera
#from ad_retrieval.ad_retrieval import AdSystem
import ad_retrieval.ad_retrieval as AdSystem
import nearest_neighbor_color
import colorDetection

from PIL import Image

# initialize the HOG descriptor/person detector
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

# initialize HAAR pretrained haar cascade classifiers
faceCascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
genderCascade = cv2.CascadeClassifier("./haarcascade_gender_alt2.xml")

# initialize our camera feed
cam = VideoCamera()

#initialize ad system
ads = AdSystem.create_ads_list()

# while the video stream is open, get the image frame by frame
while cam.video.isOpened():
	#Get the image frame
	image = cam.get_frame()

	image = imutils.resize(image, width=min(400, image.shape[1]))

	orig = image.copy()

	# detect pedestrians in the image
	(rects, weights) = hog.detectMultiScale(image, winStride=(4, 4),
		padding=(8, 8), scale=1.05)

	# apply non-maxima suppression to the bounding boxes using a
	# fairly large overlap threshold to try to maintain overlapping
	# boxes that are still people
	rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])
	pick = non_max_suppression(rects, probs=None, overlapThresh=0.65)

	# If we did not find any pedestrains, do manual close-range object detection
	if not len(pick):
		# convert image to gray scale, since haar cascade was trained on greyscale images
		gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

		# Find faces in the image
		faces = faceCascade.detectMultiScale(
		    gray,
		    scaleFactor=1.1,
		    minNeighbors=5,
		    minSize=(30, 30),
		    flags = 0
		)

		# For each face, manually scale the bounding rectangle to encompass the person's body
		for (x, y, w, h) in faces:
			scale = w * h / 100;
			xA = x - scale;
			xB = x + scale + w;
			yA = y - (scale / 2);
			yB = y + (10 * scale)+ h;

			cropped_face = image[yA:yB, xA:xB]
			# Detect gender in the image
			genders = genderCascade.detectMultiScale(cropped_face, 1.1, 5)
			color = (255,0,0) if len(genders) else (255, 192, 203)
			gender = "Male" if len(genders) else "Female"
			cv2.putText(image,"Gender: %s" % (gender), (x, y), cv2.FONT_HERSHEY_PLAIN, 1, (255,255,255))

			#Display the common color in the image if the bounding box was not cropped
			try:
				rgb = (image[(x+x+w)/2][y+2*h])
				for i in xrange(0, 40):
					for j in xrange(0, 40):
						image[i][j] = rgb
				rgb_real = [rgb[2], rgb[1], rgb[0]]
				temp_col = nearest_neighbor_color.find_closest_color(rgb_real)
				ad = AdSystem.get_random_ad(temp_col, gender, ads)
				if ad is not None:
					print(ad)
					cv2.imshow("Ad", ad)
			except:
				pass

			cv2.rectangle(image, (xA, yA), (xB, yB), color, 2)
	else:
		for (xA, yA, xB, yB) in pick:
			cv2.rectangle(image, (xA, yA), (xB, yB), (0, 255, 0), 2)

	# show the output images
	cv2.imshow("Pedestrian", image)
	if cv2.waitKey(5) & 0xFF == ord('q'):
 		break

cv2.destroyAllWindows()


class Codec:
    def serialize(self, root):
        def dfs(node):
            if node:
                ret.append(str(node.val))
                dfs(node.left)
                dfs(node.right)
            else: ret.append('#')
        ret = []
        dfs(root)
        return ','.join(ret)

    def deserialize(self, data):
        def dfs():
            val = next(vals)
            if val == '#': return None
            node = TreeNode(int(val))
            node.left = dfs()
            node.right = dfs()
            return node

        vals = iter(data.split(','))
        return dfs()


from math import factorial
f = open("comb.in", "r")
f1 = open("comb.out", "w")

def choose(n, k):
    if n < k:
        return 0
    return factorial(n) // (factorial(k) * factorial(n - k))

def combination(n, k, m):
    result = []
    a      = n
    b      = k
    x      = (choose(n, k) - 1) - m
    for i in range(0, k):
        a = a - 1
        while choose(a, b) > x:
            a = a - 1
        result.append(n - 1 - a)
        x = x - choose(a, b)
        b = b - 1
    return result

n, k, p = list(map(int, f.readline().strip().split()))
a = (combination(n, k, p))
for i in range(len(a)):
    a[i] += 1
    f1.write(str(a[i]) + ' ')


from application.pub import Publisher
from application.sub import Subscriber
from application.broker import Broker
import time
import threading
from kazoo.client import KazooClient

sub1_msg = None
sub2_msg = None

def receive(sub, which):
    while keep_receive:
        msg = sub.receive()
        if which == 1:
            global sub1_msg
            sub1_msg = msg['value']
        if which == 2:
            global sub2_msg
            sub2_msg = msg['value']

keep_receive = True

mode=2

zk_root = '/test_temp_dir'

zookeeper = '127.0.0.1:2181'
zk = KazooClient(hosts=zookeeper)

broker = Broker({'mode': mode, 'port': 5555, 'zookeeper':zookeeper,
                  'logfile': 'log/temp_broker.log', 'broker_addr':'tcp://127.0.0.1:5555'},zk_root=zk_root)

pub1 = Publisher(mode=mode, ip_address='tcp://127.0.0.1:5000',pub_name='Pub1',
                zk_address=zookeeper, logfile='log/temp_pub.log', zk_root=zk_root)

pub2 = Publisher(mode=mode, ip_address='tcp://127.0.0.1:5001',pub_name='Pub2',
                zk_address=zookeeper, logfile='log/temp_pub.log', zk_root=zk_root)

pub3 = Publisher(mode=mode, ip_address='tcp://127.0.0.1:5002',pub_name='Pub3',
                zk_address=zookeeper, logfile='log/temp_pub.log', zk_root=zk_root)

sub1 = Subscriber(ip_self='tcp://127.0.0.1:5010', ip_zookeeper=zookeeper, name='Sub1',
                   comm_type=mode, logfile='log/temp_sub.log', zk_root=zk_root)

sub2 = Subscriber(ip_self='tcp://127.0.0.1:5011', ip_zookeeper=zookeeper, name='Sub2',
                   comm_type=mode, logfile='log/temp_sub.log', zk_root=zk_root)

sub_t1 = threading.Thread(target=receive, args=(sub1, 1))
sub_t2 = threading.Thread(target=receive, args=(sub2, 2))

def test_start():
    zk.start()
    try:
        zk.delete(zk_root, recursive=True)
    except:
        pass
    try:
        zk.create(zk_root)
    except:
        pass
    thread1 = threading.Thread(target=broker.start)
    thread1.start()
    time.sleep(1)

def test_publisher_register():
    res1 = pub1.register([{'topic': 'hello', 'history': 3}])
    res2 = pub2.register([{'topic': 'hello', 'history': 5}])
    pubs = zk.get_children('%s/Topic/hello/Pub'%zk_root)

    assert res1 == 0 and res2 == 0
    assert len(pubs) == 2
    time.sleep(3)

def test_subscriber_register():
    res1 = sub1.register([{'topic': 'hello', 'history': 4}])
    res2 = sub2.register([{'topic': 'hello', 'history': 6}])
    subs = zk.get_children('%s/Topic/hello/Sub' % zk_root)

    sub_t1.start()
    sub_t2.start()

    assert res1 == 0 and res2 == 0
    assert len(subs) == 2

    time.sleep(3)

# sub1 cannot receive pub1 (history) or pub2 (strength)
def test_publish_and_receive1():

    pub1.publish('hello', 'test1_pub1')
    pub1.publish('hello', 'test1_pub2')

    time.sleep(0.5)
    assert sub1_msg != 'test1_pub1'

# pub1 off line. pub2 becomes the strongest, sub1 can receive from pub2.
def test_publish_and_receive2():

    pub1.drop_system()
    time.sleep(1)

    pub2.publish('hello', 'test2_pub2')
    time.sleep(0.5)
    assert sub1_msg == 'test2_pub2'

# sub2 cannot receive from pub2 (history)
def test_publish_and_receive3():

    pub2.publish('hello', 'test3_pub2')
    time.sleep(0.5)

    assert sub2_msg != 'test3_pub2'

# pub2 off line, pub1 on. sub1 still cannot receive from pub1.
def test_publish_and_receive4():

    pub2.drop_system()
    pub1.register([{'topic': 'hello', 'history': 3}])
    time.sleep(1)

    pub1.publish('hello', 'test4_pub1')
    time.sleep(0.5)

    assert sub1_msg != 'test4_pub1'

# pub1 off, pub3 on. sub1 can receive from pub3.
def test_publish_and_receive5():

    pub1.drop_system()
    res1 = pub3.register([{'topic': 'hello', 'history': 7}])
    time.sleep(1)

    pub3.publish('hello', 'test5_pub3')
    time.sleep(0.5)
    assert sub1_msg == 'test5_pub3'

def test_pub_exit():
    pub3.drop_system()

def test_sub_exit():
    global keep_receive
    keep_receive = False
    sub1.exit()
    sub2.exit()

def test_broker_exit():
    broker.stop()

def test_clean():
    try:
        zk.delete(zk_root, recursive=True)
    except:
        pass


import typing as t
from math import sqrt

def primes(limit: int) -> t.List[int]:
    if limit <= 1:
        return []

    prime_table = [False] * 2 + [True] * (limit - 1)

    for i in range(2, int(sqrt(limit)) + 1):
        if prime_table[i] is True:
            for n in range(i**2, limit + 1, i):
                prime_table[n] = False

    return [i for i, v in enumerate(prime_table) if v is True]


# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""
Wrapper class for requests.Session adds some common OpenStack functionality

- log all requests and responses at debug level
- json-encode request body passed in to request() in json keyword arg
- set default user_agent at Transport creation; set to None to skip the header
- set default verify at Transport creation

"""

import json
import logging

import requests
import six
from six.moves import urllib

import openstack
from openstack import exceptions

DEFAULT_USER_AGENT = 'python-OpenStackSDK/' + openstack.__version__

_logger = logging.getLogger(__name__)
JSON = 'application/json'

class Transport(requests.Session):

    _user_agent = DEFAULT_USER_AGENT

    REDIRECT_STATUSES = (301, 302, 303, 305, 307)
    DEFAULT_REDIRECT_LIMIT = 30

    def __init__(
            self,
            user_agent=None,
            verify=True,
            redirect=DEFAULT_REDIRECT_LIMIT,
            accept=JSON,
    ):
        """Wraps requests.Session to add some OpenStack-specific features

        :param string user_agent: Set the default ``User-Agent`` header;
                                  Header is omitted if ``None`` and no value
                                  is supplied in the ``request()`` call.
        :param boolean/string verify: If ``True``, the SSL cert will be
                                      verified. A CA_BUNDLE path can also be
                                      provided.
        :param boolean/integer redirect: (integer) The maximum number of
                                         redirections followed in a request.
                                         (boolean) No redirections if False,
                                         requests.Session handles redirection
                                         if True. (optional)
        :param string accept: Type of output to accept

        User agent handling is as follows:

        * if user_agent arg is included in the request() call, use it
        * else if 'User-Agent' is set in the headers dict, use it
        * else if user_agent arg is included in the __init__() call, use it
        * else use DEFAULT_USER_AGENT

        """

        super(Transport, self).__init__()
        if user_agent:
            self._user_agent = user_agent
        self.verify = verify
        self._redirect = redirect
        self._accept = accept

    def request(self, method, url, redirect=None, **kwargs):
        """Send a request

        :param string method: Request HTTP method
        :param string url: Request URL
        :param boolean/integer redirect: (integer) The maximum number of
                                         redirections followed in a request.
                                         (boolean) No redirections if False,
                                         requests.Session handles redirection
                                         if True. (optional)

        The following additional kw args are supported:
        :param object json: Request body to be encoded as JSON
                            Overwrites ``data`` argument if present
        :param string accept: Set the ``Accept`` header; overwrites
                                  any value that may be in the headers dict.
                                  Header is omitted if ``None``.
        :param string user_agent: Set the ``User-Agent`` header; overwrites
                                  any value that may be in the headers dict.
                                  Header is omitted if ``None``.

        Remaining kw args from requests.Session.request() supported

        """

        headers = kwargs.setdefault('headers', {})

        # JSON-encode the data in json arg if present
        # Overwrites any existing 'data' value
        json_data = kwargs.pop('json', None)
        if json_data is not None:
            kwargs['data'] = json.dumps(json_data)
            headers['Content-Type'] = JSON

        # Set User-Agent header if user_agent arg included, or
        # fall through the default chain as described above
        if 'user_agent' in kwargs:
            headers['User-Agent'] = kwargs.pop('user_agent')
        elif self._user_agent:
            headers.setdefault('User-Agent', self._user_agent)
        else:
            headers.setdefault('User-Agent', DEFAULT_USER_AGENT)

        if redirect is None:
            redirect = self._redirect

        if isinstance(redirect, bool) and redirect:
            # Fall back to requests redirect handling
            kwargs['allow_redirects'] = True
        else:
            # Force disable requests redirect handling, we will manage
            # redirections below
            kwargs['allow_redirects'] = False
        if 'accept' in kwargs:
            accept = kwargs.pop('accept')
        else:
            accept = self._accept
        if accept:
            headers.setdefault('Accept', accept)

        self._log_request(method, url, **kwargs)

        resp = self._send_request(method, url, redirect, **kwargs)

        self._log_response(resp)

        try:
            resp.raise_for_status()
        except requests.RequestException as e:
            raise exceptions.HttpException(six.text_type(e), details=resp.text)
        if accept == JSON:
            try:
                resp.body = resp.json()
            except ValueError as e:
                # this may be simplejson.decode.JSONDecodeError
                # Re-raise into our own exception
                raise exceptions.InvalidResponse(response=resp.text)

        return resp

    def _send_request(self, method, url, redirect, **kwargs):
        # NOTE(jamielennox): We handle redirection manually because the
        # requests lib follows some browser patterns where it will redirect
        # POSTs as GETs for certain statuses which is not want we want for an
        # API. See: https://en.wikipedia.org/wiki/Post/Redirect/Get

        resp = super(Transport, self).request(method, url, **kwargs)

        self._log_response(resp)

        if resp.status_code in self.REDIRECT_STATUSES:
            # Be careful here in python True == 1 and False == 0
            if isinstance(redirect, bool):
                redirect_allowed = redirect
            else:
                redirect -= 1
                redirect_allowed = redirect >= 0

            if redirect_allowed:
                try:
                    location = resp.headers['location']
                except KeyError:
                    _logger.warn(
                        "Redirection from %s failed, no location provided",
                        resp.url,
                    )
                else:
                    new_resp = self._send_request(
                        method,
                        location,
                        redirect,
                        **kwargs
                    )

                    new_resp.history = list(new_resp.history)
                    new_resp.history.insert(0, resp)
                    resp = new_resp

        return resp

    def _log_request(self, method, url, **kwargs):
        if not _logger.isEnabledFor(logging.DEBUG):
            return

        if 'params' in kwargs and kwargs['params']:
            url += '?' + urllib.parse.urlencode(kwargs['params'])

        string_parts = [
            "curl -i",
            "-X '%s'" % method,
            "'%s'" % url,
        ]

        # kwargs overrides the default
        if (('verify' in kwargs and kwargs['verify'] is False) or
                not self.verify):
            string_parts.append('--insecure')

        for element in kwargs['headers'].items():
            header = " -H '%s: %s'" % element
            string_parts.append(header)

        if 'data' in kwargs and kwargs['data'] is not None:
            string_parts.append("--data '")
            string_parts.append(kwargs['data'])
            string_parts.append("'")
        _logger.debug("REQ: %s" % " ".join(string_parts))

    def _log_response(self, response):
        _logger.debug(
            "RESP: [%s] %r" % (
                response.status_code,
                response.headers,
            ),
        )
        if response._content_consumed:
            _logger.debug(
                "RESP BODY: %s",
                response.text,
            )
        _logger.debug(
            "encoding: %s",
            response.encoding,
        )


from flask import *

from extensions import *

main = Blueprint('main', __name__, template_folder='templates')

@main.route('/')
def main_route():
    return render_template("index.html")

@main.route('/hello')
def main_hello():
    Nusername = request.args.get('username')
    cur = db.cursor()
    cur.execute('SELECT albumid, title FROM Album')
    results = cur.fetchall()
    print_str = "
"
    for result in results:
        print_str += "
%s	%s
" % (result['albumid'], result['title'])
    print_str += "
"
    options = {
        'name': Nusername
	}
    return render_template("hello.html", **options)


import cv2
import numpy as np
import pytesseract

# get grayscale image
def get_grayscale(image):
    return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# noise removal
def remove_noise(image):
    return cv2.medianBlur(image, 5)

# thresholding
def thresholding(image):
    return cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# dilation
def dilate(image):
    kernel = np.ones((5,5),np.uint8)
    return cv2.dilate(image, kernel, iterations = 1)

# erosion - erosion followed by dilation
def opening(image):
    kernel = np.ones((5,5),np.uint8)
    return cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)

# canny edge detection
def canny(image):
    return cv2.Canny(image, 100, 200)

# skew correction
def deskew(image):
    coords = np.column_stack(np.where(image > 0))
    angle = cv2.minAreaReact(coords)[-1]
    if angle < -45:
        angle = -(90 + angle)
    else:
        angle = -angle
    (h, w) = image.shape[:2]
    center = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
    return rotated

# template matching
def match_template(image):
    return cv2.matchTemaplte(image, template, cv2.TM_CCOEFF_NORMED)

def get_text(image):
    custom_config = r'--oem 3 --psm 6'
    return pytesseract.image_to_string(image, config=custom_config)

def show_image(image):
    while True:
        cv2.imshow('image',image)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cv2.destroyAllWindows()

# after preprocessing with the following code
image = cv2.imread("aurebesh.jpg")

gray = get_grayscale(image)
thresh = thresholding(gray)
opening = opening(gray)
canny = canny(gray)

gray_text = get_text(gray)
thresh_text = get_text(thresh)
opening_text = get_text(opening)
canny_text = get_text(canny)

print('gray text: ',gray_text)
print('thresh text: ',gray_text)
print('opening text: ',gray_text)
print('canny text: ',gray_text)


import copy
import logging
from PIL import Image
import torch
from torchvision import transforms as tf
import brambox as bb
import lightnet as ln

__all__ = ['VOCDataset']
log = logging.getLogger('lightnet.VOC.dataset')

# def identify_file(img_id):
#     return f'/Users/sai/Downloads/lightnet-master/data/VOCdevkit/{img_id}.jpg'

def identify_file(img_id):
    return f'epfl_lab/20140804_160621_00/{img_id}'

class VOCDataset(ln.models.BramboxDataset):
    """ Pascal VOC dataset, with annotations generated by `brambox.io.parser.box.PandasParser`

    Args:
        anno_file (str or Path): Path to annotation file (must be parseable by PandasParser)
        params (lightnet.engine.HyperParameters): Hyperparameters for this data (See Note)
        augment (boolean): Whether to perform data augmentation
        kwargs (optional): extra keyword arguments to pass on to the `brambox.io.load()` function

    Note:
        The hyperparameters object should at least contain the following attributes:

        - params.input_dimension (tuple): tuple containing base (width,height) for the network
        - params.class_label_map (list): List of class_labels (can be **None**, but this might lead to undeterministic behaviour)
        - params.anno_filter (str, optional): How to filter difficult annotations: ['ignore', 'rm', 'none']; Default **'none'**
        - params.flip (float): chance to flip the image
        - params.jitter (float): jitter percentage
        - params.hue (float): Hue change percentage
        - params.saturation (float): Saturation change percentage
        - params.value (float): Value change percentage
    """
    def __init__(self, anno_file, params, augment, **kwargs):
        annos = bb.io.load('pandas', anno_file, **kwargs)

        # Filter data
        self.filter = getattr(params, 'filter_anno', 'none')
        if not self.filter in ('ignore', 'rm', 'none'):
            log.error(f'filter ({self.filter}) is not one of [ignore, rm, none]. Choosing default "none" value')

        if self.filter == 'ignore':
            annos.loc[annos.difficult, 'ignore'] = True
        elif self.filter == 'rm':
            annos = annos[~annos.difficult]

        # Data transformation pipeline
        lb  = ln.data.transform.Letterbox(dataset=self)
        img_tf = ln.data.transform.Compose([lb, tf.ToTensor()])
        anno_tf = ln.data.transform.Compose([lb])
        augment = False  ## I have added.
        if augment:
            rf  = ln.data.transform.RandomFlip(params.flip)
            rc  = ln.data.transform.RandomJitter(params.jitter, True, 0.1)
            hsv = ln.data.transform.RandomHSV(params.hue, params.saturation, params.value)
            img_tf[0:0] = [hsv, rc, rf]
            anno_tf[0:0] = [rc, rf]

        super().__init__(annos, params.input_dimension, params.class_label_map, identify_file, img_tf, anno_tf)


import sys, os, math
from scipy import spatial
from collections import Counter
import numpy as np

OutputDir = "outputs/"
ifile = sys.argv[1] #interactionfile
matrixfile = sys.argv[2] #ligand vectorfile

def cosineSim(vec1, vec2):   #TODO: own cosine sim
  #vec1f = [float(i) for i in vec1]
  #vec2f = [float(i) for i in vec2]
  result = 1 - spatial.distance.cosine(vec1, vec2)

  return result

def formatsim(score):
 sims_out= '{:.6f}'.format(score)
 simsst= str(sims_out).replace("00000000","0")

 return simsst

def loadInteractions(dfilename):

    dic = {}
    with open(dfilename) as f:
        for line in f:
            if line.strip():
                darr = line.split()
                elist = []
                if (darr[0] not in dic.keys()):
                    elist.append(darr[1])
                    dic[darr[0]] = elist

                elif (darr[0] in dic.keys()): ## and (darr[0] in proteins)
                    nlist = dic[darr[0]]
                    nlist.append(darr[1])
                    dic[darr[0]] = nlist

    f.close()
    return dic

def loadData(filename):
    print(filename)
    fingerprints = {}
    with open(filename) as fr:
        for line in fr:
            if 'null' in line.split("\t")[1]:
                fingerprints[line.split("\t")[0]]= "0"
            else:
                fingerprints[line.split("\t")[0]] = line.split("\t")[1]
    return fingerprints

protligdic = loadInteractions(ifile)
fpdictionary = loadData(matrixfile)

def getSmiFp(protlig,datax, protein):

    #fsize = datax.shape[0]
    #print(fsize)
    sumVec = np.zeros((1, 165), dtype=float)

    count = 1
    if protein in protlig.keys():
        ligands = protlig[protein]
        for ligand in ligands:
            vec = datax[ligand]
            bvec = convert2binary(vec)
            bvecf = np.array(bvec, dtype=float)
            sumVec = sumVec + bvecf #map(sum, zip(sumVec, vec))

        sumVec = sumVec / len(ligands)
    else:
        print(protein)

    return sumVec
def convert2binary(maccsfp):
	#binVec = np.zeros((1, 165), dtype=float)
	binVec = [0 for line in range(0,165)]
	maccsfp = maccsfp.replace("{","")
	maccsfp = maccsfp.replace("}\n","")

	maccsones = maccsfp.split(",")
	for ones in maccsones:
		binVec[int(ones)-1] =1

	return binVec

def constructSimMatrixv2(pairfile):   # text file folder & pair list
    if not os.path.exists(OutputDir):
        os.makedirs(OutputDir)

    f = open(os.path.join(OutputDir,  "proteins_smi_simmat.txt"), "w+")

    with open(pairfile) as fr:
        for line in fr:

            pairs = line.split()
            bioid = pairs[0][1:]
            bioid2 = pairs[1][1:]

            biotxt1 = getSmiFp(protligdic, fpdictionary, bioid)
            biotxt2 = getSmiFp(protligdic, fpdictionary, bioid2)
                #print(biotxt1)
            sims = cosineSim(biotxt1, biotxt2)
            simsst = formatsim(sims)

            f.write(bioid + "\t" + bioid2 + "\t" + str(simsst) + "\n")

    f.close()

#constructSimMatrixv2(sys.argv[2])
constructSimMatrixv2( sys.argv[3]) # pair file and option "fp" "vec"


# coding: utf-8

# # Simple Linear Regression using Scikit Learn

# ### Simple Linear Regression Equation
#
#

# ### y = a0 + a1*X

# In[44]:

#Import Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# In[45]:

#Read Student Grades .csv file and divide the data into dependent and independent variables.
data = pd.read_csv('Student_Grades_Data.csv')
data.head()

# In[46]:

data.shape

# In[47]:

X = data.iloc[:, :-1].values
y = data.iloc[:, 1].values

# In[48]:

X

# In[49]:

y

# In[50]:

#Split the data into training and test datasets
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)

# In[51]:

y_test

# In[52]:

#Fit the Simple Linear Regression Model
from sklearn.linear_model import LinearRegression
LinReg = LinearRegression()
LinReg.fit(X_train, y_train)

# In[53]:

#Print the
print(f'a0 = {LinReg.intercept_}')
print(f'a1 = {LinReg.coef_}')

# In[54]:

#Predicted grade scores from test dataset
y_predict = LinReg.predict(X_test)
y_predict

# In[55]:

#Actual grade scores from test dataset
y_test

# In[56]:

#Grades Vs Time to Study visualization on Training Data
plt.scatter(X_train, y_train, color='Blue')
plt.plot(X_train, LinReg.predict(X_train), color='Black')
plt.title('Grades Vs Time to Study (On Training Data)')
plt.xlabel('Time to Study')
plt.ylabel('Grades')
plt.show()

# In[57]:

#Grades Vs Time to Study visualization on Test Data
plt.scatter(X_test, y_test, color='Red')
plt.plot(X_train, LinReg.predict(X_train), color='Black')
plt.title('Grades Vs Time to Study (On Test Data)')
plt.xlabel('Time to Study')
plt.ylabel('Grades')
plt.show()

# In[66]:

#Predicting Grade of a student when he studied for 10 Hrs. Example of how to pass an external value,
#Independent of Test or Training Dataset

Predict_Grade = LinReg.predict(10)
Predict_Grade

# In[59]:

#Model Evaluation using R-Square
from sklearn import metrics
r_square = metrics.r2_score(y_test, y_predict)
print('R-Square Error:', r_square)

# In[60]:

#For Illustration Purpose Only.
#Considering Multiple Linear Equation with two Variables : grade = a0 + a1*time_to_study + a2*class_participation
#Model Evaluation using Adjusted R-Square.
# Here n = no. of observations and p = no. of independent variables

n = 50
p = 2
Adj_r_square = 1-(1-r_square)*(n-1)/(n-p-1)
print('Adjusted R-Square Error:', Adj_r_square)

# In[61]:

#Model Evaluation using Mean Square Error (MSE)
print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_predict))

# In[62]:

#Model Evaluation using Root Mean Square Error (RMSE)
print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_predict)))

# In[63]:

#Model Evaluation using Mean Absolute Error (MAE)
print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_predict))

# In[ ]:


import pyproj
from libpysal import weights
from rtree import index
from shapely.geometry import Point
from shapely.prepared import prep

from mesa_geo.geoagent import GeoAgent

class GeoSpace:
    def __init__(self, crs="epsg:3857"):
        """Create a GeoSpace for GIS enabled mesa modeling.

        Args:
            crs: Coordinate reference system of the GeoSpace
                If `crs` is not set, epsg:3857 (Web Mercator) is used as default.
                However, this system is only accurate at the equator and errors
                increase with latitude.

        Properties:
            crs: Project coordinate reference system
            idx: R-tree index for fast spatial queries
            bbox: Bounding box of all agents within the GeoSpace
            agents: List of all agents in the Geospace

        Methods:
            add_agents: add a list or a single GeoAgent.
            remove_agent: Remove a single agent from GeoSpace
            agents_at: List all agents at a specific position
            distance: Calculate distance between two agents
            get_neighbors: Returns a list of (touching) neighbors
            get_intersecting_agents: Returns list of agents that intersect
            get_agents_within: Returns a list of agents within
            get_agent_contains: Returns a list of agents contained
            get_agents_touches: Returns a list of agents that touch
            update_bbox: Update the bounding box of the GeoSpace
        """
        self.crs = pyproj.CRS(crs)
        self.WGS84 = pyproj.CRS("epsg:4326")
        self.Transformer = pyproj.Transformer.from_crs(
            self.crs, self.WGS84, skip_equivalent=True, always_xy=True
        )

        self.bbox = None
        self._neighborhood = None

        # Set up rtree index
        self.idx = index.Index()
        self.idx.agents = {}

    def add_agents(self, agents):
        """Add a list of GeoAgents to the Geospace.

        GeoAgents must have a shape attribute. This function may also be called
        with a single GeoAgent."""
        if isinstance(agents, GeoAgent):
            agent = agents
            if hasattr(agent, "shape"):
                self.idx.insert(id(agent), agent.shape.bounds, None)
                self.idx.agents[id(agent)] = agent
            else:
                raise AttributeError("GeoAgents must have a shape attribute")
        else:
            self._recreate_rtree(agents)

        self.update_bbox()

    def remove_agent(self, agent):
        """Remove an agent from the GeoSpace."""
        self.idx.delete(id(agent), agent.shape.bounds)
        self.update_bbox()

    def get_relation(self, agent, relation):
        """Return a list of related agents.

        Args:
            agent: the agent for which to compute the relation
            relation: must be one of 'intersects', 'within', 'contains',
                'touches'
            other_agents: A list of agents to compare against.
                Omit to compare against all other agents of the GeoSpace
        """
        related_agents = []
        possible_agents = self._get_rtree_intersections(agent.shape)
        for other_agent in possible_agents:
            if getattr(agent.shape, relation)(other_agent.shape):
                yield other_agent

    def _get_rtree_intersections(self, shape):
        """Calculate rtree intersections for candidate agents."""
        return (self.idx.agents[i] for i in self.idx.intersection(shape.bounds))

    def get_intersecting_agents(self, agent, other_agents=None):
        intersecting_agents = self.get_relation(agent, "intersects")
        return intersecting_agents

    def get_neighbors_within_distance(
        self, agent, distance, center=False, relation="intersects"
    ):
        """Return a list of agents within `distance` of `agent`.

        Distance is measured as a buffer around the agent's shape,
        set center=True to calculate distance from center.
        """
        if center:
            shape = agent.shape.center().buffer(distance)
        else:
            shape = agent.shape.buffer(distance)
        possible_neighbors = self._get_rtree_intersections(shape)
        prepared_shape = prep(shape)
        for other_agent in possible_neighbors:
            if getattr(prepared_shape, relation)(other_agent.shape):
                yield other_agent

    def agents_at(self, pos):
        """Return a list of agents at given pos."""
        if not isinstance(pos, Point):
            pos = Point(pos)
        return self.get_relation(pos, "within")

    def distance(self, agent_a, agent_b):
        """Return distance of two agents."""
        return agent_a.shape.distance(agent_b.shape)

    def _create_neighborhood(self):
        """Create a neighborhood graph of all agents."""
        agents = self.agents
        shapes = [agent.shape for agent in agents]
        self._neighborhood = weights.contiguity.Queen.from_iterable(shapes)
        self._neighborhood.agents = agents
        self._neighborhood.idx = {}
        for agent, key in zip(agents, self._neighborhood.neighbors.keys()):
            self._neighborhood.idx[agent] = key

    def get_neighbors(self, agent):
        """Get (touching) neighbors of an agent."""
        if not self._neighborhood or self._neighborhood.agents != self.agents:
            self._create_neighborhood()

        idx = self._neighborhood.idx[agent]
        neighbors_idx = self._neighborhood.neighbors[idx]
        neighbors = [self.agents[i] for i in neighbors_idx]
        return neighbors

    def _recreate_rtree(self, new_agents=None):
        """Create a new rtree index from agents shapes."""

        if new_agents is None:
            new_agents = []
        old_agents = list(self.agents)
        agents = old_agents + new_agents

        # Bulk insert agents
        index_data = ((id(agent), agent.shape.bounds, None) for agent in agents)

        self.idx = index.Index(index_data)
        self.idx.agents = {id(agent): agent for agent in agents}

    def update_bbox(self, bbox=None):
        """Update bounding box of the GeoSpace."""
        if bbox:
            self.bbox = bbox
        elif not self.agents:
            self.bbox = None
        else:
            self.bbox = self.idx.bounds

    @property
    def agents(self):
        return list(self.idx.agents.values())

    @property
    def __geo_interface__(self):
        """Return a GeoJSON FeatureCollection."""
        features = [a.__geo_interface__() for a in self.agents]
        return {"type": "FeatureCollection", "features": features}


#!/usr/bin/env python3

# Perform a Globus directory transfer, reusing refresh tokens we've already obtained for PARSL.
# Note this is NOT a PARSL transfer

import os
import json
from globus_sdk import (NativeAppAuthClient, TransferClient,
                        RefreshTokenAuthorizer, TransferData)
from globus_sdk.exc import GlobusAPIError

def load_tokens_from_file(filepath):
    """Load a set of saved tokens."""
    with open(filepath, 'r') as f:
        tokens = json.load(f)

    return tokens

def save_tokens_to_file(filepath, tokens):
    """Save a set of tokens for later use."""
    with open(filepath, 'w') as f:
        json.dump(tokens, f)

def update_tokens_file_on_refresh(token_response):
    """
    Callback function passed into the RefreshTokenAuthorizer.
    Will be invoked any time a new access token is fetched.
    """
    save_tokens_to_file(TOKEN_FILE, token_response.by_resource_server)

#dcde_parsl_client_id = 'e4466165-2a4c-48c9-916e-df7e4f4bd82c'
# This is (ahem!) appropriation of the PARSL client ID.  Use just for
# debugging purposes (trying to figure out my '400 invalid grant' error):
dcde_parsl_client_id = '8b8060fd-610e-4a74-885e-1051c71ad473'

# This is the token obtained by running parsl-globus-auth so that PARSL can
# authenticate to Globus:
TOKEN_FILE='/home/dcde1000006/.parsl/.globus.json'

source_endpoint_id = 'e133a52e-6d04-11e5-ba46-22000b92c6ec'
destination_endpoint_id = '23f78cc8-41e0-11e9-a618-0a54e005f950'
source_dir = '/dtemp/mscfops/d3c724/relion-tut/relion21_tutorial/PrecalculatedResults'
dest_dir = '/sdcc/u/dcde1000006/globus-scratch/relion-PrecalculatedResults'

# First authorize using those refresh tokens:

try:
    tokens = load_tokens_from_file(TOKEN_FILE)

except:
    print("Valid refresh tokens not found in {}.  Unable to authorize to Globus.  Exiting!".format(TOKEN_FILE))
    sys.exit(-1)

transfer_tokens = tokens['transfer.api.globus.org']

try:
    auth_client = NativeAppAuthClient(client_id=dcde_parsl_client_id)
except:
    print ("ERROR: Globus NativeAppAuthClient() call failed!  Unable to obtain a Globus authorizer!")
    sys.exit(-1)

authorizer = RefreshTokenAuthorizer(
    transfer_tokens['refresh_token'],
    auth_client,
    access_token=transfer_tokens['access_token'],
    expires_at=transfer_tokens['expires_at_seconds'],
    on_refresh=update_tokens_file_on_refresh)

try:
    tc = TransferClient(authorizer=authorizer)
except:
    print ("ERROR: TransferClient() call failed!  Unable to call the Globus transfer interface with the provided auth info!")
    sys.exit(-1)
# print(transfer)

# Now we should have auth, try setting up a transfer.

tdata = TransferData(tc, source_endpoint_id,
                     destination_endpoint_id,
                     label="DCDE Relion transfer",
                     sync_level="size")

tdata.add_item(source_dir, dest_dir,
               recursive=True)

transfer_result = tc.submit_transfer(tdata)

print("task_id =", transfer_result["task_id"])

while not tc.task_wait(transfer_result['task_id'], timeout=1200, polling_interval=10):
    print(".", end="")
print("\n{0} completed!".format(transfer_result['task_id']))

os.listdir(path=dest_dir)


def write(buf):
    for x in range(0, len(buf)):
        print('Case %d: %d' % (x + 1, buf[x]))

buf =[]
while True:
    x = (int)(input())
    if x == 0:
        break
    buf.append(x)
write(buf)


import freesasa
import Bio.PDB as PDB
import Bio.PDB.DSSP as DSSP
import glob
import numpy as np
import pandas as pd
from calc_fractions import *
from Bio.SeqUtils.IsoelectricPoint import IsoelectricPoint as IP
from Bio.PDB.Polypeptide import PPBuilder
from Bio.SeqUtils.ProtParam import ProteinAnalysis
import atomium

def calc_length(filenames):

    prot_lengths = []

    for filename in filenames:
        # parse the pdb file
        p = PDB.PDBParser(QUIET=True)
        s = p.get_structure("", filename)

        # get the sequence length
        seq = 0
        for chain in s.get_chains():
            seq += len([_ for _ in chain.get_residues() if PDB.is_aa(_)])

        # save into numpy sheet rsa
        prot_lengths.append(seq)

    return prot_lengths

def calc_surface(filenames):

    surfaces = []
    for filename in filenames:

        # get the surface area
        structure = freesasa.Structure(filename)
        result = freesasa.calc(structure)
        area_classes = freesasa.classifyResults(result, structure)

        # save this into numpy sheet result.totalArea()
        surface = result.totalArea()
        surfaces.append(surface)

    return surfaces

def ss_depth(filenames):

    frac_mod_beta_list = []
    frac_mod_alfa_list = []
    frac_exp_alfa_list = []

    for filename in filenames:
        p = PDB.PDBParser()
        structure = p.get_structure("", filename)

        model = structure[0]
        dssp = DSSP(model, filename)

        # DSSP data is accessed by a tuple (chain_id, res_id)
        all_residues = list(dssp.keys())

        # get a list with ASA values of all residues
        asa = [dssp[i][3] for i in all_residues]

        # 3 categories, like in paper
        burried = [0 if i <= 0.2 else 2 if i >= 0.5 else 1 for i in asa]

        # get a list with secondary structure of all residues (Q8)
        secondary_q8 = [dssp[i][2] for i in all_residues]

        # map the Q8 to Q3
        # helix = H, G, I
        # beta = B, E
        # loop = rest
        # 0 is alpha, 1 is beta, 2 is coil
        secondary_q3 = [0 if i in ['H', 'G', 'I'] else 1 if i in ['B', 'E'] else 2 for i in secondary_q8]

        # get the total number of sheets and helices
        count_helices = secondary_q3.count(0)
        count_sheets = secondary_q3.count(1)

        if count_sheets == 0:
            frac_mod_beta_list.append(0)
        else:
            # calculate fraction of moderately buried beta residues
            mod_beta = 0

            for i in range(len(burried)):
                if burried[i] == 1 and secondary_q3[i] == 1:
                    mod_beta += 1

            frac_mod_beta = mod_beta / count_sheets
            frac_mod_beta_list.append(frac_mod_beta)

        if count_helices == 0:
            frac_mod_alfa_list.append(0)
            frac_exp_alfa_list.append(0)
        else:
            # calc fraction of moderately buried alfa residues
            mod_alfa = 0

            for i in range(len(burried)):
                if burried[i] == 1 and secondary_q3[i] == 0:
                    mod_alfa += 1

            frac_mod_alfa = mod_alfa / count_helices
            frac_mod_alfa_list.append(frac_mod_alfa)

            # calc fraction of exposed a residues
            exp_alfa = 0

            for i in range(len(burried)):
                if burried[i] == 2 and secondary_q3[i] == 0:
                    exp_alfa += 1

            frac_exp_alfa = exp_alfa / count_helices
            frac_exp_alfa_list.append(frac_exp_alfa)

    return frac_mod_beta_list, frac_mod_alfa_list, frac_exp_alfa_list

def iso_point(filenames):
    """Funciton that calculats the isoelectric point of a list of proteins"""
    prot_charge = []
    pi = []
    aromatic_count = []
    aromaticity = []
    weight = []
    #flex = []
    inst = []

    for file in filenames:

        # parse the pdb file
        p = PDB.PDBParser(QUIET=True)
        s = p.get_structure(file, file)

        PolypeptideBuilder = PPBuilder()

        for pp in PolypeptideBuilder.build_peptides(s):
            query_chain = pp.get_sequence()

        # calculate iso-electric point etc.
        protein = IP(query_chain)
        prot_charge.append(protein.charge_at_pH(7.0))
        pi.append(protein.pi())

        # calculate molecular weight
        X = ProteinAnalysis(str(query_chain))
        # print(str(query_chain) + "\n")
        aromatic_count.append(X.count_amino_acids()['F'] + X.count_amino_acids()['W'] + X.count_amino_acids()['Y'])

        # Calculate aromaticity
        aromaticity.append(X.aromaticity())

        # molecular weight
        weight.append(X.molecular_weight())

        # flexibility calculated from aa. sequence
        #flex.append(X.flexibility())

        # stability from aa. sequence
        inst.append(X.instability_index())

    return prot_charge, pi, aromatic_count, aromaticity, weight, inst

def radius_of_giration(filenames):
    """Calculates the radius of gyration of each pdb structure and returns a list with all radii."""

    rg_list = []
    for filename in filenames:
        pdb = atomium.open(filename)
        rg = pdb.model.radius_of_gyration
        rg_list.append(rg)

    return rg_list

def get_average_bfactor(files):
    """Function that calculates the average b factor for a list of proteins"""
    av_b_factors = []

    for file in files:
        # parse the pdb file
        p = PDB.PDBParser(QUIET=True)
        s = p.get_structure(file, file)

        nratoms, sumbfactor = 0, 0.0

        for model in s:
            for chain in model:
                for residue in chain:
                    if PDB.is_aa(residue.get_resname()):
                        for atom in residue:
                            sumbfactor += atom.get_bfactor()
                            nratoms += 1

        avgbfactor = sumbfactor / nratoms
        av_b_factors.append(avgbfactor)

    return av_b_factors

def compute_features(filenames, save=False):
    """"Takes list of pdb filenames as input and returns list of features"""

    ###### Protein IDs
    protIDs = [filename.split('/')[-1].split('.pdb')[0] for filename in filenames]

    ###### Protein Sequence Length
    #print('Calculating Protein Sequence Length')
    prot_lengths = calc_length(filenames)

    ###### Surface Area
    #print("Calculating Surface Area")
    surfaces = calc_surface(filenames)

    ###### Relative Surface Area
    #print("Calculating Relative Surface Area")
    surface_seq = [surfaces[i] / prot_lengths[i] for i in range(len(surfaces))]

    ###### Secondary Structure
    #print("Calculating Secondary Structure")
    frac_mod_beta_list, frac_mod_alfa_list, frac_exp_alfa_list = ss_depth(filenames)

    ###### Isoelectron point and overall charge
    #print("Calculating Isoelecric point and charge of sequence")
    prot_charges, pis, aromatic_counts, aromaticitys, weights, instability = iso_point(filenames)

    ###### Fraction of aromatic residues
    frac_arom = []
    for i in range(len(aromatic_counts)):
        frac_arom.append(aromatic_counts[i]/prot_lengths[i])

    ###### Radius of gyration

    # print("Calculating radius of gyration")
    radius = radius_of_giration(filenames)

    ##### B factor
    bs = get_average_bfactor(filenames)

    ###### Fractions of Negative and Positive
    #print("Calculating Fractions of Negative and Positive")
    feats=feat_list(filenames)
    # turn list of tuples into tuple of lists
    frac_k_minus_r, frac_neg, frac_pos, frac_charged, pos_minus_neg, exp_score= ([a for a,b,c,d,e,f in feats],
                                                                      [b for a,b,c,d,e,f in feats],
                                                                      [c for a,b,c,d,e,f in feats],
                                                                      [d for a,b,c,d,e,f in feats],
                                                                      [e for a,b,c,d,e,f in feats],
                                                                        [f for a,b,c,d,e,f in feats])

    # Save features in file to pass to R script
    #print("Saving features")
    arr = np.column_stack((protIDs, surfaces, prot_lengths, surface_seq, frac_mod_beta_list, frac_mod_alfa_list,
                           frac_exp_alfa_list, frac_k_minus_r, frac_neg, frac_pos, frac_charged, pos_minus_neg,exp_score,
                           prot_charges, pis, aromatic_counts, aromaticitys, weights, frac_arom, instability, bs))

    df = pd.DataFrame({'protIDs': protIDs,
        'surfaces': surfaces,
        'prot_lengths': prot_lengths,
        'surface_seq': surface_seq,
        'frac_mod_beta_list': frac_mod_beta_list,
        'frac_mod_alfa_list': frac_mod_alfa_list,
        'frac_exp_alfa_list': frac_exp_alfa_list,
        'frac_k_minus_r': frac_k_minus_r,
        'frac_neg': frac_neg,
        'frac_pos': frac_pos,
        'frac_charged': frac_charged,
        'pos_minus_neg': pos_minus_neg,
        'exp_score': exp_score,
        'iso_point': pis,
        'charge': prot_charges,
        'aromatic_counts': aromatic_counts,
        'aromatic_fracs': frac_arom,
        'aromaticitys': aromaticitys,
        'weights': weights,
        'radius': radius,
        'instability': instability,
        'b_factor': bs})

    if save:
        # np.savetxt("features.csv", arr, delimiter=",")
        # np.save('features.npy', arr, allow_pickle=True, fix_imports=True)
        df.to_csv('features.csv', index=False)

    else:
        df.to_csv('features.csv', index=False)
        return df

if __name__ == "__main__":
    filenames = glob.glob("data/training/crystal_structs/*.pdb")

    compute_features(filenames, save=True)


class httplib:
    def __init__(self, status, msg, dict):
        self.status = status
        self.msg = msg
        self.header = dict
        self.headerstr = ""

    def get_response_msg(self):
        msg = ""
        if self.status == 200:
            msg = "OK"
        elif self.status == 400:
            msg = "Bad Request"
        elif self.status == 404:
            msg = "File Not Found"
        elif self.status == 405:
            msg = "Method Not Allowed"
        elif self.status == 403:
            msg = "Security Error"
        else:
            msg = "Unknown Error"
        return msg

    def create_header(self, header, bodyvalue):  # to convert header dictionary to header_string
        print("Inside create header")
        header_string = ""
        if "Content-Type" in header:
            pass
        else:
            header["Content-Type"] = "application/json"

        if "Content-Disposition" in header:
            pass
        else:
            header["Content-Disposition"] = "inline"

        header["Content-Length"] = str(len(self.msg))
        header["Accept-language"] = "en"
        #print("dictionary is: ")
        #print(header)
        for key, value in header.items():
            header_string = header_string + key + ": " + value + "\r\n"
        return header_string

    def add_header(self, key, val):
        self.header[key] = val

    def response_head(self):
        respmsg = self.get_response_msg()
        self.headerstr = self.create_header(self.header, self.msg)
        resphead = "HTTP/1.1 " + str(self.status) + " " + respmsg + "\r\n" + self.headerstr + "\r\n"
        print("\n httblib Response head :\n" + resphead)
        return resphead


#!/usr/bin/python -tt
# -*- coding: UTF-8 -*-

# Copyright (C) 2017 Denis Ollier
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

"""
Python implementation of the rpmatch(3) libc function.

It can be imported and used in python scripts or directly run as a script.

Usage example in python scripts:

    from rpmatch import rpmatch

    response = raw_input("Do you agree? ")

    if rpmatch(response) == 1:
        # User agreed
        ...
    else:
        # User did not agree
        ...

Usage as a script from command line:

    > python -m rpmatch response

When used as a script, the following exit status codes are used:
  - 0 for a recognized affirmative response
  - 1 for a recognized negative response
  - 2 for an unrecognized response
"""

__all__ = ['rpmatch']
__author__ = 'Denis Ollier'
__copyright__ = 'Copyright (C) 2017 Denis Ollier'
__license__ = 'GPL-3.0-or-later'
__version__ = '1.0.0'

import locale
import re

def rpmatch(response):
    """
    Determine if the answer to a question is affirmative or negative

    Returns:
      0 for a recognized negative response,
      1 for a recognized affirmative response,
      -1 for an unrecognized response
    """

    # locale.nl_langinfo is not supported for all OSes (e.g: windows)
    try:
        yes = locale.nl_langinfo(locale.YESEXPR)
        no = locale.nl_langinfo(locale.NOEXPR)
    except AttributeError:
        yes = "^[yY]"
        no = "^[nN]"

    if re.match(yes, response):
        result = 1
    elif re.match(no, response):
        result = 0
    else:
        result = -1

    return result

# Make module runnable as a script
if __name__ == "__main__":

    import optparse  # argparse is better but not included in python 2.6 stdlib
    import os
    import sys

    def process_command_line():
        """Process program command line arguments"""

        # Setup option parser
        usage = (
          "\n  %prog response"
          "\n  %prog option"
        )

        description = (
          "Determine if the answer to a question is affirmative or negative"
        )

        optparser = optparse.OptionParser(usage=usage, description=description)

        # Register options
        optparser.add_option(
          "-V", "--version",
          action="store_true",
          help="show version information and exit"
        )

        # Convert arguments to local variables
        (keyword_args, positional_args) = optparser.parse_args()

        # Handle keyword arguments
        if keyword_args.version:
            sys.stdout.write(
              "%s %s\n" % (os.path.basename(sys.argv[0]), __version__)
            )
            sys.exit(os.EX_OK)

        # Look for response in positional args
        try:
            response = positional_args[0]
        except IndexError:
            optparser.print_help(file=sys.stderr)
            sys.exit(3)

        return response

    #
    # Main
    #
    locale.setlocale(locale.LC_ALL, "")
    response = process_command_line()
    sys.exit(1 - rpmatch(response))

# vi: set ft=python et sw=4 ts=4:


"""
Partie 1 : Jeu simplifié de Slideways.
Auteur : Bouchkhachakh Mohamed
Matricule : 000494455
Section : B1 -INFO - science informatique
Date : 04 novembre 2019
but : Jouer une partie de Slideways à deux joueurs depuis un terminal, sans la possibilité de déplacer une rangée
      et avec un plateau 4x4.
Entrée : Les joueurs entre la coordonnée, d'une case du plateau de jeu, qu'il souhaite jouer.
Résultat : Afiiche un plateau de jeu et se termine lorsque l'un des deux joueurs gagne la partie.
"""

import os

def cases(plateau, joueur, tour, coup_precedant):
    """
    Vérifie si chaque input des joueurs représente une case valide du plateau.
    :param plateau: Une liste de listes représentant le plateau de jeu.
    :param joueur: Représente l'input du joueur1 ou du joueur2.
    :param tour: Représente le nombre de tour, c'est à dire le nombre de case déja joué.
    :param coup_precedant : Représente la case précédente ayant été joué.
    :return: Retourne "continuer", représentant False si l'entrée est invalide ou sinon True.
    """
    emplacement = {'A1': [3, 0], 'A2': [2, 0], 'A3': [1, 0], 'A4': [0, 0],
                   'B1': [3, 1], 'B2': [2, 1], 'B3': [1, 1], 'B4': [0, 1],
                   'C1': [3, 2], 'C2': [2, 2], 'C3': [1, 2], 'C4': [0, 2],
                   'D1': [3, 3], 'D2': [2, 3], 'D3': [1, 3], 'D4': [0, 3]}
    continuer = False
    if joueur not in emplacement.keys():
        print("commande invalide")
    else :
        case = emplacement.get(joueur)
        if tour % 2 == 0: # joueur 1
            if plateau[case[0]][case[1]] == 1:
                print("cette case vous appartiens déja, veuillez ressaisir une case")
            elif joueur == coup_precedant:
                print("ce coup vient d’être joué, veuillez ressaisir une case")
            else :
                continuer = True
        elif tour % 2 == 1: # joueur 2
            if plateau[case[0]][case[1]] == 2:
                print("Cette case vous appartiens déja, veuillez ressaisir une case")
            elif joueur == coup_precedant:
                print("ce coup vient d’être joué, veuillez ressaisir une case")
            else:
                continuer = True
    return continuer

def modification(plateau, joueur, tour):
    """
    Modifie le plateau en remplaçant un chiffre du plateau par 1 ou par 2, en fonction du joueur.
    :param plateau: Une liste de listes représentant le plateau de jeu.
    :param joueur: Représente l'input du joueur1 ou du joueur2.
    :param tour: Représente le nombre de tour, c'est à dire le nombre de case déja joué.
    :return: Returne plateau avec une case changée en fonction du joueur.
    """
    emplacement = {'A1': [3, 0], 'A2': [2, 0], 'A3': [1, 0], 'A4': [0, 0],
                   'B1': [3, 1], 'B2': [2, 1], 'B3': [1, 1], 'B4': [0, 1],
                   'C1': [3, 2], 'C2': [2, 2], 'C3': [1, 2], 'C4': [0, 2],
                   'D1': [3, 3], 'D2': [2, 3], 'D3': [1, 3], 'D4': [0, 3]}
    case = emplacement.get(joueur)
    if tour % 2 == 0:
        plateau[case[0]][case[1]] = 1
    else :
        plateau[case[0]][case[1]] = 2
    return plateau

def afficher(plateau):
    """
    Affiche le plateau à l'écran. 0 est affiché par '_', 1 par 'X' et 2 par 'O'.
    :param plateau: Une liste de listes représentant le plateau de jeu.
    :return: None
    """
    os.system("cls" if os.name == "nt" else "clear")
    for i in range(4):
        print('\n', '\n', 4-i, end = '  ')
        for j in range(4):
            if plateau[i][j] == 0:
                print('_', end = '  ')
            elif plateau[i][j] == 1:
                print('X', end = '  ')
            else :
                print('O', end = '  ')
        if i == 3:
            print('\n','\n','  ', 'A', '', 'B', '','C', '','D','\n','\n')
    return None

def verif_vh(plateau):
    """
    Vérifie si quatre 0 ou quatre 1 sont alignés verticalement ou horizontalement, dans quel cas le joueur représenté
    par ce chiffre gagne la partie.
    :param plateau: Une liste de listes représentant le plateau de jeu.
    :return: 0 si il n'y a pas d'alignement, sinon 1 ou 2.
    """
    continuer = False
    res = i = 0
    while i < 4 and not continuer:
        for j in range(4):
            p1 = plateau[i][j - 4]      # pour la vérification horizontale, 4 = nombre d'alignement pour gagner.
            p2 = plateau[i - 4][j]      # pour la vérification verticale
            if not continuer and p1 != 0 and p1 == plateau[i][j-3] and p1 == plateau[i][j-2] and p1 == plateau[i][j-1]:
                res = p1
                continuer = True
            elif not continuer and p2 != 0 and p2 == plateau[i-3][j] and p2 == plateau[i-2][j] and p2 ==plateau[i-1][j]:
                res = p2
                continuer = True
        i += 1
    return res

def verif_diagonales(plateau):
    """
    Vérifie si quatre 0 ou quatre 1 sont alignés en diagonale (de haut en bas et de bas en haut),
    dans quel cas le joueur représenté par ce chiffre gagne la partie.
    :param plateau: Une liste de listes représentant le plateau de jeu.
    :return: 0 si il n'y a pas d'alignement, sinon 1 ou 2.
    """
    continuer = False
    res = i = 0
    # Vérification des diagonales de haut en bas
    while i < 1 and not continuer:    # dans ce plateau, on ne vérifie la diagonale que pour la case [0,0]
        for j in range(1):
            case = plateau[i][j]
            if case != 0 and case == plateau[i+1][j+1] and case == plateau[i+2][j+2] and case == plateau[i+3][j+3]:
                res = case
                continuer = True
        i += 1
    # Vérification des diagonales de bas en haut
    i = 1
    while i <= 1 and not continuer:   # dans ce plateau, on ne vérifie la diagonale que pour la case [-1,0]
        for j in range(1):
            case = plateau[-i][j]
            if case != 0 and case == plateau[-i-1][j+1] and case == plateau[-i-2][j+2] and case == plateau[-i-3][j+3]:
                res = case
                continuer = True
        i += 1
    return res

def verification(plateau):
    """
    Prends en compte les fonctions de vérification horizontale, verticale ainsi que diagonales.
    :param plateau: Une liste de listes représentant le plateau de jeu.
    :return: 0 si il n'y a pas de gagnant, ou alors 1 ou 2, représentant le gagnant.
    """
    if verif_vh(plateau) != 0 :
        gagnant = verif_vh(plateau)

    elif verif_diagonales(plateau) != 0 :
        gagnant = verif_diagonales(plateau)

    else :
        gagnant = 0
    return gagnant

def boucle_jeu():
    """
    Boucle principale du jeu. Il n'y a pas d'entrée ni de return. Le jeu continue tant que l'un des deux joueurs ne
    remporte pas la victoire.
    :return: None
    """
    plateau = [[0 for i in range(4)] for j in range(4)]
    plateau.reverse()
    gagnant = tour = coup_precedant = 0

    afficher(plateau)
    while gagnant == 0:
        if tour % 2 == 0:
            joueur = str(input("Joueur 1 > "))
            while not cases(plateau, joueur, tour, coup_precedant):
                joueur = str(input("Joueur 1 > "))
        else:
            joueur = str(input("Joueur 2 > "))
            while not cases(plateau, joueur, tour, coup_precedant):
                joueur = str(input("Joueur 2 > "))
        plateau = modification(plateau, joueur, tour)
        afficher(plateau)
        if verification(plateau) != 0:
            gagnant = verification(plateau)
        tour += 1
        coup_precedant = joueur
    print("joueur", gagnant, "gagnant")
    return None

if __name__ == '__main__':
    boucle_jeu()


from typing import Any, Callable, Dict, Optional, Union

from tartiflette import Directive
from tartiflette.types.exceptions.tartiflette import SkipCollection

def skip_selection(
    directive_args: Dict[str, Any],
    selection: Union["FragmentSpreadNode", "FieldNode", "InlineFragmentNode"],
    ctx: Optional[Any],
) -> Union["FragmentSpreadNode", "FieldNode", "InlineFragmentNode"]:
    """
    Determines whether or not the selection should be collected or skipped.
    :param directive_args: arguments passed to the directive
    :param selection: the selection node to collect or skip
    :param ctx: context passed to the query execution
    :type directive_args: Dict[str, Any]
    :type selection: Union[FragmentSpreadNode, FieldNode, InlineFragmentNode]
    :type ctx: Optional[Any]
    :return: the selection node to collect
    :rtype: Union[FragmentSpreadNode, FieldNode, InlineFragmentNode]
    """
    # pylint: disable=unused-argument
    if directive_args["if"]:
        raise SkipCollection()
    return selection

class SkipDirective:
    """
    Built-in directive which allows for conditional exclusion of fields,
    fragment spreads, and inline fragments at execution time.
    """

    async def on_field_collection(
        self,
        directive_args: Dict[str, Any],
        next_directive: Callable,
        field_node: "FieldNode",
        ctx: Optional[Any],
    ) -> "FieldNode":
        """
        Determines whether or not the field should be collected or skipped at
        execution time.
        :param directive_args: arguments passed to the directive
        :param next_directive: next directive to call
        :param field_node: the field to collect or skip
        :param ctx: context passed to the query execution
        :type directive_args: Dict[str, Any]
        :type next_directive: Callable
        :type field_node: FieldNode
        :type ctx: Optional[Any]
        :return: the field node to collect
        :rtype: FieldNode
        """
        return skip_selection(
            directive_args, await next_directive(field_node, ctx), ctx
        )

    async def on_fragment_spread_collection(
        self,
        directive_args: Dict[str, Any],
        next_directive: Callable,
        fragment_spread_node: "FragmentSpreadNode",
        ctx: Optional[Any],
    ) -> "FragmentSpreadNode":
        """
        Determines whether or not the fragment spread should be collected or
        skipped at execution time.
        :param directive_args: arguments passed to the directive
        :param next_directive: next directive to call
        :param fragment_spread_node: the fragment spread to collect or skip
        :param ctx: context passed to the query execution
        :type directive_args: Dict[str, Any]
        :type next_directive: Callable
        :type fragment_spread_node: FragmentSpreadNode
        :type ctx: Optional[Any]
        :return: the fragment spread node to collect
        :rtype: FragmentSpreadNode
        """
        return skip_selection(
            directive_args,
            await next_directive(fragment_spread_node, ctx),
            ctx,
        )

    async def on_inline_fragment_collection(
        self,
        directive_args: Dict[str, Any],
        next_directive: Callable,
        inline_fragment_node: "InlineFragmentNode",
        ctx: Optional[Any],
    ) -> "InlineFragmentNode":
        """
        Determines whether or not the inline fragment should be collected or
        skipped at execution time.
        :param directive_args: arguments passed to the directive
        :param next_directive: next directive to call
        :param inline_fragment_node: the inline fragment to collect or skip
        :param ctx: context passed to the query execution
        :type directive_args: Dict[str, Any]
        :type next_directive: Callable
        :type inline_fragment_node: InlineFragmentNode
        :type ctx: Optional[Any]
        :return: the inline fragment node to collect
        :rtype: InlineFragmentNode
        """
        return skip_selection(
            directive_args,
            await next_directive(inline_fragment_node, ctx),
            ctx,
        )

def bake(schema_name: str, config: Optional[Dict[str, Any]] = None) -> str:
    """
    Links the directive to the appropriate schema and returns the SDL related
    to the directive.
    :param schema_name: schema name to link with
    :param config: configuration of the directive
    :type schema_name: str
    :type config: Optional[Dict[str, Any]]
    :return: the SDL related to the directive
    :rtype: str
    """
    # pylint: disable=unused-argument
    Directive("skip", schema_name=schema_name)(SkipDirective())
    return '''
    """Directs the executor to skip this field or fragment when the `if` argument is true."""
    directive @skip(
      """Skipped when true."""
      if: Boolean!
    ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
    '''


from toysocks.eventloop import EventLoop, Future, register_read_write, unregister
from toysocks.encrypt import Encryptor
from toysocks.utils import check_socket

import socket
import logging
import errno
from selectors import EVENT_READ, EVENT_WRITE

def relay(sock1 : socket.socket,
          sock2 : socket.socket,
          sock1_data_to_sock2_data = lambda x, offset : (x, 0),
          sock2_data_to_sock1_data = lambda x, offset : (x, 0),):

  def relay_callback(source_sock, tg_sock, event_key, event_mask):
    future.set_result((source_sock, tg_sock, event_key, event_mask))

  data_queues = {
    sock1.fileno(): [],
    sock2.fileno(): []
  }

  data_offset = {
    sock1.fileno(): 0,
    sock2.fileno(): 0
  }

  try:
    stopped = 0

    while True:
      future = Future()

      register_read_write(sock1, lambda k, m: relay_callback(sock1, sock2, k, m))
      register_read_write(sock2, lambda k, m: relay_callback(sock2, sock1, k, m))

      source_sock, tg_sock, event_key, event_mask = yield future
      unregister(sock1)
      unregister(sock2)

      try:

        if event_mask & EVENT_WRITE != 0:
          # If a write is ready, write the corresponding data to it
          if len(data_queues[source_sock.fileno()]) > 0:
            data = data_queues[source_sock.fileno()][0]
            check_socket(source_sock)
            sent = source_sock.send(data)

            # if source_sock.fileno() == sock2.fileno():
            #   logging.debug("data sent to sock2 (%d):\n%s" % (sent, data[0 : sent]))

            if sent < len(data):
              data_queues[source_sock.fileno()][0] = data[sent:]
            else:
              data_queues[source_sock.fileno()].pop(0)
            #logging.debug("sent %d" % len(data))
        if event_mask & EVENT_READ != 0:
          check_socket(source_sock)

          data = source_sock.recv(4096)
          if len(data) == 0:
            stopped += 1
            if stopped >= 2:
              break
          if tg_sock.fileno() == sock2.fileno():
            encoded_data, adjust = sock1_data_to_sock2_data(data, data_offset[sock1.fileno()])
            data_offset[sock1.fileno()] += len(data) + adjust
          else:
            encoded_data, adjust = sock2_data_to_sock1_data(data, data_offset[sock2.fileno()])
            data_offset[sock2.fileno()] += len(data) + adjust

          data_queues[tg_sock.fileno()].append(encoded_data)

      except IOError as e:
        if e.errno == errno.EWOULDBLOCK:
          pass
        elif e.errno == errno.ENOTCONN:
          pass
        elif e.errno == errno.EAGAIN:
          pass
        else:
          logging.error("relay IOError: %s" % e)
          break

  finally:
    check_socket(sock1)
    check_socket(sock2)
    sock1.close()
    sock2.close()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.

"""
Basic example for a bot that uses inline keyboards.
"""
import logging
import config
import session
import fopen_inf

from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Bot
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, CallbackContext

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)
logger = logging.getLogger(__name__)

CALLBACK_BUTTON0 = "0"  # идентификатор кнопки_1
CALLBACK_BUTTON1 = "1"  # идентификатор кнопки_2
CALLBACK_BUTTON2 = "2"  # идентификатор кнопки_3
CALLBACK_BUTTON3 = "3"  # идентификатор кнопки_4
CALLBACK_BUTTON4 = "4"  # идентификатор кнопки_5
CALLBACK_NULL = "callback_null"  # идентификатор кнопки проигнорировать
CALLBACK_RESET = "callback_reset"  # идентификатор сбросить
CALLBACK_AGREE = "callback_agree"  # идентификатор подтвердить
CALLBACK_LINK = "callback_link"  # идентификатор сслыки на сайт с описанием еды

TITLES = {
    CALLBACK_NULL: "Игнорировано",
    CALLBACK_RESET: "сброс",
    CALLBACK_AGREE: "Согласен",
    CALLBACK_LINK: "Подробнее от блюдах в меню"
}

first_food_arr = []
second_food_arr = []
third_food_arr = []
fourth_food_arr = []
list_inf_1 = []
list_inf_2 = []
list_inf_3 = []
list_inf_4 = []

#first_food_arr = ["Рассольник", "Крем суп", "Грибной суп", "Гороховый суп", "Борщ со свининой"]
#second_food_arr = ["Стейк из свинины", "Пельмени", "Тушёный рис с тыквой", "Голубцы ленивые", "Мясо по французски"]
#third_food_arr = ["Рис отваренный", "Рис на сковороде", "Картошка пюре", "Гречка", "Макароны"]
#fourth_food_arr = ["Салат \'Цезарь\'", "Салат \'Охотничий\'", "Салат \'Обжорка\'", "Салат \'Мимоза\'",
                   #"Салат \'Обалденный\'"]

counter = 0
result = [0, 0, 0, 0]  # массив результатов выбора пользователя

def agreement_keyboard():
    key = [[InlineKeyboardButton(TITLES[CALLBACK_AGREE], callback_data=CALLBACK_AGREE)],
           [InlineKeyboardButton(TITLES[CALLBACK_RESET], callback_data=CALLBACK_RESET)]]

    rm = InlineKeyboardMarkup(key)
    return rm

def base_keyboard(arrayFood):
    """
        CALLBACK_BUTTON_N - значения текста меняются с зависимости от значения counter
        counter - индекс
        counter == 0 Реализуется набор first_food_arr
        counter == 1 Реализуется набор second_food_arr
        counter == 2 Реализуется набор
        counter == 3 Реализуется набор
        counter == 4 Запускается набор подтверждения
    """
    keyboard = [[InlineKeyboardButton(arrayFood[0], callback_data=CALLBACK_BUTTON0)],
                [InlineKeyboardButton(arrayFood[1], callback_data=CALLBACK_BUTTON1)],
                [InlineKeyboardButton(arrayFood[2], callback_data=CALLBACK_BUTTON2)],
                [InlineKeyboardButton(arrayFood[3], callback_data=CALLBACK_BUTTON3)],
                [InlineKeyboardButton(arrayFood[4], callback_data=CALLBACK_BUTTON4)],
                [InlineKeyboardButton(TITLES[CALLBACK_NULL], callback_data=CALLBACK_NULL)],
                [InlineKeyboardButton(TITLES[CALLBACK_LINK],
                                      url='127.0.0.1')]]

    reply_markup = InlineKeyboardMarkup(keyboard)
    return reply_markup

def start(update, context: CallbackContext):
    update.message.reply_text('Меню')
    update.message.reply_text('Выберите {}: '.format("первое блюдо"),
                              reply_markup=base_keyboard(first_food_arr))

def button(update, context: CallbackContext):
    # слушатель кнопок
    global counter
    query = update.callback_query
    chat_id = update.effective_message.chat_id
    data = query.data
    if data in (
            CALLBACK_BUTTON0, CALLBACK_BUTTON1, CALLBACK_BUTTON2, CALLBACK_BUTTON3, CALLBACK_BUTTON4, CALLBACK_NULL):

        if data == CALLBACK_NULL:
            result[counter] = -1
        else:
            result[counter] = int(data)

        if result[counter] != -1:
            if counter == 0:
                query.edit_message_text(text="Вы выбрали {}".format(first_food_arr[int(data)]))
            if counter == 1:
                query.edit_message_text(text="Вы выбрали {}".format(second_food_arr[int(data)]))
            if counter == 2:
                query.edit_message_text(text="Вы выбрали {}".format(third_food_arr[int(data)]))
            if counter == 3:
                query.edit_message_text(text="Вы выбрали {}".format(fourth_food_arr[int(data)]))
        else:
            query.edit_message_text(text="Вы инорировали")

        counter += 1
        if counter == 1:
            context.bot.send_message(
                chat_id=chat_id,
                text="Выбирите второе блюдо",
                reply_markup=base_keyboard(second_food_arr),
            )
        elif counter == 2:
            context.bot.send_message(
                chat_id=chat_id,
                text="Выбирите гарнир",
                reply_markup=base_keyboard(third_food_arr),
            )
        elif counter == 3:
            context.bot.send_message(
                chat_id=chat_id,
                text="Выбирете салат",
                reply_markup=base_keyboard(fourth_food_arr),
            )
        elif counter == 4:
            context.bot.send_message(
                chat_id=chat_id,
                text="Подтвердите выбор",
                reply_markup=agreement_keyboard(),
            )
    elif data == CALLBACK_RESET:
        counter = 0
        context.bot.send_message(
            chat_id=chat_id,
            text="Выберите первое блюдо",
            reply_markup=base_keyboard(first_food_arr)
        )
        query.edit_message_text(text="Произведён сброс")
    elif data == CALLBACK_AGREE:
        name_first = ""
        name_second = ""
        name_third = ""
        name_fourth = ""

        if result[0] != -1:
            name_first = first_food_arr[result[0]]
        if result[1] != -1:
            name_second = second_food_arr[result[1]]
        if result[2] != -1:
            name_third = third_food_arr[result[2]]
        if result[3] != -1:
            name_fourth = fourth_food_arr[result[3]]
        query.edit_message_text(
            text="Вы выбрали\n{}\n{}\n{}\n{}".format(name_first, name_second, name_third, name_fourth),
        )

        list_info = []

        n = result[0]
        list_info.append(list_inf_4[n])

        n = result[1]
        list_info.append(list_inf_3[n])

        n = result[2]
        list_info.append(list_inf_2[n])

        n = result[3]
        list_info.append(list_inf_1[n])
    update(list_info)

def help(update, context):
    update.message.reply_text("Use /start to test this bot.")

def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)

def main():
    global first_food_arr,second_food_arr,third_food_arr,fourth_food_arr,list_inf_4,list_inf_3,list_inf_2,list_inf_1
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    first_food_arr, second_food_arr, third_food_arr, fourth_food_arr,list_inf_4,list_inf_3,list_inf_2,list_inf_1  = fopen_inf.read_data()

    bot = Bot(
        token=config.token,
    )
    # updater = Updater(token=config.TOKEN, use_context=True)
    updater = Updater(bot=bot, use_context=True)

    updater.dispatcher.add_handler(CommandHandler('start', start))
    updater.dispatcher.add_handler(CallbackQueryHandler(button))
    updater.dispatcher.add_handler(CommandHandler('help', help))
    updater.dispatcher.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until the user presses Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT
    updater.idle()

if __name__ == '__main__':
    main()