from django.urls import path

from .views import SelectielijstProcestypenListView, SelectielijstResultatenListView

app_name = "admin-api"

urlpatterns = [
    path(
        "selectielijst/resultaten",
        SelectielijstResultatenListView.as_view(),
        name="selectielijst-resultaten",
    ),
    path(
        "selectielijst/procestypen",
        SelectielijstProcestypenListView.as_view(),
        name="selectielijst-procestypen",
    ),
]


from flask import render_template, url_for, flash, redirect, request, abort, jsonify
from files import app, db
from files.models.mission import Mission
import datetime as dt

@app.route("/missions", methods=["GET"])
def get_missions():
    missions = Mission.query.all()

    return jsonify(f"{missions}"), 200

@app.route("/missions/<string:id>/crew", methods=["GET"])
def get_mission_id_crew(id):
    missions = Mission.query.get(id)

    return jsonify(f"{missions.return_crew()}"), 200

@app.route("/missions/add", methods=['POST'])
def missions_add():
    missions = Mission.query.order_by(Mission.id.desc()).first()

    m = Mission()
    m.start_date = missions.end_date

    timedelta = dt.timedelta(weeks=8)
    m.end_date = m.start_date + timedelta

    db.session.add(m)
    db.session.commit()

    return jsonify(m.output()), 201


import json
import time
import unittest

from selenium.webdriver import ActionChains
from selenium import webdriver
import HTMLTestRunner

class Testunitest(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get("http://192.168.2.104:5003/home/index?menuid=JINHAI")

        # 首先清除浏览器已有的cookies
        self.driver.delete_all_cookies()
        # 读取cookie
        with open('cookie.txt', 'r',encoding='utf-8') as cookief:
            cookieslist = json.load(cookief)
            # 方法1 将expiry类型变为int,这样就不会过期
            for cookie in cookieslist:
                if isinstance(cookie.get('expiry'), float):
                    cookie['expiry'] = int(cookie['expiry'])
                self.driver.add_cookie(cookie)
        time.sleep(10)
        self.driver.get("http://192.168.2.104:5003/home/index?menuid=JINHAI")
        self.driver.refresh()

        driver = self.driver
        driver.implicitly_wait(10)

        # 点击模块展开按钮
        elem2 = self.driver.find_element_by_id('longnows_app_flexible')
        ActionChains(self.driver).click(elem2).perform()

        # 点击进出口管理
        time.sleep(5)
        elem3 = self.driver.find_element_by_xpath('//*[@id="nav-left"]/li[3]/a/span')
        ActionChains(self.driver).click(elem3).perform()
        time.sleep(3)

        # 点击进口管理
        elem4 = self.driver.find_element_by_xpath('//*[@id="nav-left"]/li[3]/dl/dd[2]/a/span')
        ActionChains(self.driver).click(elem4).perform()
        time.sleep(5)

        # 点击进口台账模块，进入进口台账页面
        elem5 = self.driver.find_element_by_xpath('//*[@id="nav-left"]/li[3]/dl/dd[2]/dl/dd[3]/a/cite')
        ActionChains(self.driver).click(elem5).perform()
        time.sleep(8)

    def test_case1(self):
        driver = self.driver
        driver.implicitly_wait(10)

        # ====================================================表头==============================================
        # 在进口台账页面点击新增按钮,这边用到iframe
        elem6 = driver.find_element_by_xpath('//*[@id="longnows_body"]/div[2]/div[2]/div[2]/iframe')
        driver.switch_to.frame(elem6)
        # 点击新增按钮
        elem7 = driver.find_element_by_xpath('/html/body/div[2]/div[1]/div[1]/div/button[1]')
        ActionChains(driver).click(elem7).perform()
        time.sleep(5)
        # 获取当前打开的所有窗口的句柄
        num1 = driver.window_handles
        print(num1)
        driver.switch_to.window(num1[0])

        # 在进口台账的新增页面，选择进境关别下拉数据
        elem8 = driver.find_element_by_xpath('//*[@id="longnows_tab_container"]/div[3]/iframe')
        print(elem8)
        # elem8=WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,".//iframe[contains(@src,'/Dec/CopAct/Modify?Type=3&IEFlag=I')]")))
        driver.switch_to.frame(elem8)
        # ============
        # 点击进境关口下拉
        elem9 = driver.find_element_by_xpath('//*[@id="head"]/div[3]/div[2]/span/span/a')
        ActionChains(driver).click(elem9).perform()
        time.sleep(1)
        # 选择进境关闭
        elem10 = driver.find_element_by_xpath('/html/body/div[16]/div/div[1]')
        ActionChains(driver).click(elem10).perform()
        time.sleep(1)

        # ============
        # 点击入境口岸下拉
        elem11 = driver.find_element_by_xpath('//*[@id="head"]/div[3]/div[4]/span/span/a')
        ActionChains(driver).click(elem11).perform()
        time.sleep(1)
        # 选择入境口岸
        elem12 = driver.find_element_by_xpath('/html/body/div[17]/div/div[1]')
        ActionChains(driver).click(elem12).perform()
        time.sleep(1)

        # ============
        # 点击申报地海关下拉
        elem13 = driver.find_element_by_xpath('//*[@id="head"]/div[2]/div[6]/span/span/a')
        ActionChains(driver).click(elem13).perform()
        time.sleep(1)
        # 选择入境口岸
        elem14 = driver.find_element_by_xpath('/html/body/div[15]/div/div[1]')
        ActionChains(driver).click(elem14).perform()
        time.sleep(1)

        # ============
        # 点击报关行单位
        elem15 = driver.find_element_by_xpath('//*[@id="head"]/div[7]/div[2]/span/span/a')
        ActionChains(driver).click(elem15).perform()
        time.sleep(1)
        # 选择入境口岸
        elem16 = driver.find_element_by_xpath('/html/body/div[23]/div/div[1]')
        ActionChains(driver).click(elem16).perform()
        time.sleep(1)

        # ============
        # 点击监管方式
        elem17 = driver.find_element_by_xpath('//*[@id="head"]/div[9]/div[2]/span/span/a')
        ActionChains(driver).click(elem17).perform()
        time.sleep(1)
        # 选择监管方式
        elem18 = driver.find_element_by_xpath('/html/body/div[25]/div/div[1]')
        ActionChains(driver).click(elem18).perform()
        time.sleep(1)

        # ============
        # 点击起运国
        elem19 = driver.find_element_by_xpath('//*[@id="head"]/div[10]/div[2]/span/span/a')
        ActionChains(driver).click(elem19).perform()
        time.sleep(1)
        # 选择起运国
        elem20 = driver.find_element_by_xpath('/html/body/div[29]/div/div[1]')
        ActionChains(driver).click(elem20).perform()
        time.sleep(1)

        # ============
        # 点击境内目的地
        elem21 = driver.find_element_by_xpath('//*[@id="head"]/div[11]/div[2]/span/span/a')
        ActionChains(driver).click(elem21).perform()
        time.sleep(1)
        # 选择境内目的地
        elem22 = driver.find_element_by_xpath('/html/body/div[35]/div/div[1]')
        ActionChains(driver).click(elem22).perform()
        time.sleep(1)

        # ============
        # 点击特殊关确认
        elem23 = driver.find_element_by_xpath('//*[@id="head"]/div[12]/div[2]/span/span/a')
        ActionChains(driver).click(elem23).perform()
        time.sleep(1)
        # 选择特殊关系确认
        elem24 = driver.find_element_by_xpath('/html/body/div[39]/div/div[1]')
        ActionChains(driver).click(elem24).perform()
        time.sleep(1)

        # ============
        # 点击成交方式
        elem25 = driver.find_element_by_xpath('//*[@id="head"]/div[9]/div[4]/span/span/a')
        ActionChains(driver).click(elem25).perform()
        time.sleep(1)
        # 选择成交方式
        elem26 = driver.find_element_by_xpath('/html/body/div[27]/div/div[1]')
        ActionChains(driver).click(elem26).perform()
        time.sleep(1)

        # ============
        # 点击经停港
        elem27 = driver.find_element_by_xpath('//*[@id="head"]/div[10]/div[4]/span/span/a')
        ActionChains(driver).click(elem27).perform()
        time.sleep(1)
        # 选择经停港
        elem28 = driver.find_element_by_xpath('/html/body/div[30]/div/div[1]')
        ActionChains(driver).click(elem28).perform()
        time.sleep(1)

        # ============
        # 点击贸易国别（地区）
        elem29 = driver.find_element_by_xpath('//*[@id="head"]/div[11]/div[4]/span/span/a')
        ActionChains(driver).click(elem29).perform()
        time.sleep(1)
        # 选择贸易国别（地区）
        elem30 = driver.find_element_by_xpath('/html/body/div[33]/div/div[1]')
        ActionChains(driver).click(elem30).perform()
        time.sleep(1)

        # ============
        # 点击价格影响确认
        elem31 = driver.find_element_by_xpath('//*[@id="head"]/div[12]/div[4]/span/span/a')
        ActionChains(driver).click(elem31).perform()
        time.sleep(1)
        # 选择价格影响确认
        elem32 = driver.find_element_by_xpath('/html/body/div[40]/div/div[1]')
        ActionChains(driver).click(elem32).perform()
        time.sleep(1)

        # ============
        # 点击运输方式
        elem33 = driver.find_element_by_xpath('//*[@id="head"]/div[9]/div[6]/span/span/a')
        ActionChains(driver).click(elem33).perform()
        time.sleep(1)
        # 选择运输方式
        elem34 = driver.find_element_by_xpath('/html/body/div[28]/div/div[1]')
        ActionChains(driver).click(elem34).perform()
        time.sleep(1)

        # ============
        # 点击支付特殊权使确认
        elem35 = driver.find_element_by_xpath('//*[@id="head"]/div[12]/div[6]/span/span/a')
        ActionChains(driver).click(elem35).perform()
        time.sleep(1)
        # 选择支付特殊权使确认
        elem36 = driver.find_element_by_xpath('/html/body/div[41]/div/div[1]')
        ActionChains(driver).click(elem36).perform()
        time.sleep(1)

        # ============
        # 点击供应商
        elem37 = driver.find_element_by_xpath('//*[@id="head"]/div[8]/div[2]/span/span/a')
        ActionChains(driver).click(elem37).perform()
        time.sleep(1)
        # 选择供应商
        elem38 = driver.find_element_by_xpath('/html/body/div[24]/div/div[1]')
        ActionChains(driver).click(elem38).perform()
        time.sleep(1)

        # ============
        # 点击货代
        elem39 = driver.find_element_by_xpath('//*[@id="head"]/div[7]/div[4]/span/span/a')
        ActionChains(driver).click(elem39).perform()
        time.sleep(1)
        # 选择货代
        elem40 = driver.find_element_by_xpath('/html/body/div[18]/div/div[1]')
        ActionChains(driver).click(elem40).perform()
        time.sleep(1)

        # ============
        # 点击表头保存按钮
        elem41=driver.find_element_by_xpath('/html/body/div[1]/button[2]')
        elem41 = driver.find_element_by_xpath('/html/body/div[1]/button[contains(@lay-event,"headSave")]')
        ActionChains(driver).click(elem41).perform()
        time.sleep(1)

        # ===========================================表体======================================================

        # 点击表头新增按钮
        elem42 = driver.find_element_by_id('listInit')
        ActionChains(driver).click(elem42).perform()
        time.sleep(1)

        # =============
        # 点击商品料号下拉
        elem43 = driver.find_element_by_xpath('//*[@id="act_list_form"]/div[2]/div[2]/span/span/a')
        ActionChains(driver).click(elem43).perform()
        time.sleep(1)
        # 选择商品料号
        elem44 = driver.find_element_by_xpath('/html/body/div[11]/div/div[1]')
        ActionChains(driver).click(elem44).perform()
        time.sleep(1)

        # 设置申报数量
        elem45 = driver.find_element_by_id('Qty')
        elem45.clear()
        elem45.send_keys(10)
        time.sleep(1)

        # 设置申报单价
        elem46 = driver.find_element_by_id('DecPrice')
        elem46.clear()
        elem46.send_keys(6)
        time.sleep(1)

        # 设置法定第一数量
        elem47 = driver.find_element_by_id('Qty1')
        elem47.clear()
        elem47.send_keys(10)
        time.sleep(1)

        # 设置净重
        elem48 = driver.find_element_by_id('NetWt').send_keys(10)
        time.sleep(1)

        # 设置原产国
        # 点击下拉按钮
        elem49 = driver.find_element_by_xpath('//*[@id="act_list_form"]/div[9]/div[2]/span/span/a')
        ActionChains(driver).click(elem49).perform()
        time.sleep(1)
        # 选择下拉
        elem50 = driver.find_element_by_xpath('/html/body/div[58]/div/div')
        ActionChains(driver).click(elem50).perform()
        time.sleep(1)

        # 点击保存按钮
        elem51 = driver.find_element_by_xpath('/html/body/div[2]/div[1]/div/div[2]/button[contains(@lay-event,"listSave")]')
        ActionChains(driver).click(elem51).perform()
        time.sleep(1)

    def test_edit(self):
        driver = self.driver
        driver.implicitly_wait(10)

        # ====================================================表头==============================================
        # 在进口台账页面点击编辑按钮,这边用到iframe
        e_elem1 = driver.find_element_by_xpath('//*[@id="longnows_body"]/div[2]/div[2]/div[2]/iframe')
        driver.switch_to.frame(e_elem1)
        # 点击编辑按钮
        e_elem2 = driver.find_element_by_xpath('/html/body/div[2]/div[2]/div[4]/div[2]/table/tbody/tr/td/div/button[1]/i')
        ActionChains(driver).click(e_elem2).perform()
        driver.implicitly_wait(10)
        # 获取当前打开的所有窗口的句柄
        num11 = driver.window_handles
        print(num11)
        driver.switch_to.window(num11[0])
        # 进入编辑页面的iframe
        e_elem3= driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div[2]/div[3]/iframe')
        print(e_elem3)
        driver.switch_to.frame(e_elem3)
        # 修改出口日期
        e_elem4 = driver.find_element_by_xpath('//*[@id="head"]/div[3]/div[4]/span/span/a')
        ActionChains(driver).click(e_elem4).perform()
        time.sleep(2)
        e_elem5=driver.find_element_by_xpath('/html/body/div[17]/div/div[3]')
        ActionChains(driver).click(e_elem5).perform()

        #点击保存按钮
        e_elem6 = driver.find_element_by_xpath('/html/body/div[2]/div[1]/div/div[2]/button[contains(@lay-event,"listSave")]')

    def tearDown(self):
        print('Test Over')

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

if __name__=='__main__':
    testunit = unittest.TestSuite()
    testunit.addTest(Testunitest('test_case1'))
    # 获取当前时间
    testtime = time.strftime('%Y%m%d_%H%M%S_')
    # 报告地址及报告名称
    file_path = 'D:\\PythonProject\\Testunitreport\\report.html'
    file_result = open(file_path, 'wb')
    runner = HTMLTestRunner.HTMLTestRunner(
        stream = file_result,
        title = 'Test Report',
        description = 'Test Result'
    )
    # 自动进行测试
    runner.run(testunit)
    file_result.close()


def isVowel(c):
    return (c == 'A' or c == 'E' or c == 'I' or
            c == 'O' or c == 'U' or c == 'a' or
            c == 'e' or c == 'i' or c == 'o' or
            c == 'u')

def pigLatin(s):

    # the index of the first vowel is stored.
    length = len(s)
    index = -1
    for i in range(length):
        if (isVowel(s[i])):
            index = i
            break

    # Pig Latin is possible only if vowels
    # is present
    if (index == -1):
        file1= open(r"C:\Users\Shrey Kharbanda\Desktop\CSproj\fill.txt","a")
        file1.write("piglatin:"+ "\t"+ s +"\n")
        file1.close()
    # Take all characters after index (including
    # index). Append all characters which are before
    # index. Finally append "ay"
    else:
        cipher=(s[index:] + s[0:index] + "AY").lower()
        file1= open(r"C:\Users\Shrey Kharbanda\Desktop\CSproj\fill.txt","a")
        file1.write("piglatin:"+ "\t"+ cipher +"\t")
        file1.close()


import sys

input = sys.stdin.readline

# 14725 개미굴
# 개미가 가져온 정보를 토대로 개미굴을 그리는 문제
# 트라이 자료구조를 활용하여 해결 가능한 문제이다.

# 트라이의 노드 클래스
# data(키 값), child(자식노드 목록), finished(데이터의 마지막 노드인지 여부)의 세 필드값을 가진다.
class Node:
    # 생성자
    def __init__(self, data=None, finished=False):
        self.data = data
        self.finished = finished
        self.child = {}

    # 노드를 문자열로 표현
    def __str__(self, depth=0):
        res = [str(self.data)]
        for c in self.child.values():
            res.append('--' * depth + c.__str__(depth + 1))
        return '\n'.join(res)

# 트라이 클래스
class Trie:
    # 생성시 빈 노드를 생성하여 루트노드로 설정
    def __init__(self):
        self.root = Node()

    # 삽입 메소드
    def add(self, e):
        # 루트 노드에서 탐색 시작
        cur = self.root

        # 데이터의 각 요소를 키 값으로 하는 노드를 타고내려간다.
        for i in e:
            # 현재 노드의 자식노드 중에
            # 다음 요소를 키 값으로 하는 노드가 존재하지 않는다면 노드를 생성
            # 현재 노드의 자식노드 리스트에 삽입한다.
            if i not in cur.child:
                cur.child[i] = Node(i)
            cur = cur.child[i]
        # 현재 노드가 데이터의 마지막 요소를 키값으로 하는 노드임을 표시
        cur.finished = True

    # 탐색 메소드
    def search(self, key):
        # 루트 노드에서 탐색 시작
        cur = self.root

        # 데이터의 각 요소를 키 값으로 하는 노드를 타고내려간다.
        for c in key:
            # 현재 노드의 자식노드 중에
            # 다음 요소를 키 값으로 하는 노드가 존재하지 않는다면 노드를 생성
            # 찾으려는 데이터가 존재하지 않음을 결과로 반환한다.
            if c in cur.child:
                cur = cur.child[c]
            else:
                return None
        # 탐색이 종료됐을 때, 마지막 노드가 데이터의 마지막 요소를 키 값으로 하는 노드로
        # 표시되어있다면 탐색 성공.  그렇지 않다면 데이터가 존재하지 않음을 결과로 반환한다.
        return cur.data if cur.finished else None

    # 트라이를 문자열로 표현
    def __str__(self):
        return '\n'.join([c.__str__(1) for c in self.root.child.values()])

def sol14725():
    # 로봇개미의 수
    n = int(input())

    # 트라이 인스턴스
    t = Trie()

    # 로봇개미가 가져온 정보를 트라이에 삽입
    for e in sorted([input().split()[1:] for _ in range(n)]):
        t.add(e)

    # 트라이 인스턴스를 문자열화 하여 반환
    return str(t)


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

from charms.reactive import RelationBase
from charms.reactive import hook
from charms.reactive import scopes

class HiveProvides(RelationBase):
    scope = scopes.GLOBAL

    auto_accessors = ['hostname', 'port']

    @hook('{provides:hive}-relation-joined')
    def joined(self):
        conv = self.conversation()
        conv.set_state('{relation_name}.joined')

    @hook('{provides:hive}-relation-departed')
    def departed(self):
        conv = self.conversation()
        conv.remove_state('{relation_name}.joined')

    def set_ready(self):
        self.set_remote(data={
            'ready': True,
        })

    def clear_ready(self):
        self.set_remote('ready', False)

    def send_port(self, port):
        conv = self.conversation()
        conv.set_remote(data={
            'port': port,
        })


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os

def dir_exists(dirpath):
    """Tests for existence of a directory on the string filepath"""
    if os.path.exists(dirpath) and os.path.isdir(
        dirpath
    ):  # test that exists and is a directory
        return True
    else:
        return False

def file_exists(filepath):
    """Tests for existence of a file on the string filepath"""
    if os.path.exists(filepath) and os.path.isfile(
        filepath
    ):  # test that exists and is a file
        return True
    else:
        return False


import sys
from base64 import b64encode
from threading import Thread
import time
import asyncio
import io
import avro.protocol
from avro.io import DatumWriter
from autobahn.asyncio.websocket import WebSocketClientProtocol, WebSocketClientFactory

from collections import namedtuple

from avro.schema import Parse as schema_parse
from avro.protocol import Parse as protocol_parse

class ETPClientProtocol(WebSocketClientProtocol):
    def __init__(self):
        self.messageMaps = {}
        self.messageHeaderSchema = schema_parse(
            open("Schemas/Energistics/Datatypes/MessageHeader.avsc").read()
        )
        self.protocolsMessage = {}

        schema_path = "etp.avpr"

        protocol = protocol_parse(open(schema_path).read())

        for type in protocol.types:
            if "protocol" in type.other_props:
                protocol_no = int(type.other_props["protocol"])
                message_type = int(type.other_props["messageType"])
                if not protocol_no in self.protocolsMessage:
                    self.protocolsMessage[protocol_no] = {}
                self.protocolsMessage[protocol_no][message_type] = type
                self.messageMaps[type.namespace + "." + type.name] = type

    def onConnect(self, response):
        print("Connected to Server: {}".format(response.peer))

    async def onOpen(self):
        print("WebSocket connection open.")

        self.factory.messageMaps = self.messageMaps
        self.factory.messageHeaderSchema = self.messageHeaderSchema
        self.protocolsMessage = self.protocolsMessage
        self.send_etp_message(
            self.create_request_session_message(),
            "Energistics.Protocol.Core.RequestSession",
        )
        await asyncio.sleep(2)

    def send_etp_message(self, message, messageType):
        bytes_writer = io.BytesIO()
        encoder = avro.io.BinaryEncoder(bytes_writer)

        # need to send based on the message type -> cache this messageType from dictionary
        header = {
            "protocol": 0,
            "messageType": 1,
            "correlationId": 0,
            "messageId": 1,
            "messageFlags": 0,
        }

        # write header
        writer = avro.io.DatumWriter(self.factory.messageHeaderSchema)
        writer.write(header, encoder)

        # write body
        writer = avro.io.DatumWriter(self.factory.messageMaps[messageType])
        writer.write(message, encoder)

        self.sendMessage(bytes_writer.getvalue(), True)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {}".format(reason))

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
            header, message = self.decode(payload)
            print("header: {}".format(header))
            print("message: {}".format(message))
        else:
            print("Text message received: {0}".format(payload.decode("utf8")))

    def decode(self, payload):
        bytes_reader = io.BytesIO(payload)
        decoder = avro.io.BinaryDecoder(bytes_reader)

        # read header
        reader = avro.io.DatumReader(self.messageHeaderSchema)
        header = reader.read(decoder)

        message_header = namedtuple("MessageHeader", list(header.keys()))(
            *list(header.values())
        )

        reader = avro.io.DatumReader(
            self.protocolsMessage[message_header.protocol][message_header.messageType]
        )
        body = reader.read(decoder)

        message_body = namedtuple("MessageBody", list(body.keys()))(
            *list(body.values())
        )

        return message_header, message_body

    def create_request_session_message(self):
        requestSession = {
            "applicationName": "",
            "applicationVersion": "",
            "requestedProtocols": [
                {
                    "protocol": 1,
                    "protocolVersion": {
                        "major": 1,
                        "minor": 1,
                        "revision": 0,
                        "patch": 0,
                    },
                    "role": "producer",
                    "protocolCapabilities": {},
                },
                {
                    "protocol": 3,
                    "protocolVersion": {
                        "major": 1,
                        "minor": 1,
                        "revision": 0,
                        "patch": 0,
                    },
                    "role": "store",
                    "protocolCapabilities": {},
                },
                {
                    "protocol": 4,
                    "protocolVersion": {
                        "major": 1,
                        "minor": 1,
                        "revision": 0,
                        "patch": 0,
                    },
                    "role": "store",
                    "protocolCapabilities": {},
                },
                {
                    "protocol": 5,
                    "protocolVersion": {
                        "major": 1,
                        "minor": 1,
                        "revision": 0,
                        "patch": 0,
                    },
                    "role": "store",
                    "protocolCapabilities": {},
                },
                {
                    "protocol": 6,
                    "protocolVersion": {
                        "major": 1,
                        "minor": 1,
                        "revision": 0,
                        "patch": 0,
                    },
                    "role": "store",
                    "protocolCapabilities": {},
                },
            ],
            "supportedObjects": [],
        }

        return requestSession

if __name__ == "__main__":
    headers = {
        "Authorization": "Basic {}".format(
            b64encode(b"ilab.user:n@6C5rN!").decode("utf-8")
        )
    }

    factory = WebSocketClientFactory(
        "wss://witsmlstudio.pds.software/staging/api/etp",
        headers=headers,
        protocols=["energistics-tp"],
    )
    factory.protocol = ETPClientProtocol
    # self.factory.on_etp_message = self.on_etp_message

    loop = asyncio.get_event_loop()
    coro = loop.create_connection(factory, "witsmlstudio.pds.software", 80)
    loop.run_until_complete(coro)
    loop.run_forever()
    loop.close()


from django.test import TestCase
from django_filters import OrderingFilter

from ...filtersets.CategoryFilterSet import CategoryFilterSet
from ...models.Category import Category

class CategoryFilterSetTest(TestCase):
    databases = {'master', }

    @classmethod
    def setUpTestData(cls):
        cls.tested_class = CategoryFilterSet

        Category.objects.create(**{
            'title': 'q' * 50,
        })

        Category.objects.create(**{
            'title': 'w' * 50,
        })

        Category.objects.create(**{
            'title': 'e' * 50,
        })

    def test_Should_IncludeDefiniteFilters(self):
        expected_filters = [
            'order_by',
        ]
        real_filters = list(self.tested_class.get_filters())

        self.assertEqual(expected_filters, real_filters)

    def test_Should_SpecificTypeForEachFilter(self):
        expected_filters = {
            'order_by': OrderingFilter,
        }
        real_filters = {
            key: value.__class__
            for key, value in self.tested_class.get_filters().items()
        }

        self.assertEqual(expected_filters, real_filters)

    def test_When_OrderByTitle_Should_ReturnOrderedData(self):
        data = {
            'order_by': 'title',
        }
        base_queryset = Category.objects.all()

        filtered_data = self.tested_class(data=data, queryset=base_queryset)

        expected_queryset = list(base_queryset.order_by('title'))
        real_queryset = list(filtered_data.qs)

        self.assertEqual(expected_queryset, real_queryset)

    def test_When_OrderByTitleDesc_Should_ReturnOrderedDescData(self):
        data = {
            'order_by': '-title',
        }
        base_queryset = Category.objects.all()

        filtered_data = self.tested_class(data=data, queryset=base_queryset)

        expected_queryset = list(base_queryset.order_by('-title'))
        real_queryset = list(filtered_data.qs)

        self.assertEqual(expected_queryset, real_queryset)


"""Implementation of a Swiss-system tournament."""

import psycopg2

WIN = 1
LOSS = 2
TIE = 3
BYE = 4

def connect():
    """Connect to the PostgreSQL tournament database.

    :returns: tournament database connection
    :rtype: psycopg2.connection

    """
    return psycopg2.connect("dbname=tournament")

def run_query(query, query_args=(), query_type='SELECT'):
    """Run a query against the tournament database.

    The query result will depend on the query type, although the result will
    always be contained in a dict or None. The scope of this project is small
    enough that opening and closing connections per query is acceptable.

    param str query: query string to run
    param tuple query_args: query args to pass to execute
    param query_type: query type to run (SELECT | UPDATE | DELETE | INSERT)
    :returns: query result; result type depends on query type
    :rtype: dict | None

    """
    query_type = query_type.upper()

    with connect() as connection:
        with connection.cursor() as cursor:
            cursor.execute(query, query_args)

            if query_type == 'SELECT':
                result = cursor.fetchall()
            elif query_type == 'INSERT' and 'RETURNING' in query:
                try:
                    # Requires RETURNING be used
                    result, = cursor.fetchone()
                except psycopg2.ProgrammingError:
                    result = None
            elif query_type in ('UPDATE', 'DELETE', 'INSERT'):
                result = cursor.rowcount
            else:
                raise ValueError(
                    "Query type %s is not supported." % query_type)

    return {'result': result}

def delete_all_from_table(table):
    """Delete all rows from a table.

    :param str table: name of the table to delete all rows from
    :returns: count of rows deleted
    :rtype: int

    """
    query = "DELETE FROM %s;" % table
    deleted = run_query(query, query_type='DELETE')
    return deleted['result']

def delete_matches():
    """Delete all the match records from the database.

    :returns: count of rows deleted from match table
    :rtype: int

    """
    return delete_all_from_table('match')

def delete_players():
    """Delete all the player records from the database.

    :returns: count of rows deleted from player table
    :rtype: int

    """
    return delete_all_from_table('player')

def count_players():
    """Count of all players currently registered.

    :returns: count of all registered players
    :rtype: int

    """
    query = "SELECT count(id) FROM player;"
    players = run_query(query)
    return players['result'][0][0]

def register_player(name):
    """Add a player to the tournament database.

    :param str name: name of player to register
    :returns: id of the registered player
    :rtype: int

    """
    query = "INSERT INTO player (name) VALUES (%s) RETURNING id;"
    inserted = run_query(query, query_args=(name,), query_type='INSERT')
    return inserted['result']

def register_tournament(name, players):
    """Add a tournament to the tournament database.

    :param str name: name of tournament to register
    :param int players: number of tournament entrants
    :returns: id of the registered tournament
    :rtype: int

    """
    query = ("INSERT INTO tournament (name, players) "
             "VALUES (%s, %s) "
             "RETURNING id;")
    inserted = run_query(
        query, query_args=(name, players), query_type='INSERT')
    return inserted['result']

def register_player_in_tournament(player, tournament):
    """Register a player in a tournament as an entrant.

    :param int player: id of the player to register
    :param int tournament: id of the tournament to register player in
    :returns: rowcount of the player inserted, 0 | 1
    :rtype: int

    """
    query = ("INSERT INTO entrant (player_id, tournament_id) "
             "VALUES (%s, %s);")
    inserted = run_query(
        query, query_args=(player, tournament), query_type='INSERT')
    return inserted['result']

def player_standings():
    """Get a list of the players and their win records, sorted by wins.

    :returns: list of players and win records
    :rtype: list

    Return format:
        [(15, 'Bruno Walton', 2, 0), (16, "Boots O'Neal", 1, 0), ...]

    """
    query = ("SELECT id, name, wins, matches "
             "FROM player "
             "ORDER BY wins DESC;")
    standings = run_query(query)
    return standings['result']

def player_opponents(player, tournament):
    """Get a list of the played opponents for a player in a tournament.

    :param int player: id of the player to get played opponents for
    :param int tournament: id of the tournament
    :returns: list of opponents that specified player has played
    :rtype: list

    """
    subquery = ("(SELECT id "
                "FROM match "
                "WHERE player_id = %s "
                "AND tournament_id = %s)")
    query = ("SELECT player_id "
             "FROM match "
             "WHERE id IN (%s) "
             "AND player_id != %s;") % (subquery, '%s')
    opponents = run_query(
        query, query_args=(player, tournament, player))
    return [result[0] for result in opponents['result']]

def player_opponents_match_wins(player, tournament):
    """Get a sum of the played opponents match wins.

    :param int player: id of the player
    :param int tournament: id of the tournament
    :returns: sum of opponent wins for a specified player
    :rtype: int

    """
    opponents = player_opponents(player, tournament)

    opponents_count = len(opponents)
    if opponents_count == 0:
        return 0
    elif opponents_count == 1:
        placeholder = "%s"
    else:
        placeholder = ("%s, " * opponents_count)[:-2]

    query = ("SELECT sum(wins) "
             "FROM player "
             "WHERE id IN (%s);") % placeholder
    opponents_match_wins = run_query(
        query, query_args=([o for o in opponents]))

    return opponents_match_wins['result'][0][0]

def player_standings_by_tournament(tournament):
    """Get a list of the players and their win records by tournament.

    :param int tournament: id of tournament to get standings for
    :returns: list of players and win records
    :rtype: list

    Return format:
        [(15, 'Bruno Walton', 2, 0), (16, "Boots O'Neal", 1, 0), ...]

    """
    query = ("SELECT id, name, wins, matches "
             "FROM player p, entrant e "
             "WHERE p.id = e.player_id "
             "AND tournament_id = %s "
             "ORDER BY wins DESC;")
    standings = run_query(query, query_args=(tournament,))
    return standings['result']

def player_has_received_bye(player, tournament):
    """Get whether or not a player has received a bye for a tournament.

    :param int player: id of the player to check
    :param int tournament: id of tournament to check
    :returns: whether a player received a bye in a tournament; True | False
    :rtype: boolean

    """
    query = ("SELECT bye "
             "FROM entrant "
             "WHERE player_id = %s "
             "AND tournament_id = %s;")
    bye = run_query(query, query_args=(player, tournament,))

    return bye['result'][0][0]

def update_match_wins(player):
    """Update match wins in standings for a player.

    :param int player: id of the winning player
    :returns: count of the rows updated; 0 | 1
    :rtype: int

    """
    query = ("UPDATE player "
             "SET wins = wins + 1 "
             "WHERE id = %s;")
    updated = run_query(query, query_args=(player,), query_type='UPDATE')
    return updated['result']

def update_matches_played(players):
    """Update matches played in standings for a player or players.

    :param list players: id of the winning player(s)
    :returns: count of the row(s) updated
    :rtype: int

    """
    players_count = len(players)
    if players_count == 1:
        placeholder = "%s"
    else:
        placeholder = ("%s, " * players_count)[:-2]

    query = ("UPDATE player "
             "SET matches = matches + 1 "
             "WHERE id IN (%s);") % placeholder
    updated = run_query(
        query, query_args=tuple(p for p in players), query_type='UPDATE')

    return updated['result']

def report_match(winner, loser, tournament, tie=False):
    """Report the outcome of a single match between two players.

    Both win-lose and tie matches are reported by report_match. In the event
    of a tie both players are considered winners.

    :param int winner: id of the winner
    :param int loser: id of the loser
    :param int tournament: id of the tournament the match was played in
    :param bool tie: whether match was a tie; True | False
    :returns: id of the reported match
    :rtype: int

    """
    # Add winner or tie
    result_type = TIE if tie else WIN
    query = ("INSERT INTO match "
             "(player_id, tournament_id, result_id) "
             "VALUES (%s, %s, %s) "
             "RETURNING id;")
    inserted = run_query(
        query,
        query_args=(winner, tournament, result_type), query_type='INSERT')

    match_id = inserted['result']

    # Add loser or tie
    result_type = TIE if tie else LOSS
    query = ("INSERT INTO match "
             "(id, player_id, tournament_id, result_id) "
             "VALUES (%s, %s, %s, %s);")
    run_query(
        query,
        query_args=(match_id, loser, tournament, result_type),
        query_type='INSERT')

    # Update matches played and wins
    update_matches_played([winner, loser])
    update_match_wins(winner)

    # Ties count as wins
    if tie:
        update_match_wins(loser)

    return match_id

def report_match_bye(player, tournament):
    """Report a bye for a player in a tournament.

    :param int player: id of the player to report a bye for
    :param int tournament: id of the tournament to report the bye in
    :returns: rowcount of the player updated; 0 | 1
    :rtype: int

    """
    query = ("UPDATE entrant "
             "SET bye = TRUE "
             "WHERE player_id = %s "
             "AND tournament_id = %s;")
    updated = run_query(
        query, query_args=(player, tournament), query_type='UPDATE')

    # Add bye match to match table
    query = ("INSERT INTO match "
             "(player_id, tournament_id, result_id) "
             "VALUES (%s, %s, %s);")
    run_query(
        query, query_args=(player, tournament, BYE), query_type='INSERT')

    # Update matches played and wins
    update_matches_played([player])
    update_match_wins(player)

    return updated['result']

def rank_by_opponent_match_wins(standings, tournament):
    """Rank like players using opponent match wins.

    Players that have equal match wins should be ranked according to the
    strength of the opponents beaten.

    :param list standings: standings for a tournament
    :param int tournament: standings for a tournament
    :returns: standings sorted by opponent match wins
    :rtype: list

    """
    def omw_sort(player1, player2):
        if player1[2] == player2[2]:
            player1_omw = player_opponents_match_wins(player1[0], tournament)
            player2_omw = player_opponents_match_wins(player2[0], tournament)
            if player1_omw > player2_omw:
                return -1
        return 1

    return sorted(standings, cmp=omw_sort)

def swiss_pairings(tournament):
    """Pair players for the next round in a swiss-style tournament.

    Players are paired with an opponent with a equal or nearly-equal win
    record. A player cannot play the same opponent twice.

    :param int tournament: id of the tournament to pair the next round for
    :returns: tuples containing pairings in the format --
        (id1, name1, id2, name2)
    :rtype: list

    """
    standings = player_standings_by_tournament(tournament)
    standings = rank_by_opponent_match_wins(standings, tournament)
    standings = [standing[:2] for standing in standings]

    # Player receives a bye if odd number of players
    if len(standings) % 2 != 0:
        for standing in reversed(standings):
            player, _ = standing
            if not player_has_received_bye(player, tournament):
                report_match_bye(player, tournament)
                standings.pop(standings.index(standing))
                break

    players, opponents = [], []
    while standings:
        # Add the player we are going to find a match for
        player = standings.pop(0)
        players.append(player)

        opponents_played = player_opponents(player[0], tournament)
        # Iterate over the remaining opponents (standings after pop)
        for index, opponent in enumerate(iter(standings)):
            opponent_id, _ = opponent
            # Never play the same opponent twice
            if opponent_id not in opponents_played:
                # Match found; move to next player in standings
                opponents.append(standings.pop(index))
                break

    # Pair players with their respective opponents (determined above)
    pairings = []
    for matchup in zip(players, opponents):
        player, opponent = matchup
        pairings.append(player + opponent)

    return pairings


# coding: utf-8

def makeListe(entree):
    liste = []
    compteur = 0
    for index, valeur in enumerate(entree):
        if valeur == '+' or valeur == '-' or valeur == '*' or valeur == '/' or valeur == '(' or valeur == ')':
            if entree[compteur:index] != '':
                liste.append(entree[compteur:index])
            liste.append(valeur)
            compteur = index + 1
    if compteur != len(entree):
        liste.append(entree[compteur:])
    return liste

def calculate(liste):
    for index, valeur in enumerate(liste):
        if valeur == '*':
            liste[index] = float(liste[index - 1]) * float(liste[index + 1])
            liste.pop(index + 1)
            liste.pop(index - 1)
            return calculate(liste)
        if valeur == '/':
            liste[index] = float(liste[index - 1]) / float(liste[index + 1])
            liste.pop(index + 1)
            liste.pop(index - 1)
            return calculate(liste)
    for index, valeur in enumerate(liste):
        if valeur == '+':
            liste[index] = float(liste[index - 1]) + float(liste[index + 1])
            liste.pop(index + 1)
            liste.pop(index - 1)
            return calculate(liste)

        if valeur == '-':
            liste[index] = float(liste[index - 1]) - float(liste[index + 1])
            liste.pop(index + 1)
            liste.pop(index - 1)
            return calculate(liste)
    if len(liste) > 1:
        return calculate(liste)
    return liste[0]

def prepareCalcul(liste):
    for index, valeur in enumerate(liste):
        if valeur == '(':
            return prepareCalcul(liste[index + 1:])
        if valeur == ')':
            return calculate(liste[:index])

def diminution(liste):
    while '(' in liste:
        remplacement = prepareCalcul(liste)
        number = 0
        for index, valeur in enumerate(liste):
            if valeur == '(':
                number = index
            if valeur == ')':
                for i in range(index - number):
                    liste.pop(number)
                liste[number] = remplacement
                break
    return calculate(liste)

def verifInput(liste):
    nbParentheseOuvrantes = 0
    nbParentheseFermantes = 0
    for index, valeur in enumerate(liste):
        if not valeur.isdigit() and valeur not in ['+', '-', '*', '/', '(', ')', '.']:
            return 0
        if valeur == '(':
            nbParentheseOuvrantes += 1
        if valeur == ')':
            nbParentheseFermantes += 1
        if valeur == '+' or valeur == '-' or valeur == '/' or valeur == '*':
            if liste[index + 1] == '+' or liste[index + 1] == '-' or liste[index + 1] == '/' or liste[index + 1] == '*':
                return 0
    if nbParentheseFermantes != nbParentheseOuvrantes:
        return 0
    return 1

entree = str(input())
while verifInput(entree) == 0:
    print('pas bon, veuillez réécrire l expression: ')
    entree = str(input())
entree = makeListe(entree)
print(entree)
print('votre résultat: ' + str(diminution(entree)))


# -*- coding: utf-8 -*-
import openpyxl
"""DATA_OF_2017={
    'First_Number' : 749, #First_Number = 우선선발 신청한 인원 수
    'Second_Number' : 448, #Second_Number = 일반선발A 신청한 인원 수
    'Third_Number' : 1, #Third_Number = 일반선발B 신청한 인원 수
    'First_Input' : 82900, #First_Input = 우선선발의 총 용량(가중치가 포함 됨)
    'Second_Input' : 403514, #Second_Input = 일반선발A의 총 용량(가중치가 포함 됨)
    'Third_Input' : 3843, #Thrid_Input = 일반선발B의 총 용량(가중치가 포함 됨)
    'First_Capacity' : 150000, #First_Capacity = 250000(공고용량) * 0.6
    'Second_Capacity' : 75000, #Second_Capacity = 250000(공고용량) * 0.3
    'Third_Capacity' : 25000, #Third_Capacity = 250000(공고용량) * 0.1
    'Upper_Limit' : 110, #2017년 SMP 평균 가격 81.125  REC 평균 가격 103,473 (육지기준)
    'Average' : 100, # 1REC = 1000kw (가중치는 이미 계산 됨) then Upper_Limit = 110,205 (SMP가 연 평균이므로 110으로 생각)
}
"""
DATA_OF_2017 = {
    'First_Number' : 1548, #First_Number = 우선선발 신청한 인원 수
    'Second_Number' : 711,  #Second_Number = 일반선발A 신청한 인원 수
    'Third_Number' : 1, #Third_Number = 일반선발B 신청한 인원 수
    'First_Input' : 171985, #First_Input = 우선선발의 총 용량(가중치가 포함 됨)
    'Second_Input' : 575856, #Second_Input = 일반선발A의 총 용량(가중치가 포함 됨)
    'Third_Input' : 3844, #Thrid_Input = 일반선발B의 총 용량(가중치가 포함 됨)
    'First_Capacity' : 150000, #First_Capacity = 250000(공고용량) * 0.6
    'Second_Capacity' : 75000, #Second_Capacity = 250000(공고용량) * 0.3
    'Third_Capacity' : 25000, #Third_Capacity = 250000(공고용량) * 0.1
    'Upper_Limit' : 110, #2017년 SMP 평균 가격 81.125  REC 평균 가격 103,473 (육지기준) then Upper_Limit = 110,205 (SMP가 연 평균이므로 110으로 생각)
    'Average' : 103, # 1REC = 1000kw (가중치는 이미 계산 됨) then  Average = 103.473 (SMP가 연 평균이므로 103으로 생각) 우선선발, 일반선발A, 일반선발B 모두 똑같다고 가정
}

First_Average=float(DATA_OF_2017['First_Input'])/float(DATA_OF_2017['First_Number'])
Second_Average=float(DATA_OF_2017['Second_Input'])/float(DATA_OF_2017['Second_Number'])
Third_Average=float(DATA_OF_2017['Third_Input'])/float(DATA_OF_2017['Third_Number'])

Standard_Deviation_List =[5,10,20,30]  #표준편차  = 다양하게 계산 할 예정

wb=openpyxl.load_workbook("연습.xlsx")
ws=wb.active
ws["B1"],ws["B14"],ws["B27"],ws["B40"]="알파 퍼센트(공정성)","알파 퍼센트(공정성)","알파 퍼센트(공정성)","알파 퍼센트(공정성)"
ws["A1"],ws["A14"],ws["A27"],ws["A40"]="표준편차","표준편차","표준편차","표준편차"
ws["A2"],ws["A15"],ws["A28"],ws["A41"]="5","10","20","30"
ws["C1"],ws["C14"],ws["C27"],ws["C40"]="효율성","효율성","효율성","효율성"
ws["D1"],ws["D14"],ws["D27"],ws["D40"]="Jain Index","Jain Index","Jain Index","Jain Index"
ws["E1"],ws["E14"],ws["E27"],ws["E40"]="예정","예정","예정","예정"

for i in range(2,12):
    ws.cell(row=i,column=2).value=0.02*(i-1)
for i in range(2,12):
    ws.cell(row=i+13,column=2).value=0.02*(i-1)
for i in range(2,12):
    ws.cell(row=i+26,column=2).value=0.02*(i-1)
for i in range(2,12):
    ws.cell(row=i+39,column=2).value=0.02*(i-1)

in_advance_List=[0.02,0.04,0.06,0.08,0.10,0.12,0.14,0.16,0.18,0.20]

efficiency=0
Jain_fairness_index=0


from collections import UserDict
import datetime

class Field:
    def __init__(self, value):
        self.__value = None
        self.value = value

    @property
    def value(self) -> str:
        return self.__value

    @value.setter
    def value(self, value) -> None:
        self.__value = value

class Name(Field):

    @property
    def value(self) -> str:  #  це геттер, який повертає захищенне поле self.__value
        return self.__value

    @value.setter  # це сеттер який записує значення що приходить в конструктор(змінна value) тільки якщо пройде перевірку
    def value(self, value) -> None:
        if len(value) < 2:
            raise ValueError("Імʼя повинно бути довже ніж 2 симовли")
        self.__value = value

class Phone(Field):

    @property
    def value(self) -> str:  # це геттер, який повертає захищенне поле self.__value
        return self.__value

    @value.setter  # це сеттер який записує значення що приходить в конструктор(змінна value) тільки якщо пройде перевірку
    def value(self, value) -> None:
        if not all(char.isdigit() for char in value):
            raise ValueError("Номер телефону повинен складатися лише з цифр")
        self.__value = value

class Birthday(Field):

    @property
    def value(self) -> datetime:  # це геттер, який повертає захищенне поле self.__value
        return self.__value

    @value.setter  # це сеттер який записує значення що приходить в конструктор(змінна value) тільки якщо пройде перевірку
    def value(self, value) -> None:
        if not isinstance(value, datetime.date):
            raise ValueError("День народження повинен бути об'єктом datetime.date")
        self.__value = value

class Record:
    def __init__(self, name, phone=None, birthday=None):
        self.name = name
        self.optional_fields = {}
        if phone:
            self.add_phone(phone)
        if birthday:
            self.add_birthday(birthday)

    def add_field(self, field):
        if isinstance(field, Field):
            self.optional_fields[field.name] = field

    def remove_field(self, field_name):
        if field_name in self.optional_fields:
            del self.optional_fields[field_name]

    def edit_field(self, field_name, new_value):
        if field_name in self.optional_fields:
            self.optional_fields[field_name].set_value(new_value)

    def add_phone(self, phone):
        if isinstance(phone, Phone):
            self.optional_fields['Телефон'] = phone

    def add_birthday(self, birthday):
        if isinstance(birthday, Birthday):
            self.optional_fields['День народження'] = birthday

    def days_to_birthday(self):
        if 'День народження' in self.optional_fields and self.optional_fields['День народження'].value:
            today = datetime.date.today()
            birthday = self.optional_fields['День народження'].value
            next_birthday = datetime.date(today.year, birthday.month, birthday.day)
            if today > next_birthday:
                next_birthday = datetime.date(today.year + 1, birthday.month, birthday.day)
            days_remaining = (next_birthday - today).days
            return days_remaining

class AddressBook(UserDict):
    def add_record(self, record):
        self.data[record.name.value] = record

    def __iter__(self):
        self._iter_keys = iter(self.data.keys())
        return self

    def __next__(self):
        try:
            key = next(self._iter_keys)
            return self.data[key]
        except StopIteration:
            raise StopIteration

    def iterator(self, batch_size):
        iter_keys = iter(self.data.keys())
        while True:
            batch = [self.data[next(iter_keys)] for _ in range(batch_size)]
            if not batch:
                break
            yield batch

if __name__ == "__main__":
    name = Name('Білл')
    phone = Phone('1234567890')
    birthday = Birthday(datetime.date(1990, 8, 14))
    rec = Record(name, phone=phone, birthday=birthday)
    ab = AddressBook()
    ab.add_record(rec)

    assert isinstance(ab['Білл'], Record)
    assert isinstance(ab['Білл'].name, Name)
    assert isinstance(ab['Білл'].optional_fields['Телефон'], Phone)
    assert isinstance(ab['Білл'].optional_fields['День народження'], Birthday)
    assert ab['Білл'].optional_fields['Телефон'].value == '1234567890'
    assert ab['Білл'].days_to_birthday() == 365  # Change this based on current date and birthday

    print('Все Ок :)')


from funcy import lmap, partial, silent
from odd_models import DataEntity, DataEntityType, DataSet
from odd_models.models import DataTransformer
from oddrn_generator import PostgresqlGenerator

from ..models import Table
from .columns import map_column
from .metadata import get_table_metadata
from .utils import has_vector_column

def map_view(generator: PostgresqlGenerator, view: Table):
    generator.set_oddrn_paths(
        **{"schemas": view.table_schema, "views": view.table_name}
    )
    map_view_column = partial(map_column, generator=generator, path="views")

    # If view contains vector column we consider it as a vector store, otherwise - an ordinary view
    data_entity_type = (
        DataEntityType.VECTOR_STORE
        if has_vector_column(view.columns)
        else DataEntityType.VIEW
    )

    return DataEntity(
        oddrn=generator.get_oddrn_by_path("views"),
        name=view.table_name,
        type=data_entity_type,
        owner=view.table_owner,
        description=view.description,
        metadata=[get_table_metadata(entity=view)],
        dataset=DataSet(
            rows_number=silent(int)(view.table_rows),
            field_list=lmap(map_view_column, view.columns),
        ),
        data_transformer=DataTransformer(
            sql=view.view_definition, inputs=[], outputs=[]
        ),
    )


from pptx import Presentation
from pptx.util import Inches

# copy from: https://groups.google.com/forum/#!topic/python-pptx/cVRP9sSpEjA

# merge cells vertically
def mergeCellsVertically(table, start_row_idx, end_row_idx, col_idx):
    row_count = end_row_idx - start_row_idx + 1
    column_cells = [r.cells[col_idx] for r in table.rows][start_row_idx:]

    column_cells[0]._tc.set('rowSpan', str(row_count))
    for c in column_cells[1:]:
        c._tc.set('vMerge', '1')

# merge cells horizontally
def mergeCellsHorizontally(table, row_idx, start_col_idx, end_col_idx):
    col_count = end_col_idx - start_col_idx + 1
    row_cells = [c for c in table.rows[row_idx].cells][start_col_idx:end_col_idx]
    row_cells[0]._tc.set('gridSpan', str(col_count))
    for c in row_cells[1:]:
        c._tc.set('hMerge', '1')

# the workaround function to merge cells in a table
def mergeCells(table, start_row_idx, end_row_idx, start_col_idx, end_col_idx):
    for col_idx in range(start_col_idx,end_col_idx+1):
        mergeCellsVertically(table,start_row_idx, end_row_idx, col_idx)
    for row_idx in range(start_row_idx,end_row_idx+1):
        mergeCellsHorizontally(table, row_idx, start_col_idx, end_col_idx)

if __name__ == '__main__':
    prs = Presentation()
    title_only_slide_layout = prs.slide_layouts[5]
    slide = prs.slides.add_slide(title_only_slide_layout)
    shapes = slide.shapes

    shapes.title.text = 'Adding a Table'

    rows = cols = 4
    top = Inches(2.0)
    left = Inches(1.0)
    width = Inches(8.0)
    height = Inches(1)

    table = shapes.add_table(rows, cols, left, top, width, height).table

    # set column widths
    table.columns[0].width = Inches(2.0)
    table.columns[1].width = Inches(2.0)
    table.columns[2].width = Inches(2.0)
    table.columns[3].width = Inches(2.0)

    # write column headings
    table.cell(0, 0).text = 'Column1'
    table.cell(0, 1).text = 'Column2'
    table.cell(0, 2).text = 'Column3'
    table.cell(0, 3).text = 'Column4'

    # write body cells
    table.cell(1, 0).text = 'Merged vertically and horizontally'
    table.cell(1, 2).text = 'Cell 1-3'
    table.cell(2, 2).text = 'Cell 2-3'
    table.cell(3, 2).text = 'Cell 3-3'
    table.cell(1, 3).text = 'Merged vertically'
    table.cell(3, 0).text = 'Merged horizontally'
    table.cell(3, 3).text = 'Cell 3-4'

    # merge cells vertically
    mergeCellsVertically(table=table, start_row_idx=1, end_row_idx=2, col_idx=3)
    # merge cells horizontally
    mergeCellsHorizontally(table=table, row_idx=3, start_col_idx=0, end_col_idx=1)
    # merge cells vertically and horizontally
    mergeCells(table=table, start_row_idx=1, end_row_idx=2, start_col_idx=0, end_col_idx=1)
    prs.save('test.pptx')


import os
import sys
import platform

from .sheet import Sheet
from .arguments import Arguments

class sheetGod():
	AllowedCommands = [
		"help",
		"quit",
		"clear",
		"cls",
		"show",
		"open",
		"deleterow"
	]
	sheet = Sheet(AllowedCommands)

	def InteractiveCLI(self):
		print("sheetGod v.0.0.1 (by Doug Beney)")

		print("\n")
		print("* Website: https://sheetgod.dougie.io")
		print("* Docs: https://sheetgod.dougie.io/docs")
		print("* Contact the dev: https://sheetgod.dougie.io/contact")
		print("\n")

		self.CLI_IS_RUNNING = True
		self.sheet.setManualCommands([
			{
				"name": "exit / quit",
				"help": "Use this to quit sheetGod CLI",
			},
			{
				"name": "clear / cls",
				"help": "Use this command to clear the console."
			}
		])

		while self.CLI_IS_RUNNING:
			# CLI Interface Loop
			cmd = input("$ ")

			cmdArray = cmd.split(" ")
			mainCommand = cmdArray[0]
			cmdArray.remove(cmdArray[0])

			# If user typed exit or quit, exit immediately.
			if mainCommand in self.AllowedCommands:
				if mainCommand == "exit" or mainCommand == "quit":
					print("Goodbye!")
					self.CLI_IS_RUNNING = False
					break
				elif mainCommand == "clear" or mainCommand == "cls":
					operating_system = platform.system()
					clear_command = "clear"
					if "Windows" in operating_system:
						clear_command = "cls"
					os.system(clear_command)
				elif cmd != "":
					try:
						getattr(self.sheet, mainCommand)(*cmdArray)
					except AttributeError as err:
						print(err)
						getattr(self.sheet, "help")(cmd)
			else:
				print("Command does not exist.")
				print("¯\_(ツ)_/¯")
				print("Type 'help' for a list of commands.")

		# Printing header columns
		# print("Columns:")
		# for column in self.theSheet.row[0]:
		# 	print("- " + column)

	def __init__(self, userSubmittedCMDLIST=[]):
		self.commandList = [
			{
				"name": "CLI Mode",
				"description": "Uses CLI instead of GUI.",
				"type": "generic",
				"variants": ("-c", "--cli"),
				"function": self.InteractiveCLI,
			},
			{
				"name": "Open File",
				"description": "(Example usage: '--open=myfile.csv')",
				"type": "variable",
				"variants": ("-o", "--open"),
				"function": self.sheet.open,
			},
		]
		self.commandList = userSubmittedCMDLIST + self.commandList

		self.commands = Arguments(sys.argv, self.commandList)


from pydantic import BaseSettings, root_validator

class Settings(BaseSettings):

    google_client_id: str | None = None
    google_authorize_url: str | None = None
    google_redirect_uri: str | None = None
    google_scope: str = 'openid email'

    github_client_id: str | None = None
    github_authorize_url: str | None = None
    github_redirect_uri: str | None = None
    github_scope: str = 'openid email'

    @root_validator
    def check_google_params(cls, values):
        three_values = [
            values.get('google_client_id'),
            values.get('google_authorize_url'),
            values.get('google_redirect_uri')
        ]
        count = len([v for v in three_values if v])

        if count not in (0, 3):
            raise ValueError(
                'google_client_id, google_authorize_url and google_redirect_uri'
                ' should be either all absent or all present'
            )

        return values

    @root_validator
    def check_github_params(cls, values):
        three_values = [
            values.get('github_client_id'),
            values.get('github_authorize_url'),
            values.get('github_redirect_uri')
        ]
        count = len([v for v in three_values if v])

        if count not in (0, 3):
            raise ValueError(
                'github_client_id, github_authorize_url and github_redirect_uri'
                ' should be either all absent or all present'
            )

        return values

    class Config:
        env_prefix = 'PAPERMERGE__AUTH__'

def get_settings():
    return Settings()


# filename Dz3_Chaevye.py
# Щедрый посетитель

chek = int(input("Введите сумму счета за обед: "))
#chai15 = chek * 0.15
#chai20 = chek * 0.2
#print("Чаевый составили ", chai15, "15% и ", chai20, "20% от суммы.")
print("Чаевый составили ", (chek * 0.15), "15% и ", (chek * 0.2), "20% от суммы.")

# Выход
input("\nНажмите Ентер шобы выйти!")


#-----
# Description   : Example script to use cpu backprojection code
# Date          : Nov 2020
# Author        : Berkan Lafci
# E-mail        : lafciberkan@gmail.com
#-----

#%% Start logging
import logging
logging.basicConfig(filename='exampleCpuBP.log', filemode='w', level=logging.INFO)
logging.info('  Script      "exampleCpuBP"      : exampleCpuBP.py')

#%% Import libraries
import os
import numpy as np
import matplotlib.pyplot as plt

# stop writing __pycache__ files
import sys
sys.dont_write_bytecode = True

from pyoat import *

#%% Data paths (defined by users)
folderPath          = 'data/rawData'
scanName            = 'mouseCrossSection'

#%% read signal file
oaData              = oaReader(folderPath=folderPath, scanName=scanName, averaging=False)
sigMat              = oaData.sigMat

#%% Initialize cpuBP object
bp                  = cpuBP()

#%% Reconstruction parameters (defined by user)
bp.speedOfSound     = 1535              # change SoS based on water temperature (default: 1480)
bp.fieldOfView      = 0.024             # FOV to reconstruct (default: 0.03)
bp.pixelNumber      = 512               # increase this number for higher resolution (default: 128)
bp.cupType          = 'ring'    		# ring, multisegment, virtualRing (default: ringCup)
bp.reconType        = 'full'            # full, direct or derivative (default: full)
bp.delayInSamples   = 64                # reception delay in samples
bp.wavelengths      = [800]             # wavelengths used in acquisition
bp.lowCutOff        = 0.1e6             # low cutoff for bandpass (default: 0.1e6)
bp.highCutOff       = 6e6               # high cutoff for bandpass (default: 6e6)

#%% Reconstruction
imageRecon          = bp.reconBP(sigMat)

# #%% Visualize reconstructed images (optional)
# plt.figure()
# plt.imshow(imageRecon[:,:,0,0], cmap='gray')
# plt.show()

#%% Save reconstructed images (optional)

# save as png
imageReconRotated = np.rot90(imageRecon,1)
pngPath = 'data/pngImages'
saveImagePng(reconObject=bp, pngPath=pngPath, saveName='BP_'+scanName, imageRecon=imageReconRotated)

# save as mat
imageReconRotated = np.rot90(imageRecon,1)
matPath = 'data/matImages'
saveImageMat(reconObject=bp, matPath=matPath, saveName='BP_'+scanName, imageRecon=imageReconRotated)


import os
from PyPDF2 import PdfFileWriter, PdfFileReader

# Splits a single page pdf into several pages.
def pdf_splitter(path, parts):
    # file name.
    fname = os.path.splitext(os.path.basename(path))[0]
    pdf_writer = PdfFileWriter()
    page = get_base_page(path)
    dim = get_dim(page)
    # print(dim)
    upper_right = dim["upperRight"]
    scale = upper_right[1] / parts
    pages = []

    # Generates pages.
    for part in range(0, parts):
        page = get_base_page(path)
        page.cropBox.upperLeft = (0, part * scale)
        page.cropBox.lowerLeft = (0, (part + 1) * scale)
        pages.append(page)

    # Adds the pages to the new pdf in the right order.
    for split_page in range(len(pages)):
        pdf_writer.addPage(pages.pop())

    # Writes new pdf
    output_filename = '{}_{}.pdf'.format(fname, "split")
    with open(output_filename, 'wb') as out:
        pdf_writer.write(out)

# returns first page.
def get_base_page(path):
    pdf = PdfFileReader(path)
    return pdf.getPage(0)

# returns page dimensions.
def get_dim(page):
    return {
        "lowerLeft": page.cropBox.getLowerLeft(),
        "lowerRight" : page.cropBox.getLowerRight(),
        "upperLeft" : page.cropBox.getUpperLeft(),
        "upperRight" : page.cropBox.getUpperRight()
    }


'''
Created on Jan 29, 2017

@author: ubuntu
'''
import urllib.request
import re

url = 'http://pythonprogramming.net'
values = {'s':'basic','submit':'search'}

data = urllib.parse.urlencode(values)
data = data.encode('utf-8')

req = urllib.request.Request(url, data)
res = urllib.request.urlopen(req)

resData = res.read()

parags = re.findall(r'<p>(.*?)</p>', str(resData))

for parag in parags:
    print('==================')
    print(parag)
    print('==================')


#!/usr/bin/env python
# coding: utf-8

# In[ ]:

import numpy as np
import matplotlib.pyplot as plt
import xarray as xr

eps_r    = 0.18
q_0      = 1.42

ds1 = xr.open_dataset("data_netcdf/txE_resonant_multiscale.nc")
ds2 = xr.open_dataset("data_netcdf/txE_resonant_woelectronscale.nc")
ds3 = xr.open_dataset("data_netcdf/txE_offresonant_multiscale.nc")
ds4 = xr.open_dataset("data_netcdf/txE_offresonant_woelectronscale.nc")
ds_list = [ds1, ds2, ds3, ds4]

# In[ ]:

fig=plt.figure(figsize=(3.4,2.5),dpi=600) # figsize=(幅,高さ(inch)),dpi(dots per inch)
plt.style.use('../nature_style.txt')

###
label = [r"Resonant $v=2v_\mathrm{te}$ (Multi-scale)",
         r"Resonant $v=2v_\mathrm{te}$ (w/o electron-scale)",
         r"Off-resonant $v=2.5v_\mathrm{te}$ (Multi-scale)",
         r"Off-resonant $v=2.5v_\mathrm{te}$ (w/o electron-scale)"]
color = ["tab:red", "k", "b", "tab:green"]
linestyle = ["solid", "dashed", "solid", "dashed"]
ax=fig.add_subplot(211)
ax.axes.xaxis.set_ticklabels([])
ax.set_ylabel("Poloidal electric \n field "+r"$E_y$ ($T_\mathrm{i}/eR_0$)")
for i in range(4):
    ds = ds_list[i]
    y = ds.y
    j0Ey = ds.j0Ey
    ax.plot((y-y[0])*q_0/eps_r,j0Ey,label=label[i],c=color[i],linestyle=linestyle[i],lw=1)
ax.axhline(0,c="k",lw=0.5)
ax.set_xlim(0,1450)
ax.set_ylim(-20,20)
ax.set_yticks([-15,0,15])
fig.legend(loc="lower left",ncol=1,bbox_to_anchor=(0.15,0.88),labelspacing=0)
ax=fig.add_subplot(212)
ax.set_xlabel(r"Toroidal path length $y q / \epsilon_r$ ($\rho_\mathrm{ti}$)")
ax.set_ylabel("Radial\n displacement\n" + r"$x$ ($\rho_\mathrm{ti}$)")
for i in range(4):
    ds = ds_list[i]
    y = ds.y
    x = ds.x
    ax.plot((y-y[0])*q_0/eps_r,x-x[0],label=label[i],c=color[i],linestyle=linestyle[i],lw=1)
ax.axhline(0,c="k",lw=0.5)
ax.set_xlim(0,1450)
ax.set_ylim(-15,50)
ax.set_yticks([0,20,40])

fig.text(0.045,0.885,"a",color="k", fontfamily="sans-serif", fontweight="bold", fontsize=8)
fig.text(0.045,0.460,"b",color="k", fontfamily="sans-serif", fontweight="bold", fontsize=8)

plt.savefig("fig2.jpg",dpi=600)
plt.savefig('fig2.svg',bbox_inches="tight")
import subprocess
subprocess.call('inkscape fig2.svg -M fig2.emf', shell=True)
subprocess.call('inkscape fig2.svg -E fig2.eps', shell=True)
subprocess.call('inkscape fig2.svg -A fig2.pdf', shell=True)
plt.show()

# In[ ]:

# In[ ]:


import numpy as np
import matplotlib.pyplot as plt
import random
import math
import cPickle as pickle
import gzip
import threading
from collections import deque

def load_data():
  global training_set, training_labels, testing_set, testing_labels
  f = gzip.open('mnist.pkl.gz', 'rb')
  train, valid, test = pickle.load(f)

  [training_set, training_labels] = train
  [validation_set, validation_labels] = valid
  [testing_set, testing_labels] = test

  for i in range( len(training_set) ):
    training_set[i] = training_set[i].reshape(28*28)

  for i in range( len(testing_set) ):
    testing_set[i] = testing_set[i].reshape(28*28)

  f.close()

T = 1000
dt = 2
time_steps = int(T / dt)

# max_weight = 5e-4
# min_weight = 5e-6

max_weight = 8e-4
min_weight = 4e-6

avg_weight = 5e-5
learning_rate = 5e-9

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

load_data()
Wsyn = np.random.normal(0, 1.0, size=(28*28, 20*20))
Wsyn = np.absolute(Wsyn)
# Wsyn = np.load('XeAe.npy')
assert( (np.prod(Wsyn.shape) - np.count_nonzero(Wsyn >= 0)) == 0 )
Wsyn = Wsyn * (avg_weight / np.average(Wsyn))

Wsyn_e = np.random.normal(0, 1.0, size=(20*20, 20*20))
Wsyn_e = np.absolute(Wsyn_e)
Wsyn_e = Wsyn_e * (avg_weight / np.average(Wsyn_e))

Wsyn_i = np.random.normal(0, 1.0, size=(20*20, 20*20))
Wsyn_i = np.absolute(Wsyn_i)
Wsyn_i = Wsyn_i * (avg_weight / np.average(Wsyn_i))

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

def calc_gradient(idx, start_idx, end_idx, gradient, spikes, labels):
    start_input_intensity = 10
    input_intensity = start_input_intensity

    gradient[idx] = np.zeros(shape=(28*28, 20*20))
    spikes[idx] = []
    labels[idx] = []

    while start_idx < end_idx:

        print ("thread #" + str(idx) + " " + str(start_idx) + " " + str(input_intensity))

        ################
        v = np.zeros(20*20)
        u = np.zeros(20*20)

        v_i = np.zeros(20*20)
        u_i = np.zeros(20*20)

        Isyn = np.zeros(28*28)
        g = np.zeros(shape=(1, 28*28))

        Isyn_e = np.zeros(20*20)
        g_e = np.zeros(20*20)

        Isyn_i = np.zeros(20*20)
        g_i = np.zeros(shape=(1, 20*20))

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

        input_fires = np.zeros(shape=(time_steps, 28*28))
        input_fired_counts = np.zeros(28*28)

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

        output_fired = np.zeros(20*20)
        output_not_fired = np.zeros(20*20)
        output_fires = np.zeros(shape=(time_steps, 20*20))
        output_fired_counts = np.zeros(20*20)
        refractory = np.zeros(20*20)

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

        inh_fired = np.zeros(20*20)
        inh_not_fired = np.zeros(20*20)
        inh_fires = np.zeros(shape=(time_steps, 20*20))
        inh_fired_counts = np.zeros(20*20)
        inh_refractory = np.zeros(20*20)

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

        # what is freq / ms
        # Hz / 1000
        # (25.0 / 1000.0) = 25Hz
        # rates = state * (25.0 / 1000.0)

        rates = (training_set[start_idx] * 32.)
        rates = rates / (np.average(rates)) # divide by max rate
        rates = rates * input_intensity
        rates = rates / 1000 # divide to get ms

        for t in range(time_steps):

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

            input_fired = np.random.rand(1, 28*28) < rates * dt
            input_fires[t] = input_fired
            input_fired_counts = input_fired_counts + input_fired

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

            g = g + input_fired
            Isyn = np.dot(g, Wsyn)
            Isyn = Isyn.flatten ()
            g = np.max((1 - dt/10) * g, 0)

            g_e = g_e + inh_fired
            Isyn_e = np.dot(g_e, Wsyn_e) # this is the 400x400 synapses
            Isyn_e = Isyn_e.flatten()
            g_e = np.max((1 - dt/10) * g_e, 0)

            dv = -0.07 * dt
            v = np.clip(v + (dv + Isyn - Isyn_e) * dt, 0, 35)
            # v = np.clip(v + (dv + Isyn) * dt, 0, 35)
            not_refractory = (refractory == 0)
            v = v * not_refractory

            output_fired = v >= 35
            output_not_fired = v < 35
            output_fires[t] = output_fired
            output_fired_counts = output_fired_counts + output_fired

            refractory = refractory + output_fired * 10
            refractory = np.clip(refractory - 1, 0, 4)

            v = v * output_not_fired

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

            g_i = g_i + output_fired
            Isyn_i = np.dot(g_i, Wsyn_i)
            Isyn_i = Isyn_i.flatten()
            g_i = np.max((1 - dt/5) * g_i, 0)

            # print ("exc", np.average(g), np.average(Isyn))
            # print ("inh", np.average(g_i), np.average(Isyn_i))

            dv_i = -0.07 * dt
            v_i = np.clip(v_i + (dv_i + Isyn_i) * dt, 0, 35)
            not_inh_refractory = (inh_refractory == 0)
            v_i = v_i * not_inh_refractory

            inh_fired = v_i >= 35
            inh_not_fired = v_i < 35
            inh_fires[t] = inh_fired
            inh_fired_counts = inh_fired_counts + inh_fired

            inh_refractory = inh_refractory + inh_fired * 10
            inh_refractory = np.clip(inh_refractory - 1, 0, 4)

            v_i = v_i * inh_not_fired

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

        output_fires_post = np.zeros(shape=(time_steps, 20*20))
        output_fires_pre = np.zeros(shape=(time_steps, 20*20))

        for i in range(20*20):
            flag = 0
            for j in range(time_steps):
                if (output_fires[j][i]):
                    flag = 10
                if flag:
                    output_fires_post[j][i] = 1
                    flag = flag - 1

            flag = 0
            for j in reversed(range(time_steps)):
                if (output_fires[j][i]):
                    flag = 10
                if flag:
                    output_fires_pre[j][i] = 1
                    flag = flag - 1

        input_fires = np.transpose(input_fires)
        post = np.dot(input_fires, output_fires_post)
        pre = np.dot(input_fires, output_fires_pre)

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

        if np.sum(output_fired_counts) < 10:
            input_intensity += 1
        else:
            print ( np.sum(input_fired_counts), np.sum(output_fired_counts), np.sum(inh_fired_counts) )
            print ( np.average(input_fired_counts), np.average(output_fired_counts), np.average(inh_fired_counts) )

            input_intensity = start_input_intensity

            gradient[idx] = gradient[idx] + (pre - post) * learning_rate
            spikes[idx].append(output_fired_counts.flatten())
            labels[idx].append(training_labels[start_idx])

            start_idx = start_idx + 1

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

assignments = np.zeros(20*20)
all_spikes = deque(maxlen=1200)
all_labels = deque(maxlen=1200)
ex_number = 0
n_threads = 4

while ex_number < 24000:
    threads = []

    gradient = [None] * n_threads
    spikes = [None] * n_threads
    labels = [None] * n_threads

    prev = Wsyn

    for t in range(n_threads):
        start_idx = ex_number + t * 20
        end_idx = ex_number + (t + 1) * 20
        thread = threading.Thread(target=calc_gradient, args=(t, start_idx, end_idx, gradient, spikes, labels))
        threads.append(thread)

        print(t, start_idx, end_idx)

    for t in range(n_threads):
        threads[t].start()

    for t in range(n_threads):
        threads[t].join()

    print ("averages: ")
    print (np.average(np.absolute(gradient[0])))
    print (np.average(np.absolute(gradient[1])))
    print (np.average(np.absolute(gradient[2])))
    print (np.average(np.absolute(gradient[3])))
    print (np.average(np.absolute(Wsyn)))
    print ("min and max: ")
    print (np.max(Wsyn), np.min(Wsyn))

    for t in range(n_threads):
        Wsyn = Wsyn + gradient[t]
        all_spikes.extend(spikes[t])
        all_labels.extend(labels[t])

    Wsyn = np.clip(Wsyn, min_weight, max_weight)

    col_norm = np.average(Wsyn, axis = 0)
    col_norm = avg_weight / col_norm
    for i in range(20*20):
        Wsyn[:, i] *= col_norm[i]

    print ("difference: ")
    print (np.sum(np.absolute(Wsyn - prev)), np.sum(np.absolute(Wsyn)))
    # assert( np.sum(np.absolute(Wsyn - prev)) > (np.sum(np.absolute(Wsyn)) * 0.01) )

    ex_number += n_threads * 20

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

    if ( ex_number >= 1 and (ex_number % 2400 == 1200) ):
        assignments = np.zeros(20*20)
        maximum_rate = np.zeros(20*20)

        for num in range(10):
            idx = np.where(np.asarray(all_labels) == num)[0]
            num_assignments = len(idx)

            if num_assignments > 0:
                rate = (1.0 * np.sum(np.asarray(all_spikes)[idx], axis = 0)) / num_assignments

                for out_neuron_idx in range(20*20):
                    if maximum_rate[out_neuron_idx] < rate[out_neuron_idx]:
                        maximum_rate[out_neuron_idx] = rate[out_neuron_idx]
                        assignments[out_neuron_idx] = num

        print (maximum_rate)
        print (assignments)

    if ( ex_number >= 1 and (ex_number % 2400 == 0) ):
        correct = 0
        for ex in range(1200):
            spike_sums = np.zeros(10)
            for num in range(10):
                idx = np.where(np.asarray(assignments) == num)[0]
                if ( len(idx) > 0 ):
                    spike_sums[num] = 1.0 * np.sum(all_spikes[ex][idx]) / len(idx)

            predict = np.argsort(spike_sums)
            correct += (predict[-1] == all_labels[ex])

            print (predict, predict[-1], all_labels[ex])

        print (1.0 * correct / 1200)

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


import dataclasses
import time
from typing import Iterable

from bs4 import BeautifulSoup

from auth import login
from config import config
from session import session
from telegram_setup import send_message

@dataclasses.dataclass
class TeslaData:
    title: str
    url: str

def run_script():
    last_title = ""
    last_link = ""

    login()

    response = session.get(config.URL.format(1), headers=config.HEADERS)

    soup = BeautifulSoup(response.content, "html.parser")

    max_pagination_number = (
        soup.find_all("nav", {"class": "pagination"})[0]
        .find_next("span", {"class": "pagination__current"})
        .text
    )

    max_pagination_number = int(max_pagination_number.split("/")[1].strip())

    for page in range(1, max_pagination_number):
        for item in _get_tesla_data_by_pagination_number(page):
            if item.title != last_title and item.url != last_link:
                send_message(item.title, item.url)
                last_title = item.title
                last_link = item.url
                time.sleep(config.INTERVAL)

def _get_tesla_data_by_pagination_number(number: int) -> Iterable[TeslaData]:
    response = session.get(config.URL.format(number), headers=config.HEADERS)
    soup = BeautifulSoup(response.content, "html.parser")

    articles = soup.find_all("blog-post-card")

    for article in articles:
        title = article.find_next("p").find("a").text
        link = article.find_next("p").find("a")["href"]
        yield TeslaData(title=title, url=link)


# -*- coding:utf-8 -*-
# 파일 공유시 한글파일 명 때문에 에러 발생 --> 임의로 영어로 바꿔줌
import folium
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib
import json
import seaborn as sns
import matplotlib.pyplot as plt

my_gu = '구로구'

def my_gu_score(my_gu):
    score = pd.read_csv(f'./csv/score.csv', encoding='utf-8')
    total_index = score.점수.count()
    sum_score = sum(score.점수)
    total_avg = sum_score/total_index
    gugu = score[score.구이름.str.contains(my_gu, na=False)]
    gugu = gugu.점수.values
    gu_score = gugu[0]
    print(gu_score)
    print(f'서울 전체평균점수: {total_avg:.2f}점')
    if gu_score > total_avg:
        print('평균보다 크다!')
    elif gu_score < total_avg:
        print('평균보다 작다!')
    else:
        print('equal')
    cnt = 0
    for i in score.구이름:
        # print(i)
        a = score[score.구이름 == i]
        b = a['점수'].values
        # print(b[0])
        if b[0] > gu_score:
            cnt += 1
    print(f'전체구에서 {cnt + 1}등')
    # ,what return
# 평균대비 우리구는 몇% , (구/서울시)/서울
def my_gu_width(my_gu):
    data = pd.read_csv(f'./csv/whole_merged_data2.csv', encoding='utf-8')
    total_index = data.지역명.count()
    # print(total_index)
    # print(data)
    data = data[data.columns.difference(['공원 평균 면적',
                                  '공원 면적 합계','세대',
                                  '인구','구별 총 생산','병원수'])]
    data = data[data.지역명 == my_gu]
    int_data = data.iloc[:,0:-2]
    total_int = int_data.sum(axis=1)
    print(total_int.values)
    print(data.지역명.values)
    print(data['자치구 전체면적'].values)

my_gu_score(my_gu)
my_gu_width(my_gu)

# print('지역명','총합','자치구_전체면적')
# for i in range(1,total_index+1):
#     # print(total_int.iloc[i-1:i].values)
#     b_total = total_int.iloc[i-1:i].values
#     # print(data.지역명.iloc[i-1:i].values)
#     n_total = data.지역명.iloc[i-1:i].values
#     w_total = data['자치구 전체면적'].iloc[i-1:i].values
#     print(n_total[0] ,b_total[0] , w_total[0] )


import requests
import requests
import xml.etree.ElementTree as ET
import time
import json
import random

headers = {'Content-Type': 'text/xml', 'charset': 'UTF-8'}

hello_soap = """
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="ns1">
   <soapenv:Header/>
   <soapenv:Body>
      <ns1:hello soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
   </soapenv:Body>
</soapenv:Envelope>
"""

getMoneyStatus_soap = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:ns="ns1">
 <SOAP-ENV:Body  SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <ns:getMoneyStatus>
  </ns:getMoneyStatus>
 </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
"""

giveMoney_soap = """<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"ns1\">
   <soapenv:Header/>
   <soapenv:Body>
      <ns1:giveMoneyRequest soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">
         <username xsi:type=\"xsd:string\">XreceiverX</username>
         <uniqueTransferId xsi:type=\"xsd:string\">XuniqueTransferIdX</uniqueTransferId>
         <type xsi:type=\"xsd:string\">GIVE_MONEY</type>
         <seriesId xsi:type=\"xsd:string\"></seriesId>
         <amount xsi:type=\"ns1:billonAmount\">
            <amount xsi:type=\"xsd:unsignedLong\">XamountX</amount>
            <currency xsi:type=\"xsd:string\">XcurrencyX</currency>
            <colour xsi:type=\"xsd:unsignedLong\">0</colour>
         </amount>
         <shortDescription xsi:type=\"xsd:string\">testy</shortDescription>
         <description xsi:type=\"xsd:string\"></description>
      </ns1:giveMoneyRequest>
   </soapenv:Body>
</soapenv:Envelope>
"""

getTaskStatus = """<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="ns1">
   <soapenv:Header/>
   <soapenv:Body>
      <ns1:getTaskStatus soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <taskId xsi:type="xsd:string">XtaskIdX</taskId>
         <uniqueTransferId xsi:type="xsd:string"></uniqueTransferId>
         <callback xsi:type="xsd:boolean">false</callback>
      </ns1:getTaskStatus>
   </soapenv:Body>
</soapenv:Envelope>
"""

def get_money_status(url, currency='BIL', balance_type='freeBalance'):
    """
    :param url:
    :param currency:
    :param balance_type:
    :return:
    """
    url = 'http://' + url
    try:
        response = requests.post(url, data=getMoneyStatus_soap, headers=headers)
        root = ET.fromstring(response.content)
        requestStatus = next(root.iter('requestStatus')).text
        if requestStatus != 'SUCCESS':
            print('Zapytanie get_money_status zakonczylo sie statusem ' + requestStatus)
            return 0
        for free in root.iter(balance_type):
            if free.find('currency') is not None and free.find('currency').text == currency:
                if free.find('amount') is not None:
                    return int(free.find('amount').text)
        return 0
    except requests.exceptions.ConnectionError as err:
        print(str(err))
        return 0

def get_task_status(url, task_id):
    """
    :param url:
    :param task_id:
    :return:
    """
    url = 'http://' + url
    request = getTaskStatus.replace("XtaskIdX", task_id)
    try:
        res = {}
        response = requests.post(url, data=request, headers=headers, timeout=30)
        if False:
            print('url: ' + url)
            print(response.content)
        root = ET.fromstring(response.content)
        res['additionalInfo'] = next(root.iter('additionalInfo')).text
        res['progressPercent'] = next(root.iter('progressPercent')).text
        res['requestStatus'] = next(root.iter('requestStatus')).text
        if res['requestStatus'] == 'FINISHED_ERR':
            res['error_name'] = next(root.iter('error_name')).text
            print(res['error_name'])
        if res['requestStatus'] != 'SUCCESS':
            return {}
        res['status'] = next(root.iter('status')).text
        if res['status'] == 'FINISHED_ERR':
            res['error_name'] = json.loads(next(root.iter('additionalInfo')).text).get('error_name', 'UNKNOWN_ERROR')
        return res
    except requests.exceptions.ConnectionError as err:
        print(str(err))
        return {}

def give_money(url, receiver, amount, currency='BIL', check_status=False, id_prefix=''):
    """
    :param url:
    :param receiver:
    :param amount:
    :param currency:
    :param check_status:
    :return:
    """
    url = 'http://' + url
    try:
        give_money_ = giveMoney_soap.replace("XamountX", str(amount)).replace("XcurrencyX", currency).replace(
            'XreceiverX', receiver).replace('XuniqueTransferIdX', id_prefix + str(int(time.time())) + str(random.randint(0, 9999999999999)))
        print('wysylam ' + str(give_money_))
        response = requests.post(url, data=give_money_, headers=headers, timeout=30)
        root = ET.fromstring(response.content)
        requestStatus = next(root.iter('requestStatus')).text
        if requestStatus != 'SUCCESS':
            return False, requestStatus
        taskId = next(root.iter('taskId')).text
        return True, taskId
    except requests.exceptions.ConnectionError as err:
        print(str(err))
        return False, None
    except Exception as e:
        print(str(e))
        return False, None

def hello(url):
    """
    :param url:
    :return:
    """
    url = 'http://' + url

    try:
        response = requests.post(url, data=hello_soap, headers=headers)
        root = ET.fromstring(response.content)
        res = {}
        res['status'] = next(root.iter('status')).text
        res['pid'] = next(root.iter('pid')).text
        res['username'] = next(root.iter('username')).text
        return res
    except requests.exceptions.ConnectionError as err:
        print(str(err))
        return {}


import cv2
from mc_controller import minecraft_controller
from websurfing_controller import websurfing_controller
import keyboard

active_mode = 'minecraft'  # default to web mode

def toggle_mode(e):
    global active_mode
    if active_mode == 'web':
        print("Switching to Minecraft Mode")
        active_mode = 'minecraft'
    else:
        print("Switching to Web Surfing Mode")
        active_mode = 'web'

keyboard.on_press_key("f4", toggle_mode)

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        print("Failed to grab frame")
        break

    if active_mode == 'minecraft':
        minecraft_controller(frame, active_mode)
    elif active_mode == 'web':
        websurfing_controller(frame, active_mode)

    # Display the frame (you can add conditions to display based on the mode)
    cv2.imshow("Controller", frame)

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

cap.release()
cv2.destroyAllWindows()


from django import forms
from .models import AdminProfile
from accounts.models import Account

class AdminForm(forms.ModelForm):
    class Meta:
        model=Account
        fields=('first_name','last_name','phone_number')

    def __init__(self,*args,**kwargs):
        super(AdminForm,self).__init__(*args,**kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs['class']='form-control'

class AdminProfileForm(forms.ModelForm):
    profile_picture = forms.ImageField(required=False, error_messages = {'invalid':("Image files only")}, widget=forms.FileInput)
    class Meta:
        model=AdminProfile
        fields=('address_line_1','address_line_2','city','state','country','profile_picture')

    def __init__(self,*args,**kwargs):
        super(AdminProfileForm,self).__init__(*args,**kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs['class']='form-control'


from dao.base_dao import BaseDAO
from dao.models.favorite import Favorite
from dao.models.movie import Movie
from dao.models.user import User

class FavoritesDAO(BaseDAO[Favorite]):
    __model__ = Favorite

    def get_by_user(self, uid: int) -> list[Favorite]:
        favorites = self.session.query(Favorite) \
            .filter(Favorite.user_id == uid) \
            .all()
        return favorites

    def get_by_movie(self, mid: int) -> list[Favorite]:
        favorites = self.session.query(Favorite) \
            .filter(Favorite.movie_id == mid) \
            .all()
        return favorites

    def get_by_id(self, fid: int) -> Favorite | None:
        return self.session.query(Favorite).get(fid)

    def delete_by_id(self, fid: int) -> Favorite | None:
        item = self.get_by_id(fid)
        if item:
            self.session.delete(item)
            self.session.commit()
            return item
        else:
            return None

    def get_by_user_movie(self,
                          user_id: int,
                          movie_id: int) -> Favorite | None:
        smtm = self.session.query(Favorite)\
            .filter(Favorite.user_id == user_id)\
            .filter(Favorite.movie_id == movie_id)
        items = smtm.all()

        if len(items) == 1:
            return items[0]
        else:
            return None

    def delete_by_user_movie(self,
                             user_id: int,
                             movie_id: int) -> Favorite | None:
        item = self.get_by_user_movie(user_id, movie_id)

        if item:
            self.session.delete(item)
            self.session.commit()
            return item
        else:
            return None

    def create_by_user_movie(self,
                             user_id: int,
                             movie_id: int) -> Favorite | None:
        # Проверяем наличие аналогичной записи, если еще нет, то создаём
        item = self.get_by_user_movie(user_id, movie_id)
        if item:
            return None
        else:
            new_item = Favorite(user_id=user_id, movie_id=movie_id)
            self.session.add(new_item)
            self.session.commit()
            return new_item

    def add_movie_to_curr_user(self, user: User, movie: Movie):
        user.favorites.append(movie)
        self.session.commit()
        return user


from math import atan2, degrees

def main():

    n = int(input())
    l = [list(map(int, input().split())) for _ in range(n)]

    ans = 0
    for ind, c in enumerate(l):

        nl = [degrees(atan2(a[0]-c[0], a[1]-c[1])) for jnd, a in enumerate(l) if ind != jnd]
        nl.sort()
        # print(nl)

        i = 1
        j = 0
        while i < n - 1:
            c = nl[i] - nl[j]
            # print(nl[i], nl[j], c, 360-c)
            ans = max(ans, min(c, 360-c))
            if nl[i] - nl[j] < 180:
                i += 1
            else:
                j += 1
    print(ans)

if __name__ == '__main__':
    main()


from abmatt.converters.convert_dae import DaeConverter
from tests.lib import AbmattTest, CheckPositions

class TestConvertMapModel(AbmattTest):
    @classmethod
    def setUpClass(cls):
        cls.MAP = cls._get_brres('map_model.brres')

    def test_map_model_converts_bones_correctly(self):
        # Export the map model
        dae = self._get_tmp('.dae')
        DaeConverter(self.MAP, dae, encode=False).convert()
        converter = DaeConverter(self._get_tmp('.brres'), dae)
        converter.load_model()
        self.assertTrue(CheckPositions.model_equal(self.MAP.models[0], converter.mdl0))


import traceback
import threading
import inspect
import builtins

from . import commands

__print__ = builtins.print

class Context:

    def __init__(self, interp, command, data):
        self.interpreter = interp
        self.command = command
        self.raw_data = data

class OutputContext:

    __slots__ = ("name", "module", "qualname", "cur_line", "first_line", "file")

    def __init__(self, frame):
        import types
        frame: types.FrameType
        self.first_line = frame.f_code.co_firstlineno
        self.file = frame.f_code.co_filename
        self.name = frame.f_code.co_name
        self.module = frame.f_globals['__name__']
        self.qualname = self.module + "." + self.name
        self.cur_line = frame.f_lineno

class Interpreter(commands.GroupMixin):

    def __init__(self, name, **kwargs):
        super().__init__(kwargs)
        self.name = name
        self.opening = kwargs.get("opening", None)
        self.prompt = kwargs.get("prompt", "> ")
        self.threaded = kwargs.get("threaded", False)
        self.ctx_class = kwargs.get("ctx_class", Context)

    def _loop(self):
        __print__(self.prompt, end="")
        data = input()
        self.dispatch("input", data)

    def __print_replace(self, *args, **kwargs):
        frame = inspect.currentframe().f_back
        ctx = OutputContext(frame)
        del frame
        self.dispatch("output", ctx, *args, **kwargs)

    def run(self):
        builtins.print = self.__print_replace
        if self.opening:
            __print__(self.opening)
        self.dispatch("start")
        while True:
            try:
                self._loop()
            except (KeyboardInterrupt, EOFError):
                break
            except Exception:
                __print__(f"Ignoring exception in main loop:\n{traceback.format_exc()}")
        self.dispatch("stop")
        builtins.print = __print__

    def dispatch(self, event, *args, **kwargs):
        handler = getattr(self, f"on_{event}", None)
        if handler is not None:
            if self.threaded:
                thread = threading.Thread(target=handler, args=args, kwargs=kwargs)
                thread.start()
            else:
                handler(*args, **kwargs)

    def add_cog(self, cog):
        for name, attr in inspect.getmembers(cog):
            if isinstance(attr, commands.Command):
                self.add_command(attr)
            else:
                __print__(name, attr)

    # Default command handling

    def print(self, *args, **kwargs):
        __print__(*args, **kwargs)

    def process_command(self, data_in):
        split = data_in.split(" ", 1)
        if len(split) == 1:
            split.append("")
        name, data = split
        command = self.get_command(name)
        if command is None:
            self.dispatch("command_not_found", name, data)
        else:
            ctx = self.ctx_class(self, command, data)

            self.dispatch("before_command", name)
            try:
                command.invoke(ctx, data)
            except Exception as e:
                self.dispatch("command_error", command, e)
            self.dispatch("after_command", name)

    def process_filters(self, ctx, *output, **kwargs):
        # self.print(ctx.qualname)
        return True  # TODO

    # Default handlers:

    def on_input(self, data):
        self.process_command(data)

    def on_output(self, ctx, *args, **kwargs):
        result = self.process_filters(ctx, *args, **kwargs)
        if result:
            __print__(*args, **kwargs)

    def on_command_not_found(self, name, data):
        print(f"Unrecognized command {name}")

    def on_command_error(self, command, error):
        errmsg = "".join(traceback.format_exception(type(error), error, error.__traceback__))
        print(f"Ignoring exception in command {command.name}:\n{errmsg}")


#imports
from websocket import create_connection
import pygame
import sys
import urllib.request
import numpy as np
import cv2

# initialising pygame and create display
pygame.init()
display = pygame.display.set_mode((300, 300))
pygame.display.set_caption("WASD Keys to control")

# create websocket connection
host = "192.168.50.228"
host = "10.0.0.66"
#ws = create_connection("ws://192.168.50.228:81/control")
ws = create_connection("ws://10.0.0.66:81/control")

# speed var
speed = "250"

# quit
def quit():
    send = "(0, 0, -1, -1)"
    ws.send(send)
    pygame.quit()
    sys.exit()

# creating a running loop
while True:

    # creating a loop to check events that are occuring
    imgResp = urllib.request.urlopen(f'http://10.0.0.66/cam-lo.jpg')
    imgNp = np.frombuffer(imgResp.read(), dtype=np.uint8)
    img = cv2.imdecode(imgNp, -1)
    # all the opencv processing is done here

    # Look into Pygame instead of OpenCV to allow for keyboard inputs
    cv2.imshow('test', img)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()

        # checking if keydown event happened or not
        if event.type == pygame.KEYDOWN:

            # up
            if event.key == pygame.K_w:
                print("Key W has been pressed")
                send = "({}, {}, 1, 1)".format(speed, speed)

            # left
            if event.key == pygame.K_a:
                print("Key A has been pressed")
                send = "({}, {}, -1, 1)".format(speed, speed)

            # down
            if event.key == pygame.K_s:
                print("Key S has been pressed")
                send = "({}, {}, -1, -1)".format(speed, speed)

            # right
            if event.key == pygame.K_d:
                print("Key D has been pressed")
                send = "({}, {}, 1, -1)".format(speed, speed)

            # stop
            if event.key == pygame.K_h:
                print("Key H has been pressed")
                send = "({}, {}, 1, -1)".format(0, 0)

            # quit
            if event.key == pygame.K_q:
                print("Key Q has been pressed")
                quit()

            ws.send(send)
            print("Sent")