# 출처 - https://github.com/ddd4117/GUI/blob/master/src/camera_test.py
# 수정 - webnautes
import os
import cv2
import sys
import time
import re

from PIL import ImageFont, Image, ImageDraw
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5.QtCore import QRect, QPoint

from nets import inception
from preprocessing import inception_preprocessing
from matplotlib import pyplot as plt
import numpy as np
import tensorflow as tf
import urllib.request  # 표준 라이브러리
import json
import glob

# 학습한 모델 설정
checkpoints_dir = 'D:\\train_inception_v1_SignLanguage2_FineTune_logs\\all4'

class ShowVideo(QtCore.QObject):
    num = 1
    flag = 0
    is_run = True
    camera = cv2.VideoCapture(0)
    print(camera)
    timer = 5
    text = ""
    is_trans = False
    trans_text = ""

    ret, image = camera.read()
    height, width = image.shape[:2]

    VideoSignal1 = QtCore.pyqtSignal(QtGui.QImage)
    VideoSignal2 = QtCore.pyqtSignal(QtWidgets.QTextEdit)

    def __init__(self, parent=None):
        super(ShowVideo, self).__init__(parent)

    @QtCore.pyqtSlot()
    def startVideo(self):
        global image
        global text
        global color_swapped_image
        global is_trans
        global trans_text

        is_trans = False
        text = ""

        while True:
            ret, image = self.camera.read()
            color_swapped_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            cv2.putText(color_swapped_image, text, (300, 240), cv2.FONT_HERSHEY_PLAIN, 5.0, (255, 0, 0), 5);
            if is_trans:
                font = ImageFont.truetype("gulim.ttc", 32)
                img_pil = Image.fromarray(color_swapped_image)
                draw = ImageDraw.Draw(img_pil)
                draw.text((50, 400), trans_text, font=font, fill=(255, 255, 255, 0))
                color_swapped_image = np.array(img_pil)
            qt_image1 = QtGui.QImage(color_swapped_image.data,
                                     self.width,
                                     self.height,
                                     color_swapped_image.strides[0],
                                     QtGui.QImage.Format_RGB888)
            self.VideoSignal1.emit(qt_image1)

            loop = QtCore.QEventLoop()
            QtCore.QTimer.singleShot(1, loop.quit)  # 25 ms
            loop.exec_()

    @QtCore.pyqtSlot()
    def save(self):
        global image
        global is_run
        global num
        global text
        global is_trans

        is_trans = False
        is_run = True
        num = 1
        timer = 5

        if not os.path.isdir("image"):
            os.mkdir("image")

        while is_run:
            text = str(timer)
            timer = timer - 1

            if timer == 0:
                for i in range(1, 4):
                    path = "image/" + str(num) + ".jpg"
                    cv2.imwrite(path, image)
                    num = num + 1
                    time.sleep(0.1)
                timer = 5
            loop = QtCore.QEventLoop()
            QtCore.QTimer.singleShot(1000, loop.quit)  # 25 ms
            loop.exec_()

    @QtCore.pyqtSlot()
    def stop(self):
        global is_run
        global num
        global text

        text = ""
        is_run = False
        self.Con_Image()
        self.Api_trans()

    @QtCore.pyqtSlot()
    def Api_trans(self):
        global num
        global color_swapped_image
        global is_trans
        global trans_text

        is_trans = False
        j = 1
        inf_array = []
        com_array = []
        res_array = []
        client_id = "vIj2xvkAVXo8ArNz48NH"  # 개발자센터에서 발급받은 Client ID 값
        client_secret = "xZAQ6OTeHy"  # 개발자센터에서 발급받은 Client Secret 값
        # 요청할 주소
        url = "https://openapi.naver.com/v1/papago/n2mt"

        # 이미지 평가 코드
        slim = tf.contrib.slim

        image_size = inception.inception_v1.default_image_size

        for i in range(1, num):
            with tf.Graph().as_default():
                image_input = tf.read_file('./images/' + str(i) + '.jpg')
                image = tf.image.decode_jpeg(image_input, channels=3)
                processed_image = inception_preprocessing.preprocess_image(image,
                                                                           image_size,
                                                                           image_size,
                                                                           is_training=False)
                processed_images = tf.expand_dims(processed_image, 0)

                with slim.arg_scope(inception.inception_v1_arg_scope()):
                    logits, _ = inception.inception_v1(processed_images, num_classes=10, is_training=False)
                probabilities = tf.nn.softmax(logits)

                init_fn = slim.assign_from_checkpoint_fn(
                    os.path.join(checkpoints_dir, 'model.ckpt-5000'),

                    slim.get_model_variables('InceptionV1'))

                with tf.Session() as sess:
                    init_fn(sess)
                    np_image, probabilities = sess.run([image, probabilities])
                    probabilities = probabilities[0, 0:]
                    sorted_inds = [i[0] for i in sorted(enumerate(-probabilities), key=lambda x: x[1])]

                names = os.listdir("C:\\SignLanguage2\\SignLanguage2_photos")

                index = sorted_inds[0]
                print(str(j) + '번째 결과 : [%s] => %0.2f%%  ' % (names[index], probabilities[index]))
                if probabilities[index] >= 0.50:
                    inf_array.append(names[index])
                    print(inf_array)
                if (i % 3) == 0:
                    if len(inf_array) < 2:
                        print("동작이 인식되지 않았습니다. 재촬영을 해주세요.")
                    elif len(inf_array) == 2:
                        if inf_array.count(inf_array[0]) == 2:
                            com_array.append(inf_array[0])
                    elif len(inf_array) == 3:
                        if inf_array.count(inf_array[0]) >= 2:
                            com_array.append(inf_array[0])
                        elif inf_array.count(inf_array[1]) >= 2:
                            com_array.append(inf_array[1])
                    else:
                        print("오류!")
                        return
                    j = j + 1
                    inf_array.clear()

        for i in com_array:
            a = i.replace(".", "")
            p = re.compile("[^0-9]")
            print("".join(p.findall(a)))
            res_array.append("".join(p.findall(a)))

        print(res_array)
        if not res_array:
            print("인식된 동작이 없습니다.")
            self.reset()
        else:
            # 번역할 언어와 내용
            # text = input("번역할 내용을 입력하세요: ")
            text = " ".join(res_array)
            encText = urllib.parse.quote(text)
            srcLang = 'en'
            tarLang = 'ko'
            rq_data = "honorific=true&" + "source={}&target={}&text=".format(srcLang, tarLang) + encText  # 높임말인데 안될수도잉씀 나도 몰름
            # 웹 요청
            request = urllib.request.Request(url)
            request.add_header("X-Naver-Client-Id", client_id)
            request.add_header("X-Naver-Client-Secret", client_secret)

            # 결과 받아오는 부분
            response = urllib.request.urlopen(request, data=rq_data.encode("utf-8"))

            # 응답 성공적일 때
            rescode = response.getcode()
            if (rescode == 200):  # 성공
                response_body = response.read()
                rs_data = response_body.decode('utf-8')
                rs_data = json.loads(rs_data)  # 딕셔너리화
                trans_text = rs_data['message']['result']['translatedText']
                print("번역된 내용: ", trans_text)
                self.reset()
                is_trans = 1
                return trans_text
            else:  # 실패
                print("Error Code:" + rescode)

    @QtCore.pyqtSlot()
    def reset(self):
        global num
        for i in range(1, num):
            path1 = "image/" + str(i) + ".jpg"
            path2 = "images/" + str(i) + ".jpg"

    def Con_Image(self):
        img_Path = './image/'
        img_Ext = '*.jpg'
        save_Path = "./images/"
        images = []
        i = 1

        for a in glob.glob(os.path.join(img_Path, img_Ext)):
            images.append(a)
        cnt = len(images)

        if not os.path.isdir("images"):
            os.mkdir("images")

        if cnt == 0:
            print("폴더 내의 파일이 없습니다.")

        else:
            for image in images:
                path = "./images/" + str(i) + ".jpg"
                img = cv2.imread(image, 0)
                ret, thr = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
                cv2.imwrite(save_Path + str(i) + ".jpg", thr)
                i = i + 1

class ImageViewer(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ImageViewer, self).__init__(parent)
        self.image = QtGui.QImage()
        self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawImage(0, 0, self.image)
        self.image = QtGui.QImage()

    def initUI(self):
        self.setWindowTitle('Test')

    @QtCore.pyqtSlot(QtGui.QImage)
    def setImage(self, image):
        if image.isNull():
            print("Viewer Dropped frame!")

        self.image = image
        if image.size() != self.size():
            self.setFixedSize(image.size())
        self.update()

class TextSetter(QtWidgets.QTextEdit):
    def __init__(self, parent=None):
        super(TextSetter, self).__init__(parent)
        self.text = QtWidgets.QTextEdit()

    @QtCore.pyqtSlot(QtWidgets.QTextEdit)
    def setText(self, str):
        painter = QtGui.QPainter(self)
        painter.drawText(QPoint(0, 0), str)
        self.text.setText(str)
        self.update()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    thread = QtCore.QThread()
    thread.start()
    vid = ShowVideo()
    vid.moveToThread(thread)

    image_viewer1 = ImageViewer()

    vid.VideoSignal1.connect(image_viewer1.setImage)

    push_button1 = QtWidgets.QPushButton('Start')
    push_button2 = QtWidgets.QPushButton('Stop')

    push_button1.clicked.connect(vid.save)
    push_button2.clicked.connect(vid.stop)

    vertical_layout = QtWidgets.QVBoxLayout()
    horizontal_layout = QtWidgets.QHBoxLayout()
    vertical_layout2 = QtWidgets.QVBoxLayout()
    horizontal_layout.addWidget(image_viewer1)
    vertical_layout.addLayout(horizontal_layout)
    horizontal_layout.addLayout(vertical_layout2)
    vertical_layout2.addWidget(push_button1)
    vertical_layout2.addWidget(push_button2)

    layout_widget = QtWidgets.QWidget()
    layout_widget.setLayout(vertical_layout)
    main_window = QtWidgets.QMainWindow()
    main_window.setCentralWidget(layout_widget)
    main_window.show()
    vid.startVideo()
    sys.exit(app.exec_())


import argparse
import psutil
import time
import os

from app.monitor import Monitor
from app.monitor import CpuMonitor
from app.monitor import MemoryMonitor

def add_cli_args():
    parser = argparse.ArgumentParser(description=None)
    parser.add_argument('-p', '--pid', type=int, required=True,
                        help="Process id of the process")
    parser.add_argument('-f', '--frequency', type=int,
                        help="Measure frequency", default=10)
    parser.add_argument('-l', '--length', type=int,
                        help="When the length of the array reach this number "\
                                "create a log and empty the array", default=6)

    return parser

def get_cli_args():
    parser = add_cli_args()
    args = parser.parse_args()
    return args.pid, args.frequency, args.length

def start_monitor():
    cpu_monitor.start()
    memory_monitor.start()

if __name__ == '__main__':
    try:
        pid, frequency, length = get_cli_args()

        Monitor.process_id = pid
        Monitor.frequency = frequency
        Monitor.length = length

        cpu_monitor = Monitor.factory('CpuMonitor')
        memory_monitor = Monitor.factory('MemoryMonitor')

        cpu_monitor.print_process_name()

        start_monitor()

        while True:
            time.sleep(.001)
    except psutil.NoSuchProcess:
        print("There is no process with {} pid".format(pid))
    except KeyboardInterrupt:
        os._exit(0)
        print('KeyboardInterrupt')
    except Exception as e:
        print (e.message)


import argparse
import random
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from data.sampler import SubsetSequentialSampler
# Custom
import models.isresnet
import models.vgg16
from utils.config import get_configs
from utils.dataset import get_dataset, get_transform, get_training_functions_isdal
from utils.train_IDA import *
from utils.test_IDA import *
from utils.util import *
from torch.backends import cudnn
import os
import torch
import torch.nn as nn
import numpy as np
import time
from torch.utils.data import DataLoader
from ISAL import ISDALoss
# from torch.nn import functional
os.environ['CUDA_VISIBLE_DEVICES'] = "2"

parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',
                    help='number of data loading workers (default: 4)')
parser.add_argument('--epochs', default=160, type=int, metavar='N',
                    help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
                    help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
                    metavar='N',
                    help='mini-batch size (default: 256), this is the total '
                         'batch size of all GPUs on the current node when '
                         'using Data Parallel or Distributed Data Parallel')
parser.add_argument('--lr', '--learning-rate', default=0.1, type=float,
                    metavar='LR', help='initial learning rate', dest='lr')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
                    help='momentum')
parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float,
                    metavar='W', help='weight decay (default: 1e-4)',
                    dest='weight_decay')
parser.add_argument('-p', '--print-freq', default=10, type=int,
                    metavar='N', help='print frequency (default: 10)')

parser.add_argument('--seed', default=None, type=int,
                    help='seed for initializing training. ')

parser.add_argument('--lambda_0', default=1.0, type=float,
                    help='The hyper-parameter \lambda_0 for ISDA, select from {1, 2.5, 5, 7.5, 10}. '
                         'We adopt 1 for DenseNets and 7.5 for ResNets and ResNeXts, except for using 5 for ResNet-101.')
parser.add_argument('--model', default='Vgg16', type=str,
                    help='Model to be trained.  ResNet18 Vgg16'
                         'Select from resnet{18, 34, 50, 101, 152} / resnext{50_32x4d, 101_32x8d} / '
                         'densenet{121, 169, 201, 265}')
parser.add_argument('--metric', default='ISDAL', type=str,
                    help='Maxp, ISDAL, Ran')

#Maxp, ISDAL, Ran

def get_ems(model, unlabeled_loader,criterion_isda,metric="Maxp"): # Maxp, ISDAL, Ran
    model.eval()
    ems = torch.tensor([]).cuda()
    with torch.no_grad():
        for (inputs, _) in unlabeled_loader:
            inputs = inputs.cuda()
            if metric == "Maxp":
                output1= model(inputs)
                pro = F.softmax(output1,dim=1)
                ems_cur = torch.max(pro, 1).values
            if metric == "Ran":
                ems_cur =  torch.rand(len(inputs), out=None).cuda()
            if metric == "ISDAL":
                target_x = torch.tensor(len(inputs)).cuda()
                ems_cur = criterion_isda(model, inputs, target_x, 1,Val_Flag = True)
                #ems_cur = output1.max()
            ems = torch.cat((ems, ems_cur), 0)
    return ems.cpu()

# Main
if __name__ == '__main__':
    args = parser.parse_args()
    # hyper params
    port = 9999
    dataset = 'cifar10'
    method = args.metric
    num_classes = 10
    cfg = get_configs(port=port)

    # path and logger
    time_str = time.strftime('%m%d%H%M%S', time.localtime())
    dataset_root = cfg.DATASET.ROOT[dataset]
    checkpoint_dir = os.path.join('output', time_str)

    if not os.path.exists(checkpoint_dir):
        os.makedirs(checkpoint_dir)
    log_save_file = checkpoint_dir + "/log.txt"
    my_logger = Logger(method, log_save_file).get_log
    my_logger.info("Checkpoint Path: {}".format(checkpoint_dir))
    my_logger.info("Dataset : {}".format(dataset))
    my_logger.info("Model : {}".format(args.model))
    my_logger.info("ISDA lambda_0 : {}".format(args.lambda_0))
    print_config(cfg, my_logger)

    # define dataset and dataloaders
    train_transform, test_transform = get_transform(dataset)
    train_dataset, test_dataset, unlabeled_dataset = get_dataset(
        dataset_root, dataset, train_transform, test_transform
    )
    test_loader = DataLoader(test_dataset, batch_size=cfg.TRAIN.BATCH)

    Performance = np.zeros((3, 10))
    for trial in range(cfg.ACTIVE_LEARNING.TRIALS):
        # Initialize a labeled dataset by randomly sampling K=ADDENDUM=1,000 data points
        # from the entire dataset.
        indices = list(range(cfg.DATASET.NUM_TRAIN))
        random.shuffle(indices)
        labeled_set = indices[:cfg.ACTIVE_LEARNING.ADDENDUM]
        unlabeled_set = indices[cfg.ACTIVE_LEARNING.ADDENDUM:]

        random.shuffle(unlabeled_set)

        train_loader = DataLoader(train_dataset, batch_size=cfg.TRAIN.BATCH,
                                  sampler=SubsetRandomSampler(labeled_set),
                                  pin_memory=True)
        dataloaders = {'train': train_loader, 'test': test_loader}

        # Model
        if 'Res' in args.model:
            model = eval('models.isresnet.' + args.model)(num_classes=num_classes)

        if 'Vgg' in args.model:
            model = eval('models.vgg16.' + args.model)(num_classes=num_classes)

        #resnet18 = resnet.resnet18(num_classes=num_classes).cuda()
        feature_num = model.feature_num

        torch.backends.cudnn.benchmark = True
        num_images = 50000
        initial_budget = 1000
        all_indices = set(np.arange(num_images))
        initial_indices = random.sample(all_indices, initial_budget)
        sampler = torch.utils.data.sampler.SubsetRandomSampler(initial_indices)
        model = model.cuda()
        criterion_isda = ISDALoss(feature_num, num_classes).cuda()
        criterion_ce = nn.CrossEntropyLoss().cuda()

        # Active learning cycles

        acc =0
        for cycle in range(cfg.ACTIVE_LEARNING.CYCLES):
            # Randomly sample 10000 unlabeled data points
            random.shuffle(unlabeled_set)
            subset = unlabeled_set[:cfg.ACTIVE_LEARNING.SUBSET]

            # Create unlabeled dataloader for the unlabeled subset
            unlabeled_loader = DataLoader(unlabeled_dataset, batch_size=cfg.TRAIN.BATCH,
                                          sampler=SubsetSequentialSampler(subset),
                                          pin_memory=True)

            optimizers, schedulers = get_training_functions_isdal(
                cfg, model
            )

            # Training and test
            if 1:
                cur_acc = train(
                    cfg, my_logger, model, criterion_isda, optimizers,
                    schedulers, dataloaders, unlabeled_loader,
                    cfg.TRAIN.EPOCH,args, cycle
                    # querry_dataloader, task_model, optim_task_model, val_loader
                )
            torch.save(
                        {
                            'cycle': cycle,
                            'state_dict_backbone': model.state_dict()
                        },
                        '{}/isdal active_resnet18_cifar10_cycle_9epoch_200.pth'.format(checkpoint_dir)
                    )
            my_logger.info("Start Test")
            acc = cur_acc #max(acc, cur_acc)
            print("acc:", acc)
            my_logger.info("End Test")
            # print(acc1, acc2, acc)
            my_logger.info('Trial {}/{} || Cycle {}/{} || Label set size {}: lambda_0: {} Selecting metric: {} Test acc {}'.format(
                trial + 1, cfg.ACTIVE_LEARNING.TRIALS, cycle + 1,
                cfg.ACTIVE_LEARNING.CYCLES, len(labeled_set),args.lambda_0,args.metric, acc)
            )
            #print("Unlabeled dataset length:",len(unlabeled_set))
            Performance[trial, cycle] = acc

            # update dataloaders
            # Measure emc of each data points in the subset
            print("Selecting data")
            EMC_Array = get_ems(model, unlabeled_loader,criterion_isda,metric=args.metric) #Maxp, ISDAL, Ran

            # Index in ascending order
            arg = np.argsort(EMC_Array)
            #print(arg)
            # Update the labeled dataset and the unlabeled dataset, respectively
            budget = cfg.ACTIVE_LEARNING.ADDENDUM
            labeled_set += list(torch.tensor(subset)[arg][-budget:].numpy())
            unlabeled_set =\
                list(torch.tensor(subset)[arg][:-budget].numpy()) + unlabeled_set[cfg.ACTIVE_LEARNING.SUBSET:]

            # Create a new dataloader for the updated labeled dataset
            dataloaders['train'] = DataLoader(train_dataset, batch_size=cfg.TRAIN.BATCH,
                                              sampler=SubsetRandomSampler(labeled_set),
                                              pin_memory=True)
            sampler = torch.utils.data.sampler.SubsetRandomSampler(labeled_set)

            # save a ckpt
            torch.save(
                        {
                            'cycle': cycle,
                            'state_dict_backbone': model.state_dict()
                        },
                        '{}/active_resnet18_cifar10_cycle{}_epoch_199.pth'.format(checkpoint_dir, cycle)
                    )

        # np.save(checkpoint_dir + '/l_set.npy', np.array(labeled_set))

    my_logger.info("Performance summary: ")
    my_logger.info("Trail 1: {}".format(Performance[0]))
    my_logger.info("Trail 2: {}".format(Performance[1]))
    my_logger.info("Trail 3: {}".format(Performance[2]))


#! /usr/bin/env python
# Public domain; MZMcBride; 2013

import sqlite3
import wikitools

import settings

report_title = settings.rootpage + 'G'
report_template = u'''\
Cases containing a deprecated template parameter.

== [[Template:Infobox SCOTUS case|Infobox SCOTUS case]]'s "CitationNew" ==
{| class="wikitable plainlinks" style="width:100%%; margin:auto;"
|- style="white-space:nowrap;"
! No.
! Page
%s
|}
'''

conn = sqlite3.connect(settings.dbname)
cursor = conn.cursor()

cursor.execute('''
/* scotus-cites.py */
SELECT
  page_title,
  page_text
FROM page;
''')

results = cursor.fetchall()

cursor.close()
conn.close()

i = 1
output = []
anomalies = []
for row in results:
    page_title = row[0]
    page_text = row[1]
    if page_text.find('CitationNew') != -1:
        table_row = u"""\
|-
| %d
| ''[[%s]]''""" % (i, page_title)
        output.append(table_row)
        i += 1

wiki = wikitools.Wiki(settings.apiurl)
wiki.login(settings.username, settings.password)
report = wikitools.Page(wiki, report_title)
report_text = report_template % ('\n'.join(output))
report.edit(report_text, summary=settings.editsumm, bot=1, skipmd5=True)


from animal import Animal
from ..ai.state import State
from location import Location

from math import pi
import random

import nodebox.graphics as ng

class Dog(Animal):
    def __init__(self, world):
        Animal.__init__(self, world)
        self.speed = 4.0
        self.angle = 0.0

    def reset(self):
        self.loc = self.randomLocation()

    def randomLocation(self):
        # x, y = random.choice((self.world.border, self.world.width-self.world.border)), random.choice((self.world.border, self.world.height-self.world.border))
        x, y = random.randint(self.world.border, self.world.width-self.world.border), random.randint(self.world.border, self.world.height-self.world.border)
        return Location(x, y)

    # Get move from AI
    def getMove(self):
        state = self.getState()
        self.action = self.world.ai.getAction(state)
        # target centric
        if self.action == 'towards':
            self.angle = state.target_a
        elif self.action == 'away-l':
            self.angle = state.target_a + pi
        elif self.action == 'left':
            self.angle = state.target_a + 0.40 * pi
        elif self.action == 'right':
            self.angle = state.target_a - 0.40 * pi

        # save for evaluate()
        self.old_state = state

    def getState(self):
        return State(self, self.world.ai)

    # Evaluate
    def evaluate(self):
        self.new_state = self.getState()
        self.world.ai.evaluate(self.old_state, self.action, self.new_state)

    # An update is moving at certain speed in certain direction
    def update(self):
        self.loc = self.loc.move(self.world.speed * self.speed, self.angle)
        self.saveHistory()


import sys
import os

sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True

__author__ = "bigfatnoob"

import astor

from analysis.helpers import constants as a_consts
from analysis.blocks import statements as statement_block
from utils.lib import O

import properties

class Method(O):
  def __init__(self, **kwargs):
    self.file_source = None
    self.name = None
    self.return_type = None
    self.start_pos = None
    self.end_pos = None
    self.args = None
    self.statement_blocks = []  # [<Statements>]
    self._statement_groups = None  # [[<Statements>], [<Statements>]]
    self._ast = None
    self._scope = None
    self._prerequisite_statements = []
    O.__init__(self, **kwargs)

  def get_ast(self):
    return self._ast

  def get_scope(self):
    return self._scope

  def is_root(self):
    return self.name == a_consts.ROOT_SCOPE

  def split_statement_blocks(self):
    split = None
    for i, statement in enumerate(self.statement_blocks):
      if isinstance(statement, Method):
        split = i
    if split is None:
      return self.statement_blocks
    else:
      self._prerequisite_statements, statements = self.statement_blocks[:split+1], self.statement_blocks[split+1:]
    return statements

  def get_statement_groups(self):
    if self._statement_groups is not None:
      return self._statement_groups
    # self._statement_groups = Method.create_statement_groups(self.statement_blocks)
    # return self._statement_groups
    _statement_groups = []
    method_statement_blocks = self.split_statement_blocks()
    groups = Method.create_statement_groups(method_statement_blocks)
    for group in groups:
      combinations = Method.get_combinations(group)
      if combinations and len(combinations) > 0:
        _statement_groups += combinations
    for statement in method_statement_blocks:
      if isinstance(statement, statement_block.GroupedStatement) or \
         isinstance(statement, statement_block.ChoiceGroupedStatement):
        _statement_groups.append([statement])
    self._statement_groups = []
    if len(self._prerequisite_statements) >= properties.MIN_STATEMENT_SIZE:
      self._statement_groups.append(self._prerequisite_statements)
    for _statement_group in _statement_groups:
      _statement_group = self._prerequisite_statements + _statement_group
      if len(_statement_group) >= properties.MIN_STATEMENT_SIZE:
        self._statement_groups.append(_statement_group)
    return self._statement_groups

  def get_text(self):
    return astor.to_source(self._ast).strip("\n")

  def pprint(self):
    print(self.get_text())

  @staticmethod
  def print_statement_group(groups):
    for combination in groups:
      print("\n*** Combination ***")
      for statement in combination:
        statement.pprint()
      print("********************")

  @staticmethod
  def create_statement_groups(statement_blocks):
    if not statement_blocks: return []
    ret_list = []
    statement_group = []
    for statement in statement_blocks:
      statement_group.append(statement)
      if isinstance(statement, statement_block.GroupedStatement):
        sub_ret_list = Method.create_statement_groups(statement.statements)
        if sub_ret_list:
          ret_list += sub_ret_list
      elif isinstance(statement, statement_block.ChoiceGroupedStatement):
        for choice in statement.choices:
          sub_ret_list = Method.create_statement_groups(choice)
          if sub_ret_list:
            ret_list += sub_ret_list
    # min_size = properties.MIN_STATEMENT_SIZE
    min_size = 1
    if len(statement_group) >= min_size:
      ret_list.append(statement_group)
    return ret_list

  @staticmethod
  def get_combinations(statement_blocks):
    step_start = properties.MIN_STATEMENT_SIZE
    # step_start = 1
    combinations = []
    for step_size in xrange(step_start, len(statement_blocks)):
      for counter in xrange(0, len(statement_blocks) - step_size + 1):
        combinations.append(statement_blocks[counter: counter + step_size])
    combinations.append(statement_blocks)
    return combinations


import math

import numpy as np

# Calculates Rotation Matrix given euler angles.
def euler_angle_to_rotation_matrix(theta):
    """
    Converts from theta [yaw, pitch, roll] to a rotation matrix
    """

    R_x = np.array(
        [
            [1, 0, 0],
            [0, math.cos(theta[0]), -math.sin(theta[0])],
            [0, math.sin(theta[0]), math.cos(theta[0])],
        ]
    )

    R_y = np.array(
        [
            [math.cos(theta[1]), 0, math.sin(theta[1])],
            [0, 1, 0],
            [-math.sin(theta[1]), 0, math.cos(theta[1])],
        ]
    )

    R_z = np.array(
        [
            [math.cos(theta[2]), -math.sin(theta[2]), 0],
            [math.sin(theta[2]), math.cos(theta[2]), 0],
            [0, 0, 1],
        ]
    )

    R = np.dot(R_z, np.dot(R_y, R_x))

    return R

def rotation_matrix_to_euler_angle(R):
    """
    Converts a rotation matrix to [yaw, pitch, roll]
    """
    yaw = math.atan2(R[1, 0], R[0, 0])
    pitch = math.atan2(-R[2, 0], math.sqrt(R[2, 1] ** 2 + R[2, 2] ** 2))
    roll = math.atan2(R[2, 1], R[2, 2])

    return yaw, pitch, roll

def static_transform_to_extrinsic(transform):
    """
    Calculates the extrinsic matrix for a ROS static_transform_publisher

    Parameters:
    - transform: a list with [x, y, z yaw, pitch, roll]
    """
    assert len(transform) == 6

    x, y, z, yaw, pitch, roll = transform
    rotation = euler_angle_to_rotation_matrix([yaw, pitch, roll])
    translation = np.array([x, y, z]).reshape(-1, 1)
    homogeneous = get_homogeneous_transformation(rotation, translation)
    return homogeneous

def extrinsic_to_static_transform(mat):
    """Converts an extrinsic matrix into rotational and translational components.

    Args:
        mat (np.array): a 4x4 extrinsic matrix

    Returns:
        np.array: a 1x6 np.array of form x, y, z, yaw, pitch, roll
    """
    x, y, z = mat[:3, 3]
    yaw, pitch, roll = rotation_matrix_to_euler_angle(mat)

    return np.array([x, y, z, yaw, pitch, roll])

def get_homogeneous_transformation(rotation, translation):
    """
    Parameters:
    - rotation: a 3x3 rotation np array
    - translation: a 3x1 translation np array
    """
    homogeneous = np.zeros((4, 4))
    homogeneous[-1][-1] = 1
    homogeneous[:3, :3] = rotation
    homogeneous[:3, -1:] = translation
    return homogeneous

def get_relative_transformation(a_to_base, b_to_base):
    """
    Finds the relative transformation from a to b given transformations for both
    relative to base_link.

    See: https://stackoverflow.com/a/55169091/6942666 for more details

    Parameters:
    - a_to_base: 4x4 np.array representing homoegenous transformation of a to base_link
    - b_to_base: 4x4 np.array representing homoegenous transformation of b to base_link
    """

    base_to_a = np.linalg.inv(a_to_base)
    return base_to_a @ b_to_base

if __name__ == "__main__":
    """
    <node pkg="tf" type="static_transform_publisher"
        respawn="true"
        name="camera_static_transform_publisher"
        args="0.5080 0.0 0.1778 0 0.05 0 base_link camera 100"
    />

    <node pkg="tf" type="static_transform_publisher"
        respawn="true"
        name="velodyne_static_transform_publisher"
        args="0.4445 0.0 0.09525 0.0 0.06981 0.0 base_link velodyne 100"
    />

    Camera static transform:
    [[ 0.99875026  0.          0.04997917  0.508     ]
    [ 0.          1.          0.          0.        ]
    [-0.04997917  0.          0.99875026  0.1778    ]
    [ 0.          0.          0.          1.        ]]

    Velodyne static transform:
    [[ 0.99756427  0.          0.06975331  0.4445    ]
    [ 0.          1.          0.          0.        ]
    [-0.06975331  0.          0.99756427  0.09525   ]
    [ 0.          0.          0.          1.        ]]

    Camera relative to Velodyne
    [[ 0.99980379  0.          0.0198087  -0.05929486]
    [ 0.          1.          0.          0.        ]
    [-0.0198087   0.          0.99980379 -0.08562051]
    [ 0.          0.          0.          1.        ]]

    Overall camera to velodyne transform
    Translation (x, y, z): -0.059294861111785835 0.0 -0.08562051124429254
    Rotation (y, p, r): 0.0 0.019810000000000008 0.0
    """

    print("Camera static transform: ")
    # Add values for the camera to base here
    camera_to_base = static_transform_to_extrinsic([0.5080, 0.0, 0.1778, 0, 0.05, 0])
    print(camera_to_base)

    print("Velodyne static transform: ")
    # Add values for the velodyne to base here
    velodyne_to_base = static_transform_to_extrinsic(
        [0.4445, 0.0, 0.09525, 0.0, 0.06981, 0.0]
    )
    print(velodyne_to_base)

    print("Camera relative to Velodyne")
    # Add values for the camera to velodyne here
    camera_to_velodyne = get_relative_transformation(camera_to_base, velodyne_to_base)
    print(camera_to_velodyne)

    print("Overall camera to velodyne transform")
    x, y, z, yaw, pitch, roll = extrinsic_to_static_transform(camera_to_velodyne)
    print("Translation (x, y, z):", x, y, z)
    print("Rotation (y, p, r):", yaw, pitch, roll)


import os, re, ROOT, sys, time
from ROOT import TFile,TTree,TH1,TROOT,TDirectory,TPad,TCanvas,TColor
from array import array

def process_sample(sample):
    # Run info
    chain_Runs = ROOT.TChain("Runs")
    chain_Runs.Add(sample)
    nEvents = 0
    for run in chain_Runs:
        print (run.genEventCount_)
        #nEvents += run.genEventCount
    print (nEvents)

#process_sample("/eos/cms/store/user/dmytro/QCD_Pt-15to20_MuEnrichedPt5_TuneCP5_13TeV_pythia8/crab_NanoAOD_QCD_Pt-15to20_MuEnrichedPt5_TuneCP5_13TeV_pythia8_Bmm5-01/191014_050926/0000/output_1.root")

process_sample("/eos/cms/store/group/phys_muon/dmytro/tmp/NanoAOD/505/QCD_Pt-30to50_MuEnrichedPt5_TuneCP5_13TeV_pythia8+RunIIAutumn18MiniAOD-102X_upgrade2018_realistic_v15-v3+MINIAODSIM/4237CE15-B026-5949-B143-C194A7B018FF.root")

#process_sample("/eos/cms/store/group/phys_muon/dmytro/tmp/NanoAOD/507/BsToMuMu_BMuonFilter_SoftQCDnonD_TuneCP5_13TeV-pythia8-evtgen+RunIIAutumn18MiniAOD-102X_upgrade2018_realistic_v15-v1+MINIAODSIM/02F7319D-D4D6-8340-B94F-2D882775B406.root")


import unittest
from classes.location import Louer, Salle

class TestLocation(unittest.TestCase):

    def test_str(self):
        s = Louer(250, 500,"Bahamas", "Auchan", "Durant")
        d = s.__str__()
        self.assertEquals(d, "Date de début de location : 250; Date de fin de location : 500; Salle louée : Bahamas; Organisme locataire : Auchan; Client : Durant")

class TestSalle(unittest.TestCase):

    def test_str(self):
        r = Salle (1, "Bahamas", "1300€")
        d = r.__str__()
        self.assertEquals(d, "Code Salle :1; Nom Salle :Bahamas; Prix de la Salle :1300€")


def isOK(index, key, a):
    if a[index] >= key:
        return True
    else:
        return False

def binary_search(key, a, N):
    ng = -1
    ok = N

    while abs(ok - ng) > 1:
        mid = (ok + ng) // 2
        if isOK(mid, key, a):
            ok = mid
        else:
            ng = mid

    return ok

N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
C = list(map(int,input().split()))

A.sort()
C.sort()

# C > B > Aの組み合わせを見つける
# C > B と　B > A の組み合わせの数をカウントしてその積をたす
ans = 0
for i in range(N):
    key = B[i]
    A_index = binary_search(key, A, N)
    C_index = binary_search(key + 1, C, N)
    # print('key: ',key)
    # print('A: ', A[A_index],'   ',A_index)
    # print('C: ', C[C_index],'   ',C_index)

    count_A = A_index
    count_C = N - C_index

    ans += count_A * abs(N-C_index)

print(ans)


import os
import json
from dataclasses import dataclass
from typing import Optional

import boto3
from botocore.exceptions import ClientError, NoCredentialsError

from api.business_logic.enums import Env
from api import ROOT

@dataclass
class Config:
    connection_string: str

class ConfigLoader:
    """
    Responsible for loading the configuration file. Configuration settings are
    accessed through the object returned from load_config method.
    """
    conf: Optional[Config] = None
    secret_name = "pg-db-2-secret"
    region_name = "us-east-1"

    @classmethod
    def load_config(cls) -> Config:
        if cls.conf is None:
            if Env(int(os.getenv("ENVM"))) == Env.PROD:
                cls.conf = cls._get_secret_conf()
            else:
                cls.conf = cls._get_local_conf()
        return cls.conf

    @classmethod
    def _get_secret_conf(cls) -> Config:
        client = boto3.client(
            service_name="secretsmanager",
            region_name=cls.region_name,
            )
        try:
            response = client.get_secret_value(SecretId=cls.secret_name)
            secret = json.loads(response["SecretString"])
            conn_str = f"postgres://{secret['username']}:{secret['password']}@{secret['host']}:{secret['port']}/egym"
            return Config(connection_string=conn_str)
        except ClientError as e:
            raise e
        except NoCredentialsError as e:
            raise Exception("Unable to fetch AWS credentials to load secret connection string.")

    @staticmethod
    def _get_local_conf() -> Config:
        with open(os.path.join(ROOT, "configuration", "conf.json")) as f:
            json_conf = json.load(f)
        return Config(**json_conf)


from typing import Any, Dict

from notifications.email.src.services.enricher import BaseEnricher
from notifications.email.src.services.mailer import BaseMailer
from notifications.email.src.services.templater import BaseTemplater

import orjson
from pika.adapters.blocking_connection import BlockingChannel
from pika.spec import Basic, BasicProperties
import logging

class EventNotImplementedError(Exception):
    pass

class Worker:
    def __init__(
            self,
            mailer: BaseMailer,
            templater: BaseTemplater,
            enrichers: Dict[str, BaseEnricher],
    ) -> None:
        self.mailer = mailer
        self.templater = templater
        self.enrichers = enrichers

    def handle(
        self,
        channel: BlockingChannel,
        method: Basic.Deliver,
        properties: BasicProperties,
        body: bytes,
    ) -> None:
        body_json = orjson.loads(body)
        event_type = body_json['event_type']
        user_id = body_json['user_id']

        try:
            template = self.templater.get_template(event_type)
        except Exception:
            logging.error('Mistake while getting temlate.')
            channel.basic_ack(method.delivery_tag)
            return

        try:
            user_data = self.enrichers['user'].get_data(user_id)
        except Exception:
            logging.error('Mistake while getting users data.')
            channel.basic_ack(method.delivery_tag)
            return

        try:
            context = self._get_context(event_type, body_json)
        except EventNotImplementedError:
            logging.error('Неизвестный тип события.')
            return

        email_content = self.templater.render_template(template, context)
        try:
            self.mailer.send_message(
                email=user_data.email,
                content=email_content,
                subject=template.subject
            )
        except Exception as e:
            logging.error('Mistake while sending letter.', exc_info=e)
            channel.basic_ack(method.delivery_tag)

    def _get_context(self, event_type, message: Dict[str, Any]):
        if event_type == 'notification_about_new_film':
            return self.enrichers['movie'].get_data(message['movie_id'])
        else:
            raise EventNotImplementedError


# pulper

import RPi.GPIO as GPIO
import time

class Motor(object):
    def __init__(self):
        print("Initializing Motor...")
        # ENA - GPIO 16 - Enable Offline Turning
        # DIR - GPIO 20
        # PUL = GPIO 26

        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)

        self.dir_pin = 20
        self.pul_pin = 26
        self.ena_pin = 16

        GPIO.setup(self.dir_pin, GPIO.OUT)
        GPIO.setup(self.pul_pin, GPIO.OUT)
        GPIO.setup(self.ena_pin, GPIO.OUT)

        GPIO.output(self.ena_pin, GPIO.LOW)

        self.running = False
        self.stop_command = False
        self.run_count = 0

        print("...Motor ready")

    def run_stepper(self, delay, clock_wise):
        # validate parameters
        if (delay < 0.1):
            print("Delay cannot be below 0.1 milli-seconds")
            return

        # delay from ms to s
        delay = delay / 1000

        print("Start running motor...")

        self.run_count += 1
        for i in range(5000):
            if self.stop_command == True:
                self.stop_command = False
                print("motor stopped")
                break

            self.running = True

            # GPIO.output(XEnable, 0)

            if clock_wise == True:
                GPIO.output(self.dir_pin, 1)
            else:
                GPIO.output(self.dir_pin, 0)

            GPIO.output(self.pul_pin, 1)
            time.sleep(delay)
            GPIO.output(self.pul_pin, 0)
            time.sleep(delay)

            # print("in run count: " + str(self.run_count))

        self.running = False
        print("Run complete")


from pathlib import Path
import pandas as pd

STORE = Path(__file__).parent.absolute() / "data"
STORE.mkdir(parents=True, exist_ok=True)

def beds(url="https://stopcorona.tn.gov.in/beds.php"):
    df = pd.read_html(url, attrs={"id": "dtBasicExample"})
    df = df[0]
    df.columns = [c[0] if c[0] == c[1] else " ".join(c) for c in df.columns]
    df.to_csv(STORE / "beds.csv", index=False)
    # archive hourly
    now = pd.to_datetime('now').tz_localize('UTC').tz_convert('Asia/Calcutta')
    now = now.strftime("%Y-%m-%d--%H")
    print(f"{now}.csv with {len(df)} rows")
    # df.to_csv(STORE / f"beds-{now}.csv", index=False)

if __name__ == "__main__":
    #
    beds()


import numpy as np
import skimage.io

# You should change the file /usr/lib/python3/dist-packages/caffe/io.py
# To fix "ValueError: Could not find a format to write the specified file in mode 'i'"
# Find the "load_image" function and modify it like this:
def load_image(filename, color=True):
    # MODIFY START
    img = skimage.img_as_float(skimage.io.imread(filename, as_gray=not color, plugin="pil")).astype(np.float32)
    # MODIFY END
    if img.ndim == 2:
        img = img[:, :, np.newaxis]
        if color:
            img = np.tile(img, (1, 1, 3))
    elif img.shape[2] == 4:
        img = img[:, :, :3]

    return img


import csv

def read_csv(filename,delimiter=','):
    with open(filename, 'r') as csvfile:
        reader = csv.reader(csvfile, skipinitialspace=True,delimiter=delimiter)
        header = next(reader)  # Skip header row
        for row in reader:
            yield row

def generate_csv(source, out, delimiter=','):
    delm = "|"
    columns = ["number".ljust(7), "name".center(14), "hex".center(9), "rgb".center(16), "hsl".center(16)]
    with open(out, 'w', newline='') as file:
        writer = csv.writer(file, delimiter=delm)
        writer.writerow(columns)
        for row in read_csv(source, delimiter=delimiter):
            number = row[0].ljust(4," ")
            name = row[1].replace(" (SYSTEM)", "").ljust(17," ")
            hexa = row[2].ljust(9)
            rgb = row[3].replace("rgb", "").ljust(16)
            hsl = row[4].replace("hsl", "").replace("%", "")
            columns = [number, name, hexa, rgb, hsl]
            writer.writerow(columns)

source = "xtermcolor.csv"
out = "256color.csv"
delimiter = ";"
# generate_csv(source, out)

generate_csv(source, out, delimiter)


# IMPORTS
from imutils import face_utils
import argparse
import dlib
import cv2
import os
import numpy as np
from PIL import Image
import pickle
import EmojiModifier
from face_parameter import *

people = []

def place_emoji(image_cv2, image_pil, detector, predictor, models):

    #image = imutils.resize(image, width=800)
    gray = cv2.cvtColor(image_cv2, cv2.COLOR_BGR2GRAY)

    # Detect faces
    rects = detector(gray, 1)

    model_index = 0
    # Loop over the face detections
    for (i, rect) in enumerate(rects):
        #Check people
        if(len(people) == 0):
            tmp = []
            tmp.append(rect)
            center = ( (rect.tr_corner().x - rect.tl_corner().x) / 2 + rect.tl_corner().x, (rect.bl_corner().y - rect.tl_corner().y) / 2 + rect.tl_corner().y)
            tmp.append(center)
            tmp.append(model_index)
            people.append(tmp) #[Rect, Center, Model]
        else:
            new_center = ( (rect.tr_corner().x - rect.tl_corner().x) / 2 + rect.tl_corner().x, (rect.bl_corner().y - rect.tl_corner().y) / 2 + rect.tl_corner().y)
            for p in people:
                if(p[0].tl_corner().x <= new_center[0] <= p[0].tr_corner().x and p[0].tl_corner().y <= new_center[1] <= p[0].br_corner().y):
                    model_index = p[2]
                    p[0] = rect
                    p[1] = new_center
                    break
            else:
                tmp = []
                tmp.append(rect)
                center = ( (rect.tr_corner().x - rect.tl_corner().x) / 2 + rect.tl_corner().x, (rect.bl_corner().y - rect.tl_corner().y) / 2 + rect.tl_corner().y)
                tmp.append(center)

                if people[-1][-1] == (len(models) - 1):

                    model_index = 0
                else:
                    model_index += 1

                tmp.append(model_index)
                people.append(tmp) #[Rect, Center, Model]

        # Detect face points
        shape = predictor(gray, rect)
        shape = face_utils.shape_to_np(shape)

        features = get_features(shape)

        # Prediction
        emotion = loadmod.predict([features])

        # Get rotation
        angleY = rotation_head_y(shape)
        angleZ = rotation_head_z(shape)

        # Choose 3D model
        model = models[model_index]

        # Get mouth
        mouthX = dist_mouth_horizontal(shape, rect)
        mouthY = dist_mouth_vertical(shape, rect)
        mouth = [mouthX, mouthY]

        if model.find("Normal_Mouth") >= 0:
            mouth.append(shape[48:67])

        # Get 3D Emoji
        emoji = EmojiModifier.EmojiModifier(model, mouth, emotion, [0, angleY, angleZ])

        # Place Emoji
        w = abs(shape[8][1] - shape[19][1]) * 2
        h = w
        x = shape[27][0] - abs(shape[8][1] - shape[19][1])
        y = shape[27][1] - abs(shape[8][1] - shape[19][1])

        emoji.image = emoji.image.resize((w, h), Image.ANTIALIAS)

        image_pil.paste(emoji.image, (x, y, (x + w), (y + h)), emoji.image)

    if not os.path.exists(folder):
        os.mkdir(folder)

    return image_pil

if __name__ == "__main__":

    ap = argparse.ArgumentParser()
    ap.add_argument("-p", "--picture",help="Image path")
    ap.add_argument("-v","--video", help="Video path")
    args = ap.parse_args()

    landmark_predictor = "shape_predictor_68_face_landmarks.dat"
    loadmod = pickle.load(open("new_LR_learning.sav", 'rb'))

    folder = 'output_images\\'

    models = ["Umatchicken_Beak_Mouth", "Umapion_Beak_Mouth", "Umatchii_Straight_Normal_Mouth"]

    # Initialize face detector and facial landmark predictor
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor(landmark_predictor)

    # Image
    if args.picture:
        image_cv2 = cv2.imread(args.picture)
        image_pil = Image.open(args.picture)
        new_image = place_emoji(image_cv2, image_pil, detector, predictor, models)
        new_image.save(folder + "output.png", 'png')

    elif args.video:
        # Video
        cap = cv2.VideoCapture(args.video)

        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        out = cv2.VideoWriter(folder + 'output.mp4', fourcc, cap.get(5), (int(cap.get(3)), int(cap.get(4))))

        while(cap.isOpened()):
            ret, frame = cap.read()
            if ret == True:
                cv2.imwrite("tmp.jpg", frame)
                image_cv2 = cv2.imread("tmp.jpg")
                image_pil = Image.open("tmp.jpg")
                new_image = place_emoji(image_cv2, image_pil, detector, predictor, models)
                imagev2 = cv2.cvtColor(np.array(new_image), cv2.COLOR_BGR2RGB)
                out.write(imagev2)
            else:
                break

        os.remove("tmp.jpg")
        cap.release()
        out.release()
        cv2.destroyAllWindows()


from mongoengine import EmbeddedDocument, Document
from mongoengine.fields import EmbeddedDocumentField, DateTimeField,  ListField, StringField, IntField, ReferenceField

class Phone(EmbeddedDocument):
    phone = IntField()

class Birthday(EmbeddedDocument):
    birthday = DateTimeField()

class Person(Document):
    name = StringField()
    birthday = EmbeddedDocumentField(Birthday)
    phones =ListField(EmbeddedDocumentField(Phone))


first_step = input('You\'re at a crossroad. Where do you want to go? Type "left" or "right" ')
if first_step == "Left".lower():
    second_step = input(
        'You\'ve come to a lake. There is an island in the middle of the lake. Type "wait" to wait for a boat. Type "swim" to swim across. ')
    if second_step == "Wait".lower():
        third_step = input(
            "You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue. Which colour do you choose? ")
        if third_step == "Red".lower():
            print("It's a room full of fire. Game Over.")
        elif third_step == "Blue".lower():
            print("You enter a room of beasts. Game Over.")
        elif third_step == "Yellow".lower():
            print("You found the treasure! You Win!")
        else:
            print("Game Over")
    else:
        print("You get attacked by an angry trout. Game Over.")

else:
    print("You fell into a hole. Game Over.")


import numpy as np
import os
import sys
import tensorflow as tf
from PIL import Image

sys.path.append("./models/research")
from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util

def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size

  return np.array(image.getdata()).reshape(
      (im_height, im_width, -1)).astype(np.uint8)

def run_inference_for_single_image(image, graph):
  with graph.as_default():
    with tf.Session() as sess:
      # Get handles to input and output tensors
      ops = tf.get_default_graph().get_operations()
      all_tensor_names = {output.name for op in ops for output in op.outputs}
      tensor_dict = {}
      for key in [
          'num_detections', 'detection_boxes', 'detection_scores',
          'detection_classes', 'detection_masks'
      ]:
        tensor_name = key + ':0'
        if tensor_name in all_tensor_names:
          tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
              tensor_name)
      if 'detection_masks' in tensor_dict:
        # The following processing is only for single image
        detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
        detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
        # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
        real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
        detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
        detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
        detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
            detection_masks, detection_boxes, image.shape[0], image.shape[1])
        detection_masks_reframed = tf.cast(
            tf.greater(detection_masks_reframed, 0.5), tf.uint8)
        # Follow the convention by adding back the batch dimension
        tensor_dict['detection_masks'] = tf.expand_dims(
            detection_masks_reframed, 0)
      image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

      # Run inference
      output_dict = sess.run(tensor_dict,
                             feed_dict={image_tensor: np.expand_dims(image, 0)})

      # all outputs are float32 numpy arrays, so convert types as appropriate
      output_dict['num_detections'] = int(output_dict['num_detections'][0])
      output_dict['detection_classes'] = output_dict[
          'detection_classes'][0].astype(np.uint8)
      output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
      output_dict['detection_scores'] = output_dict['detection_scores'][0]
      if 'detection_masks' in output_dict:
        output_dict['detection_masks'] = output_dict['detection_masks'][0]
  return output_dict

def crop_and_save(image_path, save_path, percent_points=0.0):
  MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
  PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'

  PATH_TO_LABELS = os.path.join('.', 'models', 'research', 'object_detection', 'data', 'mscoco_label_map.pbtxt')
  category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)

  detection_graph = tf.Graph()
  with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
      serialized_graph = fid.read()
      od_graph_def.ParseFromString(serialized_graph)
      tf.import_graph_def(od_graph_def, name='')

  with Image.open(image_path) as image:
    image_np = load_image_into_numpy_array(image)
    image_np_expanded = np.expand_dims(image_np, axis=0)
    output_dict = run_inference_for_single_image(image_np, detection_graph)

    best_box = output_dict["detection_boxes"][0]

    (rawX0, rawY0, rawX1, rawY1) = best_box

    rawX0 -= percent_points
    rawY0 -= percent_points
    rawX1 += percent_points
    rawY1 += percent_points

    (width, height) = image.size
    rawX0 *= width
    rawX1 *= width
    rawY0 *= height
    rawY1 *= height

    if os.path.exists(save_path):
       os.remove(save_path)

    image.crop( (rawX0, rawY0, rawX1, rawY1) ).save(save_path)

def dart_coords(image_path):
  """
  Returns the coordinates of a dart as an ordered pair
  """

  MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
  PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'

  PATH_TO_LABELS = os.path.join('.', 'models', 'research', 'object_detection', 'data', 'mscoco_label_map.pbtxt')
  category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)

  detection_graph = tf.Graph()
  with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
      serialized_graph = fid.read()
      od_graph_def.ParseFromString(serialized_graph)
      tf.import_graph_def(od_graph_def, name='')

  with Image.open(image_path) as image:
    image_np = load_image_into_numpy_array(image)
    image_np_expanded = np.expand_dims(image_np, axis=0)
    output_dict = run_inference_for_single_image(image_np, detection_graph)

    for (i, identifier) in enumerate( output_dict["detection_classes"] ):
      objectClass = category_index[identifier]["name"]
      if objectClass == "tie":
        box = output_dict["detection_boxes"][i]
        best_box = box
        break

    (rawX0, rawY0, rawX1, rawY1) = best_box
    (width, height) = image.size
    rawX0 *= width
    rawX1 *= width
    rawY0 *= height
    rawY1 *= height

    return ( int( (rawX0+rawX1)//2 ), int( (rawY0+rawY1)//2 ) )

if __name__ == "__main__":
	filePath = "image3darts.png"
	crop_and_save(filePath, "crop_testing.jpg")
	print(dart_coords(filePath))


import threading
import socket
import time

buf_size = 1024

class ConnThread(threading.Thread):
    def __init__(self, client, addr):
        super().__init__()
        self.client = client  # 浏览器
        self.addr = addr  # 浏览器ip地址
        self.server = None  # 目标服务器

    def run(self):
        src_data, hostname, port, ssl_flag = self.get_data_from_header(self.client)
        dst_data = self.get_data_from_host(hostname, port, src_data, ssl_flag)

        if dst_data and not ssl_flag:
            self.ssl_client_server_client(dst_data)
        elif ssl_flag:
            sample_data_to_client = b"HTTP/1.0 200 Connection Established\r\n\r\n"
            self.ssl_client_server_client(sample_data_to_client)
        else:
            print('pls check network. cannot get hostname:' + hostname)

    @staticmethod
    def get_data_from_header(client):
        """
        解析浏览器请求
        """
        while True:
            try:
                header = client.recv(buf_size)
                src_data = header
            except Exception as e:
                print('获取请求异常：'+str(e))
                raise e
            if header:
                headers = header.split(b'\r\n')
                ssl_flag = headers[0].find(b'CONNECT') > -1
                host_str = headers[1].decode()[6:]
                if ':' in host_str:
                    arr = host_str.split(':')
                    hostname = arr[0]
                    port = int(arr[1])
                else:
                    hostname = host_str
                    port = 80
                break
        return src_data, hostname, port, ssl_flag

    def get_data_from_host(self, hostname, port, src_data, ssl_flag):
        """
        http：与目标服务器建立连接，转发请求，获取返回
        https ：与目标服务器建立连接
        """
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        all_dst_data = ""
        try:
            self.server.connect((str(hostname), port))
        except Exception as e:
            print(e)
            print("get_data_from_host: cannot get host:" + hostname)
            self.server.close()
            return False
        try:
            if ssl_flag:
                return all_dst_data
            else:
                self.server.sendall(src_data)
        except Exception as e:
            print(e)
            print("cannot send data to host:" + hostname)
            self.server.close()
            return False
        rc_data = self.server.recv(buf_size)
        return rc_data

    def ssl_client_server_client(self, dst_data):
        """
        启动两个线程双向收发数据
        """
        try:
            self.client.sendall(dst_data)
        except Exception as e:
            print(e)
            print("cannot sent data(HTTP/1.0 200) to SSL client")
            return False
        threadlist = []
        t1 = threading.Thread(target=self.ssl_client_server)
        t2 = threading.Thread(target=self.ssl_server_client)
        threadlist.append(t1)
        threadlist.append(t2)
        for t in threadlist:
            t.start()
        # 等待与目标服务器断开连接
        while not self.server._closed:
            time.sleep(1)
        self.client.close()

    def ssl_client_server(self):
        while True:
            try:
                ssl_client_data = self.client.recv(buf_size)
            except Exception as e:
                print("client disconnct ")
                print(e)
                self.client.close()
                return False

            if ssl_client_data:
                try:
                    self.server.sendall(ssl_client_data)
                except Exception as e:
                    print("server disconnct Err")
                    self.server.close()
                    return False
            else:
                self.client.close()
                return False

    def ssl_server_client(self):
        while True:
            try:
                ssl_server_data = self.server.recv(buf_size)
            except Exception as e:
                print("server disconnct ")
                self.server.close()
                return False

            if ssl_server_data:
                #####send data to client
                try:
                    self.client.sendall(ssl_server_data)
                except Exception as e:
                    print("Client disconnct Err")
                    self.client.close()
                    return False
            else:
                self.server.close()
                return False

class Server(object):
    def __init__(self, host, port):
        tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        tcp_server.bind((host,port))
        tcp_server.listen(20)
        self.tcp_sever = tcp_server

    def start(self):
        while True:
            try:
                client, addr = self.tcp_sever.accept()
                ConnThread(client,addr).start()
            except Exception as e:
                print('Error Happen！')
                print(e)

if __name__ == "__main__":
    Server("0.0.0.0", 80).start()


import re

class TelefonesBr:
    def __init__(self, telefone):
        if self.valida_telefone(telefone):
            self.numero = telefone
        else:
            raise ValueError("Número incorreto.")

    def __str__(self):
        return self.formata_numero()

    # Para validação do número, necessário que o usuário digite com parênteses no DDD
    def valida_telefone(self, telefone):
        padrao = "([0-9]{2,3})?(\([0-9]{2})\)([0-9]{4,5})([0-9]{4})"
        resposta = re.findall(padrao, telefone)
        if resposta:
            return True
        else:
            return False

    # Para formatação do número, necessário que o usuário digite com parênteses no DDD
    def formata_numero(self):
        padrao = "([0-9]{2,3})?(\([0-9]{2}\))([0-9]{4,5})([0-9]{4})"
        resposta = re.search(padrao, self.numero)
        numero_formatado = "+{}({}){}-{}".format(
            resposta.group(1),
            resposta.group(2),
            resposta.group(3),
            resposta.group(4)
        )
        return numero_formatado


# -*- coding: utf-8 -*-
"""
interspecifics - taller OpenCV
Sesion 01, Ejemplo 05

Analiza los colores de los pixeles de
la captura de video en vivo con openCV
Created on Thu Aug 22 21:12:29 2019
@author: E
"""

import cv2
from time import sleep

video = cv2.VideoCapture(3)
nombre_ventana = "CV05_pixeles_video_en_vivo"
nframe = 0;
ultimo_clic = [0,0]

def detecta_clics(event, x, y, flags, param):
    global ultimo_clic
    if event == cv2.EVENT_LBUTTONDOWN:
        #cv2.imshow(nombre_ventana, img)
        ultimo_clic = [x, y]
        pixel= frame[y, x]
        pixel_b, pixel_g, pixel_r = pixel
        print('Ultimo click en:', ultimo_clic, '\tColor de pixel:', pixel)

cv2.namedWindow(nombre_ventana)
cv2.setMouseCallback(nombre_ventana, detecta_clics)

sleep(1)
check, frame = video.read()
print('Dimensiones de la imagen:', frame.shape)

while(True):
    check, frame = video.read()
    cv2.rectangle(frame, (ultimo_clic[0], ultimo_clic[1]), (ultimo_clic[0]+5, ultimo_clic[1]+5), (0, 255, 0), 1)
    cv2.imshow(nombre_ventana, frame)
    key = cv2.waitKey(1)
    # si es 'q', termina el programa
    if key == ord('q'):
        break
    nframe+=1
video.release()
cv2.destroyAllWindows()


#!/usr/bin/env python

from __future__ import division, print_function

import argparse
from matplotlib import pyplot
from pprint import pprint

from process import process

def main():
    args = getargs()
    print('processing')
    data = process(args)
    print('plotting')
    plot(data, args)

def plot(data, args):
    extent = (args.ranges[0], args.ranges[0] + args.ranges[2],
              args.ranges[1] + args.ranges[2], args.ranges[1])
    pyplot.imshow(data, interpolation='none', extent=extent)
    pyplot.gca().invert_yaxis()
    pyplot.show()

def getargs():
    parser = argparse.ArgumentParser(description='produce an mandelbrot plot')
    parser.add_argument('-r', '--ranges', type=float, nargs=3,
            default=[-2.0, -2.0, 4.0],
            help='what section of the set to calculate.')
    parser.add_argument('-m', '--maxiter', default=70, type=int,
            help='the number of iterations to run per point.')
    parser.add_argument('-g', '--granularity', default=1000, type=int,
            help='the number of points to calculate across each axis.')
    return parser.parse_args()

if __name__ == '__main__':
    main()

    # import cProfile, pstats
    # cProfile.run('main()', 'Profile.prof')
    # s = pstats.Stats('Profile.prof')
    # s.strip_dirs().sort_stats('time').print_stats()


from Products.LinguaPlone.tests.base import LinguaPloneTestCase
from Products.LinguaPlone.tests.utils import makeContent
from Products.LinguaPlone.tests.utils import makeTranslation

class TestGeneratedMethods(LinguaPloneTestCase):

    def afterSetUp(self):
        self.addLanguage('de')
        self.addLanguage('fr')
        self.setLanguage('en')
        self.english = makeContent(self.folder, 'SimpleType', 'doc')
        self.english.setLanguage('en')
        self.alsoenglish = makeContent(self.folder, 'SimpleType', 'doctwo')
        self.alsoenglish.setLanguage('en')
        self.german = makeTranslation(self.english, 'de')
        self.french = makeContent(self.folder, 'SimpleType', 'frenchdoc')
        self.french.setLanguage('fr')
        self.folder_en = makeContent(self.folder, 'SimpleFolder', 'folder')
        self.folder_en.setLanguage('en')

    def test_setModificationDate(self):
        """
        LinguaPlone autogenerates a method for setModificationDate overriding
        the one present at Products.Archetypes.ExtensibleMetadata.
        This method in Archetypes has a default value for a parameter and it
        handles it autogenerating the modification date.
        This test shows that if you call setModificationDate without a parameter
        it will call the field default value
        """
        from DateTime import DateTime
        now = DateTime()

        self.english.setModificationDate(now)
        self.assertEqual(self.english.modified(), now)
        self.english.setModificationDate()
        self.failUnless(self.english.modified() > now)


from django.urls import path, include, re_path
from .views import UserList, UserDetail

# dj rest auth with jwt
# from dj_rest_auth.views import (LoginView, LogoutView, PasswordChangeView,
#                                 PasswordResetConfirmView, PasswordResetView,
#                                 UserDetailsView)
# from rest_framework_simplejwt.views import TokenVerifyView
# from django.views.generic import TemplateView
app_name = "api"

urlpatterns = [
    # Users
    path("users/", UserList.as_view(), name="user-list"),
    path("users/<int:pk>", UserDetail.as_view(), name="user-detail"),
]


from flask import jsonify, make_response
from typing import List

import json

def is_prime_number(num):
    """Checks if a number is prime or not.
    Args:
        num: an integer
    Returns:
        A boolean: True if input number is prime, and False otherwise
    """
    if type(num) == int:
        if num < 2:
            return False
        elif num == 2:
            return True
        elif num > 2 and num % 2 == 0:
            return False
        else:
            for i in range(3, int(num**0.5)+1, 2):
                if num % i == 0:
                    return False
            return True
    else:
        return False

def separate_prime_and_non_primes(list1):
    """Checks given list for prime numbers.
    Args:
        list1: a List containing numbers
    Returns:
        A tuple: contains a list of prime input numbers and a list of non-prime input numbers.
    """
    primes = []
    non_primes = []
    for i in range(len(list1)):
        if is_prime_number(list1[i]):
            primes.append(list1[i])
        else:
            non_primes.append(list1[i])

    return (primes, non_primes)

def find_primes(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    # Object that gets passed back to server
    response_json = {
        'data': {
            'primes': None,
            'non_primes': None,
            'message': None,
            'has_error': False
        }
    }

    primes = None
    non_primes = None
    error_message = None
    has_error = False

    # Parse data into JSON
    request_json = request.get_json()

    # List is retrieved
    list1 = request_json['data'].get('list1')

    if type(list1) != list:
        error_message = 'Invalid user input: expected a list.'
        has_error = True

    if not has_error and (len(list1) == 0):
        error_message = 'Invalid user input: the list was empty.'
        has_error = True

    if not has_error and any(type(element) == float for element in list1):
        # Allow for decimal numbers in the list, but don't consider them
        error_message = 'At least one decimal number was inputted, and all decimal numbers are non-prime.'

    if not has_error and any(element < 0 for element in list1):
        # Allow for negative numbers in the list, but don't consider them
        error_message = 'At least one negative number was inputted, and all negative numbers are non-prime.'

    if not has_error:
        try:
            primes, non_primes = separate_prime_and_non_primes(list1)
        except ValueError as e:
            error_message = str(e)
            has_error = True
        except Exception as e:
            error_message = 'Something went wrong: ' + str(e) + '.'
            has_error = True

    response_json['data']['primes'] = primes
    response_json['data']['non_primes'] = non_primes
    response_json['data']['message'] = error_message
    response_json['data']['has_error'] = has_error

    return make_response(jsonify(response_json))


# 导入包
# 导入OpenCV库
import cv2
from hyperlpr import *

def spotImg(path):
    # 读入图片
    image = cv2.imread(path)
    # 识别结果
    result = HyperLPR_plate_recognition(image)
    print(result)
    for i, r in enumerate(result):
        txt, confidence, rect = r
        '''
            cx: 中心点x
            xy: 中心点y
            w:  宽度
            h:  高度
        '''
        cx, cy, w, h = rect
        print(cx, cy, w, h)

spotImg("demo.jpg")


#!/usr/bin/python3
import paho.mqtt.client as mqtt

# fonction associées
def on_connect(client, userdata, flags, rc):
	print("Connected with result code "+str(rc))
	client.subscribe("/evenement")

def on_message(client, userdata, msg):
        msg_receipt = str(msg.payload.decode())
        print(" message : {} ".format(msg_receipt))
        print("j envoies"+str(msg_receipt))

        client.publish("/web",msg_receipt)
        if "STAT" not in msg_receipt:
            client.publish("/tampon",msg_receipt)

client = mqtt.Client()
client.connect("localhost",1883,60)

# callbacks
client.on_connect = on_connect
client.on_message = on_message

client.loop_forever()


from selenium import webdriver
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://www.baidu.com")

driver.find_element(By.ID, "kw").send_keys("selenium")
driver.find_element(By.ID, "su").click()

# get all the cookie
cookies = driver.get_cookies()

# 返回字典的key为BAIDUID的cookie
cookie = driver.get_cookie("BAIDUID")
print(cookies, "\n")
print(cookie)

# delete all the cookie message
driver.delete_all_cookies()

driver.quit()