"""Module utilitaire_test.py - Module annexe utilisé pendant les tests
(enregistre tous les messages passés sur Ivy, et les enregistre dans un fichier)"""

import os
import time
import sys
from ivy.std_api import IvyStart, IvyStop, IvyInit, IvyBindMsg, IvySendMsg

IVYAPPNAME = "IvyTest"
MSG = "(.*)"
STOPMSG = "StopIvyTest"

def results_to_file(test_name, warn_res, std_res, test_time=int(time.time())):
    """Fonction qui enregistre les résultats d'un test dans un fichier"""
    filepath = "pytest_custom_logs/{}.txt".format(test_time)
    dirpath = "pytest_custom_logs"
    os.makedirs(dirpath, exist_ok=True)
    with open(filepath, "a") as file:
        file.write("-- TEST: {} --\n".format(test_name))
        std_out = std_res.readouterr().out
        if std_out != "":
            file.write("Captured stdout:\n")
            file.write(std_out)
        if len(warn_res) > 0:
            file.write("\nCaptured Warnings:\n")
            for elt in warn_res:
                file.write(str(elt)+"\n")
            file.write("\n")

def read_ivytest_file(test_name):
    """Lit les messages enregistrés par l'utilitaire_ivytest,
    puis supprime le fichier temporaire"""
    file_name = "{}.txt".format(test_name)
    msg_list = []
    with open(file_name, 'r') as file:
        for line in file:
            line_split = line.strip().split("#")
            msg_list.append((line_split[0], line_split[1]))
    if os.path.isfile(file_name):
        os.remove(file_name)
    return msg_list

class RadioTest:
    """Objet connecté au channel Ivy, enregistre tous les messages
    Un compte à rebours (en secondes) peut être demandé
    pour déclencher l'arrêt automatique après un certain temps
    (afin d'éviter les threads qui continuent à tourner en arrière plan)
    """
    def __init__(self, test_name):
        IvyInit (IVYAPPNAME,IVYAPPNAME+" is ready!")
        self.bus = "127.255.255.255:2010"
        self.nom = IVYAPPNAME
        IvyBindMsg (self.on_msg, MSG)
        IvyBindMsg (self.on_stopmsg, STOPMSG)
        self.file_name = "{}.txt".format(test_name)
        with open(self.file_name, "w") as file:
            file.write("")

    def on_msg(self, sender, message):
        """Enregistre chaque message reçu sur Ivy"""
        with open(self.file_name, "a") as file:
            file.write("{}#{}\n".format(str(sender), str(message)))

    def send_cmd(self, cmd):
        """Envoie un message sur le bus Ivy"""
        IvySendMsg(cmd)

    def on_stopmsg(self, *args):
        """Exécuté quand la commande d'arrêt du test est enregistrée"""
        self.stop()

    def start(self):
        """Démarrage du serveur ivy"""
        IvyStart(self.bus)

    def stop(self, *args):
        """Arrêt du serveur ivy"""
        IvyStop()

if __name__ == '__main__':
    if len(sys.argv) >= 2:
        test_nm = sys.argv[1]
        test_radio = RadioTest(test_nm)
        test_radio.start()
        if len(sys.argv) > 2:
            time.sleep(0.5)
            for msg in sys.argv[2:]:
                test_radio.send_cmd(msg)
    else:
        print("Arguments invalides")


from openerp.osv import osv, fields
from datetime import datetime
from dateutil.relativedelta import relativedelta
from openerp.tools.translate import _

class mrp_repair(osv.Model):
    _inherit = 'mrp.repair'
    _columns = {
              'technician_id':fields.many2one('res.users', 'Technician'),
              'courier_type' : fields.selection([('ups', 'UPS'), ('fedex', 'FEDEX'), ('usps', 'USPS'), ('dhl', 'DHL'), ('drop', 'Drop-off'), ('other', 'Other')], 'Courier Type'),
              'box' : fields.selection([('yes', 'Yes'), ('no', 'No')], 'Original Box'),
              'condition' : fields.selection([('yes', 'Yes'), ('no', 'No')], 'New condition'),
              'accessory' : fields.text('Accessories', size=1024),
              'damaged_area' : fields.text('Visible Damage', size=1024),
              'component' : fields.text('Component Serials', size=1024),
              'guarantee_limit': fields.date('Guarantee limit', readonly=True, help="The guarantee limit is computed as: last move date + warranty stamped on the last move. If the current date is below the guarantee limit, each operation and fee you will add will be set as 'not to invoiced' by default. Note that you can change manually afterwards."),
              'tracking_no': fields.char('Tracking No', size=64)
              }

    def create(self, cr, uid, vals, context=None):
        if vals.has_key('move_id') and vals['move_id'] and vals.has_key('product_id') and vals['product_id']:
            move =  self.pool.get('stock.move').browse(cr, uid,vals['move_id'])
            product = self.pool.get('product.product').browse(cr, uid, vals['product_id'])
            limit = datetime.strptime(move.date_expected, '%Y-%m-%d %H:%M:%S') + relativedelta(months=int(product.warranty))
            vals['guarantee_limit'] = limit.strftime('%Y-%m-%d')
        return super(mrp_repair, self).create(cr, uid, vals, context=context)

    def write(self, cr, uid,ids, vals, context=None):
        for repair in self.browse(cr,uid,ids):
            prod_id=repair.product_id.id
            move_id=repair.move_id.id
        if vals.has_key('move_id') and vals['move_id']:
            move_id=vals['move_id']
        if vals.has_key('product_id') and vals['product_id']:
            prod_id=vals['product_id']
        move =  self.pool.get('stock.move').browse(cr, uid,move_id)
        product = self.pool.get('product.product').browse(cr, uid, prod_id)
        limit = datetime.strptime(move.date_expected, '%Y-%m-%d %H:%M:%S') + relativedelta(months=int(product.warranty))
        vals['guarantee_limit'] = limit.strftime('%Y-%m-%d')
        return super(mrp_repair, self).write(cr, uid,ids, vals, context=context)

    def action_repair_done(self, cr, uid, ids, context=None):
        res = super(mrp_repair, self).action_repair_done(cr, uid, ids, context)
        repair_id = self.pool.get('crm.rma.line').search(cr, uid, [('repair_id', 'in', ids)])
        if repair_id:
            rma_id = self.pool.get('crm.rma.line').browse(cr, uid, repair_id[0]).rma_id.id
            rma_obj = self.pool.get('crm.rma').browse(cr, uid, rma_id)
            for line in rma_obj.rma_lines:
                repaired = line.repair_id.repaired
                if not repaired :
                    break
            if repaired:
                self.pool.get('crm.rma').write(cr, uid, [rma_id], {'state':'repaired'})
        return res

class mrp_repair_category(osv.Model):
        _name = 'mrp.repair.category'
        _columns = {
              'name':fields.char('Name', size=64, required=True),
              }

class mrp_repair_component(osv.Model):
        _name = 'mrp.repair.component'
        _columns = {
              'name':fields.char('Name', size=64, required=True),
              'category_id':fields.many2one('mrp.repair.category', 'Category'),
              }

class mrp_repair_symptom(osv.Model):
        _name = 'mrp.repair.symptom'
        _columns = {
              'name':fields.char('Name', size=64, required=True),
              'compo_id':fields.many2one('mrp.repair.component', 'Component'),
              }

class mrp_repair_action(osv.Model):
        _name = 'mrp.repair.action'
        _columns = {
              'name':fields.char('Name', size=64, required=True),
              'sympt_id':fields.many2one('mrp.repair.symptom', 'Symptom'),
              }

class mrp_repair_line(osv.Model):
    _inherit = 'mrp.repair.line'
    _columns = {
              'categ_id':fields.many2one('mrp.repair.category', 'Category'),
              'component_id':fields.many2one('mrp.repair.component', 'Component'),
              'symptom_id':fields.many2one('mrp.repair.symptom', 'Symptom'),
              'action_id':fields.many2one('mrp.repair.action', 'Action Taken'),
              'symptom_note':fields.text('Symptom Notes', size=1024),
              }

    def onchange_operation_type(self, cr, uid, ids, type, guarantee_limit, company_id=False, context=None):
        """ On change of operation type it sets source location, destination location
        and to invoice field.
        @param product: Changed operation type.
        @param guarantee_limit: Guarantee limit of current record.
        @return: Dictionary of values.
        """
        res = super(mrp_repair_line, self).onchange_operation_type(cr, uid, ids, type, guarantee_limit, company_id, context)
        warehouse_obj = self.pool.get('stock.warehouse')
        warehouse_ids = warehouse_obj.search(cr, uid, [])
        if warehouse_ids:
            warehouse = warehouse_obj.browse(cr, uid, warehouse_ids[0])
            if type == 'add':
                res['value'].update({'location_dest_id': warehouse.lot_return_id.id})
            elif type == 'remove':
                res['value'].update({'location_id': warehouse.lot_return_id.id})
        return res

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


import sys, heapq
input = sys.stdin.readline

def main():
    n, m = map(int, input().split())
    res = list()
    graph = list(list() for _ in range(n+1))
    in_degree = [0] * (n+1)
    q = list()

    for i in range(m):
        a, b = map(int, input().split())
        graph[a].append(b)
        in_degree[b] += 1

    for i in range(1, n+1):
        if in_degree[i] == 0:
            heapq.heappush(q, i)

    while q:
        lst = heapq.heappop(q)
        res.append(lst)
        for i in graph[lst]:
            in_degree[i] -= 1
            if in_degree[i] == 0:
                heapq.heappush(q, i)
    print(* res)

main()


#!/usr/bin/python
# coding: utf-8
from sys import stdin, stdout

def main():
	arr=[9]
	i=0
	for item in arr:
		tmp=str(item)+'0'
		arr.append(long(tmp))
		tmp=str(item)+'9'
		arr.append(long(tmp))
		i+=1
		if(i==10000):
			break
	num=[0]
	for i in xrange(1,501):
		for item in arr:
			if(item%i==0):
				num.append(item)
				break
	t=int(raw_input())
	list=stdin.readlines()
	for n in list:
		n=int(n)
		stdout.write(str(num[n])+"\n")

if __name__ == "__main__":
	main()

'''

You are given an integer N. Can you find the least positive integer X made up of only 9’s and 0’s such that X is a multiple of N?

Update
X is made up of one or more occurences of 9 and zero or more occurences of 0.

Input Format
The first line contains an integer T which denotes the number of test cases. T lines follow.
Each line contains the integer N for which the solution has to be found.

Output Format
Print the answer X to STDOUT corresponding to each test case. The output should not contain any leading zeroes.

Constraints
1 <= T <= 10^4
1 <= N <= 500

Sample Input
3
5
7
1

Sample Output
90
9009
9

Explanation
90 is the smallest number made up of 9’s and 0’s divisible by 5. You can derive similarly for other cases.

'''


import aiohttp

from ....bot import Bot
from ....types.slack.attachment import Attachment
from ....utils.html import get_root
from ....utils.http import USER_AGENT

PACKTPUB_URL = "https://www.packtpub.com/free-learning"
HEADERS = {
    "User-Agent": USER_AGENT,
}

async def say_packtpub_dotd(bot: Bot, channel):
    attachments: list[Attachment] = []
    url = "https://www.packtpub.com/free-learning"
    async with aiohttp.ClientSession(headers=HEADERS) as session, session.get(
        url,
    ) as resp:
        data = await resp.read()

    h = get_root(data)

    try:
        container = h.cssselect("main.product")[0]
        title = str(
            container.cssselect("h3.product-info__title")[0].text_content(),
        ).replace("Free eBook - ", "")
        image_url = str(container.cssselect("img.product-image")[0].get("src"))

        attachments.append(
            Attachment(
                fallback=f"{title} - {PACKTPUB_URL}",
                title=title,
                title_link=PACKTPUB_URL,
                text=(
                    f"오늘의 Packt Book Deal of The Day: {title} -"
                    f" {PACKTPUB_URL}"
                ),
                image_url=image_url,
            ),
        )
    except IndexError:
        pass

    if attachments:
        await bot.api.chat.postMessage(
            channel=channel,
            text="오늘자 PACKT Book의 무료책이에요!",
            attachments=attachments,
        )
    else:
        await bot.say(channel, "오늘은 PACKT Book의 무료책이 없는 것 같아요")


import subprocess
import socket
import time
import os
from loguru import logger
from device.pyminitouch import config

def str2byte(content):
    """ compile str to byte """
    return content.encode(config.DEFAULT_CHARSET)

def is_device_connected(device_id, adb):
    """ return True if device connected, else return False """
    try:
        device_name = subprocess.check_output(
            [adb, "-s", device_id, "shell", "getprop", "ro.product.model"]
        )
        device_name = (
            device_name.decode(config.DEFAULT_CHARSET)
            .replace("\n", "")
            .replace("\r", "")
        )
    except subprocess.CalledProcessError:
        return False
    return True

class MNTInstaller(object):
    """ install minitouch for android devices """

    def __init__(self, device_id, adb):
        self._ADB = adb
        self.device_id = device_id
        self.abi = self.get_abi()
        if self.is_mnt_existed():
            logger.info("minitouch already existed in {}".format(device_id))
        else:
            self.download_target_mnt()

    def get_abi(self):
        abi = subprocess.getoutput(
            "{} -s {} shell getprop ro.product.cpu.abi".format(self._ADB, self.device_id)
        )
        logger.info("device {} is {}".format(self.device_id, abi))
        return abi

    def download_target_mnt(self):
        # 获取当前文件的绝对路径
        current_path = os.path.abspath(__file__)
        # 获取当前文件的目录
        dir_path = os.path.dirname(current_path)
        # 拼接获取 libs 目录下文件的绝对路径
        file_path = os.path.join(dir_path, 'libs', '{}', 'minitouch')
        mnt_path = file_path.format(self.abi)

        # push and grant
        subprocess.check_call(
            [self._ADB, "-s", self.device_id, "push", mnt_path, config.MNT_HOME]
        )
        subprocess.check_call(
            [self._ADB, "-s", self.device_id, "shell", "chmod", "777", config.MNT_HOME]
        )
        logger.info("minitouch already installed in {}".format(config.MNT_HOME))

    def is_mnt_existed(self):
        file_list = subprocess.check_output(
            [self._ADB, "-s", self.device_id, "shell", "ls", "/data/local/tmp"]
        )
        return "minitouch" in file_list.decode(config.DEFAULT_CHARSET)

class MNTServer(object):

    def __init__(self, device_id, adb, port):
        assert is_device_connected(device_id, adb)
        self._ADB = adb
        self.device_id = device_id
        logger.info("searching a usable port ...")
        self.port = port
        logger.info("device {} bind to port {}".format(device_id, self.port))

        # check minitouch
        self.installer = MNTInstaller(device_id, adb)

        # keep minitouch alive
        self._forward_port()
        self.mnt_process = None
        self._start_mnt()

        # make sure it's up
        time.sleep(1)
        assert (
            self.heartbeat()
        ), "minitouch did not work. see https://github.com/williamfzc/pyminitouch/issues/11"

    def stop(self):
        self.mnt_process and self.mnt_process.kill()
        logger.info("device {} unbind to {}".format(self.device_id, self.port))

    def _forward_port(self):
        """ allow pc access minitouch with port """
        command_list = [
            self._ADB,
            "-s",
            self.device_id,
            "forward",
            "tcp:{}".format(self.port),
            "localabstract:minitouch",
        ]
        logger.debug("forward command: {}".format(" ".join(command_list)))
        output = subprocess.check_output(command_list)
        logger.debug("output: {}".format(output))

    def _start_mnt(self):
        command_list = [
            self._ADB,
            "-s",
            self.device_id,
            "shell",
            "/data/local/tmp/minitouch",
        ]
        logger.info("start minitouch: {}".format(" ".join(command_list)))
        self.mnt_process = subprocess.Popen(command_list, stdout=subprocess.DEVNULL)

    def heartbeat(self):
        return self.mnt_process.poll() is None

class MNTConnection(object):
    """ manage socket connection between pc and android """
    _DEFAULT_BUFFER_SIZE = config.DEFAULT_BUFFER_SIZE

    def __init__(self, port, default_host):
        self._DEFAULT_HOST = default_host
        self.port = port
        # build connection
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect((self._DEFAULT_HOST, self.port))
        self.client = client

        # get minitouch server info
        socket_out = client.makefile()

        # v <version>
        # protocol version, usually it is 1. needn't use this
        socket_out.readline()

        # ^ <max-contacts> <max-x> <max-y> <max-pressure>
        _, max_contacts, max_x, max_y, max_pressure, *_ = (
            socket_out.readline().replace("\n", "").replace("\r", "").split(" ")
        )
        self.max_contacts = max_contacts
        self.max_x = max_x
        self.max_y = max_y
        self.max_pressure = max_pressure

        # $ <pid>
        _, pid = socket_out.readline().replace("\n", "").replace("\r", "").split(" ")
        self.pid = pid

        logger.info(
            "minitouch running on port: {}, pid: {}".format(self.port, self.pid)
        )
        logger.info(
            "max_contact: {}; max_x: {}; max_y: {}; max_pressure: {}".format(
                max_contacts, max_x, max_y, max_pressure
            )
        )

    def disconnect(self):
        self.client and self.client.close()
        self.client = None
        logger.info("minitouch disconnected")

    def send(self, content):
        """ send message and get its response """
        byte_content = str2byte(content)
        self.client.sendall(byte_content)
        return self.client.recv(self._DEFAULT_BUFFER_SIZE)


# Author : Suvash Kumar
# Website : www.suvashkumar.xyz

import speech_recognition as sr

recognizer = sr.Recognizer()
audio_file = "speech.wav"

with sr.AudioFile(audio_file) as source:
	audio_data = recognizer.record(source)
	print("Recognizing this speech ......")
	text = recognizer.recognize_google(audio_data)
	print("Content of this audio : ",text)


'''
날짜: 2022. 08. 26
시간복잡도:

문제:
풀이: x부터 bfs로 모든 노드 걸리는 시간 잰다. 마지막에 K시간만큼 걸린애들만 출력
12:53 ~
'''
from collections import deque
import sys
input = sys.stdin.readline

def bfs(res, start, visited):
    q = deque()
    q.append([start,0]) # 시작노드, 시작노드부터 걸린 거리
    visited[start] = True # 현재노드 방문체크

    while q:
        v, c = q.popleft()
        # 종료조건
        if c > k: # bfs니까 하나라도 나오면 종료됨
            break
        # 정답넣기
        if c == k:
            res.append(v)
        # 안본 곳이라면 -> 연결된애들 값추가하고 q에 넣어봐야지
        for i in arr[v]:
            if not visited[i]:
                visited[i] = True # 방문했다고 체크
                q.append([i,c+1])

n, m, k, start = map(int, input().split())
# 1. 맵 생성
arr = [[] for _ in range(n+1)]
visited = [False] * (n+1)

# 2.길 연결
for i in range(m):
    a, b = map(int, input().split()) # a-b
    arr[a].append(b) # 길 연결
# print(arr)
res = []
bfs(res, start, visited)
# print(res)
# 출력
res = sorted(res)

if len(res)==0: # 도시 없으면 -1
    print(-1)
else:
    for i in res: # 도시 있으면 오름차순으로 출력
        print(i)

조민식/03-dfs-bfs/part3-15-특정 거리의 도시 찾기-더좋게.py


from visuals.pointwindow import PointWindow
from OpenGL.GL import *
import opencl
import cv
import mesh

if not 'window' in globals():
    window = PointWindow(size=(640,480))

def load_obj():
    mesh.load_random()
    window.update_points(mesh.points[:,:3])
    window.lookat = mesh.points[:,:3].mean(0)
    opencl.load_mesh(mesh.vertices, mesh.faces)
    window.Refresh()

if not 'obj' in mesh.__dict__: load_obj()

def make_random_ray():
    # Create two random points, one on the r=2 sphere...
    x1 = np.random.rand(3)-0.5
    x1 /= np.sqrt(np.dot(x1, x1))
    x1 *= 2

    # and another on the r=0.5 sphere
    x2 = np.random.rand(3)-0.5
    x2 /= np.sqrt(np.dot(x2, x2))
    x2 *= 0.3

    dir = x2 - x1
    dir /= np.sqrt(np.dot(dir,dir))
    ray = x1, dir
    return ray

def random_ray():
    global ray
    ray = make_random_ray()

@window.eventx
def EVT_CHAR(evt):
    key = evt.GetKeyCode()
    if key == ord(' '):
        random_ray()
        window.Refresh()

@window.event
def post_draw():
    glLightfv(GL_LIGHT0, GL_POSITION, (-40, 200, 100, 0.0))
    glLightfv(GL_LIGHT0, GL_AMBIENT, (0.3, 0.3, 0.3, 0.0))
    glLightfv(GL_LIGHT0, GL_DIFFUSE, (0.3, 0.3, 0.3, 0.0))
    glEnable(GL_LIGHT0)
    glEnable(GL_LIGHTING)
    glEnable(GL_COLOR_MATERIAL)
    glEnable(GL_DEPTH_TEST)
    glShadeModel(GL_SMOOTH)
    #mat = glGetFloatv(GL_MODELVIEW_MATRIX).transpose()
    glPushMatrix()
    glScale(1.0/mesh.scale,1.0/mesh.scale,1.0/mesh.scale)
    glCallList(mesh.obj.gl_list)
    glPopMatrix()
    glDisable(GL_LIGHTING)

    if 1:
        glColor(1,1,0)
        mesh.mybvh.draw_boxes()

    if 'ray' in globals():
        glColor(1,1,0)
        nodes, tri, t = mesh.mybvh.intersect(*ray)
        x1,d = ray
        if t > 1000: t = 1000

        verts, line_inds, _ = mesh.bvh.BVH.box_vertices(nodes)
        glEnableClientState(GL_VERTEX_ARRAY)
        glVertexPointerf(verts)
        glDrawElementsui(GL_LINES, line_inds)
        glDisableClientState(GL_VERTEX_ARRAY)

        glPushAttrib(GL_ALL_ATTRIB_BITS)
        glPointSize(10)
        glColor(0,1,0)
        glDisable(GL_DEPTH_TEST)
        glBegin(GL_POINTS)
        glVertex(*(x1+d*t))
        glEnd()
        glEnable(GL_DEPTH_TEST)
        glLineWidth(3)
        glBegin(GL_LINES)
        glVertex(*x1)
        glVertex(*(x1+d*t))
        glEnd()
        glPopAttrib(GL_ALL_ATTRIB_BITS)

    if 0:
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        #opencl.compute_raytrace(mat).wait()

        global img
        img = opencl.get_img()
        cvim = cv.CreateImage((640,480),8,3)
        cv.SetData(cvim, np.array(img[:,:,:3]*255,'u1').data)
        cv.ShowImage('im',cvim)

window.Refresh()


import subprocess
import numpy as np
import os

base = os.getcwd()

paths = [
'ee_mumu/SubProcesses/P1_epem_mupmum',
'gg_tt/SubProcesses/P1_gg_ttx',
'gg_ttg/SubProcesses/P1_gg_ttxg',
'gg_ttgg/SubProcesses/P1_gg_ttxgg',
'gg_ttggg/SubProcesses/P1_gg_ttxggg',
]

for path in paths:
   p = subprocess.Popen(f'cd {path}; mpirun -n 56 ./check',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
   stdout,stderr = p.communicate()
   stdout = stdout.decode("utf-8")

   value = []
   error = []
   for line in stdout.split('\n'):
      if 'time' in line:
         #print(line)
         try:
            values = line.split('=')[1]
            v,e = values.split('+-')
            value.append(float(v))
            error.append(float(e))
         except: continue

   value = np.array(value)
   error = np.array(error)

   mean = np.mean(value)
   std = np.sqrt(np.sum(np.square(error))) / error.shape[0]

   print("%50s: %10.6e +/- %10.6e  rate:  %10.6e" % (path,mean,std,1/mean*error.shape[0]))


import pickle
import logging
import itertools
from io import StringIO
from fnmatch import fnmatch

from collections import OrderedDict, defaultdict

import colorama
from colorama import Fore, Back, Style

from stringparser import Parser

from lantz.log import ColorizingFormatter, SocketListener

def queue_from_record(rec):
    # TODO
    return ('a', 'b')
    #return rec.lantz_driver, rec.lantz_name

try:
    from msvcrt import getch
except ImportError:
    import sys, tty, termios
    def getch():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

COLS = 80

def restyle(text, new):
    """Replace style with a new one.

    :param text: the styled text.
    :param new: the new style, a value from colorame.Style.
    """
    for style in (Style.DIM, Style.BRIGHT, Style.NORMAL):
        text = text.replace(style, new)
    return text

def pos(row, column):
    """Move cursor to a given row and column.
    """
    return '\x1b[%d;%dH' % (row, column)

def clear():
    """Clear screen.
    """
    return '\x1b[2J'

RETITLE = logging.LogRecord('', 0, '', '', '', '', '', '')
REDRAW = logging.LogRecord('', 0, '', '', '', '', '', '')

def level_name(level):
    """For a level defined in the logging module, return its name
    """
    if level == logging.DEBUG:
        return 'DEBUG'
    elif level == logging.INFO:
        return 'INFO'
    elif level == logging.WARNING:
        return 'WARNING'
    elif level == logging.CRITICAL:
        return 'CRITICAL'
    elif level == logging.ERROR:
        return 'ERROR'
    return str(level)

class MessageListFormatter(ColorizingFormatter):
    """Log formatter for Message List View.

    :param queues: The list of queues with sorted logging messages. Each queue
                   corresponds to one instrument.
    """

    FMT = Style.NORMAL + '%(asctime)s <color>%(levelname)-8s</color>' + Style.RESET_ALL + ' %(message)s'

    FIRST_ROW = 2
    ROWS = 24

    def __init__(self, queues, *args, **kwargs):
        super().__init__(fmt=self.FMT, datefmt='%H:%M:%S', *args, **kwargs)
        self.queues = queues
        self.redraw = True
        self._title = ''
        self._current = ''
        self.last_records = []

    @property
    def current(self):
        return self._current

    @current.setter
    def current(self, value):
        self._current = value
        self.redraw = True

    @property
    def title(self):
        return self._title

    @title.setter
    def title(self, value):
        self._title = value
        self.redraw = True

    SEL = Style.BRIGHT + Back.RED + Fore.WHITE

    def format(self, record):
        if record is RETITLE:
            return pos(0, 0) + self.title

        if not record is REDRAW:
            self.last_records.append(record)
            if len(self.last_records) > self.ROWS:
                self.last_records = self.last_records[-self.ROWS:]

        buf = StringIO()
        self.redraw = False
        buf.write(clear())
        buf.write(pos(0, 0))
        buf.write(self.title)
        for row, saved_record in zip(range(self.ROWS), self.last_records):
            buf.write(pos(row + self.FIRST_ROW, 0))
            queue = queue_from_record(saved_record)
            if queue == self._current:
                buf.write(self.SEL + ' ' + Style.RESET_ALL)
            else:
                buf.write(' ')
            buf.write(queue[1].ljust(30))

            buf.write(super().format(saved_record))

        return buf.getvalue()

class DriverListFormatter(ColorizingFormatter):
    """Log formatter for Driver List View.

    :param queues: The list of queues with sorted logging messages. Each queue
                   corresponds to one instrument.
    """

    FMT = Style.NORMAL + '%(asctime)s <color>%(levelname)-8s</color>' + Style.NORMAL + ' %(message)s'

    FIRST_ROW = 2
    LOG_HEIGHT = 4

    def __init__(self, queues, *args, **kwargs):
        super().__init__(fmt=self.FMT, datefmt='%H:%M:%S', *args, **kwargs)
        self.queues = queues
        self.redraw = True
        self._title = ''
        self._current = ''

    @property
    def current(self):
        return self._current

    @current.setter
    def current(self, value):
        self._current = value
        self.redraw = True

    @property
    def title(self):
        return self._title

    @title.setter
    def title(self, value):
        self._title = value
        self.redraw = True

    def format(self, record):
        if record is RETITLE:
            return pos(0, 0) + self.title

        buf = StringIO()
        if self.redraw or record is REDRAW:
            self.redraw = False
            buf.write(clear())
            buf.write(pos(0, 0))
            buf.write(self.title)
            self._write_view(buf)
        else:
            self._write_record(record, buf)
        return buf.getvalue()

    def _write_view(self, buf):
        for num, (name, state) in enumerate(self.queues.items()):
            self._write_record_helper(num, name, state, buf)

    def _write_record(self, record, buf):
        queue = queue_from_record(record)
        num = list(self.queues.keys()).index(queue)
        state = self.queues[queue]
        self._write_record_helper(num, queue, state, buf)

    def _write_record_helper(self, num, name, state, buf):
        row = num * self.LOG_HEIGHT + self.FIRST_ROW
        buf.write(pos(row, 0))

        if name == self._current:
            buf.write(Back.RED + Fore.WHITE + Style.BRIGHT)
            buf.write((' ' + '.'.join(name)).ljust(COLS))
        else:
            buf.write(Back.WHITE + Fore.BLACK)
            buf.write((' ' + '.'.join(name)).ljust(COLS))
        buf.write(Style.RESET_ALL)
        for subrow, saved_record in zip(range(1, self.LOG_HEIGHT), state.last_records):
            buf.write(pos(row + subrow, 0))
            buf.write('  ' + super().format(saved_record))

class DriverFormatter(ColorizingFormatter):
    """Log formatter for Driver View.

    :param queues: The list of queues with sorted logging messages. Each queue
                   corresponds to one instrument.
    """

    FIRST_ROW = 3
    COL_WIDTH = 40
    PROP_HEIGHT = 15
    LOG_HEIGHT = 4

    FMT = Style.NORMAL + '%(asctime)s <color>%(levelname)-8s</color>' + Style.NORMAL + ' %(message)s'

    def __init__(self, queues, *args, **kwargs):
        super().__init__(fmt=self.FMT, datefmt='%H:%M:%S', *args, **kwargs)
        self.queues = queues
        self.redraw = True
        self._title = ''
        self._current = ''

    @property
    def current(self):
        return self._current

    @current.setter
    def current(self, value):
        self._current = value
        self.redraw = True

    @property
    def title(self):
        return self._title

    @title.setter
    def title(self, value):
        self._title = value
        self.redraw = True

    def format(self, record):
        if record is RETITLE:
            return pos(0, 0) + self.title

        buf = StringIO()
        if self.redraw or record is REDRAW:
            self.REDRAW = False
            buf.write(clear())
            buf.write(pos(0, 0))
            buf.write(self.title)
            self._write_view(buf)
        else:
            self._write_record(record, buf)

        return buf.getvalue()

    def _write_view(self, buf):
        current = self._current
        buf.write(pos(2, 0))
        buf.write(Back.RED + Fore.WHITE + Style.BRIGHT)
        buf.write((' ' + '.'.join(current)).ljust(COLS))
        buf.write(pos(self.FIRST_ROW + self.PROP_HEIGHT, 0))
        buf.write(Style.RESET_ALL)
        buf.write(Back.WHITE + Fore.BLACK)
        buf.write((' Messages').ljust(COLS))
        buf.write(Style.RESET_ALL)
        if current not in self.queues:
            return
        state = self.queues[current]
        for num, (name, value) in enumerate(state.feats.items()):
            col = num // self.PROP_HEIGHT * self.COL_WIDTH
            row = num % self.PROP_HEIGHT + self.FIRST_ROW
            self._write_property(row, col, name, value, buf)

        self._write_log_helper(state, buf)

    def _write_log_helper(self, state, buf):
        row = self.FIRST_ROW + self.PROP_HEIGHT
        for subrow, saved_record in zip(range(1, self.PROP_HEIGHT), state.last_records):
            buf.write(pos(row + subrow, 0))
            buf.write('  ' + super().format(saved_record))

    def _write_record(self, record, buf):
        queue = queue_from_record(record)
        state = self.queues[queue]
        if hasattr(record, 'lantz_feat'):
            if queue not in self.queues:
                return
            name, value = record.lantz_feat
            num = list(state.feats.keys()).index()
            col = num // self.PROP_HEIGHT * self.COL_WIDTH
            row = num % self.PROP_HEIGHT + self.FIRST_ROW
            self._write_property(row, col, name, value, buf)

        self._write_record_helper(0, '.'.join(queue), state, buf)

    def _write_property(self, row, col, name, value, buf):
        if name:
            buf.write(pos(row, col + 0))
            buf.write(name)
        buf.write(pos(row, col + 20))
        buf.write(value)

#: Parser for set messages.
SETTER = Parser('{0:s} was set to {1:s}')

#: Parser for get messages.
GETTER = Parser('Got {1:s} for {0:s}')

class InstrumentState(object):
    """A class to build up the state of the instrument by parsing incoming
    log records. It also remember the last received log records.
    """

    #: Number of log records to remember.
    REMEMBER = 10

    def __init__(self):
        self.count = 0
        self.last_records = []
        self.feats = OrderedDict()

    def handle(self, record):
        self.count += 1
        self.last_records.append(record)
        if len(self.last_records) > self.REMEMBER:
            self.last_records = self.last_records[-self.REMEMBER:]
        if hasattr(record, 'lantz_feat'):
            self.feats[record.lantz_feat[0]] = record.lantz_feat[1]

class LantzMonitor(SocketListener):
    """Text UI to display log records incoming via tcp or udp.
    """

    def __init__(self, tcphost, udphost, level=logging.INFO,
                 filter_='lantz.*'):
        super().__init__(tcphost, udphost)

        self.queues = defaultdict(InstrumentState)
        self.filter = filter_ or '*'
        self._level = level
        self.formatters = [MessageListFormatter(self.queues),
                           DriverListFormatter(self.queues),
                           DriverFormatter(self.queues)]
        self.handler = logging.StreamHandler()
        self.handler.setFormatter(self.formatters[0])
        self.retitle('Welcome, press h for help.')

    @property
    def level(self):
        return self._level

    @level.setter
    def level(self, value):
        self._level = value
        self.retitle()

    def loop(self):
        view = 0
        queue = 0
        last_help = 0
        messages = itertools.cycle(('Change logging level: 1-5',
                                    'Change view: [ ]',
                                    'Select instrument: , .',
                                    'Quit: q',
                                    'Press h for help.'))
        while 1:
            command = getch()

            if command in ('1', '2', '3', '4', '5'):
                self.level = int(command) * 10

            elif command in ('[', ']'):
                view = (view + (-1 if command == '[' else 1)) % 3
                self.handler.setFormatter(self.formatters[view])
                self.handler.handle(REDRAW)

            elif command in (',', '.'):
                queue = (queue + (-1 if command == ',' else 1)) % len(self.queues)
                for formatter in self.formatters:
                    formatter.current = list(self.queues.keys())[queue]
                self.handler.handle(REDRAW)

            elif command in ('q', chr(3)):
                raise SystemExit

            elif command == 'h':
                self.retitle(next(messages))

            elif command in (chr(13), ):
                view = 2
                self.handler.setFormatter(self.formatters[view])
                self.handler.handle(REDRAW)

            else:
                self.retitle("Unknown command '{}' (ord {})".format(command, ord(command)))

    def retitle(self, message=''):
        title = '<> Lantz <> Queues: {:3d} <> Level: {:8s} <> {}'.format(len(self.queues),
                                                                    level_name(self._level),
                                                                    message)
        title = Back.BLUE + Fore.WHITE + title.ljust(COLS) + Style.RESET_ALL
        for formatter in self.formatters:
            formatter.title = title
        self.handler.handle(RETITLE)

    def on_record(self, record):
        if not fnmatch(record.name or '', self.filter):
            return
        if record.levelno < self.level:
            return
        with self._lock:
            queue = queue_from_record(record)
            if queue not in self.queues:
                self.queues[queue] = InstrumentState()
                self.retitle()
            if len(self.queues) == 1:
                for formatter in self.formatters:
                    formatter.current = queue
            self.queues[queue].handle(record)
            self.handler.handle(record)

###########################
# standalone main
###########################

def main():
    import argparse

    colorama.init()
    parser = argparse.ArgumentParser(description='Text based tool to monitor Lantz messages logged to a socket..')
    parser.add_argument('-t', '--tcp', default='0.0.0.0', dest='tcphost',
                        help='Where to listen for TCP traffic (host[:port])')
    parser.add_argument('-u', '--udp', default='0.0.0.0', dest='udphost',
                        help='Where to listen for UDP traffic (host[:port])')
    parser.add_argument('--filter', default=None,
                        help='Filter to apply to incomming records')
    parser.add_argument('-l', '--level', choices=range(1, 6), default=2, type=int,
                        help='Logging level (debug, info, warn, error, critical')
    args = parser.parse_args()

    print(clear())
    monitor = LantzMonitor(args.tcphost, args.udphost,
                           args.level * 10, args.filter)

    try:
        monitor.loop()
    except (KeyboardInterrupt, SystemExit):
        monitor.stop()
    print(clear())
    print('Lantz Monitor stopped')

if __name__ == '__main__':
    main()


dopustimie = ['-','.',',']
ints = ['0','1','2','3','4','5','6','7','8','9']
number = input("Введите число: ")
s = 0
for i in number:
    if not ((i in dopustimie) or (i in ints)):
         print("Введено недопустимое значение для вводимого числа")
         break
    if i in ints: s += int(i)
print(f"Сумма цифр введенного числа равна {s}.")


import pytest
import trio
from hypothesis import given, settings, strategies as st

from pytest_trio.plugin import _trio_test_runner_factory

# deadline=None avoids unpredictable warnings/errors when CI happens to be
# slow (example: https://travis-ci.org/python-trio/pytest-trio/jobs/406738296)
# max_examples=5 speeds things up a bit
our_settings = settings(deadline=None, max_examples=5)

@our_settings
@given(st.integers())
@pytest.mark.trio
async def test_mark_inner(n):
    assert isinstance(n, int)

@our_settings
@pytest.mark.trio
@given(st.integers())
async def test_mark_outer(n):
    assert isinstance(n, int)

@our_settings
@pytest.mark.parametrize("y", [1, 2])
@given(x=st.none())
@pytest.mark.trio
async def test_mark_and_parametrize(x, y):
    assert x is None
    assert y in (1, 2)

async def scheduler_trace():
    """Returns a scheduler-dependent value we can use to check determinism."""
    trace = []

    async def tracer(name):
        for i in range(10):
            trace.append((name, i))
            await trio.sleep(0)

    async with trio.open_nursery() as nursery:
        for i in range(5):
            nursery.start_soon(tracer, i)

    return tuple(trace)

def test_the_trio_scheduler_is_deterministic_under_hypothesis():
    traces = []

    @our_settings
    @given(st.integers())
    @pytest.mark.trio
    async def inner(_):
        traces.append(await scheduler_trace())

    # The pytest.mark.trio doesn't do it's magic thing to
    # inner functions, so we invoke it explicitly here.
    inner.hypothesis.inner_test = _trio_test_runner_factory(
        None, inner.hypothesis.inner_test
    )
    inner()  # Tada, now it's a sync function!

    assert len(traces) >= 5
    assert len(set(traces)) == 1


import math
import sys

def f(x, y):
    try:
        result = math.nan
        result = math.sqrt(x)/y
    except TypeError:
        print('Please enter two numbers!')
    except ValueError:
        print('x must be non-negative!')
    finally:
        print(sys.exc_info())
        return result


__all__ = [
    "AutoOrder",
    "date_handler",
    "privacy_handler",
    "cheap_user_hash",
    "find_user_in_mutual_guilds",
    "find_users_by_display_name",
    "find_users_by_username",
]

from datetime import date
import logging
from typing import Optional

import discord
from discord.ext.commands import BadArgument, Command

from sandpiper.user_data.enums import PrivacyType
from .time import parse_date

logger = logging.getLogger("sandpiper.common.discord")

class AutoOrder:
    """
    Decorate commands/groups with an instance of this class to magically
    order them in definition-order in Sandpiper's help command! You should use
    a new instance of this class for each cog to ensure top-level
    commands/groups get ordered correctly.

    This can also be done manually by adding an ``order`` kwarg in the
    command/group decorator call.

    Technically, it adds an 'order' key to the command's __original_kwargs__
    dict, as this is perhaps the only attribute that persists across command
    copies (commands are apparently copied for each help command invocation,
    therefore we lose any other attributes we may set, like a command.order).
    """

    def __init__(self):
        self.top_level_order = 0

    def __call__(self, command: Command):
        if command.parent is None:
            # Use state to order these top-level commands since the cog isn't
            # bound yet and therefore we can't query the command count
            order = self.top_level_order
            self.top_level_order += 1
        else:
            # Order by parent's commands count
            order = len(command.parent.commands) - 1

        command.__original_kwargs__["order"] = order
        return command

def cheap_user_hash(user_id: int) -> int:
    return user_id >> 22

def date_handler(date_str: str) -> date:
    try:
        return parse_date(date_str)
    except ValueError as e:
        logger.info(f"Failed to parse date (str={date_str!r} reason={e})")
        raise BadArgument(
            "Bad date format. Try something like this: `1997-08-27`, "
            "`31 Oct`, `June 15 2001`"
        )

def privacy_handler(privacy_str: str) -> PrivacyType:
    privacy_str = privacy_str.upper()
    try:
        return PrivacyType[privacy_str]
    except KeyError:
        privacy_names = [n.lower() for n in PrivacyType.__members__.keys()]
        raise BadArgument(f"Privacy must be one of {privacy_names}")

def find_user_in_mutual_guilds(
    client: discord.Client,
    whos_looking: int,
    for_whom: int,
    *,
    short_circuit: bool = False,
) -> list[discord.Member]:
    """
    Find a user who shares mutual guild's with someone else.

    :param client: the client with access to guild members
    :param whos_looking: the source user who is looking for the target
    :param for_whom: the target user being searched for
    :param short_circuit: whether to return on the first found member
    :return: a list of guild members representing the target user
    """
    found_members = []
    for g in client.guilds:
        g: discord.Guild
        if g.get_member(whos_looking):
            member = g.get_member(for_whom)
            if member:
                if short_circuit:
                    return member
                found_members.append(member)
    return found_members

def find_users_by_username(
    client: discord.Client, name: str
) -> [list[tuple[int, str]]]:
    """
    Search for users by their Discord username.

    :param client: the client with access to users
    :param name: the substring to search for
    :return: a list of users whose names match
    """
    users = []
    name = name.casefold()
    for user in client.users:
        user: discord.User
        if name in f"{user.name.casefold()}#{user.discriminator}":
            users.append((user.id, f"{user.name}#{user.discriminator}"))
    return users

def find_users_by_display_name(
    client: discord.Client,
    whos_looking: int,
    name: str,
    *,
    guild: Optional[discord.Guild] = None,
) -> [list[tuple[int, str]]]:
    """
    Search for users by their display name (nickname in a guild). You may pass
    in a guild to optimize the search by limiting to only that guild.

    :param client: the client with access to guild members
    :param whos_looking: the user who is searching
    :param name: a substring to search for in user display names
    :param guild: an optional guild to limit the search to
    :return: a list of tuples of (user_id, display_name) with matching users
    """

    users = []
    name = name.casefold()

    def search_guild(guild: discord.Guild):
        if not guild.get_member(whos_looking):
            return
        for member in guild.members:
            member: discord.Member
            if name in member.display_name.casefold():
                users.append((member.id, member.display_name))

    if guild:
        search_guild(guild)
    else:
        for guild in client.guilds:
            search_guild(guild)

    return users


# -*- coding: utf-8 -*-

import time

from trac.core import *
from trac.config import Option
from trac.wiki import wiki_to_html, wiki_to_oneliner
from trac.util import format_datetime, pretty_timedelta

class IScreenshotChangeListener(Interface):
    """Extension point interface for components that require notification
    when screenshots are created, modified, or deleted."""

    def screenshot_created(screenshot):
        """Called when a screenshot is created. Only argument `screenshot` is
        a dictionary with screenshot field values."""

    def screenshot_changed(screenshot, old_screenshot):
        """Called when a screenshot is modified.
        `old_screenshot` is a dictionary containing the previous values of the
        fields and `screenshot` is a dictionary with new values. """

    def screenshot_deleted(screenshot):
        """Called when a screenshot is deleted. `screenshot` argument is
        a dictionary with values of fields of just deleted screenshot."""

class IScreenshotsRenderer(Interface):
    """Extension point interface for components providing view on
       screenshots."""

    def render_screenshots(req, name, data):
        """Provides template and data for screenshots view. Inputs request
           object and dictionary with screenshots data and should return tuple
           with template name modified or unchanged data and content type."""

    def get_screenshots_view(req):
        """Returns tuple with name and title of implemented screenshots
           view."""

class ScreenshotsApi(Component):

    # Get list functions

    def _get_items(self, cursor, table, columns, where = '', values = ()):
        sql = 'SELECT ' + ', '.join(columns) + ' FROM ' + table + (where
          and (' WHERE ' + where) or '')
        self.log.debug(sql % values)
        cursor.execute(sql, values)
        items = []
        for row in cursor:
            row = dict(zip(columns, row))
            items.append(row)
        return items

    def get_versions(self, cursor):
        # Get versions from database.
        return self._get_items(cursor, 'version', ('name',
          'description'))

    def get_components(self, cursor):
        # Get components from database.
        return self._get_items(cursor, 'component',
          ('name', 'description'))

    def get_screenshots(self, cursor):
        # Get screenshots from database.
        return self._get_items(cursor, 'screenshot', ('id', 'name',
          'description', 'time', 'author', 'tags', 'file', 'width', 'height'))

    def get_screenshots_complete(self, cursor):
        screenshots = self.get_screenshots(cursor)
        for screenshot in screenshots:
            screenshot['components'] = self.get_screenshot_components(cursor,
              screenshot['id'])
            screenshot['versions'] = self.get_screenshot_versions(cursor,
              screenshot['id'])
        return screenshots

    def get_filtered_screenshots(self, cursor, components, versions):
        has_none_version = True
        has_none_component = True
        columns = ('id', 'name', 'description', 'time', 'author', 'tags',
          'file', 'width', 'height')
        versions_str = (', '.join(['%s'] * len(versions))) or 'NULL'
        components_str = (', '.join(['%s'] * len(components))) or 'NULL'
        sql = 'SELECT DISTINCT ' + ', '.join(columns) + ' FROM screenshot s ' \
          'LEFT JOIN (SELECT screenshot, version FROM screenshot_version) v ' \
          'ON s.id = v.screenshot LEFT JOIN (SELECT screenshot, component ' \
          'FROM screenshot_component) c ON s.id = c.screenshot WHERE ' \
          'v.version IN (' + versions_str + ')' + (('none' in versions) and \
          ' OR v.version IS NULL' or '') + ' OR c.component IN (' + \
          components_str + ')' + (('none' in components) and \
          ' OR c.component IS NULL' or '')
        self.log.debug(versions + components)
        self.log.debug(sql % tuple(versions + components))
        cursor.execute(sql, versions + components)
        screenshots = []
        for row in cursor:
            row = dict(zip(columns, row))
            screenshots.append(row)
        return screenshots

    # Get one item functions

    def _get_item(self, cursor, table, columns, where = '', values = ()):
        sql = 'SELECT ' + ', '.join(columns) + ' FROM ' + table + (where
          and (' WHERE ' + where) or '')
        self.log.debug(sql, values)
        cursor.execute(sql, values)
        for row in cursor:
            row = dict(zip(columns, row))
            return row

    def get_screenshot(self, cursor, id):
        # Get screenshot from database.
        screenshot = self._get_item(cursor, 'screenshot', ('id', 'name',
          'description', 'time', 'author', 'tags', 'file', 'width', 'height'),
          'id = %s', (id,))

        if screenshot:
            # Append components and versions.
            screenshot['components'] = self.get_screenshot_components(cursor,
              screenshot['id'])
            screenshot['versions'] = self.get_screenshot_versions(cursor,
              screenshot['id'])
            return screenshot
        else:
            return None

    def get_screenshot_by_time(self, cursor, time):
        # Get screenshot from database.
        screenshot = self._get_item(cursor, 'screenshot', ('id', 'name',
          'description', 'time', 'author', 'tags', 'file', 'width', 'height'),
          'time = %s', (time,))

        # Append components and versions.
        if screenshot:
            screenshot['components'] = self.get_screenshot_components(cursor,
              screenshot['id'])
            screenshot['versions'] = self.get_screenshot_versions(cursor,
              screenshot['id'])
            return screenshot
        else:
            return None

    def get_screenshot_components(self, cursor, id):
        sql = 'SELECT component FROM screenshot_component WHERE screenshot = %s'
        self.log.debug(sql % (id,))
        cursor.execute(sql, (id,))
        components = []
        for row in cursor:
            components.append(row[0])
        return components

    def get_screenshot_versions(self, cursor, id):
        sql = 'SELECT version FROM screenshot_version WHERE screenshot = %s'
        self.log.debug(sql % (id,))
        cursor.execute(sql, (id,))
        versions = []
        for row in cursor:
            versions.append(row[0])
        return versions

    # Add item functions

    def _add_item(self, cursor, table, item):
        fields = item.keys()
        values = item.values()
        sql = "INSERT INTO %s (" % (table,) + ", ".join(fields) + ") VALUES (" \
          + ", ".join(["%s" for I in xrange(len(fields))]) + ")"
        self.log.debug(sql % tuple(values))
        cursor.execute(sql, tuple(values))

    def add_screenshot(self, cursor, screenshot):
        self._add_item(cursor, 'screenshot', screenshot)

    def add_component(self, cursor, component):
        self._add_item(cursor, 'screenshot_component', component)

    def add_version(self, cursor, version):
        self._add_item(cursor, 'screenshot_version', version)

    # Edit item functions

    def _edit_item(self, cursor, table, id, item):
        fields = item.keys()
        values = item.values()
        sql = "UPDATE %s SET " % (table,) + ", ".join([("%s = %%s" % (field))
          for field in fields]) + " WHERE id = %s"
        self.log.debug(sql % tuple(values + [id]))
        cursor.execute(sql, tuple(values + [id]))

    def edit_screenshot(self, cursor, id, screenshot):
        # Replace components.
        self.delete_components(cursor, id)
        for component in screenshot['components']:
            component = {'screenshot' : id,
                         'component' : component}
            self.add_component(cursor, component)

        # Replace versions.
        self.delete_versions(cursor, id)
        for version in screenshot['versions']:
            version = {'screenshot' : id,
                       'version' : version}
            self.add_version(cursor, version)

        # Update screenshot values.
        del screenshot['components']
        del screenshot['versions']
        self._edit_item(cursor, 'screenshot', id, screenshot)

    # Delete item functions

    def delete_screenshot(self, cursor, id):
        # Delete screenshot.
        sql = "DELETE FROM screenshot WHERE id = %s"
        self.log.debug(sql % (id,))
        cursor.execute(sql, (id,))

        # Delete versions and components.
        self.delete_versions(cursor, id)
        self.delete_components(cursor, id)

    def delete_versions(self, cursor, id):
        sql = "DELETE FROM screenshot_version WHERE screenshot = %s"
        self.log.debug(sql % (id,))
        cursor.execute(sql, (id,))

    def delete_components(self, cursor, id):
        sql = "DELETE FROM screenshot_component WHERE screenshot = %s"
        self.log.debug(sql % (id,))
        cursor.execute(sql, (id,))


def run():
  #Creating the variables
  cover_type = str(input("What type of cover does the book have?"))

  #deciding what type of cover it is and what response it will give out
  if cover_type == "soft":
    shape = str(input("Is the book perfect-bound?"))
    if shape == "yes":
      print("Soft cover, perfect bound books are very popular!")
    else:
      print("Soft covers with coils or stitches are great for short books")
  else:
    print("Books with hard covers can be more expensive!")

run()


"""
Computes a quantitative metric for Grad-CAM obtained heatmaps.
Basically, computed an IoU between the heatmap and the ground truth (on MNISTs).
"""
import os
import sys
import argparse
import json
import numpy as np
import pandas as pd
import torch
from torchvision import transforms
import torchvision.datasets as tv_datasets
from torchvision import transforms as tv_transforms
from torchvision.utils import save_image, make_grid
from PIL import Image
from tqdm import tqdm
from gradcam.utils import visualize_cam
from gradcam import GradCAM, GradCAMpp
import matplotlib.pyplot as plt
import seaborn as sns
from torchmetrics import JaccardIndex

import warnings
warnings.filterwarnings("ignore")

from experiment_utils import set_env, REPO_PATH, seed_everything
set_env()

from cgn_framework.mnists.models.classifier import CNN
from cgn_framework.mnists.train_cgn import save
from cgn_framework.mnists.dataloader import get_tensor_dataloaders, TENSOR_DATASETS

def main(args):
    seed_everything(0)

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    # load model and its weights from a checkpoint
    model = CNN()

    # load checkpoint
    print("Loading model weights from checkpoint: {}".format(args.weight_path))
    ckpt = torch.load(os.path.join(REPO_PATH, "cgn_framework", args.weight_path), map_location='cpu')
    model.load_state_dict(ckpt)
    model = model.eval()
    model = model.to(device)

    # load the test dataloader to evaluate GradCAM on
    print("Loading dataset: {}".format(args.dataset))
    dl_train, dl_test = get_tensor_dataloaders(args.dataset, 64)
    ds_test = dl_test.dataset

    # load original MNIST to obtain binary maps
    T = tv_transforms.Compose([
        tv_transforms.Resize((32, 32), Image.NEAREST),
        tv_transforms.ToTensor(),
    ])
    original = tv_datasets.MNIST(
        root="./mnists/data/MNIST/", download=True, train=False, transform=T,
    )

    # define the target layer to be used
    target_layer = model.model[8]
    gradcam = GradCAM(model, target_layer)

    # for metric computation
    jaccard = JaccardIndex(num_classes=2)
    jaccard = jaccard.to(device)

    # apply GradCAM on the test set
    iterator = tqdm(
        range(len(ds_test)),
        colour="red",
        bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}',
        desc="Computing GradCAM",
        disable=args.disable_tqdm,
    )
    iou_values = []
    labels = []
    show = False
    for i in iterator:

        # get image
        image, label = ds_test[i]
        image = image.to(device)

        # get gradcam mask
        gc_mask, _ = gradcam(image.unsqueeze(0))
        heatmap, result = visualize_cam(gc_mask, image)
        gc_mask = gc_mask.squeeze(0).to(device)

        # get coresponding GT mask from original dataset
        gt_mask = original[i][0]
        gt_mask = gt_mask.to(device)
        gt_mask_binary = gt_mask > 0.5

        iou = jaccard(gc_mask, gt_mask_binary)
        iou_values.append(iou.cpu().item())
        labels.append(label)

        if show:
            grid = make_grid([gt_mask, gc_mask], padding=0)
            plt.title(f"IoU: {iou:.4f}", fontsize=18)
            plt.imshow(grid.permute((1, 2, 0)))
            plt.show()

    df = pd.DataFrame(None, columns=["iou", "label"])
    df["iou"] = iou_values
    df["label"] = torch.stack(labels).numpy()

    class_wise_results = dict(df.groupby("label")["iou"].mean())
    class_wise_results["overall_mean"] = np.mean(iou_values)
    class_wise_results["overall_std"] = np.std(iou_values)

    return class_wise_results

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--dataset', type=str, required=True, choices=TENSOR_DATASETS,
                        help='Provide dataset name.')
    parser.add_argument('--batch_size', type=int, default=64, metavar='N',
                        help='input batch size for training (default: 64)')
    parser.add_argument('--seed', type=int, default=0,
                        help='random seed')
    parser.add_argument('--weight_path', type=str, required=True,
                        help='path to the classifier checkpoint')
    parser.add_argument('--disable_tqdm', action='store_true',
                        help='disable tqdm progress bar')

    args = parser.parse_args()

    print("::::: Configs :::::")
    print(args)

    print("::::: Running :::::")
    results = main(args)

    # save results
    args.model = args.weight_path.split("/")[-3]
    save_path = os.path.join(
        REPO_PATH,
        "experiments",
        "results",
        f"{args.dataset}_{args.model}_seed_{args.seed}_gradcam_iou.pth",
    )
    torch.save(results, save_path)

    print("::::: Results :::::")
    print(json.dumps(str(results), indent=4))


class BST():
    def __init__(self, root):
        self.root = root

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

def insert(root, node):
    if not root:
        root = node
    # going left
    if node.value < root.value:
        if not root.left:
            root.left = node
            return
        else:
            insert(root.left, node)
            return
    # going right
    elif node.value > root.value:
        if not root.right:
            root.right = node
            return
        else:
            insert(root.right, node)
            return

def isPresent(root, val):
    if not root:
        return 0
    elif val == root.value:
        return 1
    elif val < root.value:
        if not root.left:
            return 0
        else:
            return isPresent(root.left, val)
    elif val > root.value:
        if not root.right:
            return 0
        else:
            return isPresent(root.right, val)


from vncdotool import api

# 创建 VNC 会话
vnc = api.connect('10.151.116.71:1')

#vnc.mouseMove(315, 300)
#print(vnc.x)
#vnc.mousePress(1)
#vnc.mouseMove(270, 885)
#print(vnc.x)
#vnc.mousePress(1)

vnc.keyPress('1')
vnc.captureScreen('screen.png')
print('screen ok')


import pandas as pd

def _get_array(data, var, tech, locations):
    arr = data[var]
    arr = arr.loc[{'y': tech}]
    if locations is not None:
        arr = arr.loc[{'x': locations}]
    return arr

def zero(data, tech, var='r', locations=None):
    """
    Returns timesteps where ``var`` for the technology ``tech``
    across the given list of ``locations`` is zero.

    If ``locations`` not given, uses all available locations.

    """
    arr = _get_array(data, var, tech, locations)
    s = arr.mean(dim='x').to_pandas()  # Get a t-indexed Series

    return s[s == 0].index

def _concat_indices(indices):
    return pd.concat([i.to_series() for i in indices]).sort_index().index

def _get_minmax_timestaps(series, length, n, how='max', padding=None):
    # Get the max/min timestamps
    group = series.groupby(pd.TimeGrouper(length)).mean()
    timesteps = []
    for _ in range(n):
        if how == 'max':
            ts = group.idxmax()
        elif how == 'min':
            ts = group.idxmin()
        timesteps.append(ts)
        group = group.drop(ts)

    # Get range of timestamps including padding
    full_timesteps = []
    for ts in timesteps:
        ts_end = ts + pd.Timedelta(length)
        if padding is not None:
            ts -= pd.Timedelta(padding)
            ts_end += pd.Timedelta(padding)
        ts_range = pd.date_range(ts, ts_end, freq='1H')[:-1]
        full_timesteps.append(ts_range)

    ts_index = _concat_indices(full_timesteps)

    return ts_index

def extreme(data, tech, var='r', how='max',
            length='1D', n=1, groupby_length=None,
            locations=None, padding=None):
    """
    Returns timesteps for period of ``length`` where ``var`` for the technology
    ``tech`` across the given list of ``locations`` is either minmal
    or maximal.

    Parameters
    ----------
    data : xarray.Dataset
    tech : str
        Technology whose `var` to find extreme for.
    var : str, optional
        default 'r'
    how : str, optional
        'max' (default) or 'min'.
    length : str, optional
        Defaults to '1D'.
    n : int, optional
        Number of periods of `length` to look for, default is 1.
    groupby : str, optional
        Group time series and return `n` periods of `length`
        for each group.
    locations : list, optional
        List of locations to use, if None, uses all available locations.
    padding : int, optional
        Pad beginning and end of the unmasked area by the number of
        timesteps given.

    """
    arr = _get_array(data, var, tech, locations)
    full_series = arr.mean(dim='x').to_pandas()  # Get a t-indexed Series

    if groupby_length:
        groupby = pd.TimeGrouper(groupby_length)
        group_indices = []
        grouping = full_series.groupby(groupby)
        for k in grouping.groups.keys():
            s = grouping.get_group(k)
            group_indices.append(_get_minmax_timestaps(s, length, n, how, padding))
        ts_index = _concat_indices(group_indices)
    else:
        ts_index = _get_minmax_timestaps(full_series, length, n, how, padding)

    return ts_index


"""
A collection of useful function snippets that irrelevant with the main modules
or await for further refactor
"""
import logging
from typing import Any, Callable, Iterator, Optional, Sequence, Tuple

import numpy as np
import tensorflow as tf

logger = logging.getLogger(__name__)

try:
    import cirq
except ImportError as e:
    logger.warning(e)
    logger.warning("Therefore some functionality in %s may not work" % __name__)

from ..circuit import Circuit
from .. import gates as G
from ..gates import array_to_tensor, num_to_tensor

Array = Any
Tensor = Any
Graph = Any

class FakeModule:
    def __getattr__(self, name: str) -> str:
        return name

fake_module = FakeModule()

##############
## qml related functions to be refactored
##############

# tf specific

def amplitude_encoding(
    fig: Tensor,
    qubits: int,
    index: Optional[Sequence[int]] = None,
    index_func: Optional[Callable[[int, int], Sequence[int]]] = None,
) -> Tensor:
    if fig.shape[-1] == 1:
        fig = tf.reshape(fig, shape=fig.shape[:-1])
    if len(fig.shape) == 2:
        fig = fig[tf.newaxis, ...]
    fig = tf.reshape(fig, shape=(fig.shape[0], fig.shape[1] * fig.shape[2]))
    norm = tf.linalg.norm(fig, axis=1)
    norm = norm[..., tf.newaxis]
    fig = fig / norm
    if fig.shape[1] < 2**qubits:
        fig = tf.concat(
            [
                fig,
                tf.zeros([fig.shape[0], 2**qubits - fig.shape[1]], dtype=tf.float64),
            ],
            axis=1,
        )
    if index is None and index_func is not None:
        index = []
        for i in range(32):
            # magic number here, only valid for MNIST data
            for j in range(32):
                l = index_func(i, j)
                r = 0
                for p, q in enumerate(l):
                    r += q * 2 ** (9 - p)
                index.append(r)
    if index is not None:
        fig = tf.constant(fig.numpy()[:, index], dtype=fig.dtype)
    return fig

def recursive_index(x: int, y: int) -> Sequence[int]:
    rl = []
    for k in range(5):
        rl.append((x // (2 ** (4 - k))) % 2)
        rl.append((y // (2 ** (4 - k))) % 2)
    return rl

def mnist_amplitude_data(
    a: int,
    b: int,
    binarize: bool = False,
    index: Optional[Sequence[int]] = None,
    index_func: Optional[Callable[[int, int], Sequence[int]]] = None,
    loader: Any = None,
    threshold: float = 0.4,
) -> Tensor:
    def filter_pair(x: Tensor, y: Tensor, a: int, b: int) -> Tuple[Tensor, Tensor]:
        keep = (y == a) | (y == b)
        x, y = x[keep], y[keep]
        y = y == a
        return x, y

    if loader is None:
        loader = tf.keras.datasets.mnist
    (x_train, y_train), (x_test, y_test) = loader.load_data()
    x_train, x_test = x_train[..., np.newaxis] / 255.0, x_test[..., np.newaxis] / 255.0

    if binarize:
        x_train[x_train > threshold] = 1.0
        x_train[x_train <= threshold] = 0.0
        x_test[x_test > threshold] = 1.0
        x_test[x_test <= threshold] = 0.0
    x_train, y_train = filter_pair(x_train, y_train, a, b)
    x_test, y_test = filter_pair(x_test, y_test, a, b)
    x_train = tf.image.pad_to_bounding_box(x_train, 2, 2, 32, 32)
    x_test = tf.image.pad_to_bounding_box(x_test, 2, 2, 32, 32)
    x_train_q = amplitude_encoding(x_train, 10, index=index, index_func=index_func)
    x_test_q = amplitude_encoding(x_test, 10, index=index, index_func=index_func)
    return (x_train_q, y_train), (x_test_q, y_test)

def mnist_generator(
    x_train: Tensor, y_train: Tensor, batch: int = 1, random: bool = True
) -> Iterator[Any]:
    if isinstance(x_train, tf.Tensor):
        x_train = x_train.numpy()
    if isinstance(y_train, tf.Tensor):
        y_train = y_train.numpy()
    i = np.array(list(range(batch)))
    while True:
        if random:
            i = np.random.randint(low=0, high=x_train.shape[0], size=batch)
        else:
            i += batch
            i = i % x_train.shape[0]
        yield tf.constant(x_train[i]), tf.constant(y_train[i])

def generate_random_circuit(
    inputs: Tensor, nqubits: int = 10, epochs: int = 3, layouts: Tensor = None
) -> Circuit:
    inputs = tf.cast(inputs, dtype=tf.complex64)
    c = Circuit(nqubits, inputs=inputs)
    if layouts is None:
        layouts = np.random.choice([0, 1, 2], size=[epochs, nqubits])
    layouts = tf.reshape(layouts, shape=[epochs, nqubits])
    for epoch in range(epochs):
        for i in range(nqubits):
            flg = layouts[epoch, i]
            if flg == 0:
                c.rx(i, theta=num_to_tensor(np.pi / 2))  # type: ignore
            elif flg == 1:
                c.ry(i, theta=num_to_tensor(np.pi / 2))  # type: ignore
            else:
                c.wroot(i)  # type: ignore
        for i in range(nqubits):  # entangling layer
            c.swap(i, (i + 1) % nqubits)  # type: ignore
    return c

# the following vags are not the recommended fashion to write qml tasks in tensorcircuit now.
# also the hardcoded circuit structure is a bad practice, they are here for backward compatibility
# instead use vvag or keras paradigm now

def naive_qml_vag(
    gdata: Graph,
    nnp: Tensor,
    preset: Sequence[int],
    nqubits: int = 10,
    epochs: int = 3,
    target: int = 0,
) -> Tuple[Tensor, Tensor]:
    # used for structure searching?
    xs, ys = gdata
    loss = 0.0
    for x, y in zip(xs, ys):
        circuit = generate_random_circuit(
            x, nqubits=nqubits, epochs=epochs, layouts=preset
        )
        value = circuit.expectation(
            (
                G.z(),  # type: ignore
                [
                    target,
                ],
            )
        )
        y = tf.cast(y, dtype=tf.complex64)
        y = 2 * y - 1
        loss += (value - y) ** 2
    return tf.constant(tf.cast(loss, dtype=tf.float32)), tf.zeros_like(nnp)  # MSE loss

def train_qml_vag(
    gdata: Graph,
    nnp: Tensor,
    preset: Optional[Sequence[int]] = None,
    nqubits: int = 10,
    epochs: int = 3,
    batch: int = 64,
    validation: bool = False,
) -> Any:
    xs, ys = gdata
    with tf.GradientTape() as tape:
        tape.watch(nnp)
        cnnp = tf.cast(nnp, dtype=tf.complex64)
        c = Circuit(nqubits, inputs=np.ones([1024], dtype=np.complex64) / 2**5)
        for epoch in range(epochs):
            for i in range(nqubits):
                c.rz(i, theta=cnnp[3 * epoch, i])  # type: ignore
            for i in range(nqubits):
                c.ry(i, theta=cnnp[3 * epoch + 1, i])  # type: ignore
            for i in range(0, nqubits, 2):
                # c.swap(i, (i + 1) % 10)  # type: ignore
                c.exp(  # type: ignore
                    i,
                    (i + 1) % 10,
                    unitary=array_to_tensor(G._swap_matrix),
                    theta=cnnp[3 * epoch + 2, i],
                )
            for i in range(1, nqubits, 2):
                # c.swap(i, (i + 1) % 10)  # type: ignore
                c.exp(  # type: ignore
                    i,
                    (i + 1) % 10,
                    unitary=array_to_tensor(G._swap_matrix),
                    theta=cnnp[3 * epoch + 2, i],
                )
        for i in range(nqubits):
            c.rx(i, theta=cnnp[3 * epochs, i])  # type: ignore
        count = 0
        loss = 0
        for x, y in zip(xs, ys):
            y = tf.cast(y, dtype=tf.float32)  # [1, 0] binary
            c.replace_inputs(tf.cast(x, dtype=tf.complex64))
            flg = False
            yp = 0.0

            for i in range(nqubits):
                yp += cnnp[3 * epochs + 1, i] * c.expectation(
                    (
                        G.z(),  # type: ignore
                        [
                            i,
                        ],
                    ),
                    reuse=flg,
                )

                flg = True

            yp = tf.cast(yp, dtype=tf.float32)
            yp = tf.math.sigmoid(
                (yp + tf.math.real(cnnp[3 * epochs + 2, 0])) * 15
            )  ## [0,1] intepreted as probability
            if tf.math.abs(yp - y) < 0.5:
                count += 1
            loss += (yp - y) ** 2
        # print("accuracy:", count / batch)
        gr = tape.gradient(loss, cnnp)
        if not validation:
            return tf.constant(count / batch, dtype=tf.float32), gr
        else:
            return count / batch  # evaluate as validation kernel

def validate_qml_vag(
    gdata: Graph,
    nnp: Tensor,
    preset: Optional[Sequence[int]] = None,
    nqubits: int = 10,
    epochs: int = 3,
    batch: int = 64,
) -> Any:
    xs, ys = gdata
    cnnp = tf.cast(nnp, dtype=tf.complex64)
    c = Circuit(nqubits, inputs=np.ones([1024], dtype=np.complex64) / 2**5)
    for epoch in range(epochs):
        for i in range(nqubits):
            c.rz(i, theta=cnnp[3 * epoch, i])  # type: ignore
        for i in range(nqubits):
            c.ry(i, theta=cnnp[3 * epoch + 1, i])  # type: ignore
        for i in range(0, nqubits, 2):
            # c.swap(i, (i + 1) % 10)  # type: ignore
            c.exp(  # type: ignore
                i,
                (i + 1) % 10,
                unitary=array_to_tensor(G._swap_matrix),
                theta=cnnp[3 * epoch + 2, i],
            )
        for i in range(1, nqubits, 2):
            # c.swap(i, (i + 1) % 10)  # type: ignore
            c.exp(  # type: ignore
                i,
                (i + 1) % 10,
                unitary=array_to_tensor(G._swap_matrix),
                theta=cnnp[3 * epoch + 2, i],
            )
    for i in range(nqubits):
        c.rx(i, theta=cnnp[3 * epochs, i])  # type: ignore
    count = 0
    loss = 0
    for x, y in zip(xs, ys):
        y = tf.cast(y, dtype=tf.float32)  # [1, 0] binary
        c.replace_inputs(tf.cast(x, dtype=tf.complex64))
        flg = False
        yp = 0.0

        for i in range(nqubits):
            yp += cnnp[3 * epochs + 1, i] * c.expectation(
                (
                    G.z(),  # type: ignore
                    [
                        i,
                    ],
                ),
                reuse=flg,
            )

            flg = True

        yp = tf.cast(yp, dtype=tf.float32)
        yp = tf.math.sigmoid(
            (yp + tf.math.real(cnnp[3 * epochs + 2, 0])) * 15
        )  ## [0,1] intepreted as probability
        if tf.math.abs(yp - y) < 0.5:
            count += 1
        loss += (yp - y) ** 2

    return {
        "val_loss": loss / batch,
        "val_accuracy": count / batch,
    }  # evaluate as validation kernel

##############
## really small and irrelavant pieces below
##############

def color_svg(circuit: cirq.Circuit, *coords: Tuple[int, int]) -> Any:
    """
    color cirq circuit SVG for given gates,
    a small tool to hack the cirq SVG

    :param circuit:
    :param coords: integer coordinate which gate is colored
    :return:
    """
    import xml
    from cirq.contrib.svg import SVGCircuit

    svg_str = SVGCircuit(circuit)._repr_svg_()
    DOMTree = xml.dom.minidom.parseString(svg_str)  # type: ignore
    xpos = []
    ypos = []
    for r in DOMTree.getElementsByTagName("rect"):  # [0].setAttribute("fill", "gray")
        xpos.append(int(float(r.getAttribute("x"))))
        ypos.append(int(float(r.getAttribute("y"))))
    xpos = sorted(list(set(xpos)))
    ypos = sorted(list(set(ypos)))
    # xpos_dict = dict(zip(range(len(xpos)), xpos))
    # ypos_dict = dict(zip(range(len(ypos)), ypos))
    i_xpos_dict = dict(zip(xpos, range(len(xpos))))
    i_ypos_dict = dict(zip(ypos, range(len(ypos))))
    for r in DOMTree.getElementsByTagName("rect"):
        x, y = int(float(r.getAttribute("x"))), int(float(r.getAttribute("y")))
        if (i_xpos_dict[x], i_ypos_dict[y]) in coords:
            r.setAttribute("fill", "gray")
    return DOMTree.toxml()

def repr2array(inputs: str) -> Array:
    """
    transform repr form of an array to real numpy array

    :param inputs:
    :return:
    """
    # used to transform np.array in print form into live np.array
    inputs = inputs.split("]")  # type: ignore
    inputs = [l.strip().strip("[") for l in inputs if l.strip()]  # type: ignore
    outputs = []
    for l in inputs:
        o = [float(c.strip()) for c in l.split(" ") if c.strip()]
        outputs.append(o)
    return np.array(outputs)

# duplicated, will remove later
# use the version in applications.physics.baseline.py
def TFIM1Denergy(
    L: int, Jzz: float = 1.0, Jx: float = 1.0, Pauli: bool = True
) -> float:
    # PBC
    # nice tutorial: https://arxiv.org/pdf/2009.09208.pdf
    # further investigation on 1 TFIM solution structure is required
    # will fail on AFM phase Jzz>Jx and Jzz>0 and odd sites (frustration in boundary)
    e = 0
    if Pauli:
        Jx *= 2
        Jzz *= 4
    for i in range(L):
        q = np.pi * (2 * i - (1 + (-1) ** L) / 2) / L
        e -= np.abs(Jx) / 2 * np.sqrt(1 + Jzz**2 / 4 / Jx**2 - Jzz / Jx * np.cos(q))
    return e

def Heisenberg1Denergy(L: int, Pauli: bool = True, maxiters: int = 1000) -> float:
    # PBC
    error = 1e-15
    eps = 1e-20  # avoid zero division
    phi = np.zeros([L // 2, L // 2])
    phi2 = np.zeros([L // 2, L // 2])
    lamb = np.array([2 * i + 1 for i in range(L // 2)])
    for _ in range(maxiters):
        k = 1 / L * (2 * np.pi * lamb + np.sum(phi, axis=-1) - np.diag(phi))
        for i in range(L // 2):
            for j in range(L // 2):
                phi2[i, j] = (
                    np.arctan(
                        2
                        / (
                            1 / (np.tan(k[i] / 2) + eps)
                            - 1 / (np.tan(k[j] / 2) + eps)
                            + eps
                        )
                    )
                    * 2
                )
        if np.allclose(phi, phi2, rtol=error):  # converged
            break
        phi = phi2.copy()
    else:
        raise ValueError(
            "the maxiters %s is too small for bethe ansatz to converge" % maxiters
        )
    e = -np.sum(1 - np.cos(k)) + L / 4
    if Pauli is True:
        e *= 4
    return e  # type: ignore


import matplotlib.pyplot as plt
import numpy as np
from detectron2.utils.colormap import random_color
from detectron2.utils.visualizer import Visualizer

class VisualizerPerspective(Visualizer):
    def draw_arrow(
        self,
        x_pos,
        y_pos,
        x_direct,
        y_direct,
        color=None,
        linestyle="-",
        linewidth=None,
    ):
        """
        Args:
            x_data (list[int]): a list containing x values of all the points being drawn.
                Length of list should match the length of y_data.
            y_data (list[int]): a list containing y values of all the points being drawn.
                Length of list should match the length of x_data.
            color: color of the line. Refer to `matplotlib.colors` for a full list of
                formats that are accepted.
            linestyle: style of the line. Refer to `matplotlib.lines.Line2D`
                for a full list of formats that are accepted.
            linewidth (float or None): width of the line. When it's None,
                a default value will be computed and used.

        Returns:
            output (VisImage): image object with line drawn.
        """
        if color is None:
            color = random_color(rgb=True, maximum=1)
        if linewidth is None:
            linewidth = self._default_font_size / 3
        linewidth = max(linewidth, 1)
        self.output.ax.quiver(
            x_pos,
            y_pos,
            x_direct,
            y_direct,
            color=color,
            scale_units="xy",
            scale=1,
            antialiased=True,
            headaxislength=3.5,
            linewidths=0.1,  # , width=0.01
        )
        return self.output

    def draw_lati(
        self, latimap, alpha_contourf=0.4, alpha_contour=0.9, contour_only=False
    ):
        """Blend latitude map
        """
        height, width = latimap.shape
        y, x = np.mgrid[0:height, 0:width]
        cmap = plt.get_cmap("seismic_r")
        bands = 20
        levels = np.linspace(-np.pi / 2, np.pi / 2, bands - 1)
        if not contour_only:
            pp = self.output.ax.contourf(
                x,
                y,
                latimap,
                levels=levels,
                cmap=cmap,
                alpha=alpha_contourf,
                antialiased=True,
            )
            pp2 = self.output.ax.contour(
                x,
                y,
                latimap,
                pp.levels,
                cmap=cmap,
                alpha=alpha_contour,
                antialiased=True,
                linewidths=5,
            )
            for c in pp2.collections:
                c.set_linestyle("solid")
        else:
            # only plot central contour
            pp = self.output.ax.contour(
                x,
                y,
                latimap,
                levels=[0],
                cmap=cmap,
                alpha=alpha_contour,
                antialiased=True,
                linewidths=15,
            )
        return self.output


from flask import Flask, render_template, request
from werkzeug.utils import redirect
from database import Database

app = Flask(__name__)
app.config.from_pyfile('server.cfg')

"""
Use the following commands to interact with the database:
  db.get() to get all of the reviews
  db.get(id) to get a single review
  db.create(title, text, rating) to add a new review
  db.update(id, title, text, rating) to update a review
  db.delete(id) to delete a review
"""
db = Database(app)

# Homepage
@app.route('/')
def show_all_reviews():
    reviews = db.get()
    return render_template("home.html", reviews = reviews)

# Display the create review page
@app.route("/createreview")
def create_review():
    return render_template("review.html", review = None)

# Display the edit review page
@app.route("/editreview/<review_id>", methods=['GET', 'POST'])
def edit_review(review_id):
    review = db.get(review_id)
    return render_template("review.html", review = review)

# Create either a brand new review, or submit changes to a previous review
@app.route("/submitreview", methods=['GET', 'POST'])
def submit_review():
    if (request.form.get("review_id")):
        review_id = request.form.get("review_id")
        title = request.form.get("title")
        review_text = request.form.get("review_text")
        rating = request.form.get("rating")
        db.update(review_id, title, review_text, rating)
    else:
        title = request.form.get("title")
        review_text = request.form.get("review_text")
        rating = request.form.get("rating")
        db.create(title, review_text, rating)
    return redirect("/createreview")

# Deletes a given review and redirects to homepage
@app.route("/deletereview/<review_id>")
def delete_review(review_id):
    db.delete(review_id)
    return redirect("/")

# Displays a given review
@app.route("/displayreview/<review_id>")
def display_review(review_id):
    review = db.get(review_id)
    return render_template("display_review.html", review = review)

if __name__ == '__main__':
    app.run(debug=True)


"""
This example shows that you can add attributes at run
time to an object which is created using the "attrs"
framework. The attribute will not be printed when printing
the instances. The attribute is accessible from outside
and from within the object and is seen in dir(object).
"""

from attr import attrs, attrib

@attrs
class MyObject:
    def __init__(self):
        self.another = None
    a = attrib(default=None)  # type: int
    b = attrib(default=None)  # type: int

    def add_attribute(self, val):
        # noinspection PyAttributeOutsideInit
        self.another = val

    def print(self):
        print(self.another)

m = MyObject()
m.a = 6
m.b = 7
m.add_attribute(11)

m.print()
print(m.another)
print(m)
print(dir(m))


from views import CreateMixin, ListingMixin, RetrieveMixin, UpdateMixin, DestroyMixin
# from registration import User
import json

# class Cars(CreateMixin, ListingMixin, RetrieveMixin, UpdateMixin, DestroyMixin, User):

#     def save(self):
#         with open('data1.json', 'w') as file:
#             json.dump(self.objects, file)
#         return {'msg': 'saved'}

#     def __init__(self, brand, model, year, engine, color, body, mileage, price):
#         self.brand = brand
#         self.model = model
#         self.year = year
#         self.engine = engine
#         self.color = color
#         self.body = body
#         self.mileage = mileage
#         self.price = price

# log = User()
# print(log.register('JohnSnowNothing4567', 'qwerty1234', 'qwerty1234'))
# print(log.login('JohnSnowNothing4567', 'qwerty1234'))

class Cars(CreateMixin, ListingMixin, RetrieveMixin, UpdateMixin, DestroyMixin):
    def save(self):
        with open('data1.json', 'w') as file:
            json.dump(self.objects, file)
        return {'msg': 'saved'}

class Order:
    discount = 5
    def __init__(self) -> None:
        self.orders = []
        self.product = Cars()
        self.product.post(title = 'Iphone 14 Pro Max', description = 'The best new phone!', qty = 5, price = 1300)
        self.product.post(title = 'Samsung S22 Ultra', description = 'The best new phone by Samsung', qty = 10, price = 900)

    def create_order(self, objects):
        ls = []
        for item in objects:
            for product in self.product.objects:
                if item['id'] == product['id']:
                    self.subtract_qty(item, product)
                    ls.append({'title': product['title'], 'qty': item['qty'], 'price': product['price']})
        self.orders.append(ls)
        money = self.total_count(ls)
        return {'Order': ls, 'Total sum': money}

    def total_count(self, objects):
        total_count = 0
        for product in objects:
            price = product['price']
            qty = product['qty']
            total_count += self.make_discount(price, self.discount) * qty
        return total_count

    def subtract_qty(self, item, product):
        result = product['qty'] - item['qty']
        if result < 0:
            raise Exception('Too many qty or product!')
        product['qty'] = result

    def make_discount(self, price, percent):
        return price - (price / 100 * percent)

orders = Order()
print('Before: ', orders.product.objects)
products = [{'id': 1, 'qty': 3}, {'id': 2, 'qty': 2}]
print(orders.create_order(products))
print('After: ', orders.product.objects)

# cars = Cars()
# print(cars.post(title = 'Iphone 14 Pro Max', description = 'The best new phone!', qty = 5, price = 1300))
# print(cars.post(title = 'Redmi Note 10', description = 'The best phone for own price!', qty = 10, price = 300))
# print(cars.get())
# print(cars.patch(2, title = 'Redmi Note 100'))
# print(cars.get_detail(2))
# print(cars.delete(2))
# print(cars.get())
# print(cars.post(title = 'Samsung S22 Ultra', description = 'The best new phone by Samsung', qty = 10, price = 900))
# print(cars.save())


import turtle

PenWrite = 6

first_width=300
first_vertical=-300

direction = 0

while(PenWrite>0):
    turtle.penup()
    turtle.goto(-300,first_width)
    turtle.pendown()

    turtle.forward(500)

    first_width-=100
    PenWrite-=1

turtle.left(270)
PenWrite = 6

while(PenWrite>0):
    turtle.penup()
    turtle.goto(first_vertical,300)
    turtle.pendown()

    turtle.forward(500)

    first_vertical+=100

    PenWrite-=1

turtle.exitonclick()


import math

def quat_to_euler(q) :
  roll_a = 2.0 * (q[0]*q[1] + q[2]*q[3]);
  roll_b = 1.0 - 2.0 * (q[1]*q[1] + q[2]*q[2]);
  roll = math.atan2 (roll_a, roll_b);

  pitch_sin = 2.0 * (q[0]*q[2] - q[3]*q[1]);
  pitch = math.asin (pitch_sin);

  yaw_a = 2.0 * (q[0]*q[3] + q[1]*q[2]);
  yaw_b = 1.0 - 2.0 * (q[2]*q[2] + q[3]*q[3]);
  yaw = math.atan2 (yaw_a, yaw_b);
  return [roll,pitch,yaw]

# was (roll, pitch, yaw)
def euler_to_quat(rpy):
  roll =  rpy[0]
  pitch = rpy[1]
  yaw =   rpy[2]

  sy = math.sin(yaw*0.5);
  cy = math.cos(yaw*0.5);
  sp = math.sin(pitch*0.5);
  cp = math.cos(pitch*0.5);
  sr = math.sin(roll*0.5);
  cr = math.cos(roll*0.5);
  w = cr*cp*cy + sr*sp*sy;
  x = sr*cp*cy - cr*sp*sy;
  y = cr*sp*cy + sr*cp*sy;
  z = cr*cp*sy - sr*sp*cy;
  return np.array([w,x,y,z])


#Name: Ashok Surujdeo
#Email: Ashok.Surujdeo65@myhunter.cuny.edu
#Date: February 9, 2021
#This program prints: Backwards Acronym

phrase = input("Your phrase in capital letters:")
print(phrase.upper())
newphrase = phrase.split()
newphrase.reverse()
acronym = ""
for i in newphrase:
    acronym = acronym + i[0].upper()

print("Acronym:", acronym)


import dlib
import logging
import numpy as np
from skimage.transform import rescale, estimate_transform, warp

FACE_DETECTOR_PATH = 'Data/net-data/mmod_human_face_detector.dat'
SHAPE_PREDICTOR_PATH = 'Data/net-data/shape_predictor_68_face_landmarks.dat'

class ImageProcessor(object):
    def __init__(self):
        super(ImageProcessor, self).__init__()
        self.face_detector = dlib.cnn_face_detection_model_v1(FACE_DETECTOR_PATH)
        self.shape_predictor = dlib.shape_predictor(SHAPE_PREDICTOR_PATH)

    def uncrop_pos(self, cropped_pos, cropping_tform):
        cropped_vertices = np.reshape(cropped_pos, [-1, 3]).T
        z = cropped_vertices[2, :].copy() / cropping_tform.params[0, 0]
        cropped_vertices[2, :] = 1
        vertices = np.dot(np.linalg.inv(cropping_tform.params), cropped_vertices)
        vertices = np.vstack((vertices[:2, :], z))
        pos = np.reshape(vertices.T, [256, 256, 3])
        return pos

    def clean_image(self, image):
        image = image[:,:,:3]
        if image.shape != (256, 256, 3):
            max_size = max(image.shape[0], image.shape[1])
            if max_size > 1000:
                image = rescale(image, 1000. / max_size)
                image = (image * 255).astype(np.uint8)
            image = np.around(image, decimals=1).astype(np.uint8)
        return image

    def get_cropping_transform(self, image):
        detected_faces = self.face_detector(image, 1)
        if len(detected_faces) == 0:
            logging.info('no detected face')
            return None
        logging.info('face detected')

        d = detected_faces[0].rect  ## only use the first detected face (assume that each input image only contains one face)
        left = d.left()
        right = d.right()
        top = d.top()
        bottom = d.bottom()
        old_size = (right - left + bottom - top) / 2
        center = np.array([right - (right - left) / 2.0, bottom - (bottom - top) / 2.0 + old_size * 0.14])
        size = int(old_size * 1.58)

        shape = self.shape_predictor(image, d)
        coords = np.zeros((68, 2), dtype=int)
        for i in range(0, 68):
            coords[i] = (shape.part(i).x, shape.part(i).y)

        src_pts = np.array([[center[0] - size / 2, center[1] - size / 2], [center[0] - size / 2, center[1] + size / 2],
                            [center[0] + size / 2, center[1] - size / 2]])
        DST_PTS = np.array([[0, 0], [0, 255], [255, 0]])
        tform = estimate_transform('similarity', src_pts, DST_PTS)
        return tform

    def crop_image(self, image, cropping_tform):
        float_img = image / 256.0 / 1.1
        if not cropping_tform:
            return float_img
        else:
            return warp(float_img, cropping_tform.inverse, output_shape=(256, 256))

    def get_cropped_image(self, image):
        image = self.clean_image(image)
        logging.info('cleaned images')
        crop_tform = self.get_cropping_transform(image)
        if crop_tform is None:
            return image, None
        cropped_image = self.crop_image(image, crop_tform)
        return cropped_image, crop_tform

    def concat_images(self, image1, image2):
        concat_images = np.concatenate((image1, image2), axis=2)
        return concat_images