# -*- coding = utf-8 -*-
# @time:2020/9/22 23:51
# Author:TC
# @File:网格搜索+xgboost.py
# @Software:PyCharm

from sklearn.datasets import load_iris
from xgboost import plot_importance
from matplotlib import pyplot as plt
from sklearn.metrics import accuracy_score
import xgboost as xgb
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import roc_auc_score

iris = load_iris()
X,y = iris.data,iris.target
col = iris.target_names
train_x, valid_x, train_y, valid_y = train_test_split(X, y, test_size=0.3, random_state=1)   # 分训练集和验证集
parameters = {
              'max_depth': [5, 10, 15, 20, 25],
              'learning_rate': [0.01, 0.02, 0.05, 0.1, 0.15],
              'n_estimators': [500, 1000, 2000, 3000, 5000],
              'min_child_weight': [0, 2, 5, 10, 20],
              'max_delta_step': [0, 0.2, 0.6, 1, 2],
              'subsample': [0.6, 0.7, 0.8, 0.85, 0.95],
              'colsample_bytree': [0.5, 0.6, 0.7, 0.8, 0.9],
              'reg_alpha': [0, 0.25, 0.5, 0.75, 1],
              'reg_lambda': [0.2, 0.4, 0.6, 0.8, 1],
              'scale_pos_weight': [0.2, 0.4, 0.6, 0.8, 1]

}

xlf = xgb.XGBClassifier(max_depth=10,
            learning_rate=0.01,
            n_estimators=2000,
            silent=True,
            objective='multi:softmax',
            num_class=3 ,
            nthread=-1,
            gamma=0,
            min_child_weight=1,
            max_delta_step=0,
            subsample=0.85,
            colsample_bytree=0.7,
            colsample_bylevel=1,
            reg_alpha=0,
            reg_lambda=1,
            scale_pos_weight=1,
            seed=0,
            missing=None)

gs = GridSearchCV(xlf, param_grid=parameters, scoring='accuracy', cv=3)
gs.fit(train_x, train_y)

print("Best score: %0.3f" % gs.best_score_)
print("Best parameters set: %s" % gs.best_params_ )


from Domain.TeamClass import Team
from Repository.repo import TeamRepository
repo=TeamRepository()
def printRepo(repo):
    print("Current repo ")
    for elem in repo.get_data():
        print(elem)

t1=Team("t1",990,1)
t2=Team("t2",90,2)
t3=Team("t3",190,3)
try:
    repo.add_a_team(t1)

except Exception as e:
    print("Exception !")
try:
    repo.add_a_team(t2)

except Exception as e:
    print("Exception !")

try:
    repo.add_a_team(t3)

except Exception as e:
    print("Exception !")

print("Add a team: ")
printRepo(repo)
repo.delete_team_with_score_under_100()
printRepo(repo)
repo.filter_score_above_100()
printRepo(repo)
repo.update_score_of_a_given_team(0,300)
printRepo(repo)
repo.sort_descending()
printRepo(repo)


from typing import List, Optional, Tuple

class Node:
    def __init__(self, key=None, value=None):
        self.key = key
        self.value = value
        self.left = None
        self.right = None
        self.parent = None

class TreeMap:
    def __init__(self):
        self.root = None
        self.length = 0

    def __delitem__(self, key):
        self.remove(key)

    def __getitem__(self, key):
        return self.get(key)

    def __setitem__(self, key, value):
        self.set(key, value)

    def __len__(self):
        return self.length

    def __iter__(self):
        return self._inorder_generator(self.root)

    def _inorder_generator(self, node):
        if node is not None:
            yield from self._inorder_generator(node.left)
            yield node
            yield from self._inorder_generator(node.right)

    def _insert(self, new_node: Node):
        parent_node = None
        current_node = self.root

        while current_node is not None:
            parent_node = current_node
            if new_node.key < current_node.key:
                current_node = current_node.left
            else:
                current_node = current_node.right

        new_node.parent = parent_node
        if parent_node is None:
            self.root = new_node
        elif new_node.key < parent_node.key:
            parent_node.left = new_node
        else:
            parent_node.right = new_node

        new_node.left = None
        new_node.right = None

    def _transplant(self, x: Node, y: Node):
        if x.parent is None:
            self.root = y
        elif x == x.parent.left:
            x.parent.left = y
        else:
            x.parent.right = y
        if y is not None:
            y.parent = x.parent

    def _minimum(self, node: Node):
        while node.left is not None:
            node = node.left
        return node

    def _delete(self, target_node: Node):
        if target_node.left is None:
            self._transplant(target_node, target_node.right)

        elif target_node.right is None:
            self._transplant(target_node, target_node.left)

        else:
            min_node = self._minimum(target_node.right)
            min_node_right = min_node.right
            if min_node.parent == target_node:
                min_node_right.parent = target_node

            else:
                self._transplant(min_node, min_node.right)
                min_node.right = target_node.right
                min_node.right.parent = min_node

            self._transplant(target_node, min_node)
            min_node.left = target_node.left
            min_node.left.parent = min_node

    def _find(self, node: Node, key) -> Tuple[Optional[Node], Optional[Node]]:
        if node is None:
            return None, None

        if key == node.key:
            return node, node.parent
        elif key < node.key:
            return self._find(node.left, key)
        else:
            return self._find(node.right, key)

    def get(self, key):
        node, _ = self._find(self.root, key)
        if node is not None:
            return node.value
        return None

    def set(self, key, value):
        node, parent = self._find(self.root, key)
        if node is not None:
            node.value = value
        else:
            node = Node(key, value)
            if parent is None:
                self._insert(node)
            elif key < parent.key:
                parent.left = node
            else:
                parent.right = node
            self.length += 1

    def remove(self, key):
        node, _ = self._find(self.root, key)
        if node is not None:
            self._delete(node)
            self.length -= 1
        return None

    def keys(self):
        for node in self:
            yield node.key

    def values(self):
        for node in self:
            yield node.value

    def items(self):
        for node in self:
            yield node.key, node.value

class Solution:
    def run_commands(self, commands: List[str], arguments: List[Optional[List]]):
        tree_map = None
        commands_output = list()
        for index in range(len(commands)):
            if commands[index] == "TreeMap":
                tree_map = TreeMap()
                commands_output.append(None)
                continue
            if commands[index] == "put":
                commands_output.append(tree_map.set(arguments[index][0], arguments[index][1]))
                continue
            if commands[index] == "remove":
                commands_output.append(tree_map.remove(arguments[index][0]))
                continue
            if commands[index] == "get":
                commands_output.append(tree_map.get(arguments[index][0]))
                continue
        return commands_output


import logging
import subprocess
import os
import time
import shlex
from ..config import sim_config

class Sim():
	def __init__(self, port, time_till_timeout = sim_config.time_till_timeout):
		'''
			A Sim object starts and holds the donkeysim subprocess.
			It must be pinged every time_till_timeout seconds with self.keep_alive_ping() or self.is_timeout() will return True

			WARNING: IF THE PORT IS UNAVAILABLE NO ERROR IS THROWN AND A DONKEYSIM SUBPROCESS WILL START WITH UNKNOWN PORT

			Args:
				port ([int]): port number the sim will listen to. Must be available (use the PortHandler class)
				time_till_timeout (int, optional): Time until timeout without pings. Defaults to sim_config.time_till_timeout.
		'''
		self.port = int(port)
		self.SimLogger = logging.getLogger(f"SimProcess {self.port}")
		self.SimLogger.setLevel(logging.DEBUG)
		self.start_time = time.time()
		self.last_ping_time = time.time()
		self.time_till_timeout = time_till_timeout
		self.process = self.start_sim_proc()
		self.is_in_use = True

	def start_sim_proc(self):
		'''
			Starts the donkeysim subprocess using the self.port argument and returns the subprocess instance
		'''
		self.SimLogger.debug(f"Launching sim at port {self.port}")
		cmd = os.environ["SIM_PATH"] + " --port " + str(self.port)
		print(shlex.split(cmd))
		proc = subprocess.Popen(shlex.split(cmd))
		self.SimLogger.debug(f"Launched sim at port {self.port}")
		return proc

	def ping(self):
		'''
			The Sim instance must be pinged at least once every self.time_till_timeout seconds to stay alive.
		'''
		self.SimLogger.debug(f"Pinging sim at port {self.port}. Last ping time = {self.last_ping_time}")
		self.last_ping_time = time.time()

	def is_timeout(self):
		'''
			Checks if the process has been pinged to stay alive less that self.time_till_timeout seconds ago
		'''
		self.SimLogger.debug(f"Checking timeout for sim {self.port}")
		if (time.time() - self.last_ping_time) > self.time_till_timeout:
			self.SimLogger.debug(f"Sim found to be timed out with current time : {time.time()} and last_ping_time = {self.last_ping_time}")
			return True
		self.SimLogger.debug(f"not timed out")
		return False

	def is_alive(self):
		'''
			Returns True if the donkeysim process is still running.
		'''
		return (self.process.poll() == None)

	def kill(self):
		'''
			Kill the donkeysim subprocess and set self.process to None.
		'''
		self.SimLogger.debug(f"Killing {self}")
		self.process.kill()
		self.process = None

	def safety_check_port_arg():
		pass
		# TODO: Inquire as to the safety of this

	def __str__(self):
		return (f"Sim instance at port {self.port}")

	def __repr__(self):
		return str(self)

# if __name__ == "__main__":
#     sim = Sim(8889, 5)
#     # sim.permapoll()
#     while True:
#         time.sleep(1)
#         print(sim.is_alive())
#         if (not sim.should_be_alive()):
#             sim.kill_sim()


"""Add meta to file

Revision ID: ab5b51940dfc
Revises: 9a91325da470
Create Date: 2021-09-16 21:34:08.756075

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = "ab5b51940dfc"
down_revision = "9a91325da470"
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("file", sa.Column("meta", sa.JSON(), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("file", "meta")
    # ### end Alembic commands ###


'''
Ex02:
Faça um programa que receba uma temperatura em fahrenheit e converta para celcius; Ao final diga se está calor ou não (> 30 == Calor).

Formula: (ºF - 32) * 5/9
'''

#Entrada
temp_f = float(input('Digite a temperatura em fahrenheit: '))

#Processamento
temp_c = (temp_f - 32) * 5/9
if temp_c > 30:
    sensacao = 'calor'
elif temp_c >= 20:
    sensacao = 'agradável'
else:
    sensacao = 'frio'

#Saída
print(f'Hoje o dia está em {temp_c:.2f}ºC.')
print(f'Então está fazendo {sensacao}!')


from tkinter import *
import tkinter.font as font

#calculator window
root = Tk()
myFont = font.Font(family="Lemon Milk")
root.title("Calculator")
root.geometry("292x630")

#input text field
e = Entry(0,width = 45,borderwidth = 5)
e.grid(row=0,column=0,padx=5,pady=5,columnspan=3)

#inputing into the text field
def click(number):
    current = e.get()
    e.delete(0,END)
    e.insert(0,str(current) + str(number))

#defining functions
def clear():
    e.delete(0, END)

def add():
    f_num= e.get()
    global fnum
    global math
    math = "addition"
    fnum = float(f_num)
    e.delete(0, END)

def sub():
    f_num= e.get()
    global fnum
    global math
    math = "subtraction"
    fnum = float(f_num)
    e.delete(0, END)

def mul():
    f_num= e.get()
    global fnum
    global math
    math = "multiplication"
    fnum = float(f_num)
    e.delete(0, END)

def div():
    f_num= e.get()
    global fnum
    global math
    math = "divison"
    fnum = float(f_num)
    e.delete(0, END)

def equal():
    snum = e.get()
    e.delete(0, END)

    if math == "addition":
        e.insert(0,fnum + float(snum))

    if math == "subtraction":
        e.insert(0,fnum - float(snum))

    if math == "multiplication":
        e.insert(0,fnum * float(snum))

    if math == "divison":
        e.insert(0,fnum / float(snum))

#defining buttons
button1 = Button(root,text="1",padx=32,pady=30,command = lambda : click(1))
button2 = Button(root,text="2",padx=30,pady=30,command = lambda : click(2))
button3 = Button(root,text="3",padx=30,pady=30,command = lambda : click(3))
button4 = Button(root,text="4",padx=30,pady=30,command = lambda : click(4))
button5 = Button(root,text="5",padx=30,pady=30,command = lambda : click(5))
button6 = Button(root,text="6",padx=30,pady=30,command = lambda : click(6))
button7 = Button(root,text="7",padx=30,pady=30,command = lambda : click(7))
button8 = Button(root,text="8",padx=30,pady=30,command = lambda : click(8))
button9 = Button(root,text="9",padx=30,pady=30,command = lambda : click(9))
button0 = Button(root,text="0",padx=30,pady=30,command = lambda : click(0))
buttondot = Button(root,text=".",padx=32,pady=30,command = lambda : click("."))
add = Button(root,text="+",padx=30,pady=30,command = add)
sub = Button(root,text="-",padx=31,pady=30,command = sub)
mul = Button(root,text="*",padx=32,pady=30,command = mul)
div = Button(root,text="/",padx=31,pady=30,command = div)
equal = Button(root,text="=",padx=29,pady=30,command = equal)
clear = Button(root,text="CL",padx=73,pady=30,command = clear)

#setting fonts
button1["font"] = myFont
button2["font"] = myFont
button3["font"] = myFont
button4["font"] = myFont
button5["font"] = myFont
button6["font"] = myFont
button7["font"] = myFont
button8["font"] = myFont
button9["font"] = myFont
button0["font"] = myFont
add["font"] = myFont
sub["font"] = myFont
mul["font"] = myFont
div["font"] = myFont
equal["font"] = myFont
clear["font"] = myFont
buttondot["font"] = myFont

#mapping buttons onto root layout
button1.grid(row=3,column=0)
button2.grid(row=3,column=1)
button3.grid(row=3,column=2)
button4.grid(row=2,column=0)
button5.grid(row=2,column=1)
button6.grid(row=2,column=2)
button7.grid(row=1,column=0)
button8.grid(row=1,column=1)
button9.grid(row=1,column=2)
button0.grid(row=4,column=0)
add.grid(row=4,column=1)
sub.grid(row=4,column=2)
mul.grid(row=5,column=0)
div.grid(row=5,column=1)
buttondot.grid(row=5,column=2)
equal.grid(row=6,column=2)
clear.grid(row=6,column=0,columnspan = 2)

root.mainloop()


import os
import gym
import random
import argparse
import numpy as np
import tensorflow as tf
from networks import CartPoleNetwork
from self_play import self_play
from replay import ReplayBuffer
from config import get_cartpole_config

gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
    tf.config.experimental.set_memory_growth(gpu, True)

SEED = 10

def set_seeds(seed=SEED):
    os.environ['PYTHONHASHSEED'] = str(seed)
    random.seed(seed)
    np.random.seed(seed)
    tf.random.set_seed(seed)

if __name__ == "__main__":
    with tf.device('/GPU:0'):
        parser = argparse.ArgumentParser(description='Train MuZero.')
        parser.add_argument('--num_simulations', type=int, default=50)
        parser.add_argument('--save_dir', type=str, default="tmp_results")
        parser.add_argument('--seed', type=int, default=SEED)
        args = parser.parse_args()
        print("num simulations:", args.num_simulations)

        # Set seeds for reproducibility
        set_seeds(args.seed)
        # Create the cartpole network
        network = CartPoleNetwork(
            action_size=2, state_shape=(None, 4), embedding_size=4, max_value=200)
        print("Network Made")
        # Set the configuration for muzero
        config = get_cartpole_config(args.num_simulations)  # Create Environment
        env = gym.make('CartPole-v0')

        # Create buffer to store games
        replay_buffer = ReplayBuffer(config)
        print(args)
        os.makedirs(args.save_dir, exist_ok=True)
        self_play(env, config, replay_buffer, network, save_dir=args.save_dir)


def sum(num1,num2):
    return num1+num2

def sub(num1,num2):
    return num1-num2

def mul(num1,num2):
    return num1*num2

def div(num1,num2):
    if num2<0:
        print("number is not divide by zero")
    else:
        return num1/num2

def cal():

    num1=(int(input("Enter the first number:")))
    num2=(int(input("Enter the second number:")))

    keeplooping=True

    while keeplooping:

        print("Enter 1 for sum")
        print("Enter 2 for sub")
        print("Enter 3 for mul")
        print("Enter 4 for div")

        op=(int(input("Enter the option:")))

        if op==1:
            ans=sum(num1,num2)
            print(ans)

        elif op==2:
            ans=sub(num1,num2)
            print(ans)

        elif op==3:
            ans=mul(num1,num2)
            print(ans)

        elif op==4:

            ans=div(num1,num2)
            print(ans)

    else:
        keeplooping=False
       # break

cal()


import random
class Solution:
	def __init__(self, nums):
		self.nums = nums

	def reset(self):
		return self.nums

	def shuffle(self):
		'''
		temp = []
		nn = self.nums.copy()
		for num in nums:
			temp.append(num)
		return temp
		'''
		temp = self.nums.copy()
		random.shuffle(temp)
		return temp

nums = [1,2,3,4,5]
sol = Solution(nums)
print(sol.shuffle())
print(sol.reset())
print(sol.shuffle())
print(sol.reset())


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import glob
import filter

def remove_objects(img, lower_size=None, upper_size=None):
    # find all objects
    nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(img)

    sizes = stats[1:, -1]
    _img = np.zeros((labels.shape))

    # process all objects, label=0 is background, objects are started from 1
    for i in range(1, nlabels):

        # remove small objects
        if (lower_size is not None) and (upper_size is not None):
            if lower_size < sizes[i - 1] and sizes[i - 1] < upper_size:
                _img[labels == i] = 255

        elif (lower_size is not None) and (upper_size is None):
            if lower_size < sizes[i - 1]:
                _img[labels == i] = 255

        elif (lower_size is None) and (upper_size is not None):
            if sizes[i - 1] < upper_size:
                _img[labels == i] = 255

    return _img

def filter_loss(input,test):

    input = input.astype(int)
    test = test.astype(int)

    miss_mask = cv2.bitwise_xor(input,test)

    loss = cv2.countNonZero(miss_mask)

    return loss

#学習データ
train_data = sorted(glob.glob('./output/*.jpg'))
test_data = sorted(glob.glob('./test_data/*.jpg'))

print(train_data)

#画像サイズ
img_size = 768*960
#学習データの量
file_num = len(train_data)

fin_loss = 1

for remove_area in range(5000,20000+1,1000):#面積による除去の許容面積の全探索
    print(remove_area)
    loss = 0
    for train_path,test_path in zip(train_data,test_data):

        train_img = cv2.imread(train_path, cv2.IMREAD_GRAYSCALE)
        test_img = cv2.imread(test_path, cv2.IMREAD_GRAYSCALE)

        fin_mask = remove_objects(train_img,lower_size=remove_area)

        loss += filter_loss(fin_mask,test_img)/img_size

    loss = loss/file_num
    if loss < fin_loss:
        output = remove_area
        fin_loss = loss

print('final output:')
print(output)

for i,path in enumerate(train_data):

    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

    output_img = remove_objects(img,lower_size=output)

    path = './final_output/sample'+str(i)+'.jpg'
    cv2.imwrite(path,output_img)


"""
867. Transpose Matrix
Given a 2D integer array matrix, return the transpose of matrix.

The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

Example1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]

Example2:
Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]

Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
-10^9 <= matrix[i][j] <= 10^9
"""

"""
Note:
1. brute-force: O(mn) time | O(1) space - where m is len(matrix) and n is len(matrix[i])
"""

from typing import List
class Solution:
    def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
        m, n = len(matrix), len(matrix[0])
        newMatrix = [[0] * m for _ in range(n)]
        for row in range(m):
            for col in range(n):
                newMatrix[col][row] = matrix[row][col]
        return newMatrix

# Unit Tests
import unittest
funcs = [Solution().transpose]

class TestTranspose(unittest.TestCase):
    def testTranspose1(self):
        for func in funcs:
            matrix = [[1,2,3],[4,5,6],[7,8,9]]
            self.assertEqual(func(matrix=matrix), [[1,4,7],[2,5,8],[3,6,9]])

    def testTranspose2(self):
        for func in funcs:
            matrix = [[1,2,3],[4,5,6]]
            self.assertEqual(func(matrix=matrix), [[1,4],[2,5],[3,6]])

if __name__ == "__main__":
    unittest.main()


'''
3. Escreva um programa que leia um valor em metros e o exiba convertido em milímetros.
'''

valor = float(input("Digite o valor em metros: "))
#1m = 100cm = 1,00cm
#1cm = 10mm = 1,0mm
cm = valor * 100
mm = cm * 10
print(f"O valor {valor} em mm é: {mm}")


import requests
from bs4 import BeautifulSoup

url = 'https://finance.yahoo.com/quote/MSFT/balance-sheet?p=MSFT'
page = requests.get(url)
page_content = page.content
soup = BeautifulSoup(page_content, 'html.parser')
table = soup.find_all('div', {'class': "M(0) Whs(n) BdEnd Bdc($seperatorColor) D(itb)"})
for t in table:
    rows = t.find_all('div', {'class': 'D(tbr) fi-row Bgc($hoverBgColor):h'})
    for row in rows:
        print(row.get_text())


import unittest
import os

from actualizar import HuayraUpdate

RUTAS_TESTING = {
    'source.list': './tests/sources.list',
    'source.list_backup': './tests/sources.list.%s',
    'huayra_repo_url': 'http://repo.huayra.conectarigualdad.gob.ar/huayra',
    'huayra_version': './tests/huayra_version'
}

HUAYRA_VERSION_LIST = {
    '1.0': 'brisa',
    '2.0': 'pampero'
}

HUAYRA_1_REPOS = """
#

# deb cdrom:[Debian GNU/Linux 7.0.0 _Wheezy_ - Official Snapshot i386 LIVE/INSTALL Binary 20130614-19:09]/ wheezy contrib main non-free

## Repositorio oficial de Debian GNU/Linux
deb http://ftp.debian.org/debian/ wheezy main contrib non-free

## Repositorio de Huayra GNU/Linux
deb http://repo.huayra.conectarigualdad.gob.ar/huayra/ brisa main contrib non-free

## Repositorio de Huayra GNU/Linux (updates)
deb http://repo.huayra.conectarigualdad.gob.ar/huayra/ brisa-updates main contrib non-free

## Repositorio de Mate Desktop
deb http://repo.huayra.conectarigualdad.gob.ar/huayra/ mate-brisa main

deb http://security.debian.org/ wheezy/updates main contrib non-free
deb-src http://security.debian.org/ wheezy/updates main contrib non-free
"""

class Test(unittest.TestCase):
    def test_reescribir_rutas(self):
        a = HuayraUpdate()
        b = HuayraUpdate(rutas=RUTAS_TESTING)

        self.assertNotEqual(a.rutas, b.rutas)

    def test_version_brisa(self):
        open(RUTAS_TESTING['huayra_version'], 'w').write('')
        os.unlink(RUTAS_TESTING['huayra_version'])

        a = HuayraUpdate(rutas=RUTAS_TESTING)
        self.assertEqual(a.version_actual, '1.0')

    def test_version_pampero(self):
        with open(RUTAS_TESTING['huayra_version'], 'w') as fd:
            fd.write('2.0RC1')

        a = HuayraUpdate(rutas=RUTAS_TESTING)
        self.assertEqual(a.version_actual, '2.0')

    def test_resguardar(self):
        open(RUTAS_TESTING['huayra_version'], 'w').write('')
        os.unlink(RUTAS_TESTING['huayra_version'])

        with open(RUTAS_TESTING['source.list'], 'w') as fd:
            fd.write(HUAYRA_1_REPOS)

        a = HuayraUpdate(rutas=RUTAS_TESTING)
        a.resguardar_repos()

        with open(RUTAS_TESTING['source.list'], 'r') as fd:
            archivo_original = fd.read()

        with open(RUTAS_TESTING['source.list_backup'] % HUAYRA_VERSION_LIST[a.version_actual], 'r') as fd:
            archivo_resguardo = fd.read()

        self.assertEqual(archivo_original, archivo_resguardo)

        ### ------

        with open(RUTAS_TESTING['source.list'], 'w') as fd:
            fd.write('TEST')

        a = HuayraUpdate(rutas=RUTAS_TESTING)
        a.resguardar_repos()

        with open(RUTAS_TESTING['source.list'], 'r') as fd:
            archivo_original = fd.read()

        with open(RUTAS_TESTING['source.list_backup'] % HUAYRA_VERSION_LIST[a.version_actual], 'r') as fd:
            archivo_resguardo = fd.read()

        self.assertNotEqual(archivo_original, archivo_resguardo)

    def test_modificar_repos(self):
        pass

    def test_hay_actualizaciones_pendientes(self):
        open(RUTAS_TESTING['huayra_version'], 'w').write('')
        os.unlink(RUTAS_TESTING['huayra_version'])

        with open(RUTAS_TESTING['source.list'], 'w') as fd:
            fd.write(HUAYRA_1_REPOS)

        a = HuayraUpdate(rutas=RUTAS_TESTING)
        self.assertEqual(a.hay_actualizaciones_pendientes(), True)

if __name__ == '__main__':
    unittest.main()


arr=input()
i=0
new=[]
if(arr[0]=='B'):
    new.append('W')
else:
    new.append('B')

W=int(input())
B=int(input())
found=0
while (i<len(arr)):
    no=0
    print(arr[i+1])
    if(new[i-1]=='W'and arr[i+1]=='B' and B):
        B-=1
        new.append("B")
    else:
        no+=1
    if(new[i-1]=='B'and arr[i+1]=='W' and W):
        new.append("W")
        W-=1
    else:
        no+=1
    if(no==2):
        break
    i+=1
print(new)
if(i==len(arr)):
    print("YES")
else:
    print("NO")


from typing import Union

from django.shortcuts import get_object_or_404
from rest_framework import permissions
from rest_framework.exceptions import PermissionDenied

from paasng.platform.applications.constants import ApplicationRole
from paasng.platform.applications.models import Application, ApplicationMembership
from paasng.platform.modules.models import Module

from .base import ProtectedResource
from .tools import user_has_perm, user_has_perms

class ApplicationResource(ProtectedResource):

    permissions = [
        ('view_application', 'Can view application'),
        ('checkout_source', 'Can checkout source'),
        ('commit_source', 'Can checkout source'),
        ('manage_services', 'Can checkout source'),
        ('manage_processes', 'Can manage process'),
        ('view_logs', 'Can view logs'),
        ('manage_deploy', 'Can manage deployments'),
        ('manage_env_protection', 'Can manage env protection'),
        ('manage_members', 'Can manage memberships'),
        ('manage_product', 'Can manage product which is related to this application'),
        ('review_app', 'Can review app when it will be online'),
        ('edit_app', 'Can edit app, such as name'),
        ('delete_app', 'Can delete app'),
        ('manage_cloud_api', 'Can manage cloud api'),
        ('manage_access_control', 'Can manage access control'),
    ]

    def _get_role_of_user(self, user, obj):
        """Get the role of application"""
        role = get_user_app_role(user, obj)
        return ApplicationRole(role).name.lower()

application_resource = ApplicationResource()

application_resource.add_nobody_role()
application_resource.add_role(
    'administrator',
    {
        'view_application': True,
        'checkout_source': True,
        'commit_source': True,
        'manage_services': True,
        'manage_processes': True,
        'view_logs': True,
        'manage_deploy': True,
        'manage_env_protection': True,
        'manage_members': True,
        'manage_product': True,
        'review_app': True,
        'edit_app': True,
        'delete_app': True,
        'manage_cloud_api': True,
        'manage_access_control': True,
    },
)
application_resource.add_role(
    'developer',
    {
        'view_application': True,
        'checkout_source': True,
        'commit_source': True,
        'manage_services': True,
        'manage_processes': True,
        'view_logs': True,
        'manage_deploy': True,
        'manage_env_protection': False,
        'manage_members': False,
        'manage_product': True,
        'review_app': False,
        'edit_app': True,
        'delete_app': False,
        'manage_cloud_api': True,
        'manage_access_control': True,
    },
)
application_resource.add_role(
    'operator',
    {
        'view_application': True,
        'checkout_source': False,
        'commit_source': False,
        'manage_services': False,
        'manage_processes': False,
        'view_logs': False,
        'manage_deploy': False,
        'manage_env_protection': False,
        'manage_members': False,
        'manage_product': True,
        'review_app': True,
        'edit_app': True,
        'delete_app': False,
        'manage_cloud_api': True,
        'manage_access_control': True,
    },
)

def get_user_app_role(user, obj: Union[Application, Module]):
    # Module 权限完全兼容 Application
    if isinstance(obj, Module):
        application = obj.application
    else:
        application = obj

    try:
        # Currently, user can only have one role
        membership = ApplicationMembership.objects.get(application=application, user=user.pk)
    except (ApplicationMembership.DoesNotExist, ApplicationMembership.MultipleObjectsReturned):
        return ApplicationRole.NOBODY.value
    return membership.role

def application_perm_class(perm_name):
    """A factory function which generates a Permission class for DRF permission check"""
    if perm_name not in application_resource._permissions:
        raise ValueError('"%s" is not a valid permission name for Application' % perm_name)

    class Permission(permissions.BasePermission):
        def has_object_permission(self, request, view, obj):
            return user_has_perm(request.user, perm_name, obj)

    return Permission

def check_application_perms(user, perm_names, application):
    for perm_name in perm_names:
        if perm_name not in application_resource._permissions:
            raise ValueError('"%s" is not a valid permission name for Application' % perm_name)
    if not user_has_perms(user, perm_names, application):
        raise PermissionDenied('You are not allowed to do this operation.')

def application_perm_required(perm_name):
    """This decorator can only be used when these conditions are meet:

    - decorated func if a method in ViewSet
    - there is a "code" kwargs in request path which represents application code
    """
    if perm_name not in application_resource._permissions:
        raise ValueError('"%s" is not a valid permission name for Application' % perm_name)

    def decorated(func):
        def view_func(self, request, *args, **kwargs):
            application = get_object_or_404(Application, code=kwargs['code'])
            if not user_has_perm(request.user, perm_name, application):
                raise PermissionDenied('You are not allowed to do this operation.')

            return func(self, request, *args, **kwargs)

        return view_func

    return decorated

def application_perm_required_with_uuid(perm_name):
    """This decorator can only be used when these conditions are meet:

    - decorated func if a method in ViewSet
    - there is a "application_id" kwargs in request.data
    """
    if perm_name not in application_resource._permissions:
        raise ValueError('"%s" is not a valid permission name for Application' % perm_name)

    def decorated(func):
        def view_func(self, request, *args, **kwargs):
            application = get_object_or_404(Application, pk=request.data.get('application_id'))
            if not user_has_perm(request.user, perm_name, application):
                raise PermissionDenied('You are not allowed to do this operation.')

            return func(self, request, *args, **kwargs)

        return view_func

    return decorated


from raise_utils.data import DataLoader
from raise_utils.learners import NaiveBayes

def test_nb_works():
    clf = NaiveBayes()
    data = DataLoader.from_file("../promise/camel-1.2.csv")
    clf.set_data(*data)
    clf.fit()

    assert True  # Check if we reached here


#--------INICIALIZAR ARCHIVOS-----------------#
archivo = open("C:/Users/romer/Desktop/Python/automatas/nfa4.txt", "r")
salida = open("C:/Users/romer/Desktop/Python/automatas/salida.txt", "w")

datos = archivo.read().splitlines()

estados = []

movements = {}

alfabeto = []

#------------OBTENCION DE DATOS---------------------#
for i in datos:

    if datos.index(i) > datos.index("Estados") and datos.index(i) < datos.index("Alfabeto"):
        if i[0] == '*' or i[0] == '>':
            movements[i[1:]] = {}
            estados.append(i)
        else:
            movements[i] = {} #Para casos donde el alfabeto sea del tipo q0,q1,q2
            estados.append(i)

    elif datos.index(i) > datos.index("Alfabeto") and datos.index(i) < datos.index("Transiciones"):
        alfabeto.append(i)

    elif datos.index(i) > datos.index("Transiciones"):
        lista = i.split()
        if lista[1] not in movements[lista[0]]:
            movements[lista[0]][lista[1]] = [lista[3]]
        else:
            movements[lista[0]][lista[1]].append(lista[3])

print("Estados",estados)
print("Alfabeto",alfabeto)
print("Transiciones",movements,"\n")

#-----------PRIMER PASO DE MOVIMIENTOS--------------#
new_movements = {}

for state in movements:
    for letter in movements[state]:
        string = '{'+ ','.join(str(key) for key in movements[state][letter]) + '}'
        new_movements[string] = {}
        for letter in alfabeto:
            new_movements[string][letter] = []

remove = []

for i in new_movements:
    temp = i[1:-1].split(",")
    for j in temp:
        if movements[j]:
            for letter in alfabeto:
                temp2 = movements[j][letter]
                for k in temp2:
                    if k not in new_movements[i][letter]:
                        new_movements[i][letter].append(k)

for i in new_movements:
    if new_movements[i]['0'] and new_movements[i]['1']:
        continue
    else:
        remove.append(i)

#------BORRAR VACIOS----------#
for keys in remove:
    del new_movements[keys]

print("Primera Iteracion",new_movements)

#----------ESTO TIENE QUE SER UN CICLO------------------#
stop = False
while stop==False:
    new2 = dict(new_movements)
    list2 = list(new2.keys())

    for state in new2:
        for letter in new2[state]:
            string = '{'+ ','.join(str(key) for key in new2[state][letter]) + '}'
            if string not in list(new_movements.keys()):
                new_movements[string] = {}
                for letter in alfabeto:
                    new_movements[string][letter] = []

    for i in new_movements:
        temp = i[1:-1].split(",")
        for j in temp:
            if movements[j]:
                for letter in alfabeto:
                    temp2 = movements[j][letter]
                    #print(i,letter,temp2)
                    for k in temp2:
                        if k not in new_movements[i][letter]:
                            new_movements[i][letter].append(k)

    if len(list2) == len(list(new_movements.keys())):
        break

print("Resultado final", new_movements)

salida.writelines("Estados\n")
for i in list(new_movements.keys()):
    init = False
    end = False
    string_init = '>'+i[1:-1]

    if string_init in estados:
        salida.writelines(f'>{i}\n')
        init = True
    else:
        new_arr = i[1:-1].split(',')
        for j in new_arr:
            string_end = '*'+j
            if string_end in estados:
                salida.writelines(f'*{i}\n')
                end = True
    if init == False and end == False:
        salida.writelines(f'{i}\n')

salida.writelines("Alfabeto\n")
for i in alfabeto:
    salida.writelines(f'{i}\n')
salida.writelines("Transiciones\n")
for i in new_movements:
    for j in alfabeto:
        string = '{'+ ','.join(str(key) for key in new_movements[i][j]) + '}'
        salida.writelines(f'{i} {j} ->  {string}\n')

salida.close()
archivo.close()


from django.shortcuts import render
from .models import Order, OrderItem
from .forms import OrderCreateForm
from cart.cart import Cart
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404, redirect
from .render import render_to_pdf
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import render_to_string
from shop.models import Product
from django.contrib.auth.decorators import login_required
import datetime
from datetime import date
from django.contrib import messages
from django.contrib.auth.models import User
from django.db import connection
from django.db.models import Q

@login_required(login_url="/account/signin/")
def order_create(request):
    cart = Cart(request)
    form = OrderCreateForm(request.POST or None)
    received_amount = request.POST.get('montant_recu')

    if request.method == 'POST':
        if form.is_valid():
            # order = form.save()
            total_cost = 0
            order = form.save(commit=False)
            if cart.coupon:
                order.coupon = cart.coupon
                order.discount = cart.coupon.discount
            order.utilisateur = request.user
            order.save()
            for item in cart:
                article = Product.objects.filter(libelle=item['product'])
                # Verifer si le montant saisi est inférieur au montant à payer
                if float(received_amount) < cart.get_total_price_after_discount():
                    messages.error(request, "Le montant " + received_amount + " est inférieur au montant à payer")
                    return redirect('orders:order_create')
                # Validation de la commande
                else:
                    for product in article:
                        prod = product.libelle
                        qte=product.quantite
                        finalQte=qte-item['quantity']
                        product.quantite=finalQte
                        article.update(quantite=finalQte)
                        # Vérification de la quantité en stock :
                        if product.quantite <= 10:
                            messages.warning(request,
                                          "Le seuil en stock du produit " + product.libelle + " est "
                                          + str(product.quantite) + " veuillez en rajouter! ")
                        OrderItem.objects.create(order=order,
                                     product=item['product'],
                                     price=item['price'],
                                     tva=item['tax_rate'],
                                     quantity=item['quantity'])
            # clear the cart
            cart.clear()
            return render(request,
                            'orders/order/created.html',
                            {'order': order,'refund':received_amount, 'cart':cart})
    else:
        form = OrderCreateForm()
    return render(request,
                'orders/order/create.html',
                {'cart': cart, 'form': form,'refund':received_amount})

@staff_member_required
def admin_order_detail(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    return render(request,
                  'admin/orders/order/detail.html',
                  {'order': order})

@staff_member_required
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    utilisateur=request.user
    pdf = render_to_pdf('orders/order/pdf.html', {'order': order, 'user':utilisateur})
    if pdf:
        response= HttpResponse(pdf,content_type='application/pdf')
        response['Content-Disposition'] = 'filename=\
                "order_{}.pdf"'.format(order.id)
        return response
    else:
        return HttpResponse("Fichier n'existe pas")

@login_required(login_url='/account/signin')
def order_list(request):
    order_list= Order.objects.all().order_by('-date_creation')
    return render(request,
                  'orders/order/order_list.html',
                  {'order_list':order_list})

@login_required(login_url='/account/signin')
def order_detail(request, id):
    order = get_object_or_404(Order, id=id)
    return render(request,
                  'orders/order/detail.html',
                  {'order': order})

@login_required(login_url='/account/signin')
def order_pdf(request, id):
    order = get_object_or_404(Order, id=id)
    utilisateur=request.user
    pdf = render_to_pdf('orders/order/pdf.html', {'order': order, 'user':utilisateur})
    if pdf:
        response= HttpResponse(pdf,content_type='application/pdf')
        response['Content-Disposition'] = 'filename=\
                "order_{}.pdf"'.format(order.id)
        return response
    else:
        return HttpResponse("Fichier n'existe pas")

@login_required(login_url="/account/signin/")
def daily_report(request):
    template = 'shop/product/list.html'
    orders=Order.objects.filter(utilisateur_id=request.user.id , date_creation= date.today().strftime("%Y-%m-%d"))
    daily_orders=Order.objects.filter(date_creation= date.today().strftime("%Y-%m-%d"))
    total_amount=0
    daily_totalAmount=0
    for order in orders:
        if order.utilisateur:
            total_amount=total_amount + order.get_total_cost()
    for daily_order in daily_orders:
        if daily_order.date_creation:
            daily_totalAmount=daily_totalAmount+daily_order.get_total_cost()
    print(daily_totalAmount)
    return render(request,
                  template,{'totalAmountPerDay':total_amount, 'daily_Sales':daily_totalAmount})
@staff_member_required(login_url="/account/signin")
def most_saled_products(request):
    template = 'orders/order/reports.html'
    list_product = []
    totol_quantity=0
    all_ord_items = OrderItem.objects.all()
    for element in all_ord_items:
        totol_quantity=totol_quantity+element.quantity
    print(totol_quantity)
    items = OrderItem.objects.all().distinct().order_by('-quantity')[:10]

    return render(request,
                  template,
                  {'data':items,
                   'total_quantity':totol_quantity})

@staff_member_required(login_url="/account/signin")
def most_valued_order(request):
    somme_benefice=0
    template = 'orders/order/important_sold.html'
    product = Product.objects.filter(order_items__in=OrderItem.objects.all())
    produit=Product.objects.all()
    top_sold = product.distinct().order_by('-prix')[:10]
    print(top_sold)
    for item in top_sold:
        if item.pk:
            somme_benefice = somme_benefice + item.get_cost_margin()
    return render(request,
                  template,
                  {'top_sold':top_sold,
                   'benefice':somme_benefice
                   })

@staff_member_required(login_url="/account/signin")
def chart(request, pk=None):

    order_list=[i['quantity'] for i in OrderItem.objects.all().values('quantity')]
    # print(order_list)

    context={'order_list':order_list}
    return render(request,
                  'orders/order/chart.html',
                  context)

@staff_member_required(login_url="/account/signin")
def monthly_report(request):
    if request.method == 'GET':
        # from_date=datetime.datetime.strptime(request.GET.get('datedebut',None),'%Y-%m-%d')
        from_date = request.GET.get('datedebut', None)
        to_date = request.GET.get('datefin',None)
        utilisateur = request.GET.get('user', None)
        orderList=Order.objects.filter(Q(date_creation__range=(from_date,to_date))).order_by('-id')
        # print(orderList)
        #|Order.objects.filter(Q(utilisateur=utilisateur))
    return  render(request,
                   'orders/order/monthly_report.html', {'orderList':orderList})


# 시저 암호

# 어떤 문장의 각 알파벳을 일정한 거리만큼 밀어서 다른 알파벳으로 바꾸는 암호화 방식을 시저 암호라고 합니다.
# 예를 들어 "AB"는 1만큼 밀면 "BC"가 되고, 3만큼 밀면 "DE"가 됩니다.
# "z"는 1만큼 밀면 "a"가 됩니다. 문자열 s와 거리 n을 입력받아 s를 n만큼 민 암호문을 만드는 함수, solution을 완성해 보세요.

def solution(s, n):
    # 소문자 나열
    lower_alphabet = "abcdefghijklmnopqrstuvwxyz"
    # 대문자 나열
    upper_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    answer = ''

    # 입력 받은 문자마다 n만큼 이동한 알파벳을 저장
    for char in s:
        if char == " ":
            answer += " " # 공백인 경우 공백 넣기
        # 소문자인 경우
        elif char in lower_alphabet:
            # n만큼 넘어간 위치의 알파벳을 반환하려면 길이가 넘어가는 경우 다시 0부터 시작할 수 있게 idx를 만들어야 한다.
            idx = (lower_alphabet.index(char) + n) % len(lower_alphabet)
            answer += lower_alphabet[idx]
        # 대문자인 경우
        elif char in upper_alphabet:
            idx = (upper_alphabet.index(char) + n) % len(upper_alphabet)
            answer += upper_alphabet[idx]

    return answer

print(solution("AB", 1))
print(solution("z", 1))
print(solution("a B z", 4))


"""
Singly Linked List implementation in Python 3.10

Node: (the first node is called: head)
- data: data it stored in Node
- next_node: contains the reference to next node

LinkedLists are used as: queues/stacks/graphs

"""
from typing import Any

# Create a Node:
class Node:
    """
    Class that creates each node
    - data: data that is stored in Node
    - next_node: reference to the next node
    """
    def __init__(self, data: Any, next_node: Any = None):
        self.data = data
        self.next = next_node

    def __repr__(self):
        return self.data

# Create a LinkedList:
class LinkedList:
    """
    Implementing a Linked Lists
    - nodes: list of predefined values to be treated as Node
    """
    def __init__(self, nodes = None):
        self.head = None
        if nodes is not None:
            node = Node(data=nodes.pop(0))
            self.head = node
            for i in nodes:
                node.next = Node(data=i)
                node = node.next

    def add_left(self, node):
        node.next = self.head
        self.head = node

    def add_right(self, node):
        if self.head is None:
            self.head = node
            return
        for current_node in self:
            pass
        current_node.next = node

    def add_after(self, target, new_node):
        if self.head is None:
            raise Exception("LinkedList is empty.")

        for node in self:
            if node.data == target:
                new_node.next = node.next
                node.next = new_node
                return

        raise Exception(f"Node with data {target} not found")

    def add_before(self, target, new_node):
        if self.head is None:
            raise Exception("LinkedList is empty.")

        if self.head.data == target:
            return self.add_left(new_node)

        prev_node = self.head
        for node in self:
            if node.data == target:
                prev_node.next = new_node
                new_node.next = node
                return
            prev_node = node

        raise Exception(f"Node with data {target} not found")

    def remove(self, target):
        if self.head is None:
            raise Exception("LinkedList is empty.")

        if self.head.data == target:
            self.head = self.head.next
            return

        previous_node = self.head
        for node in self:
            if node.data == target:
                previous_node.next = node.next
                return
            previous_node = node

        raise Exception(f"Node with data {target} not found")

    def __iter__(self):
        node = self.head
        while node is not None:
            yield node
            node = node.next

    def __repr__(self) -> str:
        node = self.head
        nodes = []
        while node is not None:
            nodes.append(node.data)
            node = node.next

        nodes.append("None")
        return " -> ".join(nodes)


#!/usr/bin/env python3
# По материалам интернета:
# https://habrahabr.ru/post/321834/
# https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html

# Отключение предупреждений и информационных сообщений по уровням.
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# Отключение предупреждений по категориям.
import warnings
warnings.filterwarnings(action = 'ignore', category = FutureWarning)

from keras.preprocessing.image import ImageDataGenerator, img_to_array
from keras.models import Sequential, Model
from keras.callbacks import ModelCheckpoint
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D

import numpy as np
import h5py
import matplotlib.pyplot as plt

# Параметры.
train_data_size = 3000
validate_data_size = 210
batch_size = 16
epochs = 20
image_size = 35
# Включён режим тестирование без обучения.
test_only = True
# Включён режим пошагового обучения с загрузкой файла весов, полученных на предыдущем шаге.
next_training_phase = False
# Блокировка первого свёрточного слоя.
lock_convolution_layer1 = False
# Блокировка второго свёрточного слоя.
lock_convolution_layer2 = False
# Блокировка третьего свёрточного слоя.
lock_convolution_layer3 = False
# Блокировка четвёртого свёрточного слоя.
lock_convolution_layer4 = False
# Блокировка пятого свёрточного слоя.
lock_convolution_layer5 = False
# Блокировка шестого свёрточного слоя.
lock_convolution_layer6 = False
# Блокировка полносвязных слоёв.
lock_dense_part = False
tests_number = 20

# Модель.
model = Sequential()
# filters - сколько вариации пикселя будет из одного пикселя
# kernel - сколько обовляется пикселей одновременно с исходным
# padding - вид обработки краев
# input_shape (size, size, кол-во каналов (rgb))
model.add(Convolution2D(filters = 32, kernel_size = (3, 3), padding = 'valid',
    input_shape = (image_size, image_size, 3)))
# Вызов функции активации вида relu
model.add(Activation('relu'))
model.add(Convolution2D(filters = 32, kernel_size = (3, 3), padding = 'valid'))
model.add(Activation('relu'))
# Сужение изображения в 2 раза
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Convolution2D(filters = 32, kernel_size = (3, 3), padding = 'valid'))
model.add(Activation('relu'))
model.add(Convolution2D(filters = 32, kernel_size = (3, 3), padding = 'valid'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
# model.add(Convolution2D(filters = 64, kernel_size = (3, 3), padding = 'valid'))
# model.add(Activation('relu'))
# model.add(Convolution2D(filters = 64, kernel_size = (3, 3), padding = 'valid'))
# model.add(Activation('relu'))
# model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Flatten())
# Кол-во нейронов на relu
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.5))
# Кол-во нейронов на softmax (10 папок) - softmax для распознавания хорошо
model.add(Dense(10))
model.add(Activation('softmax'))
data_generator = ImageDataGenerator(rescale = 1.0 / 255)
if test_only:
    print('Testing only.')
else:
    if next_training_phase:
        print('Continued training.')
        model.load_weights('best_model.hdf5')
    else:
        print('The starting phase of training.')
    if lock_convolution_layer1:
        print('Locking of the first convolution layer.')
        for layer in model.layers[0:2]:
            layer.trainable = False
    if lock_convolution_layer2:
        print('Locking of the second convolution layer.')
        for layer in model.layers[2:5]:
            layer.trainable = False
    if lock_convolution_layer3:
        print('Locking of the third convolution layer.')
        for layer in model.layers[5:7]:
            layer.trainable = False
    if lock_convolution_layer4:
        print('Locking of the fourth convolutional layer.')
        for layer in model.layers[7:10]:
            layer.trainable = False
    if lock_convolution_layer5:
        print('Locking of the fifth convolutional layer.')
        for layer in model.layers[10:12]:
            layer.trainable = False
    if lock_convolution_layer6:
        print('Locking of the sixth convolutional layer.')
        for layer in model.layers[12:15]:
            layer.trainable = False
    if lock_dense_part:
        print('Locking dense layers.')
        for layer in model.layers[15:]:
            layer.trainable = False
model.compile(loss = 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy'])
if not test_only:
    # Обучение.
    train_generator = data_generator.flow_from_directory('data/train',
        target_size = (image_size, image_size), batch_size = batch_size, class_mode = 'categorical')
    validation_generator = data_generator.flow_from_directory('data/validation',
        target_size = (image_size, image_size), batch_size = batch_size, class_mode = 'categorical')
    model.fit_generator(train_generator, callbacks = [ModelCheckpoint('best_model.hdf5',
        monitor = 'val_acc', save_best_only = True, save_weights_only = False, mode = 'auto')],
        steps_per_epoch = train_data_size // batch_size, epochs = epochs,
        validation_data = validation_generator, validation_steps = validate_data_size // batch_size)
# Тестирование.
model.load_weights('best_model.hdf5')
test_generator = data_generator.flow_from_directory('data/test',
    target_size = (image_size, image_size), batch_size = tests_number, class_mode = 'categorical')
model.evaluate_generator(test_generator, steps = tests_number)
data, labels = test_generator.next()
images = np.asarray([img_to_array(item) for item in data])
predictions = np.asarray(model.predict(data))
samples = [sample for sample in zip(images, predictions, labels)]
plt.figure(figsize = (10, 8))
plt.subplots_adjust(left = 0.05, right = 0.95, bottom = 0.05, top = 0.95, wspace = 0.2, hspace = 0.2)
for index, sample in enumerate(samples[:tests_number]):
    plt.subplot(4, 5, index + 1)

    image = sample[0]

    max_value = 0.0
    prediction = 0
    for i in range(10):
        value = sample[1][i]
        if (value > max_value):
            prediction = i
            max_value = value

    max_value = 0.0
    max_label = 0
    for i in range(10):
        value = sample[2][i]
        if (value > max_value):
            max_label = i
            max_value = value

    if(prediction == max_label):
        plt.text(0, 0, max_label, fontsize=11, color='green')
        plt.text(30, 0, prediction, fontsize=11, color='green')
    else:
        plt.text(0, 0, max_label, fontsize=11, color='blue')
        plt.text(30, 0, prediction, fontsize=11, color='red')

    plt.imshow(image)
    plt.axis('off')
plt.gcf().canvas.set_window_title('Первые 20 результатов тестирования')
plt.show()


import numpy as np
import unittest
from numpy.testing import assert_almost_equal

from oitg.circuits.clifford import *
from oitg.circuits.composite_pulses import *
from oitg.circuits.gate import *
from oitg.circuits.qasm import *
from oitg.circuits.to_matrix import *

class QasmTest(unittest.TestCase):
    def test_gate(self):
        self.assertEqual(list(gate_to_qasm(Gate("rx", (0.4, ), (1, )))),
                         ["rx(0.4) q[1]"])
        self.assertEqual(list(gate_to_qasm(Gate("cz", (), (
            0,
            1,
        )))), ["cz q[0], q[1]"])

    def test_gate_experiment(self):
        exp = [
            Gate("rx", (0.4, ), (2, )),
            Gate("cz", (), (0, 1)),
        ]
        self.assertEqual(list(gate_experiment_to_qasm(exp)), [
            "OPENQASM 2.0", "include \"qelib1.inc\"", "qreg q[3]", "creg r[3]",
            "rx(0.4) q[2]", "cz q[0], q[1]", "measure q -> r"
        ])

def is_inverse_up_to_phase(a, b):
    return np.isclose(a.shape[0], np.abs(np.trace(np.dot(a, b))), atol=1e-6)

class UnitaryTest(unittest.TestCase):
    def test_fill(self):
        assert_almost_equal(
            single_gate_matrix(Gate("rx", (np.pi, ), (0, )), 2),
            [[0, 0, -1j, 0], [0, 0, 0, -1j], [-1j, 0, 0, 0], [0, -1j, 0, 0]])
        assert_almost_equal(
            single_gate_matrix(Gate("rx", (np.pi, ), (1, )), 2),
            [[0, -1j, 0, 0], [-1j, 0, 0, 0], [0, 0, 0, -1j], [0, 0, -1j, 0]])

    def test_permute(self):
        assert_almost_equal(single_gate_matrix(Gate("cx", (), (0, 1)), 2),
                            [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
        assert_almost_equal(single_gate_matrix(Gate("cx", (), (1, 0)), 2),
                            [[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])

    def test_rxy(self):
        assert_almost_equal(local_matrix(Gate("rxy", (0, 0.1234), (0, ))),
                            local_matrix(Gate("rx", (0.1234, ), (0, ))))
        assert_almost_equal(local_matrix(Gate("rxy", (np.pi / 2, 0.1234), (0, ))),
                            local_matrix(Gate("ry", (0.1234, ), (0, ))))

    def test_gate_sequence(self):
        cz_seq = [
            Gate("h", (), (0, )),
            Gate("cz", (), (0, 1)),
            Gate("h", (), (0, )),
        ]
        cx_seq = [Gate("cx", (), (1, 0))]
        assert_almost_equal(gate_sequence_matrix(cz_seq), gate_sequence_matrix(cx_seq))

class CompositePulseTest(unittest.TestCase):
    def test_correctness(self):
        for method in bb1, reduced_c_in_sk:
            for _ in range(100):
                phase, amount = np.random.rand(2) * np.pi
                raw_gate = Gate("rxy", (phase, amount), (0, ))
                composite_gate = list(method(raw_gate))
                self.assertTrue(
                    is_inverse_up_to_phase(gate_sequence_matrix(composite_gate),
                                           np.conj(local_matrix(raw_gate)).T))

    def test_expand_bb1(self):
        gates = [
            Gate("rx", (np.pi, ), (0, )),
            Gate("cz", (), (0, 1)),
            Gate("ry", (np.pi, ), (0, ))
        ]
        result = list(expand_using(bb1, gates))
        self.assertEqual(len(result), 11)
        result = list(expand_using(bb1, gates, insert_barriers=False))
        self.assertEqual(len(result), 9)
        expand_using(bb1, gates, ignore_unsupported_gates=False)
        self.assertRaises(
            UnsupportedGate,
            lambda: list(expand_using(bb1, gates, ignore_unsupported_gates=False)))


import time
import pandas as pd
from datetime import datetime
import numpy as np

from sklearn import preprocessing
import matplotlib
import matplotlib.pyplot as plt

import seaborn as sns
from scipy.stats import pearsonr
import os
from matplotlib.font_manager import FontProperties
from statistics import stdev

import pwrcommon as pc

prec = 'fp64'
mode = 'load'
app = 'pymm'

def pltIndividual(output,fileID,size):

        file = output+fileID+size
        gpu0Pwr = pc.readMetrics(file)
        GPU0MeanPwr = gpu0Pwr['pwr'].mean()
        plt.figure()
        plt.plot(gpu0Pwr['time'], gpu0Pwr['pwr'],label = "Real-time")
        meanGPUPwr = [GPU0MeanPwr for x in range(len(gpu0Pwr))]
        plt.plot(gpu0Pwr['time'], meanGPUPwr, linestyle = '--',label = "Mean")
        plt.xlabel('Time')
        plt.ylabel('GPU Power Consumption (W)')
        plt.title('Matrix size: '+size+'x'+size)
        plt.legend()
        plt.grid()
        plt.ticklabel_format(useOffset=False)
        plt.savefig(output+fileID+size+'.png')

        meanGPUPwr.clear()

def getPwrPerfCounters(output,fileID,size,pwrThresh = 100):
        #os.chdir('../')
        #baseDir = os.getcwd()
        #file = baseDir+'/test/output/'+app+'-'+prec+'-'+mode+'-'+size
        file = output+fileID+size
        # striping non-computing power consumption

        data = pc.readMetrics(file)

        gdata, cpStartTime,cpEndTime = pc.getComputationStartEnd (data,pwrThresh)
        df = pc.getStablePwr(gdata,cpStartTime,cpEndTime)

        #gpu0Pwr['time'] =  (df['time'] - (df['time'].iloc[0]))

        tot_seconds = max(df['time']) - min(df['time'])
        #timedelta = tot_time - datetime(1900, 1, 1)

        #tot_seconds = timedelta.total_seconds()
        print ('\nTotal Seconds',tot_seconds)
        s=0.0
        if size == '16' or size == '32' or size == '48' or size == '64' or  size == '72':
                s = float(size) * 320
        else:
                s = float(size)

        gflop = 2*s*s*s/1e9
        print('\nGFlops:',gflop)
        if tot_seconds != 0:
                gflops = gflop/tot_seconds
        else:
                gflops = gflop

        return (df['pwr'].mean()),gflops

def pltPwrPerf(output,fileID,loadSize,thresh):
        flops = []
        meanPwr = []
        fltPerW = []
        normflops = []
        normMeanPwr = []
        for size in loadSize:
                pwr,gfs = getPwrPerfCounters(output,fileID,size,thresh)
                meanPwr.append(pwr)
                flops.append(gfs)
                fltPerW.append(gfs/pwr)

        # TDP
        tdpY = [250,250,250,250,250]
        print ('\nGfltPerW:',fltPerW)
        print ('\nGFlops:',flops)
        print ('\nMeanPwr:',meanPwr)
        # attainable GFLOPS: 7065
        pltGFLOPS(output,fileID,loadSize,meanPwr,tdpY,flops)
        pltGFLOPSWatt(output,fileID,loadSize, meanPwr,tdpY,fltPerW)

def pltGFLOPS(output,fileID,loadSize, meanPwr,tdpY,flops):
        fig = plt.figure()
        ax = fig.add_subplot(111)

        #tdp line
        lns1 = ax.plot(loadSize, meanPwr, 'H', color = 'b',label = 'MeanPower(W)')
        lns2 = ax.plot(loadSize, tdpY, '--', color = 'b',label = 'Thermal Design Power(TDP)')
        ax2 = ax.twinx()
        #attainable flops line
        attainableY = [7065,7065,7065,7065,7065]
        lns3 = ax2.plot(loadSize, attainableY, '--', color = 'r',label = 'Attainable GFLOPS')
        lns4 = ax2.plot(loadSize, flops, 'o', color = 'r',label = 'GFLOPS')

        # added these four lines
        lns = lns1+lns2+lns3+lns4
        labs = [l.get_label() for l in lns]
        ax.legend(lns, labs, loc=4)

        ax.grid()
        ax.set_xlabel("Data Points (FP64)")
        ax.set_ylabel("Mean Power Usage (W)")
        ax2.set_ylabel("GFLOPS")
        ax2.set_ylim(0, 4500)
        ax.set_ylim(0,275)
        plt.title('GFLOPS versus Power Usage')
        plt.savefig(output+fileID+'-gflops.png')

def pltGFLOPSWatt(output,fileID,loadSize, meanPwr,tdpY,fltPerW):
        #GFLOPS/WATT
        #attainable GFLOPS/WATT: 7065/250=28.26

        Gflopsperwatt = [28.26,28.26,28.26,28.26,28.26]
        fig = plt.figure()
        ax = fig.add_subplot(111)

        #mean power usage
        lns1 = ax.plot(loadSize, meanPwr, 'H', color = 'b',label = 'Power(W)')
        # tdp
        lns2 = ax.plot(loadSize, tdpY, '--', color = 'b',label = 'TDP')
        ax2 = ax.twinx()
        #attainable flops/watt line
        lns3 = ax2.plot(loadSize, fltPerW, 'o', color = 'r',label = 'GFLOPS/Watt')
        lns4 = ax2.plot(loadSize, Gflopsperwatt, '--', color = 'r',label = 'Attainable GFLOPS/Watt')
        # added these four lines
        lns = lns1+lns2+lns3+lns4
        labs = [l.get_label() for l in lns]
        ax.legend(lns, labs, loc=4)

        ax.grid()
        ax.set_xlabel("Data Points (FP64)")
        ax.set_ylabel("Mean Power")
        ax2.set_ylabel("GFLOPS/Watt")
        ax2.set_ylim(0, 22)
        ax.set_ylim(0,275)
        plt.title('GFLOPS/Watt vs Power Usage')

        plt.savefig(output+fileID+'-gflopswatt.png')


import pandas as pd
df= pd.read_csv("Seed_Data.csv")
print(df.describe)
df.info()

X = df.iloc[:,0:7]
X.info()

y = df.iloc[:,7]
print(y.describe)

import sklearn
from sklearn import svm
from sklearn.svm import SVC

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test= train_test_split(X,y, test_size=0.2,random_state=13)
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train=sc.fit_transform(X_train)
X_test=sc.fit(X_test)
clf = svm.SVC()
clf.fit(X_train,y_train)

pred = clf.predict(X_test)
print(pred)
sklearn.metrics.accuracy_score(y_test,pred)
print(sklearn.metrics.classification_report(y_test,pred))


import numpy as np
import pandas as pd

# load table with classification events without trash marks (by Lera Scavronskaya script probability_final.ipynb) or cleaning_marks_by_Lera_script.py

table = pd.read_csv('/net/server/data/Archive/prob_learn/data_processing/Events_no_mio_cleaned/events_classification_clean.tsv', sep = '\t')

#create unique lists of subjects and runs
subjects = set(table['subj'].tolist())
runs = set(table['run'].tolist())

for subj in subjects:
    for r in runs:
        subj_table = table.loc[(table['subj'] == subj) & (table['run'] == r)]

        first = subj_table['event[0] (time)'].tolist()
        second = subj_table['event[1]'].tolist()
        third = subj_table['event[2] (label)'].tolist()

        all_events = []
        for i in range(len(subj_table)):
            event = []
            event.append(first[i])
            event.append(second[i])
            event.append(third[i])
            all_events.append(event)

        all_ev_array = np.array(all_events)

        np.savetxt("/net/server/data/Archive/prob_learn/data_processing/Raw_events_without_trash_marks/{0}_{1}_events_clean.txt".format(subj, r), all_ev_array,  fmt="%s")

        #load txt
        #ontent = np.loadtxt('/home/vtretyakova/Рабочий стол/probabitily_teta/test.txt', dtype='int')


import numpy as np
from six import string_types
import tensorflow as tf

DEFAULT_PADDING = 'SAME'

def layer(tf_op):
    '''
    Python装饰器的用法，具体教程看这个链接：
    http://wiki.jikexueyuan.com/project/explore-python/Functional/decorator.html
    装饰器的作用是：封装成可以组装的基本网络层（卷积、膨胀卷积、池化等），方便组装复杂网络
    '''
    def layer_decorated(self, *args, **kwargs):
        '''
        装饰器用于装饰(包裹、封装)原有函数的输出，返回的是包装后的函数layer_decorated
        需要装饰的函数，在其函数名上方追加装饰器@layer
        '''
        # 如果没有提供‘name’参数，自动根据操作名称提供一个unique名称
        name = kwargs.setdefault('name', self.get_unique_name(tf_op.__name__))
        # 提取操作层的输入
        if len(self.terminals) == 0:
            raise RuntimeError('No input variables found for layer %s.' % name)
        elif len(self.terminals) == 1:
            layer_input = self.terminals[0]
        else:
            layer_input = list(self.terminals)
        # 调用原函数，获得操作层的输出
        layer_output = tf_op(self, layer_input, *args, **kwargs)
        # 将输出存入类中的self.layers变量
        self.layers[name] = layer_output
        # 把当前输出缓存为下一层的输入
        self.feed(layer_output)
        # 返回类对象本身，以实现链式调用
        return self

    # 返回包装函数layer_decorated
    return layer_decorated

class Network(object):
    '''
    基础网络类，提供基本操作
    '''
    def __init__(self, inputs, trainable=True, is_training=False, num_classes=21):
        # 网络的输入节点
        self.inputs = inputs
        # 当前操作层的输出终端节点list，下一个操作层的输入缓存
        self.terminals = []
        # 操作层缓存器，存储网络输入节点和各层的输出节点
        self.layers = dict(inputs)
        # 是否训练
        self.trainable = trainable
        # dropout的开关变量
        self.use_dropout = tf.placeholder_with_default(tf.constant(1.0),
                                                       shape=[],
                                                       name='use_dropout')
        # 开始构建网络
        self.setup(is_training, num_classes)

    def setup(self, is_training):
        '''网络构建函数，需要子类做实现 '''
        raise NotImplementedError('Must be implemented by the subclass.')

    def load(self, data_path, session, ignore_missing=False):
        '''加载网络权重参数
        data_path: numpy-serialized网络权重参数的文件路径
        session: 当前的 TensorFlow session
        ignore_missing: 是否忽略丢失层的serialized权重参数
        '''
        # 读取numpy-serialized网络权重参数的文件
        data_dict = np.load(data_path).item()
        # 遍历scope
        for op_name in data_dict:
            with tf.variable_scope(op_name, reuse=True):
                # 遍历权重参数名称和权重参数值
                for param_name, data in data_dict[op_name].iteritems():
                    try:
                        # 获取权重参数变量
                        var = tf.get_variable(param_name)
                        # 赋值权重参数变量
                        session.run(var.assign(data))
                    except ValueError:
                        if not ignore_missing:
                            raise

    def feed(self, *args):
        '''Set the input(s) for the next operation by replacing the terminal nodes.
        The arguments can be either layer names or the actual layers.
        '''
        assert len(args) != 0
        # 清空操作层的输入缓存
        self.terminals = []
        # 将函数输入存入 输入缓存
        for fed_layer in args:
            if isinstance(fed_layer, string_types):
                try:
                    fed_layer = self.layers[fed_layer]
                except KeyError:
                    raise KeyError('Unknown layer name fed: %s' % fed_layer)
            # 输入缓存
            self.terminals.append(fed_layer)
        # 返回类对象
        return self

    def get_output(self):
        '''获取当前操作时刻的网络输出节点'''
        return self.terminals[-1]

    def get_unique_name(self, prefix):
        '''基于prefix输入名称，生成unique名称
        '''
        # 为prefix输入名称（例如 conv），计算索引值（例如 1）
        ident = sum(t.startswith(prefix) for t, _ in self.layers.items()) + 1
        # 在prefix输入名称后，追加索引值名称（例如 conv_1）
        return '%s_%d' % (prefix, ident)

    def make_var(self, name, shape):
        '''新建新的TensorFlow变量.'''
        return tf.get_variable(name, shape, trainable=self.trainable)

    def validate_padding(self, padding):
        '''验证边界补值类型：补零，不补值'''
        assert padding in ('SAME', 'VALID')

    @layer
    def conv(self,
             input,
             k_h,
             k_w,
             c_o,
             s_h,
             s_w,
             name,
             relu=True,
             padding=DEFAULT_PADDING,
             group=1,
             biased=True):
        '''2D卷积'''

        # 验证padding类型
        self.validate_padding(padding)
        # 获取输入通道数量
        c_i = input.get_shape().as_list()[-1]
        # 验证group参数
        assert c_i % group == 0
        assert c_o % group == 0
        # 基于不同的输入和卷积核，定义卷积函数
        convolve = lambda i, k: tf.nn.conv2d(i, k, [1, s_h, s_w, 1], padding=padding)
        with tf.variable_scope(name) as scope:
            # 为卷积核，新建权重参数
            kernel = self.make_var('weights', shape=[k_h, k_w, c_i / group, c_o])
            if group == 1:
                # 普通卷积
                output = convolve(input, kernel)
            else:
                # 拆分通道，进行分组卷积
                input_groups = tf.split(3, group, input)
                kernel_groups = tf.split(3, group, kernel)
                output_groups = [convolve(i, k) for i, k in zip(input_groups, kernel_groups)]
                # 串接分组卷积结果
                output = tf.concat(3, output_groups)
            # 添加篇置
            if biased:
                biases = self.make_var('biases', [c_o])
                output = tf.nn.bias_add(output, biases)
            if relu:
                # ReLU 激活函数
                output = tf.nn.relu(output, name=scope.name)
            return output

    @layer
    def atrous_conv(self,
                    input,
                    k_h,
                    k_w,
                    c_o,
                    dilation,
                    name,
                    relu=True,
                    padding=DEFAULT_PADDING,
                    group=1,
                    biased=True):
        '''2D膨胀卷积'''

        # 验证padding类型
        self.validate_padding(padding)
        # 获取输入通道数量
        c_i = input.get_shape().as_list()[-1]
        # 验证group参数
        assert c_i % group == 0
        assert c_o % group == 0
        # 基于不同的输入和卷积核，定义膨胀卷积函数
        convolve = lambda i, k: tf.nn.atrous_conv2d(i, k, dilation, padding=padding)
        with tf.variable_scope(name) as scope:
            # 为卷积核，新建权重参数
            kernel = self.make_var('weights', shape=[k_h, k_w, c_i / group, c_o])
            if group == 1:
                # 普通卷积
                output = convolve(input, kernel)
            else:
                # 拆分通道，进行分组膨胀卷积
                input_groups = tf.split(3, group, input)
                kernel_groups = tf.split(3, group, kernel)
                output_groups = [convolve(i, k) for i, k in zip(input_groups, kernel_groups)]
                # 串接分组膨胀卷积结果
                output = tf.concat(3, output_groups)
            # 添加篇置
            if biased:
                biases = self.make_var('biases', [c_o])
                output = tf.nn.bias_add(output, biases)
            if relu:
                # ReLU 激活函数
                output = tf.nn.relu(output, name=scope.name)
            return output

    @layer
    def relu(self, input, name):
        '''ReLU激活'''
        return tf.nn.relu(input, name=name)

    @layer
    def max_pool(self, input, k_h, k_w, s_h, s_w, name, padding=DEFAULT_PADDING):
        '''最大池化'''
        self.validate_padding(padding)
        return tf.nn.max_pool(input,
                              ksize=[1, k_h, k_w, 1],
                              strides=[1, s_h, s_w, 1],
                              padding=padding,
                              name=name)

    @layer
    def avg_pool(self, input, k_h, k_w, s_h, s_w, name, padding=DEFAULT_PADDING):
        '''均值池化'''
        self.validate_padding(padding)
        return tf.nn.avg_pool(input,
                              ksize=[1, k_h, k_w, 1],
                              strides=[1, s_h, s_w, 1],
                              padding=padding,
                              name=name)

    @layer
    def lrn(self, input, radius, alpha, beta, name, bias=1.0):
        '''局部响应归一化'''
        return tf.nn.local_response_normalization(input,
                                                  depth_radius=radius,
                                                  alpha=alpha,
                                                  beta=beta,
                                                  bias=bias,
                                                  name=name)

    @layer
    def concat(self, inputs, axis, name):
        '''通道串接'''
        return tf.concat(concat_dim=axis, values=inputs, name=name)

    @layer
    def add(self, inputs, name):
        '''逐像素相加'''
        return tf.add_n(inputs, name=name)

    @layer
    def fc(self, input, num_out, name, relu=True):
        '''全连接层'''
        with tf.variable_scope(name) as scope:
            input_shape = input.get_shape()
            if input_shape.ndims == 4:
                # The input is spatial. Vectorize it first.
                dim = 1
                for d in input_shape[1:].as_list():
                    dim *= d
                feed_in = tf.reshape(input, [-1, dim])
            else:
                feed_in, dim = (input, input_shape[-1].value)
            weights = self.make_var('weights', shape=[dim, num_out])
            biases = self.make_var('biases', [num_out])
            op = tf.nn.relu_layer if relu else tf.nn.xw_plus_b
            fc = op(feed_in, weights, biases, name=scope.name)
            return fc

    @layer
    def softmax(self, input, name):
        '''softmax层'''
        input_shape = map(lambda v: v.value, input.get_shape())
        if len(input_shape) > 2:
            # For certain models (like NiN), the singleton spatial dimensions
            # need to be explicitly squeezed, since they're not broadcast-able
            # in TensorFlow's NHWC ordering (unlike Caffe's NCHW).
            if input_shape[1] == 1 and input_shape[2] == 1:
                input = tf.squeeze(input, squeeze_dims=[1, 2])
            else:
                raise ValueError('Rank 2 tensor input expected for softmax!')
        return tf.nn.softmax(input, name)

    @layer
    def batch_normalization(self, input, name, is_training, activation_fn=None, scale=True):
        '''BN层'''
        with tf.variable_scope(name) as scope:
            output = tf.contrib.layers.batch_norm(
                input,
                activation_fn=activation_fn,
                is_training=is_training,
                updates_collections=None,
                scale=scale,
                scope=scope)
            return output

    @layer
    def dropout(self, input, keep_prob, name):
        '''dropout层'''
        keep = 1 - self.use_dropout + (self.use_dropout * keep_prob)
        return tf.nn.dropout(input, keep, name=name)


n = 0
ll = list()
la = list()

with open("q3.txt") as f:
  ins = f.read()
  # print(ins)
  for l in ins.split('\n'):
      print(f"here - {l}")
      ll.append(list(map(int, l.split())))

  print(len(ll))
  for i in range(int(len(ll)/3)):
      for j in range(3):
          ln = [ll[i*3][j], ll[i*3+1][j], ll[i*3+2][j]]
          ln.sort()
          la.append(ln)
  print(len(la))
  for l in la:
      if l[0]+l[1] > l[2]:
          n += 1
# [401, 613, 725], [211, 312, 402], [215, 328, 520]]
  print(n)


import os
import argparse
from render import *

def run_script(args):
    steps = args.num_steps
    env_name = args.env
    seed = args.seed

    if args.episodic:
        train_beh = lambda x: "python3 ./BCQ/discrete_BCQ/main.py --env=" + str(env_name) + " --max_timesteps=" + str(x) + " --seed=" + str(seed) + " --episodic --train_behavioral"
        gen_buff = lambda x: "python3 ./BCQ/discrete_BCQ/main.py --env=" + str(env_name) + " --max_timesteps=" + str(x) + " --seed=" + str(seed) + " --episodic --generate_buffer"
        train_bcq = lambda x: "python3 ./BCQ/discrete_BCQ/main.py --env=" + str(env_name) + " --max_timesteps=" + str(x) + " --seed=" + str(seed) + " --episodic"
    else:
        train_beh = lambda x: "python3 ./BCQ/discrete_BCQ/main.py --env=" + str(env_name) + " --max_timesteps=" + str(x) + " --seed=" + str(seed) + " --train_behavioral"
        gen_buff = lambda x: "python3 ./BCQ/discrete_BCQ/main.py --env=" + str(env_name) + " --max_timesteps=" + str(x) + " --seed=" + str(seed) + " --generate_buffer"
        train_bcq = lambda x: "python3 ./BCQ/discrete_BCQ/main.py --env=" + str(env_name) + " --max_timesteps=" + str(x) + " --seed=" + str(seed)

    for command in [train_beh, gen_buff, train_bcq]:
        os.system(command(steps))

    for dir in ["./results/BCQ_", "./results/behavioral_", "./results/buffer_performance_"]:
        os.system("mv " + dir + str(env_name) + "_" + str(seed) + ".npy " + dir + str(env_name) + "_" + str(steps) + "_" + str(seed) + ".npy")

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--env", default="LunarLander-v2")                      # OpenAI gym environment name
    parser.add_argument("--goal", default=200)                                  # sucess score / goal
    parser.add_argument("--seed", default=0, type=int)                          # Sets Gym, PyTorch and Numpy seeds
    parser.add_argument("--num_steps", default=500000)                          # Max time steps to run environment or train for
    parser.add_argument("--render_only", default=0)                             # only render or run_script and render
    parser.add_argument("--include_baselines", default=0)                       # include baselines result while rendering
    parser.add_argument("--episodic", action="store_true")                      # If true, task is episodic
    args = parser.parse_args()

    if str(args.render_only) == '0':
        run_script(args)
        render_script(args)
    else:
        render_script(args)


import sys
from collections import deque
input = sys.stdin.readline
dr = [-1, 1, 0, 0]
dc = [0, 0, -1, 1]

R, C = map(int, input().split())
MAP = [list(map(int, input().split())) for _ in range(R)]

air = deque([[0, 0]])
q = deque()

visited = [[0] * C for _ in range(R)]
visited[0][0] = 1

# 처음부터 공기에 노출된 치즈 표면 저장
while air:
    ar, ac = air.popleft()
    for d in range(4):
        nar, nac = ar + dr[d], ac + dc[d]
        # 범위를 벗어나는 경우
        if nar < 0 or nar >= R or nac < 0 or nac >= C:
            continue
        # 방문한 적이 있는 경우
        if visited[nar][nac]:
            continue
        visited[nar][nac] = 1
        # 공기에 노출된 치즈 표면
        if MAP[nar][nac]:
            q.append([nar, nac])
        # 공기
        else:
            air.append([nar, nac])

t = 1
cheese = len(q)
nq = deque()
# 치즈가 녹는 과정
while q:
    r, c = q.popleft()
    for d in range(4):
        nr, nc = r + dr[d], c + dc[d]
        # 범위를 벗어나는 경우
        if nr < 0 or nr >= R or nc < 0 or nc >= C:
            continue
        # 방문한 적이 있는 경우
        if visited[nr][nc]:
            continue
        visited[nr][nc] = 1
        # 다음에 녹을 치즈
        if MAP[nr][nc]:
            nq.append([nr, nc])
        # 구멍에 의한 추가 공기
        else:
            q.append([nr, nc])
    # 다음에 더 녹을 치즈 존재여부 확인
    if len(q) == 0 and len(nq):
        t += 1
        q = nq
        cheese = len(q)
        nq = deque()

print('{}\n{}'.format(t, cheese))


import logging
from django_gcp.tasks import OnDemandTask
from example.models import ERROR_STATUS, IN_PROGRESS_STATUS, FooFightingQuestion, FooFightingTest

logger = logging.getLogger(__name__)

class FooFightingTestTask(OnDemandTask):
    """An on-demand task to prepare and ask a question to foo-fighting-service

    This process is done in an async task, rather than immediately in a request,
    because it can take several seconds to create the resources required for the question
    """

    def run(self, foo_fighting_test_id=None, **__):
        """Run a series of FooFightingQuestions to load test the hardware

        Question results should contain:
         - The number of iterations of the mandelbrot calculation completed in the duration of the question
         - The duration of the questions, which will be equal to `max_duration` if `randomise_duration` is false, otherwise will be `0 <= duration <= max_duration`

        :param int foo_fighting_test_id: The id of the test run
        :param int number_of_questions: The number of questions that will get created and sent to the foo-fighting service.
        :param int max_duration: The duration of calculation in seconds that each service will run for.
        :param bool randomise_duration: Randomise durations of calculation if True. If False, all calculations will run for max_durations seconds.
        :param int mandelbrot_array_size: The dimension of the mandelbrot array that will be calculated.
        """

        test = FooFightingTest.objects.get(id=foo_fighting_test_id)

        for idx in range(test.number_of_questions):
            logger.info("Creating question %s of %s for FooFightingTest %s", idx + 1, test.number_of_questions, test.id)

            question = FooFightingQuestion(foo_fighting_test=test, calculation_status=IN_PROGRESS_STATUS)
            question.save()

            try:
                logger.info("Running FooFightingQuestionTask with question_id=%s", question.id)
                question.ask()
            except Exception as e:
                question.calculation_status = ERROR_STATUS
                question.save()
                raise e


# $Id: TestFunctions.py 1049 2009-01-15 15:09:21Z graham $
#
# Unit testing for WebBrick library functions (Functions.py)
# See http://pyunit.sourceforge.net/pyunit.html
#

__author__      = "Graham Klyne (GK@ACM.ORG)"
__copyright__   = "Copyright 2011-2013, Graham Klyne, University of Oxford"
__license__     = "MIT (http://opensource.org/licenses/MIT)"

import sys
import os
import unittest
from string import upper

sys.path.append("../..")
from MiscUtils.Functions import *

LibName = "MiscUtils"

class TestFunctions(unittest.TestCase):
    def setUp(self):
        return

    def tearDown(self):
        return

    def doAssert(self, cond, msg):
        assert cond , msg

    # Actual tests follow

    def testNull(self):
        assert True, 'Null test failed'

    def testSuff1(self):
        assert endsWith("xxx","xxx")

    def testSuff2(self):
        assert endsWith("yyyzzz","zzz")

    def testSuff3(self):
        assert not endsWith("xxxyyy","xxx")

    def testCwd(self):
        # Check test environment current directory)
        cwd = os.getcwd()
        assert endsWith(cwd, LibName+os.sep+"tests"), "Cwd is " + cwd

    def testConcatMap1(self):
        assert concatMap(upper,["a","B","cDe","FgH"])=="ABCDEFGH"

    def testConcatMap2(self):
        assert concatMap(upper,["a"])=="A"

    def testConcatMap3(self):
        assert concatMap(upper,[])==""

    def testFstSnd1(self):
        pair=('a','b')
        assert (fst(pair)=='a') and (snd(pair)=='b')

    def testFstSnd2(self):
        pair=(1,None)
        assert (fst(pair)==1) and (snd(pair)==None)

    def testIterAll1(self):
        seq = ('a',2,'c')
        seqall = iterAll(seq)
        assert seqall.next()=='a'
        assert seqall.next()==2
        assert seqall.next()=='c'
        assert seqall.next()==None
        assert seqall.next()==None
        assert seqall.next()==None

    def testIterAll2(self):
        seq = ('a',2,'c')
        seqall = iterAll(seq,"foo")
        assert seqall.next()=='a'
        assert seqall.next()==2
        assert seqall.next()=='c'
        assert seqall.next()=="foo"
        assert seqall.next()=="foo"
        assert seqall.next()=="foo"

    def testZipAll1(self):
        # z = tuple( [x for x in zipAll((1,2,3), (4,5))] )
        z = tuple( zipAll((1,2,3), (4,5)) )
        e = ((1,4),(2,5),(3,None))
        assert z==e, z

    def testZipAll2(self):
        z = tuple( zipAll((1,2,3), (4,5), (6,7,8,9), ()) )
        e = ((1,4,6,None), (2,5,7,None), (3,None,8,None), (None,None,9,None))
        assert z==e, z

    def testAll1(self):
        assert(all(isEq(1),[1,1,1,1]))

    def testAll2(self):
        assert(not all(isEq(1),[1,1,0,1]))

    def testAny1(self):
        assert(any(isEq(1),[1,2,3,4]))

    def testAny2(self):
        assert(not any(isEq(0),[1,2,3,4]))

    def testAllEq1(self):
        assert allEq(2,[2,2,2,2])

    def testAllEq2(self):
        assert not allEq(2,[2,2,0,2])

    def testAllEq3(self):
        assert allEq(2,[])

    def testAllNe1(self):
        assert allNe(2,[0,1,3,4])

    def testAllNe2(self):
        assert not allNe(2,[0,1,2,3,4])

    def testAllNe3(self):
        assert allNe(2,[])

    def testFilterSplit1(self):
        def isOdd(v): return isEq(1)(v&1)
        vs = [1,2,3,4,5,6,7,5,3,2,1]
        (v1,v2) = filterSplit(isOdd,vs)
        assert v1 == [1,3,5,7,5,3,1], str(v1)
        assert v2 == [2,4,6,2]

    def testFilterSplit2(self):
        vs = [1,2,3,4,5,6,7,5,3,2,1]
        (v1,v2) = filterSplit(isEq(9),vs)
        assert v1 == []
        assert v2 == [1,2,3,4,5,6,7,5,3,2,1]

    def testFilterSplit3(self):
        vs = [1,2,3,4,5,6,7,5,3,2,1]
        (v1,v2) = filterSplit(isNe(9),vs)
        assert v1 == [1,2,3,4,5,6,7,5,3,2,1]
        assert v2 == []

    def testFormatIntList1(self):
        return self.assertEqual(
            "1,2,3,4,10,15,255",
            formatIntList([1,2,3,4,10,15,255]))

    def testFormatIntList2(self):
        return self.assertEqual(
            "01:02:03:04:0A:0F:FF",
            formatIntList([1,2,3,4,10,15,255],":",formatInt("%02X")))

    def testFormatList1(self):
        txt = formatList(('a','b','c'))
        assert txt=="( 'a'\n, 'b'\n, 'c'\n)", repr(txt)

    def testFormatList2(self):
        txt = formatList(('a','b','c'),left=2)
        assert txt=="( 'a'\n  , 'b'\n  , 'c'\n  )", repr(txt)

    def testFormatList3(self):
        txt = formatList(('a','b','c'),left=2,right=40)
        assert txt=="('a', 'b', 'c')", repr(txt)

    def testFormatList4(self):
        txt = formatList(('a','b',('c','d','e')),left=2,right=20)
        assert txt=="( 'a'\n  , 'b'\n  , ('c', 'd', 'e')\n  )", repr(txt)

    def testFormatDict1(self):
        txt = formatDict({'a':'foo','b':'bar'})
        assert txt=="{ 'a': 'foo'\n, 'b': 'bar'\n}", repr(txt)

    def testFormatDict9(self):
        dic = \
            { 'style': None
            , 'elems':
              ( { 'Control':
                  {'Selection': {'Values': {'Wb:Off': '0', 'Wb:On': '1'}, 'ctype': 'Wb:SwitchToggle'}}
                , 'source': {'endpoint': 'WebBrick2', 'channel': 'DO2'}
                , 'style': None
                , 'target': {'endpoint': 'WebBrick2', 'channel': 'DI1'}
                , 'label': None
                }
              ,
              )
            , 'label': 'loose'
            }
        exp = (
            "{ 'style': None\n"+
            ", 'elems': \n"+
            "  ( { 'Control': \n"+
            "      { 'Selection': \n"+
            "        { 'Values': {'Wb:Off': '0', 'Wb:On': '1'}\n"+
            "        , 'ctype': 'Wb:SwitchToggle'\n"+
            "        }\n"+
            "      }\n"+
            "    , 'source': \n"+
            "      {'endpoint': 'WebBrick2', 'channel': 'DO2'}\n"+
            "    , 'style': None\n"+
            "    , 'target': \n"+
            "      {'endpoint': 'WebBrick2', 'channel': 'DI1'}\n"+
            "    , 'label': None\n"+
            "    }\n"+
            "  )\n"+
            ", 'label': 'loose'\n"+
            "}" )
        txt = formatDict(dic,left=0,right=60,pos=0)
        assert txt==exp, "\n"+txt # "\n"+txt  # repr(txt)

    def testCompareLists1(self):
        assert compareLists([],[])==None

    def testCompareLists2(self):
        assert compareLists(['a'],['a'])==None

    def testCompareLists3(self):
        assert compareLists(None,[])==None

    def testCompareLists4(self):
        assert compareLists(['a','b','c'],['d','e','f'])==(['a','b','c'],['d','e','f'])

    def testCompareLists5(self):
        assert compareLists(['a','b','c'],['b','d','c','e'])==(['a'],['d','e'])

    def testCompareLists6(self):
        assert compareLists(['a','b','a'],['b','d','b','d'])==(['a','a'],['d','d'])

    def testCompareLists7(self):
        assert compareLists(['a','b','c'],None)==(['a','b','c'],[])

    def testCompareDicts1(self):
        assert compareDicts({},{})==None

    def testCompareDicts2(self):
        assert compareDicts({'foo':'bar'},{'foo':'bar'})==None

    def testCompareDicts3(self):
        difs = compareDicts({'a':'foo','b':'bar'},{'a':'foo'})
        assert difs==({'b':'bar'},{}), repr(difs)

    def testCompareDicts4(self):
        assert compareDicts({'a':'foo','b':'bar'},{'a':'foo','b':'baz'})==({'b':'bar'},{'b':'baz'})

    def testCompareDicts5(self):
        assert compareDicts({'a':'foo','b':{'c':'bar'}},{'a':'foo','b':{'c':'bar'}})==None

    def testCompareDicts6(self):
        d1 = \
            { 'elems':
              ( { 'Control':
                  { 'source': {'endpoint': 'WebBrick2', 'channel': 'DO2'}
                  , 'Selection': {'Values': {'Wb:Off': '0', 'Wb:On': '1'}, 'ctype': 'Wb:SwitchToggle'}
                  , 'target': {'endpoint': 'WebBrick2', 'channel': 'DI1'}
                  }
                }
              ,
              )
            , 'label': 'Shower light'
            }
        d2 = \
            { 'style': None
            , 'elems':
              ( { 'Control':
                  {'Selection': {'Values': {'Wb:Off': '0', 'Wb:On': '1'}, 'ctype': 'Wb:SwitchToggle'}}
                , 'source': {'endpoint': 'WebBrick2', 'channel': 'DO2'}
                , 'style': None
                , 'target': {'endpoint': 'WebBrick2', 'channel': 'DI1'}
                , 'label': None
                }
              ,
              )
            , 'label': 'loose'
            }
        dif1 = \
            { 'elems':
                ( { 'Control':
                    { 'source': {'endpoint': 'WebBrick2', 'channel': 'DO2'},
                      'target': {'endpoint': 'WebBrick2', 'channel': 'DI1'}
                    }
                  }
                ,
                )
            , 'label': 'Shower light'
            }
        dif2 = \
            { 'elems':
              ( { 'source': {'endpoint': 'WebBrick2', 'channel': 'DO2'}
                , 'target': {'endpoint': 'WebBrick2', 'channel': 'DI1'}
                }
              ,
              )
            , 'label': 'loose'
            }
        (dd1,dd2) = compareDicts(d1,d2)
        assert dd1==dif1, "dif1:\n"+formatDict(dd1,0,60,0)
        assert dd2==dif2, "dif2:\n"+formatDict(dd2,0,60,0)
        #assert (dd1,dd2)==(dif1,dif2),"dif1:\n"+formatDict(dd1,0,60,0)+"\ndif2:\n"+formatDict(dd2,0,60,0)

    def testCompareDicts7(self):
        d1 = \
            { 'group': 'loose'
            , 'elems':
              ( { 'Control':
                  { 'Selection':
                    { 'Values': {'Wb:Off': '0', 'Wb:On': '1'}
                    , 'ctype': 'Wb:SwitchToggle'
                    }
                  }
                , 'source':
                  {'endpoint': 'WebBrick2', 'channel': 'DO2'}
                , 'target':
                  {'endpoint': 'WebBrick2', 'channel': 'DI1'}
                }
              ,
              )
            , 'label': 'Shower light'
            }
        d2 = \
            { 'style': None
            , 'group': 'loose'
            , 'elems':
              ( { 'Control':
                  { 'Selection':
                    { 'Values': {'Wb:Off': '0', 'Wb:On': '1'}
                    , 'ctype': 'Wb:SwitchToggle'
                    }
                  }
                , 'source':
                  {'endpoint': 'WebBrick2', 'channel': 'DO2'}
                , 'style': None
                , 'target':
                  {'endpoint': 'WebBrick2', 'channel': 'DI1'}
                , 'label': None
                }
              ,
              )
            , 'label': 'Shower light'
            }
        dd = compareDicts(d1,d2)
        if dd != None:
            (dd1,dd2) = dd
            assert dd1==None, "dd1:\n"+formatDict(dd1,0,60,0)
            assert dd2==None, "dd2:\n"+formatDict(dd2,0,60,0)

    def testCompareDicts8(self):
        d1 = \
            { 'group': 'loose'
            , 'elems':
              [ { 'Control':
                  { 'Selection':
                    { 'Values': {'Wb:Off': '0', 'Wb:On': '1'}
                    , 'ctype': 'Wb:SwitchToggle'
                    }
                  }
                , 'source':
                  {'endpoint': 'WebBrick2', 'channel': 'DO2'}
                , 'target':
                  {'endpoint': 'WebBrick2', 'channel': 'DI1'}
                }
              ]
            , 'label': 'Shower light'
            }
        d2 = \
            { 'style': None
            , 'group': 'loose'
            , 'elems':
              [ { 'Control':
                  { 'Selection':
                    { 'Values': {'Wb:Off': '0', 'Wb:On': '1'}
                    , 'ctype': 'Wb:SwitchToggle'
                    }
                  }
                , 'source':
                  {'endpoint': 'WebBrick2', 'channel': 'DO2'}
                , 'style': None
                , 'target':
                  {'endpoint': 'WebBrick2', 'channel': 'DI1'}
                , 'label': None
                }
              ]
            , 'label': 'Shower light'
            }
        dd = compareDicts(d1,d2)
        if dd != None:
            (dd1,dd2) = dd
            assert dd1==None, "dd1:\n"+formatDict(dd1,0,60,0)
            assert dd2==None, "dd2:\n"+formatDict(dd2,0,60,0)

# Code to run unit tests directly from command line.
# Constructing the suite manually allows control over the order of tests.
def getTestSuite():
    suite = unittest.TestSuite()
    suite.addTest(TestFunctions("testNull"))
    suite.addTest(TestFunctions("testSuff1"))
    suite.addTest(TestFunctions("testSuff2"))
    suite.addTest(TestFunctions("testSuff3"))
    suite.addTest(TestFunctions("testCwd"))
    suite.addTest(TestFunctions("testConcatMap1"))
    suite.addTest(TestFunctions("testConcatMap2"))
    suite.addTest(TestFunctions("testConcatMap3"))
    suite.addTest(TestFunctions("testFstSnd1"))
    suite.addTest(TestFunctions("testFstSnd2"))
    suite.addTest(TestFunctions("testIterAll1"))
    suite.addTest(TestFunctions("testIterAll2"))
    suite.addTest(TestFunctions("testZipAll1"))
    suite.addTest(TestFunctions("testZipAll2"))
    suite.addTest(TestFunctions("testAll1"))
    suite.addTest(TestFunctions("testAll2"))
    suite.addTest(TestFunctions("testAny1"))
    suite.addTest(TestFunctions("testAny2"))
    suite.addTest(TestFunctions("testAllEq1"))
    suite.addTest(TestFunctions("testAllEq2"))
    suite.addTest(TestFunctions("testAllEq3"))
    suite.addTest(TestFunctions("testAllNe1"))
    suite.addTest(TestFunctions("testAllNe2"))
    suite.addTest(TestFunctions("testAllNe3"))
    suite.addTest(TestFunctions("testFilterSplit1"))
    suite.addTest(TestFunctions("testFilterSplit2"))
    suite.addTest(TestFunctions("testFilterSplit3"))
    suite.addTest(TestFunctions("testFormatIntList1"))
    suite.addTest(TestFunctions("testFormatIntList2"))
    suite.addTest(TestFunctions("testFormatList1"))
    suite.addTest(TestFunctions("testFormatList2"))
    suite.addTest(TestFunctions("testFormatList3"))
    suite.addTest(TestFunctions("testFormatList4"))
    suite.addTest(TestFunctions("testFormatDict1"))
    suite.addTest(TestFunctions("testFormatDict9"))
    suite.addTest(TestFunctions("testCompareLists1"))
    suite.addTest(TestFunctions("testCompareLists2"))
    suite.addTest(TestFunctions("testCompareLists3"))
    suite.addTest(TestFunctions("testCompareLists4"))
    suite.addTest(TestFunctions("testCompareLists5"))
    suite.addTest(TestFunctions("testCompareLists6"))
    suite.addTest(TestFunctions("testCompareLists7"))
    suite.addTest(TestFunctions("testCompareDicts1"))
    suite.addTest(TestFunctions("testCompareDicts2"))
    suite.addTest(TestFunctions("testCompareDicts3"))
    suite.addTest(TestFunctions("testCompareDicts4"))
    suite.addTest(TestFunctions("testCompareDicts5"))
    suite.addTest(TestFunctions("testCompareDicts6"))
    suite.addTest(TestFunctions("testCompareDicts7"))
    suite.addTest(TestFunctions("testCompareDicts8"))
    return suite
    # suite = unittest.makeSuite(WidgetTestCase,'test')

if __name__ == "__main__":
    # unittest.main()
    runner = unittest.TextTestRunner()
    runner.run(getTestSuite())

# End.