# 开发者：热心网友
# 开发时间：2022/8/29 19:44
# coding:utf-8

import sys
sys.path.append('./dataset')
import os.path
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader
import json
from dataset.train_dataset import Train_dataset
from dataset.valid_and_test_dataset import Valid_and_Test_dataset
from net import FCN_classical
from utils import get_confusion_matrix, DPM_statistics

csv_dir = './lookupcsv/'  # 读取csv的dir
checkpoint_dir = './history_model/'     # 保存model的dir
dpms_dir = './DPMS/'

with open('cnofig.json', 'r') as f:
    config = json.loads(f.read())

def train(model: FCN_classical, lr, epochs, exps):
    # 最优模型和最优输出
    '''
    best_model = None
    best_matrix = None  # [[tn, fn], [fp, tp]]
    best_ACC = None
    best_epoch = None
    '''
    # 开始训练
    print('STARTing...')
    for exp in range(exps):
        # 加载数据...
        train_dataset = Train_dataset(csv_dir + f'exp{exp}/', data_dir=config['fcn']["Data_dir"])
        train_datalaoder = DataLoader(train_dataset, batch_size=20, shuffle=True)
        # weight  --  消除数据不平衡
        losser = nn.CrossEntropyLoss(weight=torch.Tensor([1, train_dataset.imbalanced_ratio]))
        for epoch in range(epochs):
            optimizer = torch.optim.RMSprop(model.parameters(), lr=lr)
            lossSum = 0
            print('-'*5, f'epoch{epoch}', '-'*5)
            for time, (imgs, labels) in enumerate(train_datalaoder):
                optimizer.zero_grad()
                dpms = model(imgs)  # (?, 2, 1, 1, 1)
                dpms = dpms.view(-1, 2)  # (?, 2)
                loss = losser(dpms, labels)
                loss.backward()
                optimizer.step()
                lossSum += loss
                # Validing...
                with torch.no_grad():
                    if (time + 1) % 20 == 0:
                        matrix, ACCU, F1, MCC = valid(model, exp)
                        if MCC > best_MCC:
                            best_MCC = MCC
                            best_model = model.state_dict()
                            best_matrix = matrix
                            best_epoch = epoch
                        print(f'VALID MCC: {MCC}, VALID ACC: {ACCU}')
            # epoch 结束
            print(f'epoch_{epoch} 训练完成, train_loss: {lossSum}')
    if os.path.exists(checkpoint_dir):
        os.mkdir(checkpoint_dir)
    torch.save(best_model, '{}{}_{}.pth'.format(checkpoint_dir, 'FCN', best_epoch))
    print('Train Done !!!')

def valid(model:FCN_classical, exp):
    valid_dataset = Valid_and_Test_dataset(csv_dir + f'exp{exp}/', data_dir=config['fcn']["Data_dir"], mode='valid')
    valid_dataset = DataLoader(valid_dataset, batch_size=1, shuffle=False)
    labels = []
    dpms = []
    for img, label in valid_dataset:
        dpm = model(img).numpy().squeeze()  # (2, 46, 55, 46)
        dpms.append(dpm)
        labels.append(label)
    valid_matrix = get_confusion_matrix(dpms, labels)
    matrix, ACCU, F1, MCC = DPM_statistics(valid_matrix)
    return matrix, ACCU, F1, MCC

def test_and_generate_DPMs(model:FCN_classical, exp):
    # 加载最优模型...
    model_list = os.listdir(checkpoint_dir)
    weights = None
    for name in model_list:
        if '_FCN' in name:
            weights = torch.load(name)
            break
    assert weights
    model.load_state_dict(weights)
    print('Testing...')
    for stage in ['train', 'valid', 'test', 'AIBL', 'NACC', 'FHS']:
        # 加载数据...
        if stage in ['train', 'valid', 'test']:
            testdataset = Valid_and_Test_dataset(csv_dir + f'exp{exp}/', mode=stage)
        else:
            testdataset = Valid_and_Test_dataset(csv_dir, mode=stage)
        testloader = DataLoader(testdataset, batch_size=1, shuffle=False)
        filenames = testdataset.imgnames
        DPMs, Labels = [], []
        for idx, (img, label) in enumerate(testloader):
            DPM = model(img).numpy().squeeze()  # (2, 46, 55, 46)
            np.save(dpms_dir +f'exp{exp}' + filenames[idx] + '.npy', DPM)
            DPMs.append(DPM)
            Labels.append(label)
        matrix, ACCU, F1, MCC = DPM_statistics(DPMs, Labels)
        np.save(dpms_dir + f'exp{exp}/{stage}_MCC.npy', MCC)
        np.save(dpms_dir + f'exp{exp}/{stage}_F1.npy', F1)
        np.save(dpms_dir + f'exp{exp}/{stage}_ACC.npy', ACCU)
        print(stage + ' confusion matrix: ', matrix, ' accuracy: ', ACCU)

if __name__ == '__main__':
    neurons = 20
    exps = 1
    epochs = 20
    lr = 0.1

    model = FCN_classical(neurons=20)

    class myDataset(torch.utils.data.Dataset):
        def __init__(self):
            self.data = np.random.uniform(0, 1, size=(100, 1, 47, 47, 47))
            self.data = torch.from_numpy(self.data).to(torch.float32)
            self.label = np.random.randint(0, 1, size = (100, ))
            self.label = torch.from_numpy(self.label).to(torch.long)
            self.imbalanced_ratio = 1.0

        def __len__(self):
            return self.data.shape[0]

        def __getitem__(self, idx):
            data = self.data[idx]
            label = self.label[idx]
            return data, label

    print('STARTing...')
    for exp in range(exps):
        # 加载数据...
        train_dataset = myDataset()
        train_datalaoder = DataLoader(train_dataset, batch_size=20, shuffle=True)
        # weight  --  消除数据不平衡
        losser = nn.CrossEntropyLoss(weight=torch.Tensor([1, train_dataset.imbalanced_ratio]))
        for epoch in range(epochs):
            optimizer = torch.optim.RMSprop(model.parameters(), lr=lr)
            lossSum = 0
            print('-'*5, f'epoch{epoch}', '-'*5)
            for time, (imgs, labels) in enumerate(train_datalaoder):
                optimizer.zero_grad()
                dpms = model(imgs)  # (?, 2, 1, 1, 1)
                dpms = dpms.view(-1, 2)  # (?, 2)
                loss = losser(dpms, labels)
                loss.backward()
                optimizer.step()
                lossSum += loss
                # Validing...
                # with torch.no_grad():
                #     if (time + 1) % 20 == 0:
                #         matrix, ACCU, F1, MCC = valid(model, exp)
                #         if MCC > best_MCC:
                #             best_MCC = MCC
                #             best_model = model.state_dict()
                #             best_matrix = matrix
                #             best_epoch = epoch
                #         print(f'VALID MCC: {MCC}, VALID ACC: {ACCU}')
            # epoch 结束
            print(f'epoch_{epoch} 训练完成, train_loss: {lossSum}')
    # if os.path.exists(checkpoint_dir):
    #     os.mkdir(checkpoint_dir)
    # torch.save(best_model, '{}{}_{}.pth'.format(checkpoint_dir, 'FCN', best_epoch))
    print('Train Done !!!')


from SDN.sdwan.interface.webpages.base import BasePage
import time

class Configure(BasePage):

    SECTION_NAME = 'Configure'
    LINK_OPTION_XPATH = "//select[@id='{0}']"
    ACTION_BUTTON_XPATH = "//button[@id='{0}_button']"

    def navigate_to_configure_section(self):

        if self.navigate_to_section(name = Configure.SECTION_NAME):
            print("Navigate to Configuration Page")

    def configure_service(self, service, link_type):

        elem = self.gui_driver.driver.find_element_by_xpath(self.LINK_OPTION_XPATH.format(service))
        link_options = elem.find_elements_by_tag_name("option")
        time.sleep(3)
        for option in link_options:
            if option.get_attribute("value") == link_type:
                time.sleep(3)
                option.click()
                elem = self.gui_driver.driver.find_element_by_xpath(self.ACTION_BUTTON_XPATH.format(service))
                elem.click()

class SERVICE_TYPE(object):

    SSH = 'ssh'
    ARP = 'arp'

class LINK_TYPE(object):

    MPLS = 'MPLS'
    DIA = 'DIA'
    DROP = 'DROP'
    EDGE = 'EDGE'

    PORT_MAPPING = {MPLS:2,
                    DIA:3,
                    EDGE:1}


#coding=utf-8
from selenium import webdriver
import time
import os

path="/Users/aimee/Downloads/chromedriver"
driver = webdriver.Chrome(path)
file_path='file:///'+os.path.abspath('checkbox.html')
driver.get(file_path)

checkboxs=driver.find_elements_by_css_selector('input[type=checkbox]')
for check in checkboxs:
    check.click()

time.sleep(1)

driver.find_elements_by_css_selector('input[type=checkbox]').pop(1).click()
time.sleep(2)

driver.quit()


#! /usr/bin/env python

'''Short script to illustrate Windows menu bitmap problem after SetItemLabel'''

# contact Dan Koch <kochdb@ornl.gov> for questions

import wx

class MyFrame(wx.Frame):

	def __init__(self):

		wx.Frame.__init__(self, None, size=(300,300))

		self.menubar = wx.MenuBar()
		menu = wx.Menu()

		self.label = 'Label 1'
		item = wx.MenuItem(menu, -1, self.label)

		self.bmp = wx.Bitmap('/Users/ko5/Desktop/folder.png', wx.BITMAP_TYPE_PNG) # change filepath as needed
		item.SetBitmap(self.bmp)

		menu.AppendItem(item)
		self.menubar.Append(menu, 'File')
		self.SetMenuBar(self.menubar)

		self.Bind(wx.EVT_MENU, self.OnFile, item)

	def OnFile(self, event):

		item_id = self.menubar.FindMenuItem('File', self.label)
		item = self.menubar.FindItemById(item_id)

		if self.label == 'Label 1':
			self.label = 'Label 2'

		else:
			self.label = 'Label 1'

		item.SetItemLabel(self.label)

		item.SetBitmap(self.bmp) # uncomment this line to see workaround, must invoke twice

if __name__ == '__main__':
	app = wx.PySimpleApp()
	frame = MyFrame()
	frame.Show()
	app.MainLoop()


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 14:53:54 2018

@author: nakatanikenichi
"""

import numpy as np
import chainer.functions as F
import chainer.links as L
from chainer import Variable, optimizers

# グラフ表示を行うため、グラフ表示用のモジュールmatplotlibをpltとして読み込みます。
import matplotlib.pyplot as plt

def plotmodel(model):
    x_for_plot = Variable(np.array([[1],[2],[7]],dtype=np.float32))
    y_for_plot = model(x_for_plot)
    #plt.plot(x_for_plot.data,y_for_plot.data,"r-")
    plt.plot(x_for_plot.data,y_for_plot.data,marker='o',ls='-')
    plt.xlabel("x")
    plt.ylabel("y")

#モデルを定義します。
model = L.Linear(1,1)

#パラメータの最適化の方法を選択し、モデルと関連付けます。
optimizer = optimizers.SGD()
optimizer.setup(model)

#入力するデータ[1],[2],[7]を作成します。
x = Variable(np.array([[1],[2],[7]],dtype=np.float32))

#答えとなるデータ[2],[4],[14]を作成します。
t = Variable(np.array([[2],[4],[14]], dtype=np.float32))

#学習の回数を設定します。
times = 50

for i in range(0,times):
    #モデルの勾配データを初期化します。
    model.cleargrads()
    #optimizer.zero_grads()

    #予測します。
    y = model(x)

    #モデルの出力を表示します。
    #print(y.data)

    #予測と答えとの誤差を計算します。
    loss = F.mean_squared_error(y,t)

    #誤差逆伝搬を行い、勾配を計算します。
    #print "誤差逆伝搬前の勾配　model.W.grad :", model.W.grad
    loss.backward()
    #print "誤差逆伝搬後の勾配　model.W.grad :", model.W.grad

    #パラメータの更新を行います。
    #print "更新前のウエイト　model.W.data :", model.W.data
    optimizer.update()
    #print "更新後のウエイト　model.W.data :", model.W.data

    #モデルをグラフ表示します。
    plotmodel(model)

plt.show()


import re

f1 = open("p022_names.txt")
f2 = open("input-parsed.js", "w")

f2.write("const PROBLEM_INPUT = [")

for line in f1:
    f2.write(line)

f1.close()

f2.write("]")
f2.close()


#! /bin/env python3

import os, sys, subprocess, time, re, json, requests

def log(r):
    print('{0} {1} {2} {3}'.format(r.method, r.url, r.headers, r.body))

api_key = ''
try:
    api_key = os.environ['ETHERSCAN_API_KEY']
except KeyError:
    print('''  You need an Etherscan Api Key to verify contracts.
  Create one at https://etherscan.io/myapikey

  Then export it with `export ETHERSCAN_API_KEY=xxxxxxxx'
''')
    exit()

document = ''
try:
    document = open('out/dapp.sol.json')
except FileNotFoundError:
    exit('run dapp build first')
content = json.load(document)

if len(sys.argv) not in [3, 4]:
    print('''usage:

./verify.py <contractname> <address> [constructorArgs]
''')
    exit()

contract_name = sys.argv[1]
contract_address = sys.argv[2]
if len(contract_address) !=  42:
    exit('malformed address')
constructor_arguments = ''
if len(sys.argv) == 4:
    constructor_arguments = sys.argv[3]
contract_path = ''

for path in content['contracts'].keys():
    for name in content['contracts'][path].keys():
        if name == contract_name:
            contract_path = path
if contract_path == '':
    exit('contract name not found.')

print('Obtaining chain... ')
seth_chain = subprocess.run(['seth', 'chain'], capture_output=True)
chain = seth_chain.stdout.decode('ascii').replace('\n', '')
print(chain)

text_metadata = content['contracts'][contract_path][contract_name]['metadata']
metadata = json.loads(text_metadata)

compiler_version = 'v' + metadata['compiler']['version']

evm_version = metadata['settings']['evmVersion']

optimizer_enabled = metadata['settings']['optimizer']['enabled']

optimizer_runs = metadata['settings']['optimizer']['runs']

license_name = metadata['sources'][contract_path]['license']

license_numbers = {
    'GPL-3.0-or-later': 5,
    'AGPL-3.0-or-later': 13
}

license_number = license_numbers[license_name]

module = 'contract'

action = 'verifysourcecode'

code_format = 'solidity-single-file'

flatten = subprocess.run([
    'hevm',
    'flatten',
    '--source-file',
    contract_path
], capture_output=True)

source_code = flatten.stdout

def get_library_info():
    try:
        makefile = open('./Makefile').read()
        libraries_flags = re.findall('DAPP_LIBRARIES=\'(.*)\'', makefile)
        if len(libraries_flags) == 0:
            raise ValueError('No library flags found in Makefile')
        libraries_flag = libraries_flags[0].strip().split(' ')
        library_flag = libraries_flag[0]
        library_components = library_flag.split(':')
        if len(library_components) != 3:
            raise ValueError('Malformed library flag: ', library_components)
        library_name = library_components[1]
        library_address = library_components[2]
        return library_name, library_address
    except FileNotFoundError:
        raise ValueError('No Makefile found')

library_name = ''
library_address = ''

try:
    library_name, library_address = get_library_info()
except ValueError as e:
    print(e)
    print('Assuming this contract uses no libraries')

data = {
    'apikey': api_key,
    'module': module,
    'action': action,
    'contractaddress': contract_address,
    'sourceCode': source_code,
    'codeFormat': code_format,
    'contractName': contract_name,
    'compilerversion': compiler_version,
    'optimizationUsed': '1' if optimizer_enabled else '0',
    'runs': optimizer_runs,
    'constructorArguements': constructor_arguments,
    'evmversion': evm_version,
    'licenseType': license_number,
    'libraryname1': library_name,
    'libraryaddress1': library_address,
}

if chain in ['mainnet', 'ethlive']:
    chain_separator = False
    chain_id = ''
else:
    chain_separator = True
    chain_id = chain

url = 'https://api{0}{1}.etherscan.io/api'.format(
    '-' if chain_separator else '',
    chain_id
)

headers = {
    'User-Agent': ''
}

print('Sending verification request...')

verify = requests.post(url, headers = headers, data = data)

log(verify.request)

try:
    verify_response = json.loads(verify.text)
except json.decoder.JSONDecodeError:
    print(verify.text)
    exit('Error: Etherscan responded with invalid JSON.')

if verify_response['status'] != '1' or verify_response['message'] != 'OK':
    print('Error: ' + verify_response['result'])
    exit()

print('Sent verification request with guid ' + verify_response['result'])

guid = verify_response['result']

check_response = {}

while check_response == {} or 'pending' in check_response['result'].lower():

    if check_response != {}:
        print('Verification pending...')
        time.sleep(1)

    check = requests.post(url, headers = headers, data = {
        'apikey': api_key,
        'module': module,
        'action': 'checkverifystatus',
        'guid': guid,
    })

    if check_response == {}:
        log(check.request)

    try:
        check_response = json.loads(check.text)
    except json.decoder.JSONDecodeError:
        print(check.text)
        exit('Error: Etherscan responded with invalid JSON')

if check_response['status'] != '1' or check_response['message'] != 'OK':
    print('Error: ' + check_response['result'])
    exit()

print('Contract verified at https://{0}{1}etherscan.io/address/{2}#code'.format(
    chain_id,
    '.' if chain_separator else '',
    contract_address
))


from memory_trunk_app import models
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from memory_trunk_app.forms import MemoryForm

def update_memory(request, id):
    """
    Purpose:
        Provide users with an interface for editing memories they have
        saved to their MemoryTrunk

    Author: Sam Phillips <samcphillips.com>
    """
    memory = models.Memory.objects.get(id=id)
    if request.method == 'POST':
        if memory.user == request.user:
            # create a form instance and populate it with data from the request:
            form = MemoryForm(request.POST)
            if form.is_valid():
                memory.title=form.cleaned_data['title']
                memory.is_public=form.cleaned_data['is_public']
                memory.date=form.cleaned_data['date']
                memory.location=form.cleaned_data['location']
                memory.content=form.cleaned_data['content']
                memory.happy_factor=form.cleaned_data['happy_factor']
                memory.sad_factor=form.cleaned_data['sad_factor']
                for tag in form.cleaned_data['tags']:
                    memory.tags.add(tag)
                memory.save()
                return HttpResponseRedirect(reverse('memory_trunk_app:memory_detail', args=(memory.id,)))
        return HttpResponseRedirect('/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = MemoryForm(instance=memory)

    return render(
        request,
        'memory_update_form.html',
        {
            'form': form,
            'memory': memory
        }
    )


import os
import sys
import nlopt
import exodus
import PlatoServices
import PlatoPython
import ctypes
from contextlib import contextmanager
from numpy import *

##############################################################################
## define functionality that redirects console output to a file
##############################################################################
@contextmanager
def redirected(to=os.devnull):
    '''
    import os

    with redirected(to=filename):
        print("from Python")
        os.system("echo non-Python applications are also supported")
    '''
    fdout = sys.stdout.fileno()
    fderr = sys.stderr.fileno()

    def _redirect_stdout(to):
        sys.stdout.close()                  # + implicit flush()
        os.dup2(to.fileno(), fdout)         # fd writes to 'to' file
        sys.stdout = os.fdopen(fdout, 'w')  # Python writes to fd

    def _redirect_stderr(to):
        sys.stderr.close()                  # + implicit flush()
        os.dup2(to.fileno(), fderr)         # fd writes to 'to' file
        sys.stderr = os.fdopen(fderr, 'w')  # Python writes to fd

    with os.fdopen(os.dup(fdout), 'w') as old_stdout, os.fdopen(os.dup(fderr), 'w') as old_stderr:
        with open(to, 'w') as file:
            _redirect_stdout(to=file)
            _redirect_stderr(to=file)
        try:
            yield # allow code to be run with the redirected stdout
        finally:
            _redirect_stdout(to=old_stdout) # restore stdout.
                                            # buffering and flags such as
                                            # CLOEXEC may be different
            _redirect_stderr(to=old_stderr) # restore stderr.
                                            # buffering and flags such as
                                            # CLOEXEC may be different

# boilerplate that dynamically loads the mpi library required by PlatoPython.Analyze
ctypes.CDLL("libmpi.so",mode=ctypes.RTLD_GLOBAL)

# create initial mesh (required for Analyze to initialized correctly)
os.system('plato-cli geometry esp --input model.csm --output-model model_opt.csm --output-mesh model.exo --tesselation model.eto')

# create global Analyze instance
analyzeAppFileName = "analyzeApp.xml"
analyzeInputFile = "analyzeInput.xml"
analyze = PlatoPython.Analyze(analyzeInputFile, analyzeAppFileName, "analyze")
analyze.initialize();

# create global PlatoServices instance
engineAppFileName = "platoApp.xml"
engineInputFile = "platoInput.xml"
engine = PlatoServices.Services(engineInputFile, engineAppFileName, "services")
engine.initialize();

#define objective
def dfdx(x, grad):

  engine.importData("Parameters", "SCALAR", x.tolist())
  engine.compute("Update Geometry on Change")

  # import current design into Analyze instance
  analyze.importData("Parameters", "SCALAR", x.tolist())
  analyze.compute("Reinitialize on Change")

  # compute cell solutions
  analyze.compute("Compute Objective")
  value = analyze.exportData("Criterion Value", "SCALAR")

  if grad.size > 0:
    # export output data from Analyze instance
    analyzeGrad = analyze.exportData("Criterion Gradient", "SCALAR", len(grad))
    print( "grad:", analyzeGrad)

    for iVal in range(len(analyzeGrad)):
      grad[iVal] = analyzeGrad[iVal]

  print( "eval at: ", x.tolist())
  print( "eval to: ", value)
  return value

xinit = [0.75, 4.8]
# create nlopt instance
opt = nlopt.opt(nlopt.LD_LBFGS, len(xinit))

opt.set_min_objective(dfdx)
#opt.add_inequality_constraint(g, 1e-6)
opt.set_lower_bounds([0.6, 4.0])
opt.set_upper_bounds([0.9, 6.0])

opt.set_maxeval(20)
opt.set_ftol_rel(1e-3)
opt.set_xtol_rel(1e-3)

print( "xinit", xinit)
xopt = opt.optimize(xinit)
minf = opt.last_optimum_value()

print( "optimum is: ", minf)
print( "optimum at: ", xopt.tolist())

# finalize mpi and kokkos.  Not essential, but you'll get warnings otherwise.
analyze.finalize()
engine.finalize()

xtarget = [0.80, 5.0]
tol = 1e-3
error = 0.0
for i in range(len(xopt)):
  error += math.fabs(xopt[i]-xtarget[i])

if error > tol:
  print( "error (", error, ") exceeded tolerance")
  sys.exit(1)
else:
  print( "error (", error, ") within tolerance")
  sys.exit(0)


# George Juarez

'''
    10. Golf Scores
         The Springfork Amateur Golf Club has a tournament every weekend. The club president
         has asked you to write two programs:
              1. A program that will read each player’s name and golf score as keyboard input, and then
                 save these as records in a file named golf.txt. (Each record will have a field for the
                 player’s name and a field for the player’s score.)
              2. A program that reads the records from the golf.txt file and displays them.
'''

def main():
    move_on = 'y'
    golfScoreFile = open('golfRecords.txt','a')
    while move_on == 'y' or move_on == 'Y':
        pName = input("Enter the player's name: ")
        pScore = int(input("Enter the player's score: "))
        golfScoreFile.write(pName + "\n")
        golfScoreFile.write(str(pScore) + "\n")
        move_on = input("Would you like to continue? [y]: ")
    displayRecords = input("Would you like to display all the records from golfRecords.txt? [y]: ")
    golfScoreFile.close()
    if(displayRecords == 'y' or displayRecords == 'Y'):
        displayRecs()

def displayRecs():
    golfScoreFile = open('golfRecords.txt','r')
    lineCount = 1
    for line in golfScoreFile:
        golfRecLine = lineCount % 2
        if(golfRecLine == 0):
            print("The score of this person is: ",line)
        if(golfRecLine == 1):
            print("The name of this person is: ",line)
        lineCount = lineCount + 1
    golfScoreFile.close()

# call main

main()


# PreferenceTool
from DateTime import DateTime

software_version = context.ERP5Site_getSoftwareReleaseTagVersion()

portal = context.getPortalObject()

preference = portal.portal_preferences.getActiveSystemPreference()
preference.edit(
  preferred_credential_alarm_automatic_call=1,
  preferred_credential_recovery_automatic_approval=1,
  preferred_credential_request_automatic_approval=1,
  preferred_authentication_policy_enabled=1
)

try:
  kvm_product = context.software_product_module["kvm"]
except KeyError:
  kvm_product = context.software_product_module.newContent(
    id="kvm",
    title="KVM",
    product_line ="software/application",
    reference="kvm",
    portal_type="Software Product"
  )

if kvm_product.getValidationState() == "draft":
  kvm_product.publish()

try:
  kvm_software_release = context.software_release_module["kvm"]
except KeyError:
  kvm_software_release = context.software_release_module.newContent(
    id="kvm",
    title="KVM",
    portal_type="Software Release",
    version="0.1",
    language="en",
    effective_date=DateTime('2018/03/14 00:00:00 UTC'),
    aggregate="software_product_module/kvm"
  )

kvm_software_release.edit(
  url_string="https://lab.nexedi.com/nexedi/slapos/raw/%s/software/kvm/software.cfg" % software_version,
)

if kvm_software_release.getValidationState() == "draft":
  kvm_software_release.publishAlive()

try:
  theia_product = context.software_product_module["theia"]
except KeyError:
  theia_product = context.software_product_module.newContent(
    id="theia",
    title="Theia",
    product_line ="software/application",
    reference="theia",
    portal_type="Software Product"
  )

if theia_product.getValidationState() == "draft":
  theia_product.publish()

try:
  theia_software_release = context.software_release_module["theia"]
except KeyError:
  theia_software_release = context.software_release_module.newContent(
    id="theia",
    title="Theia",
    portal_type="Software Release",
    version="0.1",
    language="en",
    effective_date=DateTime('2018/03/14 00:00:00 UTC'),
    aggregate="software_product_module/theia"

  )

theia_software_release.edit(
  url_string="https://lab.nexedi.com/nexedi/slapos/raw/%s/software/theia/software.cfg" % software_version
)

if theia_software_release.getValidationState() == "draft":
  theia_software_release.publishAlive()

try:
  erp5_product = context.software_product_module["erp5"]
except KeyError:
  erp5_product = context.software_product_module.newContent(
    id="erp5",
    title="ERP5",
    product_line ="software/application",
    reference="erp5",
    portal_type="Software Product"
  )

if erp5_product.getValidationState() == "draft":
  erp5_product.publish()

try:
  erp5_software_release = context.software_release_module["erp5"]
except KeyError:
  erp5_software_release = context.software_release_module.newContent(
    id="erp5",
    title="ERP5",
    portal_type="Software Release",
    version="0.1",
    language="en",
    effective_date=DateTime('2018/03/14 00:00:00 UTC'),
    aggregate="software_product_module/erp5"
  )

erp5_software_release.edit(
  url_string="https://lab.nexedi.com/nexedi/slapos/raw/%s/software/erp5/software.cfg" % software_version,
)

if erp5_software_release.getValidationState() == "draft":
  erp5_software_release.publishAlive()

# some are already indexed
kw = {'portal_type': ('Authentication Event', 'Passoword Event')}
for authentication_event in portal.portal_catalog(**kw):
  portal.system_event_module.manage_delObjects(ids=[authentication_event.getId()])

notification_message_to_enable = [
  'slapos-upgrade-instance-tree.notification',
  'slapos-upgrade-delivered-instance-tree.notification',
  'slapos-upgrade-compute-node.notification',
  'slapos-upgrade-delivered-compute-node.notification',
]

for reference in notification_message_to_enable:
  search_kw = dict(portal_type='Notification Message',
    reference=reference)
  if not len(portal.portal_catalog(validation_state='validated', **search_kw)):
    portal.portal_catalog.getResultValue(validation_state='draft',
      **search_kw).validate()

# Create an manager user
try:
  demo_manager_user = context.person_module["demo_manager_user"]
except KeyError:
  demo_manager_user = context.person_module.newContent(
    id="demo_manager_user",
    title="Demo Manager Functional User",
    portal_type="Person",
    email="x@example.com"
  )

try:
  demo_manager_assignment = demo_manager_user["manager_assignment"]
except KeyError:
  demo_manager_assignment = demo_manager_user.newContent(
    id="manager_assignment",
    title="Demo Manager Functional User Assignment",
    portal_type="Assignment",
  )

demo_manager_assignment.setGroup('company')

if demo_manager_assignment.getValidationState() != "open":
  demo_manager_assignment.open()

try:
  demo_manager_login = demo_manager_user["demo_manager_login"]
except KeyError:
  demo_manager_login = demo_manager_user.newContent(
    id="demo_manager_login",
    portal_type="ERP5 Login",
    reference="demo_manager_functional_user"
  )
  demo_manager_login.setPassword("czz4yt36mshT*")

if demo_manager_login.getValidationState() != "validated":
  demo_manager_login.validate()

return "Done."


import sqlite3
import pandas as pd
import numpy as np
import os
from tqdm import tqdm
import sys
import cv2
from ast import literal_eval

sub_set0 = '/home/dataset/AFLW/aflw/data/flickr/0'
sub_set2 = '/home/dataset/AFLW/aflw/data/flickr/2'
info_dir = '/home/dataset/AFLW/aflw/data/flickr/'

data_dir ='/home/dataset/AFLW/MTCNN/'
pos_dir = '/home/dataset/AFLW/MTCNN/pos'

sqlite_path = '/home/dataset/AFLW/aflw/data/aflw.sqlite'
need_land_mark_index = (8,11,15,18,20)
con = sqlite3.connect(sqlite_path)

def Make_info():
    maker_info(sub_set0,os.path.join(info_dir,'info_set0.csv'))
    maker_info(sub_set2,os.path.join(info_dir,'info_set2.csv'))
def maker_info(set_dir,save_name):
    file_list = os.listdir(set_dir)
    print(len(file_list))
    coloms = ['file_name']
    data_frame = []
    for file_name in tqdm(file_list,file=sys.stdout):
        line = []
        file_path = os.path.join(set_dir,file_name)
        faceid=get_faceid(file_name)
        if faceid is None:
            continue
        # add face id
        line.append(faceid)
        # add file path
        line.append(file_path)
        # add rect
        line.append(list(get_rect(faceid)))
        # get landmark
        land_mark = get_landmark(faceid)
        lm_dic = {8:[0,0],11:[0,0],15:[0,0],18:[0,0],20:[0,0]}
        for lm in land_mark:
            lm_dic[lm[0]] = list(lm[1:])
        lm_list = []
        for p in lm_dic.values():
            lm_list.extend(p)
        line.append(lm_list)
        data_frame.append(line)
    df=pd.DataFrame(data_frame)
    df.to_csv(save_name)
def read_fromsqlite():
    c = con.cursor()
    res = c.execute("select name from sqlite_master where type = 'table' order by name")
    print(res.fetchall())
    res2 = c.execute("select * from FaceImages")
    print(res2.fetchmany(50))
def get_faceid(file_name):
    c = con.cursor()
    res = c.execute("select face_id from Faces where file_id=?",[file_name])
    r = res.fetchone()
    if r is None:
        return None
    return r[0]
def get_rect(face_id):
    c = con.cursor()
    res = c.execute("select x,y,w,h from FaceRect where face_id=?", [face_id])
    return res.fetchone()
def get_landmark(face_id):
    c = con.cursor()
    res = c.execute("select feature_id,x,y from FeatureCoords where feature_id in {} and face_id={}".format(str(need_land_mark_index),face_id))
    return res.fetchall()
def do_make(positive_dir,infos,save_info):
    from uuid import uuid4
    data_infos = []
    for info in infos:
        data_infos.append(pd.read_csv(info))
    df = pd.concat(data_infos)
    frame = []
    for idx in tqdm(range(df.shape[0]),file=sys.stdout):
        line=[]
        file_path, rect, landmark = df.iloc[idx,2:]
        rect = literal_eval(rect)
        if rect[0]<0 or rect[1]<0 or rect[2]<=0 or rect[3]<=0:
            continue
        landmark = literal_eval(landmark)
        img = cv2.imread(file_path)
        # img = cv2.rectangle(img,(rect[0],rect[1]),(rect[0]+rect[2],rect[1]+rect[3]),color=(0,0,255),thickness=2)
        face_img = img[rect[1]:rect[1] + rect[3], rect[0]:rect[0] + rect[2]]
        if len(face_img)==0:
            continue
        lm_list = []
        for i in range(0,len(landmark),2):
            x1 = int(landmark[i])
            y1 = int(landmark[i+1])
            if x1 !=0 and y1 !=0:
                x_n,y_n=(x1-rect[0])/rect[2],(y1-rect[1])/rect[3]
                lm_list.append(x_n)
                lm_list.append(y_n)
            else:
                lm_list.append(0.)
                lm_list.append(0.)
        fp = os.path.join(positive_dir,'{}.jpg'.format(uuid4()))
        line.append(fp)
        line.extend(lm_list)
        cv2.imwrite(fp,face_img)
        frame.append(line)
    new_info = pd.DataFrame(frame)
    new_info.to_csv(save_info)
if __name__ == '__main__':
    do_make(pos_dir,[os.path.join(info_dir,'info_set0.csv'),os.path.join(info_dir,'info_set2.csv')],os.path.join(data_dir,'data_info.csv'))


#!/usr/bin/env python3
# Поиск VLANов коммутатора на терминирующем маршрутизаторе
import sys
import codecs
import re

class Tee(object):
    # Output on the console and file

    def __init__(self, *files):
        self.files = files

    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush() # The output to be visible immediately

    def flush(self):
        for f in self.files:
            f.flush()

# Конфигуационные файлы коммутатора и маршрутизатора
# show | display set | save /var/tmp/switch.conf
switch_conf = 'spbr-astk1.conf'
# show | display set | save /var/tmp/router.conf
router_conf = 'spbr-ar2.conf'

# Файл вывода результатов
f_out = 'a.out'

# Интерфейсы коммутатора
# в сторону маршрутизатора
switch_ifd = ' ge-0/0/1 '
# в сторону коммутаторов связанных с маршрутизатором
switch_to_sw_ifd = [' ge-0/0/14 ', ' ge-0/0/21 ']

# Интерфейсы маршрутизатора
# регулярное выражение для всех лог. интерфейсов (ifl) в сторону коммутатора
router_ifl_regex = re.compile('xe-9/3/3.\w+')
# в сторону всех коммутаторов
router_ifd = [' xe-0/0/2 ', ' xe-4/1/2 ', ' xe-5/3/0 ', ' xe-8/0/0 ', ' xe-9/3/3 ']

def main():
    # Объявление глобальных переменных
    global switch_conf, router_conf, f_out
    global switch_ifd, switch_to_sw_ifd, router_ifl_regex, router_ifd

    with open(f_out, 'w') as f_out:
        # This will go to stdout and the file
        original = sys.stdout
        sys.stdout = Tee(sys.stdout, f_out)

        switch_conf = codecs.open(switch_conf, 'r', encoding='utf-8', errors='ignore').read()
        switch_conf = switch_conf.splitlines()
        router_conf = codecs.open(router_conf, 'r', encoding='utf-8', errors='ignore').read()
        router_conf = router_conf.splitlines()

        # Находим все VLANы на физ. интерфейсе (ifd) коммутатора
        # Создаём словарь sw_vlans {ifd: [VLANs]}
        sw_vlans = {}
        for line in switch_conf:
            if switch_ifd in line:
                if 'vlan members' in line:
                    line = str(line).split(' ')
                    key = line[2].strip()
                    value = line[9].strip()
                    if '-' in value:
                        value = str(value).split('-')
                        value = list(range(int(value[0]), int(value[1])+1))
                    else:
                        value = int(value.split()[-1])
                    if key not in sw_vlans:
                        sw_vlans.setdefault(key, []).append(value)
                    else:
                        if isinstance(value, list):
                            for v in value:
                                sw_vlans[key].append(v)
                        else:
                            sw_vlans[key].append(value)
        # print(sw_vlans)

        # Находим все VLANы на физ. интерфейсах (ifd) маршрутизатора
        # Создаём словарь r_vlans {ifl(ifd.unit): [VLAN]}
        r_vlans = {}
        for line in router_conf:
            for ifd in router_ifd:
                if 'set interfaces' + ifd in line and 'unit' in line:
                    # Для vlan-id
                    if ' vlan-id ' in line and 'input-vlan-map' not in line:
                        line = str(line).split(' ')
                        key = line[2].strip() + '.' + line[4].strip()
                        value = line[6].strip()
                        value = int(value.split()[-1])
                        if key not in r_vlans:
                            r_vlans.setdefault(key, []).append(value)
                        else:
                            r_vlans.key = value
                    # Для QinQ
                    elif 'vlan-tags outer' in line:
                        line = str(line).split(' ')
                        key = line[2].strip() + '.' + line[4].strip()
                        value = line[7].strip()
                        value = int(value.split()[-1])
                        if key not in r_vlans:
                            r_vlans.setdefault(key, []).append(value)
                        else:
                            r_vlans.key = value
        # print(r_vlans)

        # Находим общие значения двух словарей (VLANы) и создаём словарь r_sw_vlans {ifl(ifd.unit): [VLAN]}
        r_sw_vlans = {}
        for sw_k, sw_v in sw_vlans.items():
            for r_k, r_v in r_vlans.items():
                for i in sw_v:
                    for j in r_v:
                        if i == j:
                            r_v = ''.join(str(e) for e in r_v)
                            if r_k not in r_sw_vlans:
                                r_sw_vlans.setdefault(r_k, []).append(int(r_v))
                            else:
                                r_sw_vlans.r_k = int(r_v)
        # print(r_sw_vlans)

        # Находим все VLANы на физ. интерфейсах (ifd) коммутатора в сторону других коммутаторов
        # Создаём словарь sw_sw_vlans {ifd: [VLANs]}
        sw_sw_vlans = {}
        for line in switch_conf:
            for ifd in switch_to_sw_ifd:
                if ifd in line:
                    if 'vlan members' in line:
                        line = str(line).split(' ')
                        key = line[2].strip()
                        value = line[9].strip()
                        if '-' in value:
                            value = str(value).split('-')
                            value = list(range(int(value[0]), int(value[1])+1))
                        else:
                            value = int(value.split()[-1])
                        if key not in sw_sw_vlans:
                            sw_sw_vlans.setdefault(key, []).append(value)
                        else:
                            if isinstance(value, list):
                                for v in value:
                                    sw_sw_vlans[key].append(v)
                            else:
                                sw_sw_vlans[key].append(value)
        # print(sw_sw_vlans)

        # Сравниваем словарь r_sw_vlans и sw_sw_vlans
        for r_sw_k, r_sw_v in r_sw_vlans.items():
            # Если ifd смотрит на маршрутизатор, то выводим сразу
            if re.findall(router_ifl_regex, r_sw_k):
                print(r_sw_k, r_sw_v)
            else:
                # Или делаем проверку, что VLANы смотрят в сторону других коммутаторов
                for sw_sw_k, sw_sw_v in sw_sw_vlans.items():
                    if not re.findall(router_ifl_regex, r_sw_k):
                        for i in sw_sw_v:
                            for j in r_sw_v:
                                if i == j:
                                    print(r_sw_k, r_sw_v)

        sys.stdout = original
        # Only on stdout

if __name__ == "__main__":
    main()


import numpy as np
import matplotlib.pyplot as plt

from scipy import signal
from scipy.io import wavfile

from hidden_markov import hmm

fs, data = wavfile.read('C:/home/stefan/PRA/morse.wav')

# spectral representation
f, t, S = signal.spectrogram(data, fs)

fmin = 550 # Hz
fmax = 700 # Hz
freq_slice = np.logical_and(f >= fmin, f <= fmax)
print(freq_slice)
f1 = f[freq_slice]
S1 = S[freq_slice]
#t1 = t[freq_slice]

plt.figure(0) # spectrogram
plt.pcolormesh(t, f1, S1)
plt.ylabel('frequency [Hz]')
plt.xlabel('time [sec]')
plt.title('spectrogram')
plt.show()


import onnxruntime
import torch

def ffun_onnx(pretrained_dict_y):
    dd = {}
    for k, v in pretrained_dict_y.items():
        dd[k.replace('net.', '')] = v
    return dd

if __name__ == '__main__':
    import os

    from ftools.ai.CONFIG_BASE import FCFG_BASE
    from ftools.ai.fits.fweight import load_weight
    from nanodet.net.net_nanodet import NetNanodet
    from nanodet.net.shufflenetv2 import ShuffleNetV2

    cfg = FCFG_BASE()
    cfg.NUM_CLASSES = 3
    cfg.anc_scale = 5  # 这个是anc大小,关系到regmax的设置, 这个值越大匹配的anc与真实的GT的距离(最大和最小值)越大  octave_base_scale
    cfg.reg_max = 7  # 特图差距最大值7 分成8份
    cfg.device = torch.device('cpu')
    cfg.SIZE_WH_INPUT_TRAIN  = (320, 320)

    backbone = ShuffleNetV2(model_size='1.0x', )
    backbone.dims_out = (116, 232, 464)
    model = NetNanodet(backbone, num_class=3, reg_max=7)

    path_root_weight = r'M:\AI\weights\feadre\zz'
    _file_read_weight = os.path.join(path_root_weight, 'nanodet_type3_44_11.89_p75.6_r62.7' + '.pth')

    start_epoch = load_weight(file_weight=_file_read_weight, model=model,
                              optimizer=None, lr_scheduler=None,
                              device=cfg.device, ffun=ffun_onnx)

    batch = 1
    num_end = 10
    data_ts = torch.rand((batch, 3, *cfg.SIZE_WH_INPUT_TRAIN ), dtype=torch.float)
    reses = model(data_ts)

    for res in reses:
        print(res.reshape(batch, -1)[:, :num_end])

    # 验证
    file_onnx = 'yolov1.onnx'
    input_names = ['input']
    output_names = ['pcls', 'pt_ltrb']

    torch.onnx.export(model, data_ts, file_onnx, verbose=True,
                      input_names=input_names,
                      output_names=output_names,
                      dynamic_axes=None,
                      opset_version=11,
                      )

    onnx_session = onnxruntime.InferenceSession(file_onnx)
    res_onnx = onnx_session.run(
        output_names=output_names,
        input_feed={input_names[0]: data_ts.numpy()})

    for res in res_onnx:
        print(res.reshape(batch, -1)[:, :num_end])
    print('debug')


import ee
import geemap

# Create a map centered at (lat, lon).
Map = geemap.Map(center=[40, -100], zoom=4)

point = ee.Geometry.Point(-98.7011, 47.2624)
collection = ee.ImageCollection('LANDSAT/LC8_L1T_TOA') \
  .filterBounds(point) \
  .filterDate('2016-01-01', '2018-12-31')

# print(collection)

new_col = ee.Algorithms.Landsat.pathRowLimit(collection, 15, 100)
# print(new_col)

median = new_col.median()
vis = {'bands': ['B5', 'B4', 'B3'], 'max': 0.3}

Map.setCenter(-98.7011, 47.2624, 10)
Map.addLayer(median, vis, 'Median')

# Display the map.
Map


import os
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.utils as utils
from torch.autograd import Variable
from torch.utils.data import DataLoader
from tensorboardX import SummaryWriter
import sys
sys.path.append('/PReNet')
from PReNet.dataprep import *
from PReNet.utils import *
from torch.optim.lr_scheduler import MultiStepLR
from PReNet.SSIM import SSIM
from PReNet.generator import *

if torch.cuda.is_available():
	print('using gpu training ...')

def main():
	print('Loading dataset ...\n')
	dataset_train= Dataset(data_path= 'datasets/')
	loader_train= DataLoader(dataset= dataset_train)
	print('# of training samples :', int(len(loader_train)))
	# define some hyper-parameters
	recurr_iter= 4
	use_GPU= True
	model_path= 'logs/real/PReNet1.pth'
	num_epochs= 5

	model= Generator_lstm(recurr_iter, use_GPU)
	print_network(model)
	model.load_state_dict(torch.load(model_path))

	#loss
	criterion= SSIM()

	if use_GPU:
		model= model.cuda()
		criterion.cuda()

	#optimizer:
	optimizer= optim.Adam(model.parameters(), lr= 1e-4)
	scheduler = MultiStepLR(optimizer, milestones=[20,40], gamma=0.1)

	#record training
	writer= SummaryWriter('logs/')
	step=0
	for epoch in range(num_epochs):
		print('Epoch {}/{}'.format(epoch, num_epochs - 1))
		print('-' * 10)

		for i, (input_train, target_train) in enumerate(loader_train,0):
			input_train, target_train= Variable(input_train), Variable(target_train)
			if use_GPU:
				input_train, target_train= input_train.cuda(), target_train.cuda()
			optimizer.zero_grad()

			model.train()
			out_train,_ =model(input_train)
			pixel_metric= criterion(target_train, out_train)
			loss= -pixel_metric

			loss.backward()
			optimizer.step()

			model.eval()
			out_train, _ = model(input_train)
			out_train = torch.clamp(out_train, 0., 1.)
			print("[epoch %d][%d/%d] loss: %.4f, pixel_metric: %.4f" %
                  (epoch+1, i+1, len(loader_train), loss.item(), pixel_metric.item()))

			if step%10==0:
				writer.add_scalar('loss', loss.item(), step)
			step+=1

		model.eval()
		out_train,_ = model(input_train)
		out_train= torch.clamp(out_train,0.,1.)
		im_target= utils.make_grid(target_train.data, nrow=8, normalize=True, scale_each=True)
		im_input= utils.make_grid(input_train.data, nrow=8, normalize=True, scale_each=True)
		im_derain= utils.make_grid(out_train.data, nrow=8, normalize=True, scale_each=True)
		writer.add_image('clean image', im_target, epoch+1)
		writer.add_image('rainy image', im_input, epoch+1)
		writer.add_image('derained image', im_derain, epoch+1)

		torch.save(model.state_dict(), 'logs/real/latest.pth')

if __name__ == '__main__':
	main()


__author__ = 'Alexandre Fayette/Julien Leseine/Mathieu Pequin'

from src import *

class Card:
    #Fonction d'initialisation#
    def __init__(self, name, attack, health, cost, shield, hidden, taunt, use):
        self.name = name
        self.attack = attack
        self.health = health
        self.cost = cost
        self.shield = shield
        self.hidden = hidden
        self.taunt = taunt
        self.use = use

    #Redéfinition de la fonction d'égalité " == " (pas identité) #
    def __eq__(self, other):
         return (self.name == other.name and self.health == other.health and self.attack == other.attack and
                self.cost == other.cost and self.shield == other.shield and self.hidden == other.hidden and
                self.taunt == other.taunt)

    def print_card(self, display_mana=True):
        if self.shield != 0:
            shield = "S:" + str(self.shield)
        else:
            shield = ""

        if self.hidden != 0:
            hidden = "H"
        else:
            hidden = ""

        if self.taunt != 0:
            taunt = "T"
        else:
            taunt = ""

        if display_mana:
            print(self.name, "(", self.attack, "/", self.health, ") :", self.cost, " ", shield, " ", hidden, " ", taunt)

        else:
            print(self.name, " ( ", self.attack, "/", self.health, ") ", shield, " ", hidden, " ", taunt)

    #C#
    def take_damage(self, damage):
        if self.shield > 0:
            self.shield -= damage
            self.health -= abs(self.shield)
        else:
            self.health -= damage

    def fight_card(self, card):
        self.hidden = 0
        self.use = 0
        print("Vous attaquez ", card.get_name(), " (", card.get_attack(), "|", card.get_health(), ") avec ", self.name,
              " (", self.attack, "|", self.health, ")")
        card.take_damage(self.attack)
        self.take_damage(card.attack)

    def fight_attempt(self, player2, idx):
        if not idx.isnumeric():
            return False
        if int(idx) == 0:
            for element in player2.field:
                if (element.taunt == 1):
                    print("Impossible d'attaquer le joueur, ", element.name, " a la capacité de provocation")
                    return False
            self.use = 0
            print("Vous infligez ", self.attack, " à ", player2.name)
            player2.take_damage(self)
            return True
        attackable = True
        for element in player2.field:
            if (element.taunt == 1) and (element != player2.field[int(idx)-1]):
                attackable = False
                print("Vous ne pouvez pas attaquer cette carte, car ", element.name, " a la capacité de provocation !")
        if player2.field[int(idx)-1].hidden == 1:
            attackable = False
            print("Ce monstre est camouflé, vous ne pouvez pas l'attaquer !")
        if attackable:
            self.fight_card(player2.field[int(idx)-1])
            return True
        else:
            return False


import time

import constants
from apis import getBoardStrings, makeMove, createGame, getMoves, getMoveOpponent
from board import Board
from constants import dimensions, target
from minimax import minimax

def startGame(gameId, team2Id, firstMove=False):
    print("Started Game")
    flag = True
    if gameId == 0:
        gameId = createGame(team2Id, dimensions, target)
        firstMove = True
        print(gameId)
        time.sleep(2)
    boardString = getBoardStrings(gameId)
    board = Board(boardString["size"], boardString["target"])
    if firstMove:
        startx = starty = board.middle
        moved = makeMove(gameId, str(startx) + "," + str(starty))
        if moved["code"] == "OK":
            firstMove = False
            board.add_symbol((startx, starty), 1)
            print(board.board)
            board.showBoard()
            time.sleep(2)
            lastMove = getMoves(gameId, 1)
            moveX, moveY = lastMove["x"], lastMove["y"]
            while moveX == startx and moveY == starty:
                time.sleep(2)
                lastMove = getMoves(gameId, 1)
                moveX, moveY = lastMove["x"], lastMove["y"]
            x, y = lastMove["x"], lastMove["y"]
            board.add_symbol((x, y), -1)
            print(board.board)
            board.showBoard()
    else:
        while getMoveOpponent(gameId, 1) == "FAIL":
            time.sleep(2)
        lastMove = getMoves(gameId, 1)
        x, y = lastMove["x"], lastMove["y"]
        board.add_symbol((x, y), -1)
        print(board.board)
        board.showBoard()
    while flag:
        moveMade, point = game(gameId, board)
        time.sleep(2)
        if moveMade["code"] == "FAIL":
            time.sleep(2)
        else:
            board.add_symbol([point[0], point[1]], 1)
            board.isGameOver(point, 1)
            print("our move:")
            print(board.board)
            board.showBoard()
            lastMove = getMoves(gameId, 1)
            moveX, moveY = lastMove["x"], lastMove["y"]
            while moveX == point[0] and moveY == point[1]:
                time.sleep(3)
                lastMove = getMoves(gameId, 1)
                moveX, moveY = lastMove["x"], lastMove["y"]
            x, y = lastMove["x"], lastMove["y"]
            board.add_symbol((x, y), -1)
            print("opponent move:")
            print(board.board)
            board.showBoard()

def game(gameId, board):
    print("Starting minimax")
    openSpaces = len(board.get_open_spaces())
    if openSpaces > 30:
        constants.maxDepth = 2
    elif openSpaces > 20:
        constants.maxDepth = 3
    elif openSpaces > 10:
        constants.maxDepth = 4
    else:
        constants.maxDepth = 10
    value, points = minimax(board, 0, [])
    print(points)
    moveCoordinates = formatCoordinates(points)
    return makeMove(gameId, moveCoordinates), points

def formatCoordinates(points):
    return str(points[0]) + "," + str(points[1])


import pymongo
import requests
from datetime import datetime, timedelta

def date_format():
    return '%Y-%m-%dT%H:%M:%S.%fZ'

def get_latency(form_data):

    latency = 0
    last = None
    for i, data in enumerate(form_data):
        if i == 0:
            last = datetime.strptime(data["date"], date_format())
            continue

        now = datetime.strptime(data["date"], date_format())
        latency += now - last
        last = now

    latency /= len(form_data)

    return latency

def get_data_formated(network, gemini, init, end, train=False):
    # {
    #   "network": <network>,
    #   "last_update": <att>,
    #   "data": [{
    #       "id": <id>,
    #       "x": 0,
    #       "y": 0,
    #       "z": 0,
    #       "date": <date>
    #    }, (...) ]
    #   }, (...) ]
    # }

    get_params1 = f"startDate={init}&endDate={end}"
    get_params2 = f"deviceType=Tag&network={network}&geminiId={gemini}"

    res = requests.get(f"http://indoorsense.ddns.net:4000/api/root/gemini/save-value?{get_params1}&{get_params2}")
    data = res.json()

    formated = []
    for d in data:
        if train:
            formated.append({
                "id": d["deviceId"],
                "x": d["value"]["fv"]["x"],
                "y": d["value"]["fv"]["y"],
                "z": d["value"]["fv"]["z"],
                "date": d["when"]
            })
        else:
            formated.append({
                "geminiId": d["geminiId"],
                "network": d["value"]["nw"],
                "groupId": d["groupId"],
                "type": d["value"]["dt"],
                "id": d["deviceId"],
                "x": d["value"]["fv"]["x"],
                "y": d["value"]["fv"]["y"],
                "z": d["value"]["fv"]["z"],
                "date": d["when"]
            })

    return formated


# EXERCICIO 045 - PEDRA PAPEL TESOURA

from random import randint

itens  = ['Pedra','Papel','Tesoura']
computador = randint(0,2)

print('''Suas opções:
[0] PEDRA
[1] PAPEL
[2] TESOURA''')

jogador = int(input('Qual a sua opção: '))

print('''O computador jogou {}
E o jogador jogou {}'''.format(itens[computador],itens[jogador]))

if computador == 0:
    if jogador == 0:
        print('Empatou!')
    elif jogador == 1:
        print('Jogador venceu!')
    elif jogador == 2:
        print('Computador venceu!')
    else:
        print('Jogada Inválida!')
elif computador == 1:
    if jogador == 0:
        print('Computador venceu!')
    elif jogador == 1:
        print('Empatou!')
    elif jogador == 2:
        print('Jogador venceu!')
    else:
        print('Jogada Inválida!')
elif computador == 2:
    if jogador == 0:
        print('Jogador venceu!')
    elif jogador == 1:
        print('Computador venceu!')
    elif jogador == 2:
        print('Empatou!')
    else:
        print('Jogada Inválida!')


import pygame

from models.board import Board
from models.score import Score
from models.paddle import Paddle
from models.ball import Ball
from repositories.settings_repository import SettingsRepository
from ui.settings_dialog import SettingsDialog

class Pong:

    def __init__(self):
        self.settingsRepository = SettingsRepository('../state/settings.bin')
        self.setting = self.settingsRepository.read()
        self.settingsDialog = SettingsDialog(self.setting, self)

        pygame.init()
        pygame.display.set_caption('Pong')

        self.board = Board((self.setting.boardWidth, self.setting.boardHeight))
        self.score = Score(self.board)
        self.ball = Ball(self.board)
        self.paddle1 = Paddle(self.board)
        self.paddle2 = Paddle(self.board, left=False)

        self.userPlayer1Controller = self.setting.get_controller1(self.paddle1)
        self.userPlayer2Controller = self.setting.get_controller2(self.paddle2)

        self.gameOn = False

    def save_setting(self, setting):
        self.setting = setting
        self.settingsRepository.write(self.setting)

        self.board = Board((self.setting.boardWidth, self.setting.boardHeight))
        self.score = Score(self.board)
        self.ball = Ball(self.board)
        self.paddle1 = Paddle(self.board)
        self.paddle2 = Paddle(self.board, left=False)

        self.userPlayer1Controller = self.setting.get_controller1(self.paddle1)
        self.userPlayer2Controller = self.setting.get_controller2(self.paddle2)

    def game_on(self):
        self.gameOn = True
        self.game_loop()

    def game_off(self):
        self.gameOn = False

    def game_loop(self):
        while self.gameOn:
            self.event_check()

            self.userPlayer1Controller.did_paddle_move_alone(self.ball)
            self.userPlayer2Controller.did_paddle_move_alone(self.ball)

            score1 = self.ball.did_hit(self.paddle1)
            score2 = self.ball.did_hit(self.paddle2)

            miss1 = self.paddle1.did_miss(self.ball)
            miss2 = self.paddle2.did_miss(self.ball)

            self.score.player1 += miss2
            self.score.player2 += miss1

            self.board.render()
            self.score.render()
            self.ball.render()
            self.paddle1.render()
            self.paddle2.render()

            pygame.display.flip()

            image_data = pygame.surfarray.array3d(pygame.display.get_surface())

            self.userPlayer1Controller.learn(image_data, score1 - miss1)
            self.userPlayer2Controller.learn(image_data, score2 - miss2)

    def game_did_end(self, event):
        """
        Check if the game quit and the app closed.
        :param event:
        """
        if event.type == pygame.QUIT:
            self.game_off()
            self.userPlayer1Controller.resign()
            self.userPlayer2Controller.resign()

    def event_check(self):
        for event in pygame.event.get():
            self.score.did_reset(event)
            self.game_did_end(event)
            self.ball.event_check(event)

            self.userPlayer1Controller.did_paddle_move(event, self.ball)
            self.userPlayer2Controller.did_paddle_move(event, self.ball)

            self.userPlayer1Controller.should_learn(event)
            self.userPlayer2Controller.should_learn(event)

            self.settingsDialog.should_display(event, self.setting)

pong = Pong()
pong.game_on()


from collections import deque
import sys
input = sys.stdin.readline

def bfs(start):
    queue = deque([start])
    cnt = 0
    visited = [False]*(n+1)
    visited[start] = True
    while queue:
        now = queue.popleft()
        for next in graph[now]:
            if not visited[next]:
                queue.append(next)
                visited[next] = True
                cnt += 1
    return cnt

n,m = map(int,input().rstrip().split())
graph = [[] for _ in range(n+1)]
for i in range(m):
    x,y = map(int,input().rstrip().split())
    graph[y].append(x)

result = []
max_cnt = -sys.maxsize

for i in range(1,n+1):
    cnt = bfs(i)
    if cnt > max_cnt:
        max_cnt = cnt
        result = [i]
    elif cnt == max_cnt:
        result.append(i)

print(*result)


import logging

import greenaddress as gdk

from green_cli import context

class Session(gdk.Session):

    def __init__(self, net_params):
        super().__init__(net_params)
        self.current_block_height = None

    def callback_handler(self, event):
        logging.debug("Callback received event: {}".format(event))
        try:
            if event['event'] == 'network' and event['network'].get('login_required', False):
                logging.debug("Setting logged_in to false after network event")
                context.logged_in = False

            if event['event'] == 'block':
                self.current_block_height = event['block']['block_height']
                logging.debug(f"Updated current block height to {self.current_block_height}")
        except Exception as e:
            logging.error("Error processing event: {}".format(str(e)))

        super().callback_handler(event)


import glob
import re
import os
import fnmatch

path = "D:/SAP-C/UpStream/Database"
file_list = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in fnmatch.filter(files, '*.sql')]
#new_path = path + "/NEW"
#file_list = glob.glob(path + "*.sql")
for f in file_list:
    print("reading from {}".format(f))
    fp = open(f, encoding = 'utf-8', mode='r')
    nf = re.sub('Database', 'Database_NEW', os.path.split(f)[0]) + "/" + os.path.split(f)[1]
    print("writing into {}".format(nf))
    new_fp = open(nf, encoding = 'utf-8', mode = 'w')
    string = fp.read()

    #########
    string = re.sub('MODEL', 'REFERENCE', string)
    string = re.sub('ODS', 'FINHUB', string)
    string = re.sub('SRC\.', 'FINHUB.', string)
    string = re.sub('TSDMDL16K', 'TSDCTL16K', string)
    string = re.sub('TSIMDL16K', 'TSICTL16K', string)
    #########

    new_fp.write(string)
    fp.close()
    new_fp.close()


import matplotlib.pyplot as pl
import numpy as np
import matplotlib.animation as animation
import math
import sys

fig, ax = pl.subplots()
ns_quiv = None
psol_quiv = None
ns_txt = None
psol_txt = None
ns_vec_scalar = 0
state = "up"

def draw_quiv(o, v, c, z):
	return ax.plot([o[0], o[0] + v[0]], [o[1], o[1] + v[1]], color=c, zorder=z, lw=3)[0]
	#return ax.quiver(o[0], o[1], v[0], v[1], color=c, angles='xy', scale_units='xy', scale=1, zorder=z)

def init():
    global ns_quiv
    global ns_vec
    global psol_quiv
    global psol_vec
    global ns_txt
    global psol_txt
    global ns_vec_scalar

    z_vec         = np.array([0., 0.])
    ns_vec        = np.array([2./3., 1.])
    psol_vec      = np.array([3., 0.])

    # Quivers to draw the null space vector and the particular solution that we will
    # animate.
    ns_quiv   = draw_quiv(z_vec, ns_vec, 'r', 2)
    psol_quiv = draw_quiv(ns_vec, psol_vec, 'cyan', 2)

    # Plot lines representing the null space, row space and solution set.
    # They go "off" the x/y axis limits to make them look infinite.
    ax.plot([-10, 10], [-15, 15], color='r', zorder=0, alpha=0.5)
    ax.plot([-10, 10], [20.0/3.0, -20.0/3.0], color='b', zorder=0, alpha=0.5)
    ax.plot([-7, 13], [-15, 15], color='g', zorder=0, alpha=0.5)

    # Draw grid and set limits so that the space lines look infinite
    ax.grid();
    ax.set_xlim(-5, 5)
    ax.set_ylim(-5, 5)

    ns_txt   = ax.text((ns_vec / 2.)[0], (ns_vec / 2.)[1], r'$\alpha \vec{n_o}\in \mathrm{N}(A)$')
    psol_txt = ax.text((psol_vec / 2 + ns_vec)[0], (psol_vec / 2 + ns_vec)[1], r'$[3, 0]$')

    ax.annotate( r'Solution set'
               , xy=(.75, -3.4)
               , xytext=(10, -40)
               , textcoords='offset points'
               , fontsize='medium'
               , arrowprops=dict(facecolor='green', shrink=0.05, connectionstyle="arc3,rad=0.1", fc="g", alpha=0.5)
    )

    ax.annotate( r'$\mathrm{N}(A)$'
               , xy=(-2, -3)
               , xytext=(-10, 35)
               , textcoords='offset points'
               , fontsize='medium'
               , arrowprops=dict(facecolor='red', shrink=0.05, connectionstyle="arc3,rad=0.1", fc="r", alpha=0.5)
    )

    ax.annotate( r'$\mathrm{C}(A^T)$'
               , xy=(-3, 2)
               , xytext=(-30, -40)
               , textcoords='offset points'
               , fontsize='medium'
               , arrowprops=dict(facecolor='blue', shrink=0.05, connectionstyle="arc3,rad=-0.1", fc="b", alpha=0.5)
    )

def animate(i):
    global ns_quiv
    global ns_vec
    global psol_quiv
    global psol_vec
    global ns_txt
    global psol_txt
    global ns_vec_scalar
    global state

    if state == "up":
      ns_vec_scalar += .1
      if ns_vec_scalar > 3.:
        state = "down"
    else:
      ns_vec_scalar -= .1
      if ns_vec_scalar < -4.9:
        state = "up"

    ns_scaled_vec = ns_vec * ns_vec_scalar
    ns_quiv.set_xdata([0, ns_scaled_vec[0]])
    ns_quiv.set_ydata([0, ns_scaled_vec[1]])

    psol_quiv.set_xdata([ns_scaled_vec[0], ns_scaled_vec[0] + psol_vec[0]])
    psol_quiv.set_ydata([ns_scaled_vec[1], ns_scaled_vec[1] + psol_vec[1]])

    ns_txt.set_x((ns_scaled_vec / 2.)[0])
    ns_txt.set_y((ns_scaled_vec / 2.)[1])
    psol_txt.set_x((psol_vec / 2 + ns_scaled_vec)[0])
    psol_txt.set_y((psol_vec / 2 + ns_scaled_vec)[1])

    return psol_quiv

# init()
# pl.show()
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='James Hume @ www.jeh-tech.com'), bitrate=1800)
ani = animation.FuncAnimation(fig, animate, frames= 30*2 + 49*2+2, init_func=init, interval=100, blit=False)
ani.save('animation.mp4', writer=writer)


def kangaroo(x1,v1,x2,v2):
    if(x1<x2 and v1<v2):
        return 'NO'
    for i in range(1,10000):
        if ((i*v1)+x1)%((i*v2)+x2)==0:
            return 'YES'
    else:
        return 'NO'

    ''' if v1!=v2 and (x2-x1)%(v2-v1)==0:
        return 'YES'
    else:
        return 'NO'
    '''

if __name__=='__main__':
    x1=int(input())
    v1=int(input())
    x2=int(input())
    v2=int(input())
    print(kangaroo(x1,v1,x2,v2))


import math

peoples = int(input())
tax = float(input())
sun_lounger = float(input())
umbrella = float(input())

total_tax = peoples * tax
total_sun_lounger = math.ceil(peoples * 0.75) * sun_lounger
total_umbrella = math.ceil(peoples / 2) * umbrella

total_sum = total_tax + total_sun_lounger + total_umbrella

print(f'{total_sum:.2f} lv.')


import tkinter as tk
from tkinter.colorchooser import askcolor
from algoritmos import bresenham, circulo, curva, preenchrecursivo, preenchscanline
from elementos import *
#
#No manjaro, necessário usar:
# `pacman -S tk`
#
class App(tk.Tk):
    w_bt = 10 # largura dos botões
    frame_buffer_aux = [] # frame_buffer auxiliar
    forma_aux = None
    pivo = None
    formas = []
    def __init__(self, escala=10, largura=600, altura=700, titulo='CG-2019.2'):
        super().__init__()
        # MODOS = LIVRE, LINHA, CIRCULO, BEZIER, PREE_REC, PREE_SCAN, CORTE_LINHA, TRANSLA, ROTAC
        self.title(titulo)
        self.escala = escala
        self.altura = altura//escala # quantidade de linhas (y)
        self.largura = largura//escala # quantidade de colunas (x)
        self.ferramentas = None
        self.canvas = None
        self.frame_buffer = None
        self.lista_box = None
        self.entrada_xy = dict() # x,y,ang
        self.cor = '#000000'
        self.modo = 'LINHA' # modo inicial

    def limpa_buffer(self):
        # inicializa frame buffer
        self.frame_buffer = [['#ffffff' for x in range(self.largura)] for y in range(self.altura)]
        self.forma_aux = None
        self.pinta_buffer()
        self.pivo = None

    def show(self):
        self.canvas = self.cria_canvas() # cria canvas na tela do app
        self.limpa_buffer() # inicializa frame_buffer
        self.cria_eventos() # criação dos eventos de botões e cliques no canvas
        self.ferramentas = self.cria_ferramentas() # cria caixa de ferramentas na tela do app
        largura = (self.largura*self.escala)+((1+self.w_bt)*10) # largura da janela total
        altura = self.altura*self.escala # altura da janela total
        self.geometry("%dx%d+0+0" % (largura,altura)) # dimensões totais da tela do app
        self.resizable(False,False) # não redimensiona a janela
        self.mainloop()

    def cria_ferramentas(self):
        frame_ferramenta = tk.Frame(self) # frame para adicionar auxiliares ao Canvas
        frame_ferramenta.grid(row=0,column=1) # organiza ao lado do canvas (mesma linha, coluna 1)
        # eventos para label_ponto
        label_ponto = tk.Label(frame_ferramenta,text='(00,00)',height=2)
        label_ponto.pack()
        def motion_mouse(event):
            x,y = self.xyscala(event.x,event.y)
            x = '0'+str(x) if x < 10 else str(x)
            y = '0'+str(y) if y < 10 else str(y)
            label_ponto['text'] = '('+x+','+y+')'
        def leave_mouse(event): label_ponto['text']='(00,00)'
        self.canvas.bind('<Motion>',motion_mouse) # executa ao mover mouse sobre o canvas
        self.canvas.bind('<Leave>',leave_mouse) # executa ao retirar o mouse do canvas
        # lista formas
        label_frame = tk.LabelFrame(frame_ferramenta)
        label_frame.pack()
        tk.Label(label_frame,text='Polígonos:').pack()
        self.lista_box = tk.Listbox(label_frame,w=self.w_bt,height=2)
        self.lista_box.pack()
        sub_frame = tk.Frame(label_frame)
        sub_frame.pack()
        bt_add = tk.Button(sub_frame,text='+',command=self.add_forma,width=self.w_bt//3)
        bt_rm = tk.Button(sub_frame,text='-',command=self.rm_forma,width=self.w_bt//3)
        self.lista_box.bind('<Double-Button-1>',lambda e: self.pinta_forma())
        bt_add.grid(row=0,column=0)
        bt_rm.grid(row=0,column=1)
        label_cor = tk.Label(frame_ferramenta,bg=self.cor,width=self.w_bt) # instância do label
        # evento para mudança de cor
        def muda_cor(event):
            _,hex = askcolor(color=self.cor) # método nativo da lib tkinter
            if hex: # se retornar uma cor, e não None (em caso de cancalemento da escolha)
                self.cor = hex
                label_cor.configure(bg=self.cor)
        label_cor.bind('<Button-1>',muda_cor)
        label_cor.pack()
        botoes = self.cria_botoes_modos(frame_ferramenta)
        return {
            'ponto':label_ponto,
            'cor':label_cor,
            'botoes':botoes
        }

    def muda_opcao(self,modo):
        self.modo = modo
        self.cria_eventos()

    def cria_botoes_modos(self,pai):
        w_bt = self.w_bt
        botoes = list()
        botoes.append(tk.Button(pai,text='Limpar',command=self.limpa_buffer,width=w_bt))
        #botoes.append(tk.Button(pai,text='Livre',command=lambda: self.muda_opcao('LIVRE'),width=w_bt))
        botoes.append(tk.Button(pai,text='Linha',command=lambda: self.muda_opcao('LINHA'),width=w_bt))
        botoes.append(tk.Button(pai,text='Círculo',command=lambda: self.muda_opcao('CIRCULO'),width=w_bt))
        botoes.append(tk.Button(pai,text='Bezier',command=lambda: self.muda_opcao('BEZIER'),width=w_bt))
        botoes.append(tk.Button(pai,text='Pre. Rec',command=lambda: self.muda_opcao('PREE_REC'),width=w_bt))
        botoes.append(tk.Button(pai,text='Pre. Scan',command=lambda: self.muda_opcao('PREE_SCAN'),width=w_bt))
        botoes.append(tk.Button(pai,text='Corte Linha',command=lambda: self.muda_opcao('CORTE_LINHA'),width=w_bt))
        botoes.append(tk.Button(pai,text='Corte Poligono',command=lambda: self.muda_opcao('CORTE_POLI'),width=w_bt))
        botoes.append(tk.LabelFrame(pai)) # frame translação
        botoes.append(tk.LabelFrame(pai)) # frame rotação
        botoes.append(tk.LabelFrame(pai)) # frame escala
        botoes.append(tk.LabelFrame(pai)) # frame projeção perspectiva

        # ADICIONAL PARA TRANSLAÇÃO
        conj_translacao = botoes[-4]
        tk.Button(conj_translacao,text='Translação',command=lambda: self.muda_opcao('TRANSLA'),width=w_bt-1).pack()
        tk.Label(conj_translacao,text=' (  X  ,  Y  ) ').pack()
        frame_aux = tk.Frame(conj_translacao)
        frame_aux.pack()
        self.entrada_xy['x'] = tk.StringVar()
        self.entrada_xy['y'] = tk.StringVar()
        tk.Entry(frame_aux,width=w_bt//2,textvariable=self.entrada_xy['x']).grid(row=0,column=0)
        tk.Entry(frame_aux,width=w_bt//2,textvariable=self.entrada_xy['y']).grid(row=0,column=1)

        # ADICIONAL PARA ROTOAÇÃO
        conj_rotacao = botoes[-3]
        tk.Button(conj_rotacao,text='Rotação',command=lambda: self.muda_opcao('ROTAC'),width=w_bt-1).pack()
        tk.Label(conj_rotacao,text=' Grau ( 0º ) ').pack()
        frame_aux = tk.Frame(conj_rotacao)
        frame_aux.pack()
        self.entrada_xy['ang'] = tk.StringVar()
        tk.Entry(frame_aux,width=w_bt//2,textvariable=self.entrada_xy['ang']).grid(row=0,column=0)

        # ADICIONAL ESCALA
        conj_escala = botoes[-2]
        tk.Button(conj_escala,text='Escala',command=lambda: self.muda_opcao('ESCALA'),width=w_bt-1).pack()
        tk.Label(conj_escala,text=' (  X  ,  Y  ) ').pack()
        frame_aux = tk.Frame(conj_escala)
        frame_aux.pack()
        self.entrada_xy['x_escala'] = tk.StringVar()
        self.entrada_xy['y_escala'] = tk.StringVar()
        tk.Entry(frame_aux,width=w_bt//2,textvariable=self.entrada_xy['x_escala']).grid(row=0,column=0)
        tk.Entry(frame_aux,width=w_bt//2,textvariable=self.entrada_xy['y_escala']).grid(row=0,column=1)

        # ADICIONAL PROJEÇÃO PERSPECTIVA
        conj_perspe = botoes[-1]
        tk.Button(conj_perspe,text='Proj. Pers.',command=lambda: self.muda_opcao('PERSPEC'),width=w_bt-1).pack()
        tk.Label(conj_perspe,text='D').pack()
        frame_aux = tk.Frame(conj_perspe)
        frame_aux.pack()
        self.entrada_xy['D'] = tk.StringVar()
        #self.entrada_xy['Z_PERSP'] = tk.StringVar()
        tk.Entry(frame_aux,width=w_bt//2,textvariable=self.entrada_xy['D']).grid(row=0,column=0)
        #tk.Entry(frame_aux,width=w_bt//2,textvariable=self.entrada_xy['Z_PERSP']).grid(row=0,column=1)

        for botao in botoes:
            botao.pack()
        return botoes

    def cria_canvas(self):
        # guarda parâmetros para criação do canvas
        largura = self.largura
        altura = self.altura
        escala = self.escala
        # instância do canvas
        canvas = tk.Canvas(self,width=(largura*escala)-2,height=(altura*escala))
        canvas.grid(row=0)
        return canvas

    def add_frame_buffer(self,x,y,cor):
        if self.largura>x>=0<=y<self.altura:
            self.frame_buffer[y][x] = cor # y -> linha ; x -> coluna

    def pinta_coord(self,coord):
        # exemplo de coord [(x0,y0),(x1,y1),...,(xn,yn)]
        escala = self.escala
        for pixel in filter(lambda p: self.largura>p[0]>=0<=p[1]<self.altura,coord):
            x,y = pixel
            cor = self.frame_buffer[y][x] # y -> linha ; x -> coluna
            x = x*escala
            y = y*escala
            xfim = x+escala
            yfim = y+escala
            self.canvas.create_rectangle(
                x+1,y+1,xfim-1,yfim-1,fill=cor,outline=cor
            )

    def marca_pixel(self,x,y):
        escala = self.escala
        x = x*escala
        y = y*escala
        xfim = x+escala
        yfim = y+escala
        self.canvas.create_rectangle(
            x+1,y+1,xfim-1,yfim-1,outline=self.cor
        )

    def pinta_buffer(self):
        escala = self.escala
        largura = self.largura
        altura = self.altura
        fb = self.frame_buffer
        for y in range(altura):
            for x in range(largura):
                cor = fb[y][x]
                xesc = x*escala
                yesc = y*escala
                xfim = xesc+escala
                yfim = yesc+escala
                self.canvas.create_rectangle(
                    xesc+1,yesc+1,xfim-1,yfim-1,fill=cor,outline=cor
                )

    def xyscala(self,x,y):
        x //= self.escala
        y //= self.escala
        return x,y

    def add_forma(self):
        if self.forma_aux:
            self.forma_aux.cor_borda = self.cor
            self.formas.append(self.forma_aux)
            self.forma_aux = None
            self.lista_box.insert(tk.END,'Poligono'+str(len(self.formas)))

    def rm_forma(self):
        index = self.lista_box.curselection()
        if index:
            index = index[0]
            self.lista_box.delete(index)
            self.formas.pop(index)

    def pinta_forma(self):
        index = self.lista_box.curselection()
        if index:
            index = index[0]
            forma = self.formas[index]
            for x,y in forma.borda():
                self.add_frame_buffer(x,y,forma.cor_borda)
            self.pinta_coord(forma.borda())

    def cria_eventos(self):
        modo = self.modo
        f_event = None
        self.forma_aux = None
        self.canvas.unbind('<Double-Button-1>')
        self.canvas.unbind('<B1-Motion>')
        if modo=='LIVRE':
            def f(event):
                x,y = self.xyscala(event.x,event.y) # converte de acordo com escala
                if self.largura>x>=0<=y<self.altura:
                    self.add_frame_buffer(x,y,self.cor) # adiciona cor no pixel indicado
                    self.pinta_coord([(x,y)]) # pinta diretamente o pixel
            self.canvas.bind('<B1-Motion>',f)
            f_event = f
        elif modo=='LINHA':
            # adiciona os pontos e finaliza ao chegar no ponto inicial ou ao dar double-clik
            def f(event):
                x,y = self.xyscala(event.x,event.y) # captura x e y do canvas e converte de acordo com nossa escala
                if not self.forma_aux: # se a forma auxiliar for None (Nula)
                    self.forma_aux = Poligono((x,y)) # realiza instância de uma Linha com a coordenada inicial
                    self.add_frame_buffer(x,y,self.cor) # adiciona cor ao pixel no frame buffer
                    self.pinta_coord([(x,y)]) # pinta no Canvas a coordenada informada
                elif (x,y) != self.forma_aux.coords[-1]: # se o último vértice for diferente do novo clicado
                    for x,y in bresenham(self.forma_aux.coords[-1],(x,y)):
                        self.add_frame_buffer(x,y,self.cor) # adiciona cor ao pixel no frame buffer
                    self.pinta_coord(bresenham(self.forma_aux.coords[-1],(x,y)))
                    self.forma_aux.coords.append((x,y)) # adiciona vértice à linha
                if len(self.forma_aux.coords)>1 and self.forma_aux.coords[0] == self.forma_aux.coords[-1]:
                    self.forma_aux.fechado = True
                    self.add_forma() # adiciona e reseta self.forma_aux
            f_event = f
        elif modo=='CIRCULO':
            def f(event):
                x,y = self.xyscala(event.x,event.y) # converte de acordo com escala
                if not self.forma_aux:
                    #self.forma_aux = Circulo((x,y),None)
                    self.forma_aux = Poligono((x,y))
                else:
                    #self.forma_aux.raio = (x,y)
                    self.forma_aux = Circulo(self.forma_aux.coords[0],(x,y))
                    self.forma_aux.cor_borda = self.cor
                    for x,y in self.forma_aux.borda():
                        self.add_frame_buffer(x,y,self.forma_aux.cor_borda)
                        self.pinta_coord([(x,y)])
                    self.add_forma()
            f_event = f
        elif modo=='BEZIER':
            def f(event):
                x,y = self.xyscala(event.x,event.y) # converte de acordo com escala
                self.marca_pixel(x,y)
                if not self.forma_aux:
                    self.forma_aux = Curva((x,y))
                else:
                    self.forma_aux.coords.append((x,y))

                if len(self.forma_aux.coords)>1 and self.forma_aux.coords[-2]==self.forma_aux.coords[-1]:
                    self.forma_aux.coords.pop(-1)
                    self.forma_aux.cor_borda = self.cor
                    for x,y in self.forma_aux.borda():
                        self.add_frame_buffer(x,y,self.forma_aux.cor_borda)
                        self.pinta_coord([(x,y)])
                    self.add_forma()
            f_event = f
        elif modo=='PREE_REC':
            def f(event):
                x,y = self.xyscala(event.x,event.y) # converte de acordo com escala
                preenchrecursivo(self.frame_buffer,(x,y),self.cor)
                self.pinta_buffer()
            f_event = f
        elif modo=='PREE_SCAN':
            index =  self.lista_box.curselection()
            if index:
                index = index[0]
                preenchscanline(self.frame_buffer,self.formas[index],self.cor)
                self.pinta_buffer()
            else:
                print('selecione uma figura')
        elif modo=='CORTE_LINHA':
            def f(event):
                x,y = self.xyscala(event.x,event.y) # captura x e y do canvas e converte de acordo com nossa escala
                self.marca_pixel(x,y)
                if not self.forma_aux: # se a forma auxiliar for None (Nula)
                    self.forma_aux = Poligono((x,y)) # realiza instância de uma Linha com a coordenada inicial
                else:
                    self.forma_aux.coords.append((x,y))
                    self.forma_aux.coords.sort()
                    p_min,p_max = self.forma_aux.coords
                    self.forma_aux = None
                    index =  self.lista_box.curselection()
                    if index:
                        index = index[0]
                        linha = self.formas[index]
                        self.limpa_buffer()
                        nova_linha = Poligono(None)
                        nova_linha.coords = algoritmos.cohen_Sutherland(linha.coords,p_min,p_max)
                        for x,y in nova_linha.borda():
                            self.add_frame_buffer(x,y,self.cor)
                        self.pinta_buffer()
                    else:
                        print('selecione uma figura')
            f_event = f
        elif modo=='TRANSLA':
            index =  self.lista_box.curselection()
            if index:
                index = index[0]
                linha = self.formas[index]
                #self.limpa_buffer()
                coord_antiga = linha.borda()
                for x,y in coord_antiga:
                    self.add_frame_buffer(x,y,'#ffffff')
                self.pinta_coord(coord_antiga)
                ponto_t = int(self.entrada_xy['x'].get()),int(self.entrada_xy['y'].get())
                linha.coords = algoritmos.translate(linha,ponto_t)
                for x,y in linha.borda():
                    self.add_frame_buffer(x,y,self.cor)
                self.pinta_coord(linha.borda())
            else:
                print('selecione uma figura')
        elif modo=='ROTAC':
            def f(event):
                x,y = self.xyscala(event.x,event.y) # captura x e y do canvas e converte de acordo com nossa escala
                self.pivo = (x,y) # realiza instância de uma Linha com a coordenada inicial
                self.marca_pixel(x,y)
            f_event = f
            index =  self.lista_box.curselection()
            if index:
                index = index[0]
                linha = self.formas[index]
                #self.limpa_buffer()
                coord_antiga = linha.borda()
                for x,y in coord_antiga:
                    self.add_frame_buffer(x,y,'#ffffff')
                self.pinta_coord(coord_antiga)

                grau_rotacao = int(self.entrada_xy['ang'].get())
                linha.coords = algoritmos.rotate(linha,grau_rotacao, self.pivo if self.pivo else (0,0))
                for x,y in linha.borda():
                    self.add_frame_buffer(x,y,self.cor)
                self.pinta_coord(linha.borda())
            else:
                print('selecione uma figura')
        elif modo=='ESCALA':
            #x_escala'
            index =  self.lista_box.curselection()
            if index:
                index = index[0]
                linha = self.formas[index]
                #self.limpa_buffer()
                coord_antiga = linha.borda()
                for x,y in coord_antiga:
                    self.add_frame_buffer(x,y,'#ffffff')
                self.pinta_coord(coord_antiga)
                ponto_t = float(self.entrada_xy['x_escala'].get()),float(self.entrada_xy['y_escala'].get())
                linha.coords = algoritmos.scale(linha,ponto_t)
                for x,y in linha.borda():
                    self.add_frame_buffer(x,y,self.cor)
                self.pinta_coord(linha.borda())
            else:
                print('selecione uma figura')
        elif modo=='PERSPEC':
            z =  self.lista_box.curselection()
            if z:
                z = z[0]
                p1 = self.formas[z]
                p2 = self.formas[z-1]

                self.limpa_buffer()

                d_focal = float(self.entrada_xy['D'].get())
                #z_perps = int(self.entrada_xy['Z_PERSP'].get())

                p1_zh = list(map(lambda p: (p[0],p[1],1,1),p1.coords)) # adiciona 'z' e 'h'
                p2_zh = list(map(lambda p: (p[0],p[1],2,1),p2.coords)) # adiciona 'z' e 'h'

                p1.coords = list(map(lambda p: (p[0],p[1]),algoritmos.projecao_perspectiva(p1_zh,d_focal))) # projeção de p1
                p2.coords = list(map(lambda p: (p[0],p[1]),algoritmos.projecao_perspectiva(p2_zh,d_focal))) # projeção de p2

                cubo = Cubo(p1,p2)
                for x,y in cubo.borda():
                    self.add_frame_buffer(x,y,self.cor)
                self.pinta_coord(cubo.borda())
            else:
                print('selecione uma figura')
        elif modo=='CORTE_POLI':
            z =  self.lista_box.curselection()
            if z:
                z = z[0]
                p1 = self.formas[z]
                p2 = self.formas[z+1]

                self.limpa_buffer()

                p1_list = list(map(lambda p: [p[0],p[1]],p1.coords))[:-1] # adiciona 'z' e 'h'
                p2_list = list(map(lambda p: [p[0],p[1]],p2.coords))[:-1] # adiciona 'z' e 'h'
                coords_novo = list(map(lambda p: (round(p[0]),round(p[1])), algoritmos.Sutherland_Hodgman(p1_list,len(p1_list),p2_list,len(p2_list))))

                linha = Poligono(coords_novo[0])
                for ponto in coords_novo[1:]:
                    linha.coords.append(ponto)
                linha.coords.append(linha.coords[0])
                for x,y in linha.borda():
                    self.add_frame_buffer(x,y,self.cor)
                self.pinta_coord(linha.borda())
            else:
                print('selecione uma figura')
        # substitui evento modo de pintura atual
        self.canvas.unbind('<Button-1>')
        self.canvas.bind('<Button-1>',f_event)

app = App(escala=5)
app.show()


# position 변수를 list_assignment_and_print_methods object로 할당
position = []

# 1차원 list의 각 element에 list를 추가함으로써 2차원 list로 만듦
for i in range(19):
    # element 마다 리스트 선언
    position.append([])

    # i_n 에 대해 20(j) 반복
    for j in range(19):
        position[i].append(0)  # i_1 에대해 j_0~19 append /즉 하나의 row는 하나의 list_assignment_and_print_methods

for i in range(19):
    position[i] = list(map(int, input().split()))  # 따라서 \n을 기준으로 받는 map을 list로 선언해서 각 row로 assignment하는 것


import numpy as np
import sys
import os
import math
import imp
#from sqlalchemy import create_engine
#from sqlalchemy.orm import sessionmaker, Session
import json
from scipy.optimize import curve_fit

# Decreasing exponential (might want to introduce Amdahl's law for latency not speedup)
def func(x, a, b, c):
    return a * np.exp(-b * x) + c

def compute_p_optimum(data, mode='efficiency',cpn=28):
    if mode =='time-to-completion':
        # Pmax as the number of nodes which yields the quickest result
        pmax = math.ceil(data[data.argmin(axis=0)[1],0]/cpn)
    elif mode=='efficiency':
        # The factor between the speedup at which pmax is chosen and the initial speedup
        relative_performance_factor = 0.9
        # Compute regression fit of the performance data using a inverse exponential
        xdata = data[:,0]
        ydata = data[:,1]
        popt, pcov = curve_fit(func, xdata, ydata)
        yfit = func(xdata, *popt)
        # Compute the instantaneous slope of the fitted exponential
        slope = -np.gradient(yfit)/np.gradient(xdata)
        # Set Pmax as the number of nodes for which the slope becomes less than
        # a given percentage of the initial slope
        for i in range(slope.size):
            cslope = slope[i]
            if cslope < relative_performance_factor*slope[0]:
                pmax = xdata[i]/cpn
    return pmax

# to access database: source /home/plgrid-groups/plggcompat/anaconda2/bin/activate performance-database
# Input list: "number_of_cells" "upstrain_files_directory" "minimum_nodes_job"
# execute as: python optimization_hmm.py ./macroscale_state/out 1 28 1-1 ./nanoscale_state/out ./nanoscale_log/tmp ./nanoscale_state/out/job_list_md.json
if __name__ == '__main__':

    # static parameters
    optim = True
    rescale_from_time_prediction = False
    pmax_from_db = False
    negl_strain_tsh = 1.0e-10
    cores_per_nodes = 28
    max_nodes_talloc = 100
    pmax_arbitrary = 4

    # input parameters
    macrostatelocout = sys.argv[1]
    Pmin = int(sys.argv[2]) # Set the minimum number of nodes assigned to an microjob
    nreplicas = int(sys.argv[3])
    time_id = sys.argv[4]
    nanostatelocout = sys.argv[5]
    nanologloctmp = sys.argv[6]
    joblistfile = sys.argv[7]

    # Need to parse the material id list (material id for each cell)
    cell_list = []
    jobs_count = 0
    matcell_file = macrostatelocout+"/cell_id_mat.list"
    with open(matcell_file) as fp:
        for line in fp:
            cell = {}
            cell['id'] = line.split(" ")[0]
            cell['mat'] = line.split(" ")[1][:-1]

            # Load the strain tensor for all cells in the mesh, a null vector is loaded if the file is not found
            try:
                with open('{}/last.{}.upstrain'.format(macrostatelocout, cell['id']), 'r') as fd:
                    cell['strain_tensor'] = np.array([float(fd.readline()) for _ in range(6)])
            except IOError as e:
                # print( "Error: {} - Could not find strain file for cell {}".format(e, cell['id']))
                cell['strain_tensor'] = np.zeros(6)

            cell['strain_norm'] = np.linalg.norm(cell['strain_tensor'])

            # Only keep cells with a non-negligible strain to compute otherwise useless
            if cell['strain_norm'] > negl_strain_tsh:
                cell_list.append(cell)
                # increase jobs_count to set cell_id as line number of the matlist file
                jobs_count+=1

    # If list of jobs is 0 exit
    if jobs_count == 0:
        print(0)
    # Else produce the job list and return the total number of nodes
    else:
        # Create instance of the Performance database
        #database = imp.load_source('database', '/home/plgrid-groups/plggcompat/Common/COMPAT-Patterns-Software/OptimisationPart/database_upload.py')
        #engine = create_engine('mysql://performance_update:password@129.187.255.55/performance')
        #Session = sessionmaker(bind=engine)
        #session = Session()
        #run_ids_by_material = [instance.id for instance in session.query(database.Run).filter(database.Run.application == 'MATERIALS')]

        # Compute Pmax as the number of nodes for which the latency (time/workload)
        # is not linearly increasing with the number of nodes anymore
        if pmax_from_db:
            kernelperf_for_materials = np.array([{'id':instance.id, 'kernel_id':instance.kernel_id, 'corecount':instance.cores, 'runtime':instance.runtime} for instance in session.query(database.KernelPerf).filter(database.KernelPerf.run_id.in_(run_ids_by_material))])
            unique_kernel_id = np.unique([d['kernel_id'] for d in kernelperf_for_materials])
            eps_by_kernel_id = {}
            for instance in session.query(database.Kernel).filter(database.Kernel.id.in_(unique_kernel_id)):
                parameters = json.loads(instance.config_parameters)
                try:
                    eps_by_kernel_id[instance.id] = np.linalg.norm([parameters['strain_tensor'][val] for val in parameters['strain_tensor']])
                except KeyError:
                    pass
            ## keeping only runs with a strain norm above neg_strain_tsh, less is barely significant and the runtime might be irrelevant
            kernelperf_corecount_latency = np.array([[instance['corecount'], instance['runtime']/eps_by_kernel_id[instance['kernel_id']]] \
                for instance in kernelperf_for_materials if eps_by_kernel_id[instance['kernel_id']] > negl_strain_tsh])

            Pmax = compute_p_optimum(data=kernelperf_corecount_latency, mode='efficiency', cpn=cores_per_nodes)
        # Use a default variable (from arbitrary choice)
        else:
            Pmax = pmax_arbitrary

        # Make sure that the maximum number of nodes given to a microjob is smaller than the total number of node allocated
        assert Pmax < max_nodes_talloc

        # Compute a scaling factor that will be used to determine the number of nodes allocated to each cell job
        # accounting on the all the jobs that have to be run.
        # Either computed using the predicted execution time from performance measurements of the DB or simply using
        # the norm of the strain tensor that will be applied during the job
        if rescale_from_time_prediction:
            # Query execution time Texec for each cell for min node
            texec = []
            for cell in cell_list:
                kernelperf_id_by_run_ids_and_corecount = [instance[0] for instance in session.query(database.KernelPerf.kernel_id).distinct(database.KernelPerf.kernel_id).filter(database.KernelPerf.run_id.in_(run_ids_by_material) & database.KernelPerf.cores == Pmin*cores_per_nodes)]
                kernel_id_by_kernelperf_id_and_epsilon = []
                for instance in session.query(database.Kernel).filter(database.Kernel.id.in_(kernelperf_id_by_run_ids_and_corecount)):
                    parameters = json.loads(instance.config_parameters)
                    try:
                        # might have to allow some tolerance on that condition,
                        # as the exact same strain might not have been computed already
                        if float(parameters['strain_norm']) == cell['strain_norm']:
                            kernel_id_by_kernelperf_id_and_epsilon.append(instance.id)
                    except KeyError:
                        pass
                kernelperf_time_by_kernel_id = np.array([instance.runtime for instance in session.query(database.KernelPerf).filter(database.KernelPerf.id.in_(kernel_id_by_kernelperf_id_and_epsilon))])
                cell['texec'] = kernelperf_time_by_kernel_id.mean()

            # Compute the rescaling factor alpha such as (Pmax-Pmin)/(Texec,max - Texec,min)
            texec_min = min([cell['texec'] for cell in cell_list])
            texec_max = max([cell['texec'] for cell in cell_list])
            sfact = (Pmax-Pmin)/(texec_max - texec_min)
            pordo = Pmin - sfact*texec_min

        else:
            # Compute the rescaling factor alpha such as (Pmax-Pmin)/(eps.norm,max - eps.norm,min)
            strain_min = min([cell['strain_norm'] for cell in cell_list])
            strain_max = max([cell['strain_norm'] for cell in cell_list])
            sfact = (Pmax-Pmin)/(strain_max - strain_min)
            pordo = Pmin - sfact*strain_min

        # Compute the number of nodes allocated to each microjob P such as alpha*T and the total number of nodes
        ptot = 0
        for cell in cell_list:
            if optim:
               if rescale_from_time_prediction:
                  cell['p'] = int(round(cell['texec']*sfact + pordo))
               else:
                  cell['p'] = int(round(cell['strain_norm']*sfact + pordo))
            else:
               cell['p'] = pmax_arbitrary

            ptot += cell['p']*nreplicas

        #if ptot < 2*max_nodes_talloc:
        #    # Resize the node allocation w.r.t to the max_nodes_talloc
        #    rsfnode = 1.0*max_nodes_talloc/ptot
        #    ptot = 0
        #    for cell in cell_list:
        #        cell['p'] = int(max(1, math.floor(cell['p']*rsfnode)))
        #        ptot += cell['p']*nreplicas
        #    if ptot > max_nodes_talloc:
        #        raise ValueError("Total node allocation to high ({} > {})".format(ptot, max_nodes_talloc))
        #else:
        if ptot > max_nodes_talloc:
            # Just limit ptot to max_nodes_talloc and therefore start building up the queue
            ptot = max_nodes_talloc

        # Sort cell_ids in decreasing order of P
        cell_list_sorted = sorted(cell_list, key=lambda k: k['p'], reverse=True)

        # Write the JSON file for the PJM
        json_job_list = []
        top_json = {}
        top_json['request'] = 'submit'
        top_json['jobs'] = []
        for cell in cell_list_sorted:
            cell_job_dict = {}
            cell_job_dict['name'] = 'mdrun_cell'+str(cell['id'])+'_repl${it}'
            cell_job_dict['iterate'] = [1, nreplicas+1]
            cell_job_dict['execution'] = {}
            cell_job_dict['execution']['exec'] = 'bash'
            cell_job_dict['execution']['args'] = [nanostatelocout+"/"+"bash_cell"+str(cell['id'])+"_repl${it}.sh"]
            cell_job_dict['execution']['stdout'] = nanologloctmp+"/"+time_id+"."+str(cell['id'])+"."+str(cell['mat'])+"_${it}"+'/${jname}.stdout'
            cell_job_dict['execution']['stderr'] = nanologloctmp+"/"+time_id+"."+str(cell['id'])+"."+str(cell['mat'])+"_${it}"+'/${jname}.stderr'
            cell_job_dict['resources'] = {}
            cell_job_dict['resources']['numNodes'] = {}
            cell_job_dict['resources']['numNodes']['exact'] = cell['p']
            top_json['jobs'].append(cell_job_dict)
        json_job_list.append(top_json)

        bottom_json = {}
        bottom_json['request'] = 'control'
        bottom_json['command'] = 'finishAfterAllTasksDone'
        json_job_list.append(bottom_json)

        json = json.dumps(json_job_list)
        f = open(joblistfile,"w")
        f.write(json)
        f.close()

        # Returning the total number of nodes to the main app
        print(ptot)